@dr.pogodin/react-utils 1.46.2 → 1.47.0-alpha.1
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/babel.config.js +1 -0
- package/babel.libweb.config.js +16 -0
- package/bin/build.js +16 -10
- package/bin/setup.js +11 -8
- package/build/development/client/getInj.js.map +1 -1
- package/build/development/client/index.js.map +1 -1
- package/build/development/client/init.js.map +1 -1
- package/build/development/index.js +7 -1
- package/build/development/index.js.map +1 -1
- package/build/development/server/Cache.js.map +1 -1
- package/build/development/server/index.js +13 -8
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js +15 -8
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +7 -5
- package/build/development/server/server.js.map +1 -1
- package/build/development/shared/components/Button/index.js +6 -6
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +8 -8
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/GenericLink/index.js +5 -1
- package/build/development/shared/components/GenericLink/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +10 -9
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/Link.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +8 -6
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/NavLink.js.map +1 -1
- package/build/development/shared/components/PageLayout/index.js +6 -6
- package/build/development/shared/components/PageLayout/index.js.map +1 -1
- package/build/development/shared/components/TextArea/index.js +13 -9
- package/build/development/shared/components/TextArea/index.js.map +1 -1
- package/build/development/shared/components/Throbber/index.js +6 -6
- package/build/development/shared/components/Throbber/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/Tooltip.js +1 -0
- package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +7 -7
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js +9 -9
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/components/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/CustomDropdown/index.js +11 -11
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js +12 -12
- package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/Switch/index.js +7 -7
- package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/development/shared/utils/config.js.map +1 -1
- package/build/development/shared/utils/globalState.js.map +1 -1
- package/build/development/shared/utils/index.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv.js +14 -10
- package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +1 -0
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/time.js.map +1 -1
- package/build/production/client/getInj.js.map +1 -1
- package/build/production/client/index.js.map +1 -1
- package/build/production/client/init.js.map +1 -1
- package/build/production/index.js +4 -1
- package/build/production/index.js.map +1 -1
- package/build/production/server/Cache.js.map +1 -1
- package/build/production/server/index.js +5 -5
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js +7 -7
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +4 -4
- package/build/production/server/server.js.map +1 -1
- package/build/production/shared/components/Button/index.js +1 -1
- package/build/production/shared/components/Button/index.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 +2 -2
- package/build/production/shared/components/GenericLink/index.js.map +1 -1
- package/build/production/shared/components/Input/index.js +1 -1
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/Link.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +1 -1
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/NavLink.js.map +1 -1
- package/build/production/shared/components/PageLayout/index.js +1 -1
- package/build/production/shared/components/PageLayout/index.js.map +1 -1
- package/build/production/shared/components/TextArea/index.js +1 -1
- package/build/production/shared/components/TextArea/index.js.map +1 -1
- package/build/production/shared/components/Throbber/index.js +1 -1
- package/build/production/shared/components/Throbber/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +1 -1
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/components/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/NativeDropdown/index.js +1 -1
- package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/Switch/index.js +1 -1
- package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/production/shared/utils/config.js.map +1 -1
- package/build/production/shared/utils/globalState.js.map +1 -1
- package/build/production/shared/utils/index.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js +8 -7
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/time.js.map +1 -1
- package/build/web/client/getInj.js +54 -0
- package/build/web/client/getInj.js.map +1 -0
- package/build/web/client/index.js +38 -0
- package/build/web/client/index.js.map +1 -0
- package/build/web/client/init.js +49 -0
- package/build/web/client/init.js.map +1 -0
- package/build/web/index.js +25 -0
- package/build/web/index.js.map +1 -0
- package/build/web/server/Cache.js +54 -0
- package/build/web/server/Cache.js.map +1 -0
- package/build/web/server/index.js +211 -0
- package/build/web/server/index.js.map +1 -0
- package/build/web/server/renderer.js +516 -0
- package/build/web/server/renderer.js.map +1 -0
- package/build/web/server/server.js +231 -0
- package/build/web/server/server.js.map +1 -0
- package/build/web/server/utils/errors.js +103 -0
- package/build/web/server/utils/errors.js.map +1 -0
- package/build/web/server/utils/index.js +4 -0
- package/build/web/server/utils/index.js.map +1 -0
- package/build/web/shared/components/Button/index.js +90 -0
- package/build/web/shared/components/Button/index.js.map +1 -0
- package/build/web/shared/components/Button/style.scss +54 -0
- package/build/web/shared/components/Checkbox/index.js +35 -0
- package/build/web/shared/components/Checkbox/index.js.map +1 -0
- package/build/web/shared/components/Checkbox/theme.scss +63 -0
- package/build/web/shared/components/GenericLink/index.js +107 -0
- package/build/web/shared/components/GenericLink/index.js.map +1 -0
- package/build/web/shared/components/GenericLink/style.scss +3 -0
- package/build/web/shared/components/Input/index.js +71 -0
- package/build/web/shared/components/Input/index.js.map +1 -0
- package/build/web/shared/components/Input/theme.scss +52 -0
- package/build/web/shared/components/Link.js +20 -0
- package/build/web/shared/components/Link.js.map +1 -0
- package/build/web/shared/components/Modal/base-theme.scss +38 -0
- package/build/web/shared/components/Modal/index.js +128 -0
- package/build/web/shared/components/Modal/index.js.map +1 -0
- package/build/web/shared/components/Modal/styles.scss +3 -0
- package/build/web/shared/components/NavLink.js +13 -0
- package/build/web/shared/components/NavLink.js.map +1 -0
- package/build/web/shared/components/PageLayout/base-theme.scss +30 -0
- package/build/web/shared/components/PageLayout/index.js +38 -0
- package/build/web/shared/components/PageLayout/index.js.map +1 -0
- package/build/web/shared/components/TextArea/index.js +106 -0
- package/build/web/shared/components/TextArea/index.js.map +1 -0
- package/build/web/shared/components/TextArea/style.scss +68 -0
- package/build/web/shared/components/Throbber/index.js +26 -0
- package/build/web/shared/components/Throbber/index.js.map +1 -0
- package/build/web/shared/components/Throbber/theme.scss +26 -0
- package/build/web/shared/components/WithTooltip/Tooltip.js +226 -0
- package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -0
- package/build/web/shared/components/WithTooltip/default-theme.scss +36 -0
- package/build/web/shared/components/WithTooltip/index.js +117 -0
- package/build/web/shared/components/WithTooltip/index.js.map +1 -0
- package/build/web/shared/components/YouTubeVideo/base.scss +15 -0
- package/build/web/shared/components/YouTubeVideo/index.js +56 -0
- package/build/web/shared/components/YouTubeVideo/index.js.map +1 -0
- package/build/web/shared/components/YouTubeVideo/throbber.scss +11 -0
- package/build/web/shared/components/index.js +18 -0
- package/build/web/shared/components/index.js.map +1 -0
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +79 -0
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -0
- package/build/web/shared/components/selectors/CustomDropdown/Options/style.scss +6 -0
- package/build/web/shared/components/selectors/CustomDropdown/index.js +120 -0
- package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -0
- package/build/web/shared/components/selectors/CustomDropdown/theme.scss +118 -0
- package/build/web/shared/components/selectors/NativeDropdown/index.js +82 -0
- package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -0
- package/build/web/shared/components/selectors/NativeDropdown/theme.scss +81 -0
- package/build/web/shared/components/selectors/Switch/index.js +49 -0
- package/build/web/shared/components/selectors/Switch/index.js.map +1 -0
- package/build/web/shared/components/selectors/Switch/theme.scss +39 -0
- package/build/web/shared/components/selectors/common.js +12 -0
- package/build/web/shared/components/selectors/common.js.map +1 -0
- package/build/web/shared/components/selectors/index.js +4 -0
- package/build/web/shared/components/selectors/index.js.map +1 -0
- package/build/web/shared/utils/config.js +21 -0
- package/build/web/shared/utils/config.js.map +1 -0
- package/build/web/shared/utils/globalState.js +15 -0
- package/build/web/shared/utils/globalState.js.map +1 -0
- package/build/web/shared/utils/index.js +13 -0
- package/build/web/shared/utils/index.js.map +1 -0
- package/build/web/shared/utils/isomorphy/buildInfo.js +44 -0
- package/build/web/shared/utils/isomorphy/buildInfo.js.map +1 -0
- package/build/web/shared/utils/isomorphy/environment-check.js +17 -0
- package/build/web/shared/utils/isomorphy/environment-check.js.map +1 -0
- package/build/web/shared/utils/isomorphy/index.js +36 -0
- package/build/web/shared/utils/isomorphy/index.js.map +1 -0
- package/build/web/shared/utils/jest/E2eSsrEnv.js +230 -0
- package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -0
- package/build/web/shared/utils/jest/global.js +4 -0
- package/build/web/shared/utils/jest/global.js.map +1 -0
- package/build/web/shared/utils/jest/index.js +165 -0
- package/build/web/shared/utils/jest/index.js.map +1 -0
- package/build/web/shared/utils/splitComponent.js +221 -0
- package/build/web/shared/utils/splitComponent.js.map +1 -0
- package/build/web/shared/utils/time.js +85 -0
- package/build/web/shared/utils/time.js.map +1 -0
- package/build/web/shared/utils/webpack.js +61 -0
- package/build/web/shared/utils/webpack.js.map +1 -0
- package/build/web/styles/_global/reset.css +52 -0
- package/build/web/styles/_mixins/fonts.scss +40 -0
- package/build/web/styles/_mixins/media.scss +150 -0
- package/build/web/styles/_mixins/typography.scss +83 -0
- package/build/web/styles/global.scss +11 -0
- package/build/web/styles/mixins.scss +6 -0
- package/config/babel/node-ssr.js +5 -2
- package/config/webpack/app-base.js +10 -7
- package/config/webpack/app-development.js +3 -2
- package/package.json +16 -27
- package/src/index.ts +7 -1
- package/src/server/index.ts +6 -8
- package/src/server/renderer.tsx +7 -9
- package/src/server/server.ts +3 -5
- package/src/shared/components/Modal/base-theme.scss +1 -1
- package/src/shared/components/PageLayout/base-theme.scss +1 -1
- package/src/shared/utils/jest/E2eSsrEnv.ts +8 -1
- package/build/development/__chunk_groups__.json +0 -6
- package/build/development/style.css +0 -909
- package/build/development/web.bundle.js +0 -752
- package/build/production/__chunk_groups__.json +0 -6
- package/build/production/style.css +0 -2
- package/build/production/style.css.map +0 -1
- package/build/production/web.bundle.js +0 -3
- package/build/production/web.bundle.js.LICENSE.txt +0 -9
- package/build/production/web.bundle.js.map +0 -1
- package/dev-styles.js +0 -1
- package/null.js +0 -1
- package/prod-styles.js +0 -1
|
@@ -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 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 // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\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\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`. */\nconst { useServiceWorker } = buildInfo;\nif (useServiceWorker) {\n const { navigator } = window;\n if ('serviceWorker' in navigator) {\n window.addEventListener('load', () => {\n void (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 // eslint-disable-next-line no-console\n console.log('SW registered:', reg);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.log('SW registration failed:', err);\n }\n })();\n });\n }\n}\n"],"mappings":"aAMA,IAAAA,UAAA,CAAAC,OAAA,wCANA;AACA;AACA,GAEA,mBAIA,KAAM,CAAAC,SAAS,CAAG,
|
|
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 // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\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\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`. */\nconst { useServiceWorker } = buildInfo;\nif (useServiceWorker) {\n const { navigator } = window;\n if ('serviceWorker' in navigator) {\n window.addEventListener('load', () => {\n void (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 // eslint-disable-next-line no-console\n console.log('SW registered:', reg);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.log('SW registration failed:', err);\n }\n })();\n });\n }\n}\n"],"mappings":"aAMA,IAAAA,UAAA,CAAAC,OAAA,wCANA;AACA;AACA,GAEA,mBAIA,KAAM,CAAAC,SAAS,CAAG,GAAAF,UAAA,CAAAG,YAAY,EAAC,CAAC,CAEhC;AAUA,GAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACzC;AACAC,OAAO,CAACC,IAAI,CAAC,4DAAwD,CAAC,CAEtE;AACAC,MAAM,CAACC,kBAAkB,CAAGC,UAC9B,CAEA,yEACA,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,IAAM,CACpC,IAAK,CAAC,SAAY,CAChB,GAAI,CACF;AACA;AACA;AACA;AACA,KAAM,CAAAC,GAAG,CAAG,KAAM,CAAAF,SAAS,CACxBG,aAAa,CAACC,QAAQ,CAAC,sBAAsB,CAAC,CACjD;AACAV,OAAO,CAACW,GAAG,CAAC,gBAAgB,CAAEH,GAAG,CACnC,CAAE,MAAOI,GAAG,CAAE,CACZ;AACAZ,OAAO,CAACW,GAAG,CAAC,yBAAyB,CAAEC,GAAG,CAC5C,CACF,CAAC,EAAE,CACL,CAAC,CACH,CACF","ignoreList":[]}
|
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
// being loaded into environment by mistake (e.g. because of different
|
|
3
3
|
// packages pinning down different exact versions of the lib, thus preventing
|
|
4
4
|
// a proper dedupe and using a single common library version).
|
|
5
|
-
if(global.REACT_UTILS_LIBRARY_LOADED){throw Error("React utils library is already loaded")}else global.REACT_UTILS_LIBRARY_LOADED=true
|
|
5
|
+
if(global.REACT_UTILS_LIBRARY_LOADED){throw Error("React utils library is already loaded")}else global.REACT_UTILS_LIBRARY_LOADED=true;// TODO: This is a rapid workaround to get rid of __dirname. I guess, later
|
|
6
|
+
// we'll re-implement requireWeak() to accept import.meta.url directly, and
|
|
7
|
+
// this workaround won't be needed.
|
|
8
|
+
let dirname=require("url").pathToFileURL(__filename).toString();dirname=dirname.slice(5,dirname.lastIndexOf("/"));const server=exports.server=_utils.webpack.requireWeak("./server",dirname);const client=exports.client=server?undefined// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
6
9
|
:require("./client").default;
|
|
7
10
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_utils","require","_reactGlobalState","_components","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","global","REACT_UTILS_LIBRARY_LOADED","Error","server","webpack","requireWeak","
|
|
1
|
+
{"version":3,"file":"index.js","names":["_utils","require","_reactGlobalState","_components","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","global","REACT_UTILS_LIBRARY_LOADED","Error","dirname","pathToFileURL","__filename","toString","slice","lastIndexOf","server","webpack","requireWeak","client","undefined","default"],"sources":["../../src/index.ts"],"sourcesContent":["import 'styles/global.scss';\n\nimport { webpack } from 'utils';\n\nimport type * as ClientM from './client';\nimport type * as ServerFactoryM from './server';\n\n// It is a safeguard against multiple instances / versions of the library\n// being loaded into environment by mistake (e.g. because of different\n// packages pinning down different exact versions of the lib, thus preventing\n// a proper dedupe and using a single common library version).\nif (global.REACT_UTILS_LIBRARY_LOADED) {\n throw Error('React utils library is already loaded');\n} else global.REACT_UTILS_LIBRARY_LOADED = true;\n\n// TODO: This is a rapid workaround to get rid of __dirname. I guess, later\n// we'll re-implement requireWeak() to accept import.meta.url directly, and\n// this workaround won't be needed.\nlet dirname = import.meta.url;\ndirname = dirname.slice(5, dirname.lastIndexOf('/'));\n\nconst server = webpack.requireWeak<typeof ServerFactoryM>('./server', dirname);\n\nconst client = server\n ? undefined\n\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n : (require('./client') as typeof ClientM).default;\n\nexport {\n type AsyncCollectionT,\n type AsyncCollectionLoaderT,\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type ForceT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateResT,\n type ValueOrInitializerT,\n getGlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n withGlobalStateType,\n} from '@dr.pogodin/react-global-state';\n\nexport * from 'components';\n\nexport {\n type BeforeRenderResT,\n type BeforeRenderT,\n type ConfigT,\n type ServerSsrContext,\n type ServerT,\n} from './server';\n\nexport {\n assertEmptyObject,\n config,\n Barrier,\n Cached,\n Emitter,\n isomorphy,\n getSsrContext,\n type Listener,\n type ObjectKey,\n Semaphore,\n splitComponent,\n type Theme,\n themed,\n ThemeProvider,\n time,\n webpack,\n withRetries,\n} from 'utils';\n\nexport { client, server };\n"],"mappings":"sxFAEA,IAAAA,MAAA,CAAAC,OAAA,mBA2BA,IAAAC,iBAAA,CAAAD,OAAA,mCAmBA,IAAAE,WAAA,CAAAF,OAAA,wBAAAG,MAAA,CAAAC,IAAA,CAAAF,WAAA,EAAAG,OAAA,UAAAC,GAAA,KAAAA,GAAA,cAAAA,GAAA,0BAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,CAAAJ,GAAA,YAAAA,GAAA,IAAAK,OAAA,EAAAA,OAAA,CAAAL,GAAA,IAAAJ,WAAA,CAAAI,GAAA,SAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,CAAAL,GAAA,EAAAO,UAAA,MAAAC,GAAA,SAAAA,CAAA,SAAAZ,WAAA,CAAAI,GAAA,OAzCA;AACA;AACA;AACA;AACA,GAAIS,MAAM,CAACC,0BAA0B,CAAE,CACrC,KAAM,CAAAC,KAAK,CAAC,uCAAuC,CACrD,CAAC,IAAM,CAAAF,MAAM,CAACC,0BAA0B,CAAG,IAAI,CAE/C;AACA;AACA;AACA,GAAI,CAAAE,OAAO,CAAAlB,OAAA,QAAAmB,aAAA,CAAAC,UAAA,EAAAC,QAAA,EAAkB,CAC7BH,OAAO,CAAGA,OAAO,CAACI,KAAK,CAAC,CAAC,CAAEJ,OAAO,CAACK,WAAW,CAAC,GAAG,CAAC,CAAC,CAEpD,KAAM,CAAAC,MAAM,CAAAb,OAAA,CAAAa,MAAA,CAAGC,cAAO,CAACC,WAAW,YAAoCR,OAAO,CAAC,CAE9E,KAAM,CAAAS,MAAM,CAAAhB,OAAA,CAAAgB,MAAA,CAAGH,MAAM,CACjBI,SAEF;AAAA,CACG5B,OAAO,WAAW,CAAC,CAAoB6B,OAAO","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Cache.js","names":["Cache","items","size","constructor","maxSize","get","key","maxage","Number","MAX_VALUE","item","Date","now","timestamp","data","add","cached","entries","Object","sort","a","b","entry","itemKey","exports","default"],"sources":["../../../src/server/Cache.ts"],"sourcesContent":["type CachedItemT<DatumT> = {\n data: DatumT;\n size: number;\n timestamp: number;\n};\n\n/**\n * Implements the static cache.\n */\nexport default class Cache<DatumT> {\n private items: Record<string, CachedItemT<DatumT>> = {};\n\n private size = 0;\n\n constructor(private maxSize: number) { }\n\n /**\n * Cache lookup.\n * @param key Item key to look for.\n * @param [maxage=Number.MAX_VALUE] Optional. The maximum age of\n * cached item to serve. Default to infinite.\n * @returns Cached item, or null if the item is absent in cache,\n * or stale.\n */\n get({\n key,\n maxage = Number.MAX_VALUE,\n }: {\n key: string;\n maxage?: number;\n }): DatumT | null {\n const item = this.items[key];\n return item && Date.now() - item.timestamp < maxage ? item.data : null;\n }\n\n /**\n * Adds item to cache.\n * @param data Item to add.\n * @param key Key to store the item at.\n * @param size Byte size of the item.\n */\n add(data: DatumT, key: string, size: number): void {\n const cached = this.items[key];\n if (cached) this.size -= cached.size;\n\n this.items[key] = { data, size, timestamp: Date.now() };\n this.size += size;\n\n if (this.size > this.maxSize) {\n const entries = Object.entries(this.items);\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp);\n\n for (const entry of entries) {\n const [itemKey, item] = entry;\n delete this.items[itemKey];\n this.size -= item.size;\n if (this.size < this.maxSize / 2) break;\n }\n }\n }\n}\n"],"mappings":"6FAMA;AACA;AACA,GACe,KAAM,CAAAA,KAAc,CACzBC,KAAK,CAAwC,CAAC,CA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K,CAC7B,MAAO,KAAI,CAACrB,KAAK,CAACsB,OAAO,CAAC,CAC1B,IAAI,CAACrB,IAAI,EAAIQ,IAAI,CAACR,IAAI,CACtB,GAAI,IAAI,CAACA,IAAI,CAAG,IAAI,CAACE,OAAO,CAAG,CAAC,CAAE,KACpC,CACF,CACF,CACF,
|
|
1
|
+
{"version":3,"file":"Cache.js","names":["Cache","items","size","constructor","maxSize","get","key","maxage","Number","MAX_VALUE","item","Date","now","timestamp","data","add","cached","entries","Object","sort","a","b","entry","itemKey","exports","default"],"sources":["../../../src/server/Cache.ts"],"sourcesContent":["type CachedItemT<DatumT> = {\n data: DatumT;\n size: number;\n timestamp: number;\n};\n\n/**\n * Implements the static cache.\n */\nexport default class Cache<DatumT> {\n private items: Record<string, CachedItemT<DatumT>> = {};\n\n private size = 0;\n\n constructor(private maxSize: number) { }\n\n /**\n * Cache lookup.\n * @param key Item key to look for.\n * @param [maxage=Number.MAX_VALUE] Optional. The maximum age of\n * cached item to serve. Default to infinite.\n * @returns Cached item, or null if the item is absent in cache,\n * or stale.\n */\n get({\n key,\n maxage = Number.MAX_VALUE,\n }: {\n key: string;\n maxage?: number;\n }): DatumT | null {\n const item = this.items[key];\n return item && Date.now() - item.timestamp < maxage ? item.data : null;\n }\n\n /**\n * Adds item to cache.\n * @param data Item to add.\n * @param key Key to store the item at.\n * @param size Byte size of the item.\n */\n add(data: DatumT, key: string, size: number): void {\n const cached = this.items[key];\n if (cached) this.size -= cached.size;\n\n this.items[key] = { data, size, timestamp: Date.now() };\n this.size += size;\n\n if (this.size > this.maxSize) {\n const entries = Object.entries(this.items);\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp);\n\n for (const entry of entries) {\n const [itemKey, item] = entry;\n delete this.items[itemKey];\n this.size -= item.size;\n if (this.size < this.maxSize / 2) break;\n }\n }\n }\n}\n"],"mappings":"6FAMA;AACA;AACA,GACe,KAAM,CAAAA,KAAc,CACzBC,KAAK,CAAwC,CAAC,CAAC,CAE/CC,I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O,KAAI,CAACrB,KAAK,CAACsB,OAAO,CAAC,CAC1B,IAAI,CAACrB,IAAI,EAAIQ,IAAI,CAACR,IAAI,CACtB,GAAI,IAAI,CAACA,IAAI,CAAG,IAAI,CAACE,OAAO,CAAG,CAAC,CAAE,KACpC,CACF,CACF,CACF,CAAAoB,OAAA,CAAAC,OAAA,CAAAzB,KAAA","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=launchServer;Object.defineProperty(exports,"errors",{enumerable:true,get:function(){return _utils.errors}});Object.defineProperty(exports,"getDefaultCspSettings",{enumerable:true,get:function(){return _server.getDefaultCspSettings}});require("source-map-support/register");var _nodeHttp=_interopRequireDefault(require("node:http"));var _nodeHttps=_interopRequireDefault(require("node:https"));var
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=launchServer;Object.defineProperty(exports,"errors",{enumerable:true,get:function(){return _utils.errors}});Object.defineProperty(exports,"getDefaultCspSettings",{enumerable:true,get:function(){return _server.getDefaultCspSettings}});require("source-map-support/register");var _nodeHttp=_interopRequireDefault(require("node:http"));var _nodeHttps=_interopRequireDefault(require("node:https"));var _cloneDeep=_interopRequireDefault(require("lodash/cloneDeep"));var _defaults=_interopRequireDefault(require("lodash/defaults"));var _isFinite=_interopRequireDefault(require("lodash/isFinite"));var _isNumber=_interopRequireDefault(require("lodash/isNumber"));var _isString=_interopRequireDefault(require("lodash/isString"));var _toNumber=_interopRequireDefault(require("lodash/toNumber"));require("raf/polyfill");var _server=_interopRequireWildcard(require("./server"));var _renderer=require("./renderer");var _utils=require("./utils");function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap,n=new WeakMap;return(_interopRequireWildcard=function(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,default:e};if(null===e||"object"!=typeof e&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f)}for(const t in e)"default"!==t&&{}.hasOwnProperty.call(e,t)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(i.get||i.set)?o(f,t,i):f[t]=e[t]);return f})(e,t)}// eslint-disable-next-line import/no-unassigned-import
|
|
2
2
|
// Polyfill required by ReactJS.
|
|
3
3
|
// TODO: Double-check, if it is still required by React v19?
|
|
4
4
|
// eslint-disable-next-line import/no-unassigned-import
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* TODO: Drop this function?
|
|
8
8
|
* @param value Port name or number.
|
|
9
9
|
* @return Port number (Number), name (String), or false.
|
|
10
|
-
*/function normalizePort(value){const port=(0,
|
|
10
|
+
*/function normalizePort(value){const port=(0,_toNumber.default)(value);if((0,_isFinite.default)(port))return port;/* port number */if(!(0,_isNumber.default)(port))return value;/* named pipe */return false}/**
|
|
11
11
|
* Creates and launches web-server for ReactJS application. Allows zero
|
|
12
12
|
* or detailed configuration, supports server-side rendering,
|
|
13
13
|
* and development tools, including Hot Module Reloading (HMR).
|
|
@@ -124,8 +124,8 @@
|
|
|
124
124
|
* @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,
|
|
125
125
|
* defaults to 1 second.
|
|
126
126
|
* @return Resolves to an object with created Express and HTTP servers.
|
|
127
|
-
*/async function launchServer(webpackConfig,options={}){/* Options normalization. */const ops=(0,
|
|
128
|
-
ops.port=normalizePort(ops.port||process.env.PORT||3000);(0,
|
|
127
|
+
*/async function launchServer(webpackConfig,options={}){/* Options normalization. */const ops=(0,_cloneDeep.default)(options);// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
|
|
128
|
+
ops.port=normalizePort(ops.port||process.env.PORT||3000);(0,_defaults.default)(ops,{httpsRedirect:true});// TODO: Need a separate type for normalized options, which guarantees
|
|
129
129
|
// the logger is set!
|
|
130
|
-
ops.logger??=(0,_renderer.newDefaultLogger)({defaultLogLevel:ops.defaultLoggerLogLevel});/* Creates servers, resolves and sets the port. */const expressServer=await(0,_server.default)(webpackConfig,ops);let httpServer;if(ops.https){httpServer=_nodeHttps.default.createServer({cert:ops.https.cert,key:ops.https.key},expressServer)}else httpServer=_nodeHttp.default.createServer(expressServer);/* Sets error handler for HTTP(S) server. */httpServer.on("error",error=>{if(error.syscall!=="listen")throw error;const bind=(0,
|
|
130
|
+
ops.logger??=(0,_renderer.newDefaultLogger)({defaultLogLevel:ops.defaultLoggerLogLevel});/* Creates servers, resolves and sets the port. */const expressServer=await(0,_server.default)(webpackConfig,ops);let httpServer;if(ops.https){httpServer=_nodeHttps.default.createServer({cert:ops.https.cert,key:ops.https.key},expressServer)}else httpServer=_nodeHttp.default.createServer(expressServer);/* Sets error handler for HTTP(S) server. */httpServer.on("error",error=>{if(error.syscall!=="listen")throw error;const bind=(0,_isString.default)(ops.port)?`Pipe ${ops.port}`:`Port ${ops.port}`;/* Human-readable message for some specific listen errors. */switch(error.code){case"EACCES":ops.logger.error(`${bind} requires elevated privileges`);return process.exit(1);case"EADDRINUSE":ops.logger.error(`${bind} is already in use`);return process.exit(1);case undefined:default:throw error}});/* Listening event handler for HTTP(S) server. */httpServer.on("listening",()=>{const addr=httpServer.address();const bind=(0,_isString.default)(addr)?`pipe ${addr}`:`port ${addr.port}`;ops.logger.info(`Server listening on ${bind} in ${process.env.NODE_ENV} mode`)});httpServer.listen(ops.port);return{expressServer,httpServer}}launchServer.SCRIPT_LOCATIONS=_renderer.SCRIPT_LOCATIONS;launchServer.getDefaultCspSettings=_server.getDefaultCspSettings;launchServer.errors=_utils.errors;
|
|
131
131
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["require","_nodeHttp","_interopRequireDefault","_nodeHttps","_lodash","_server","_interopRequireWildcard","_renderer","_utils","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","normalizePort","value","port","toNumber","isFinite","isNumber","launchServer","webpackConfig","options","ops","cloneDeep","process","env","PORT","defaults","httpsRedirect","logger","newDefaultLogger","defaultLogLevel","defaultLoggerLogLevel","expressServer","serverFactory","httpServer","https","createServer","cert","key","http","on","error","syscall","bind","isString","code","exit","undefined","addr","address","info","NODE_ENV","listen","SCRIPT_LOCATIONS","getDefaultCspSettings","errors"],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport {\n cloneDeep,\n defaults,\n isFinite,\n isNumber,\n isString,\n toNumber,\n} from 'lodash';\n\n// Polyfill required by ReactJS.\n// TODO: Double-check, if it is still required by React v19?\n// eslint-disable-next-line import/no-unassigned-import\nimport 'raf/polyfill';\n\nimport type { Configuration } from 'webpack';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n type ServerT,\n getDefaultCspSettings,\n} from './server';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nimport { errors } from './utils';\n\nexport type {\n BeforeRenderResT,\n BeforeRenderT,\n ConfigT,\n ServerSsrContext,\n} from './renderer';\n\nexport { errors, getDefaultCspSettings, type ServerT };\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @param value Port name or number.\n * @return Port number (Number), name (String), or false.\n */\nfunction normalizePort(value: number | string) {\n const port = toNumber(value);\n if (isFinite(port)) return port; /* port number */\n if (!isNumber(port)) return value; /* named pipe */\n return false;\n}\n\ntype OptionsT = ServerOptionsT & {\n https?: {\n cert: string;\n key: string;\n };\n\n // TODO: Should we limit it to number | string, and throw if it is different value?\n port?: false | number | string;\n};\n\n/**\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` ⇒ `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 Resolves to an object with created Express and HTTP servers.\n */\nexport default async function launchServer(\n webpackConfig: Configuration,\n options: OptionsT = {},\n): Promise<{\n expressServer: ServerT;\n httpServer: http.Server;\n}> {\n /* Options normalization. */\n const ops = cloneDeep(options);\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n defaults(ops, { httpsRedirect: true });\n\n // TODO: Need a separate type for normalized options, which guarantees\n // the logger is set!\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer: http.Server;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer as unknown as () => void);\n } else httpServer = http.createServer(expressServer as unknown as () => void);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as { syscall?: string }).syscall !== 'listen') throw error;\n const bind = isString(ops.port) ? `Pipe ${ops.port}` : `Port ${ops.port}`;\n\n /* Human-readable message for some specific listen errors. */\n switch ((error as { code?: string }).code) {\n case 'EACCES':\n ops.logger!.error(`${bind} requires elevated privileges`);\n return process.exit(1);\n case 'EADDRINUSE':\n ops.logger!.error(`${bind} is already in use`);\n return process.exit(1);\n case undefined:\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address()!;\n const bind = isString(addr) ? `pipe ${addr}` : `port ${addr.port}`;\n ops.logger!.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n\nlaunchServer.SCRIPT_LOCATIONS = SCRIPT_LOCATIONS;\nlaunchServer.getDefaultCspSettings = getDefaultCspSettings;\nlaunchServer.errors = errors;\n"],"mappings":"mZACAA,OAAA,gCAEA,IAAAC,SAAA,CAAAC,sBAAA,CAAAF,OAAA,eACA,IAAAG,UAAA,CAAAD,sBAAA,CAAAF,OAAA,gBAEA,IAAAI,OAAA,CAAAJ,OAAA,WAYAA,OAAA,iBAIA,IAAAK,OAAA,CAAAC,uBAAA,CAAAN,OAAA,cAMA,IAAAO,SAAA,CAAAP,OAAA,eAEA,IAAAQ,MAAA,CAAAR,OAAA,YAAiC,SAAAM,wBAAAG,CAAA,CAAAC,CAAA,wBAAAC,OAAA,KAAAC,CAAA,KAAAD,OAAA,CAAAE,CAAA,KAAAF,OAAA,QAAAL,uBAAA,SAAAA,CAAAG,CAAA,CAAAC,CAAA,MAAAA,CAAA,EAAAD,CAAA,EAAAA,CAAA,CAAAK,UAAA,QAAAL,CAAA,KAAAM,CAAA,CAAAC,CAAA,CAAAC,CAAA,EAAAC,SAAA,MAAAC,OAAA,CAAAV,CAAA,YAAAA,CAAA,mBAAAA,CAAA,qBAAAA,CAAA,QAAAQ,CAAA,IAAAF,CAAA,CAAAL,CAAA,CAAAG,CAAA,CAAAD,CAAA,KAAAG,CAAA,CAAAK,GAAA,CAAAX,CAAA,SAAAM,CAAA,CAAAM,GAAA,CAAAZ,CAAA,EAAAM,CAAA,CAAAO,GAAA,CAAAb,CAAA,CAAAQ,CAAA,YAAAP,CAAA,IAAAD,CAAA,aAAAC,CAAA,KAAAa,cAAA,CAAAC,IAAA,CAAAf,CAAA,CAAAC,CAAA,KAAAM,CAAA,EAAAD,CAAA,CAAAU,MAAA,CAAAC,cAAA,GAAAD,MAAA,CAAAE,wBAAA,CAAAlB,CAAA,CAAAC,CAAA,KAAAM,CAAA,CAAAK,GAAA,EAAAL,CAAA,CAAAM,GAAA,EAAAP,CAAA,CAAAE,CAAA,CAAAP,CAAA,CAAAM,CAAA,EAAAC,CAAA,CAAAP,CAAA,EAAAD,CAAA,CAAAC,CAAA,UAAAO,CAAA,GAAAR,CAAA,CAAAC,CAAA,EA9BjC;AAeA;AACA;AACA;AAwBA;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,CAAAkB,aAAaA,CAACC,KAAsB,CAAE,CAC7C,KAAM,CAAAC,IAAI,CAAG,GAAAC,gBAAQ,EAACF,KAAK,CAAC,CAC5B,GAAI,GAAAG,gBAAQ,EAACF,IAAI,CAAC,CAAE,MAAO,CAAAA,IAAI,CAAE,iBACjC,GAAI,CAAC,GAAAG,gBAAQ,EAACH,IAAI,CAAC,CAAE,MAAO,CAAAD,KAAK,CAAE,gBACnC,MAAO,MACT,CAYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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,KAAK,CAAuBI,IAAI,EACvC,IAAK,QAAQ,CACXxB,GAAG,CAACO,MAAM,CAAEa,KAAK,CAAC,GAAGE,IAAI,+BAA+B,CAAC,CACzD,MAAO,CAAApB,OAAO,CAACuB,IAAI,CAAC,CAAC,CAAC,CACxB,IAAK,YAAY,CACfzB,GAAG,CAACO,MAAM,CAAEa,KAAK,CAAC,GAAGE,IAAI,oBAAoB,CAAC,CAC9C,MAAO,CAAApB,OAAO,CAACuB,IAAI,CAAC,CAAC,CAAC,CACxB,IAAK,CAAAC,SAAS,CACd,QACE,KAAM,CAAAN,KACV,CACF,CAAC,CAAC,CAEF,iDACAP,UAAU,CAACM,EAAE,CAAC,WAAW,CAAE,IAAM,CAC/B,KAAM,CAAAQ,IAAI,CAAGd,UAAU,CAACe,OAAO,CAAC,CAAE,CAClC,KAAM,CAAAN,IAAI,CAAG,GAAAC,gBAAQ,EAACI,IAAI,CAAC,CAAG,QAAQA,IAAI,EAAE,CAAG,QAAQA,IAAI,CAAClC,IAAI,EAAE,CAClEO,GAAG,CAACO,MAAM,CAAEsB,IAAI,CAAC,uBAAuBP,IAAI,OAC1CpB,OAAO,CAACC,GAAG,CAAC2B,QAAQ,OAAO,CAC/B,CAAC,CAAC,CAEFjB,UAAU,CAACkB,MAAM,CAAC/B,GAAG,CAACP,IAAI,CAAC,CAE3B,MAAO,CACLkB,aAAa,CACbE,UACF,CACF,CAEAhB,YAAY,CAACmC,gBAAgB,CAAGA,0BAAgB,CAChDnC,YAAY,CAACoC,qBAAqB,CAAGA,6BAAqB,CAC1DpC,YAAY,CAACqC,MAAM,CAAGA,aAAM","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":["require","_nodeHttp","_interopRequireDefault","_nodeHttps","_cloneDeep","_defaults","_isFinite","_isNumber","_isString","_toNumber","_server","_interopRequireWildcard","_renderer","_utils","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","normalizePort","value","port","toNumber","isFinite","isNumber","launchServer","webpackConfig","options","ops","cloneDeep","process","env","PORT","defaults","httpsRedirect","logger","newDefaultLogger","defaultLogLevel","defaultLoggerLogLevel","expressServer","serverFactory","httpServer","https","createServer","cert","key","http","on","error","syscall","bind","isString","code","exit","undefined","addr","address","info","NODE_ENV","listen","SCRIPT_LOCATIONS","getDefaultCspSettings","errors"],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport cloneDeep from 'lodash/cloneDeep';\nimport defaults from 'lodash/defaults';\nimport isFinite from 'lodash/isFinite';\nimport isNumber from 'lodash/isNumber';\nimport isString from 'lodash/isString';\nimport toNumber from 'lodash/toNumber';\n\n// Polyfill required by ReactJS.\n// TODO: Double-check, if it is still required by React v19?\n// eslint-disable-next-line import/no-unassigned-import\nimport 'raf/polyfill';\n\nimport type { Configuration } from 'webpack';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n type ServerT,\n getDefaultCspSettings,\n} from './server';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nimport { errors } from './utils';\n\nexport type {\n BeforeRenderResT,\n BeforeRenderT,\n ConfigT,\n ServerSsrContext,\n} from './renderer';\n\nexport { errors, getDefaultCspSettings, type ServerT };\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @param value Port name or number.\n * @return Port number (Number), name (String), or false.\n */\nfunction normalizePort(value: number | string) {\n const port = toNumber(value);\n if (isFinite(port)) return port; /* port number */\n if (!isNumber(port)) return value; /* named pipe */\n return false;\n}\n\ntype OptionsT = ServerOptionsT & {\n https?: {\n cert: string;\n key: string;\n };\n\n // TODO: Should we limit it to number | string, and throw if it is different value?\n port?: false | number | string;\n};\n\n/**\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` ⇒ `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 Resolves to an object with created Express and HTTP servers.\n */\nexport default async function launchServer(\n webpackConfig: Configuration,\n options: OptionsT = {},\n): Promise<{\n expressServer: ServerT;\n httpServer: http.Server;\n}> {\n /* Options normalization. */\n const ops = cloneDeep(options);\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n defaults(ops, { httpsRedirect: true });\n\n // TODO: Need a separate type for normalized options, which guarantees\n // the logger is set!\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer: http.Server;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer as unknown as () => void);\n } else httpServer = http.createServer(expressServer as unknown as () => void);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as { syscall?: string }).syscall !== 'listen') throw error;\n const bind = isString(ops.port) ? `Pipe ${ops.port}` : `Port ${ops.port}`;\n\n /* Human-readable message for some specific listen errors. */\n switch ((error as { code?: string }).code) {\n case 'EACCES':\n ops.logger!.error(`${bind} requires elevated privileges`);\n return process.exit(1);\n case 'EADDRINUSE':\n ops.logger!.error(`${bind} is already in use`);\n return process.exit(1);\n case undefined:\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address()!;\n const bind = isString(addr) ? `pipe ${addr}` : `port ${addr.port}`;\n ops.logger!.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n\nlaunchServer.SCRIPT_LOCATIONS = SCRIPT_LOCATIONS;\nlaunchServer.getDefaultCspSettings = getDefaultCspSettings;\nlaunchServer.errors = errors;\n"],"mappings":"mZACAA,OAAA,gCAEA,IAAAC,SAAA,CAAAC,sBAAA,CAAAF,OAAA,eACA,IAAAG,UAAA,CAAAD,sBAAA,CAAAF,OAAA,gBAEA,IAAAI,UAAA,CAAAF,sBAAA,CAAAF,OAAA,sBACA,IAAAK,SAAA,CAAAH,sBAAA,CAAAF,OAAA,qBACA,IAAAM,SAAA,CAAAJ,sBAAA,CAAAF,OAAA,qBACA,IAAAO,SAAA,CAAAL,sBAAA,CAAAF,OAAA,qBACA,IAAAQ,SAAA,CAAAN,sBAAA,CAAAF,OAAA,qBACA,IAAAS,SAAA,CAAAP,sBAAA,CAAAF,OAAA,qBAKAA,OAAA,iBAIA,IAAAU,OAAA,CAAAC,uBAAA,CAAAX,OAAA,cAMA,IAAAY,SAAA,CAAAZ,OAAA,eAEA,IAAAa,MAAA,CAAAb,OAAA,YAAe,SAAAW,wBAAAG,CAAA,CAAAC,CAAA,wBAAAC,OAAA,KAAAC,CAAA,KAAAD,OAAA,CAAAE,CAAA,KAAAF,OAAA,QAAAL,uBAAA,SAAAA,CAAAG,CAAA,CAAAC,CAAA,MAAAA,CAAA,EAAAD,CAAA,EAAAA,CAAA,CAAAK,UAAA,QAAAL,CAAA,KAAAM,CAAA,CAAAC,CAAA,CAAAC,CAAA,EAAAC,SAAA,MAAA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ACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACe,cAAe,CAAAK,YAAYA,CACxCC,aAA4B,CAC5BC,OAAiB,CAAG,CAAC,CAAC,CAIrB,CACD,4BACA,KAAM,CAAAC,GAAG,CAAG,GAAAC,kBAAS,EAACF,OAAO,CAAC,CAE9B;AACAC,GAAG,CAACP,IAAI,CAAGF,aAAa,CAACS,GAAG,CAACP,IAAI,EAAIS,OAAO,CAACC,GAAG,CAACC,IAAI,EAAI,IAAI,CAAC,CAC9D,GAAAC,iBAAQ,EAACL,GAAG,CAAE,CAAEM,aAAa,CAAE,IAAK,CAAC,CAAC,CAEtC;AACA;AACAN,GAAG,CAACO,MAAM,GAAK,GAAAC,0BAAgB,EAAC,CAC9BC,eAAe,CAAET,GAAG,CAACU,qBACvB,CAAC,CAAC,CAEF,kDACA,KAAM,CAAAC,aAAa,CAAG,KAAM,GAAAC,eAAa,EAACd,aAAa,CAAEE,GAAG,CAAC,CAE7D,GAAI,CAAAa,UAAuB,CAC3B,GAAIb,GAAG,CAACc,KAAK,CAAE,CACbD,UAAU,CAAGC,kBAAK,CAACC,YAAY,CAAC,CAC9BC,IAAI,CAAEhB,GAAG,CAACc,KAAK,CAACE,IAAI,CACpBC,GAAG,CAAEjB,GAAG,CAACc,KAAK,CAACG,GACjB,CAAC,CAAEN,aAAsC,CAC3C,CAAC,IAAM,CAAAE,UAAU,CAAGK,iBAAI,CAACH,YAAY,CAACJ,aAAsC,CAAC,CAE7E,4CACA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,qBAAqB,CAAGA,6BAAqB,CAC1DpC,YAAY,CAACqC,MAAM,CAAGA,aAAM","ignoreList":[]}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.ServerSsrContext=exports.SCRIPT_LOCATIONS=void 0;exports.default=factory;exports.isBrotliAcceptable=isBrotliAcceptable;exports.newDefaultLogger=newDefaultLogger;var _nodeFs=_interopRequireDefault(require("node:fs"));var _nodePath=_interopRequireDefault(require("node:path"));var _nodeStream=require("node:stream");var _nodeZlib=require("node:zlib");var _winston=_interopRequireDefault(require("winston"));var _reactGlobalState=require("@dr.pogodin/react-global-state");var _jsUtils=require("@dr.pogodin/js-utils");var
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.ServerSsrContext=exports.SCRIPT_LOCATIONS=void 0;exports.default=factory;exports.isBrotliAcceptable=isBrotliAcceptable;exports.newDefaultLogger=newDefaultLogger;var _nodeFs=_interopRequireDefault(require("node:fs"));var _nodePath=_interopRequireDefault(require("node:path"));var _nodeStream=require("node:stream");var _nodeZlib=require("node:zlib");var _winston=_interopRequireDefault(require("winston"));var _reactGlobalState=require("@dr.pogodin/react-global-state");var _jsUtils=require("@dr.pogodin/js-utils");var _clone=_interopRequireDefault(require("lodash/clone"));var _cloneDeep=_interopRequireDefault(require("lodash/cloneDeep"));var _defaults=_interopRequireDefault(require("lodash/defaults"));var _get=_interopRequireDefault(require("lodash/get"));var _isString=_interopRequireDefault(require("lodash/isString"));var _mapValues=_interopRequireDefault(require("lodash/mapValues"));var _omit=_interopRequireDefault(require("lodash/omit"));var _config=_interopRequireDefault(require("config"));var _nodeForge=_interopRequireDefault(require("node-forge"));var _static=require("react-dom/static");var _reactHelmet=require("@dr.pogodin/react-helmet");var _reactRouter=require("react-router");var _serializeJavascript=_interopRequireDefault(require("serialize-javascript"));var _buildInfo=require("../shared/utils/isomorphy/buildInfo");var _Cache=_interopRequireDefault(require("./Cache"));var _jsxRuntime=require("react/jsx-runtime");/**
|
|
2
2
|
* ExpressJS middleware for server-side rendering of a ReactJS app.
|
|
3
|
-
*/const sanitizedConfig=(0,
|
|
3
|
+
*/const sanitizedConfig=(0,_omit.default)(_config.default,"SECRET");// Note: These type definitions for logger are copied from Winston logger,
|
|
4
4
|
// then simplified to make it easier to fit an alternative logger into this
|
|
5
5
|
// interface.
|
|
6
6
|
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
7
7
|
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
8
8
|
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
9
|
-
let SCRIPT_LOCATIONS=exports.SCRIPT_LOCATIONS=/*#__PURE__*/function(SCRIPT_LOCATIONS){SCRIPT_LOCATIONS["BODY_OPEN"]="BODY_OPEN";SCRIPT_LOCATIONS["DEFAULT"]="DEFAULT";SCRIPT_LOCATIONS["HEAD_OPEN"]="HEAD_OPEN";return SCRIPT_LOCATIONS}({});class ServerSsrContext extends _reactGlobalState.SsrContext{chunks=[];status=200;constructor(req,chunkGroups,initialState){super((0,
|
|
9
|
+
let SCRIPT_LOCATIONS=exports.SCRIPT_LOCATIONS=/*#__PURE__*/function(SCRIPT_LOCATIONS){SCRIPT_LOCATIONS["BODY_OPEN"]="BODY_OPEN";SCRIPT_LOCATIONS["DEFAULT"]="DEFAULT";SCRIPT_LOCATIONS["HEAD_OPEN"]="HEAD_OPEN";return SCRIPT_LOCATIONS}({});class ServerSsrContext extends _reactGlobalState.SsrContext{chunks=[];status=200;constructor(req,chunkGroups,initialState){super((0,_cloneDeep.default)(initialState)??{});this.chunkGroups=chunkGroups;this.req=req}}/**
|
|
10
10
|
* Reads build-time information about the app. This information is generated
|
|
11
11
|
* by our standard Webpack config for apps, and it is written into
|
|
12
12
|
* ".build-info" file in the context folder specified in Webpack config.
|
|
@@ -14,7 +14,7 @@ let SCRIPT_LOCATIONS=exports.SCRIPT_LOCATIONS=/*#__PURE__*/function(SCRIPT_LOCAT
|
|
|
14
14
|
* suitable for cryptographical use.
|
|
15
15
|
* @param context Webpack context path used during the build.
|
|
16
16
|
* @return Resolves to the build-time information.
|
|
17
|
-
*/function getBuildInfo(context){const url=_nodePath.default.resolve(context,".build-info");return JSON.parse(_nodeFs.default.readFileSync(url,"utf8"))}/**
|
|
17
|
+
*/exports.ServerSsrContext=ServerSsrContext;function getBuildInfo(context){const url=_nodePath.default.resolve(context,".build-info");return JSON.parse(_nodeFs.default.readFileSync(url,"utf8"))}/**
|
|
18
18
|
* Attempts to read from disk the named chunk groups mapping generated
|
|
19
19
|
* by Webpack during the compilation.
|
|
20
20
|
* It will not work for development builds, where these stats should be captured
|
|
@@ -46,7 +46,7 @@ res=null}return res}/**
|
|
|
46
46
|
* DEFAULT: string[];
|
|
47
47
|
* HEAD_OPEN: string[];
|
|
48
48
|
* }}
|
|
49
|
-
*/function groupExtraScripts(scripts=[]){const res={[SCRIPT_LOCATIONS.BODY_OPEN]:"",[SCRIPT_LOCATIONS.DEFAULT]:"",[SCRIPT_LOCATIONS.HEAD_OPEN]:""};for(const script of scripts){if((0,
|
|
49
|
+
*/function groupExtraScripts(scripts=[]){const res={[SCRIPT_LOCATIONS.BODY_OPEN]:"",[SCRIPT_LOCATIONS.DEFAULT]:"",[SCRIPT_LOCATIONS.HEAD_OPEN]:""};for(const script of scripts){if((0,_isString.default)(script)){if(script)res[SCRIPT_LOCATIONS.DEFAULT]+=script}else if(script.code){if(script.location in res)res[script.location]+=script.code;else throw Error(`Invalid location "${script.location}"`)}}return res}/**
|
|
50
50
|
* Creates a new default (Winston) logger.
|
|
51
51
|
* @param {object} [options={}]
|
|
52
52
|
* @param {string} [options.defaultLogLevel='info']
|
|
@@ -81,7 +81,7 @@ res=null}return res}/**
|
|
|
81
81
|
* - `maxage?: number` – the maximum age of cached result in ms.
|
|
82
82
|
* If undefined - infinite age is assumed.
|
|
83
83
|
* @return Created middleware.
|
|
84
|
-
*/function factory(webpackConfig,options){const ops=(0,
|
|
84
|
+
*/function factory(webpackConfig,options){const ops=(0,_defaults.default)((0,_clone.default)(options),{beforeRender:async()=>Promise.resolve({}),maxSsrRounds:10,ssrTimeout:1000,staticCacheSize:1.e7});// Note: in normal use the default logger is created and set in the root
|
|
85
85
|
// server function, and this initialization is for testing uses, where
|
|
86
86
|
// renderer is imported directly.
|
|
87
87
|
ops.logger??=newDefaultLogger({defaultLogLevel:ops.defaultLoggerLogLevel});const buildInfo=ops.buildInfo??getBuildInfo(webpackConfig.context);(0,_buildInfo.setBuildInfo)(buildInfo);// publicPath from webpack.output has a trailing slash at the end.
|
|
@@ -99,7 +99,7 @@ brr instanceof Promise?brr:Promise.resolve(brr),prepareCipher(buildInfo.key)]);l
|
|
|
99
99
|
// These data come from the Webpack compilation, either from the stats
|
|
100
100
|
// attached to the request (in dev mode), or from a file output during
|
|
101
101
|
// the build (in prod mode).
|
|
102
|
-
let chunkGroups;const webpackStats=(0,
|
|
102
|
+
let chunkGroups;const webpackStats=(0,_get.default)(res.locals,"webpack.devMiddleware.stats");if(webpackStats){chunkGroups=(0,_mapValues.default)(webpackStats.toJson({all:false,chunkGroups:true}).namedChunkGroups,item=>item.assets?.map(({name})=>name)??[])}else if(CHUNK_GROUPS)chunkGroups=CHUNK_GROUPS;else chunkGroups={};/* Optional server-side rendering. */const App=ops.Application;let appHtmlMarkup="";const ssrContext=new ServerSsrContext(req,chunkGroups,initialState);let stream;if(App){const ssrStart=Date.now();// TODO: Somehow, without it TS does not realise that
|
|
103
103
|
// App has been checked to exist.
|
|
104
104
|
const App2=App;const renderPass=async()=>new Promise((resolveArg,rejectArg)=>{ssrContext.chunks=[];// NOTE: JS does not have problems if resolve() and reject() methods
|
|
105
105
|
// of a Promise are called multiple times, with different arguments;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderer.js","names":["_nodeFs","_interopRequireDefault","require","_nodePath","_nodeStream","_nodeZlib","_winston","_reactGlobalState","_jsUtils","_lodash","_config","_nodeForge","_static","_reactHelmet","_reactRouter","_serializeJavascript","_buildInfo","_Cache","_jsxRuntime","sanitizedConfig","omit","config","SCRIPT_LOCATIONS","exports","ServerSsrContext","SsrContext","chunks","status","constructor","req","chunkGroups","initialState","cloneDeep","getBuildInfo","context","url","path","resolve","JSON","parse","fs","readFileSync","readChunkGroupsJson","buildDir","res","prepareCipher","key","Promise","reject","forge","random","getBytes","err","iv","cipher","createCipher","start","isBrotliAcceptable","acceptable","get","ops","split","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","isString","code","location","Error","newDefaultLogger","defaultLogLevel","format","transports","winston","createLogger","combine","splat","timestamp","colorize","printf","level","message","stack","rest","Object","keys","length","stringify","Console","factory","webpackConfig","options","defaults","clone","beforeRender","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","setBuildInfo","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","brotliDecompress","error","html","h","toString","regex","RegExp","nonce","replace","brr","configToInject","extraScripts","all","helmet","webpackStats","locals","mapValues","toJson","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","resolveArg","rejectArg","arg","undefined","helmetContext","prerenderToNodeStream","jsx","GlobalStateProvider","state","children","StaticRouter","HelmetProvider","onError","then","result","prelude","catch","ssrRound","bailed","dirty","timeout","race","allSettled","pending","timer","logMsg","log","redirectTo","redirect","ready","pipe","Writable","destroy","write","chunk","_","payload","serializeJs","CONFIG","ISTATE","ignoreFunction","unsafe","update","util","createBuffer","finish","INJ","encode64","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","link","brotliCompress","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { Writable } from 'node:stream';\nimport { brotliCompress, brotliDecompress } from 'node:zlib';\n\nimport type { Request, RequestHandler } from 'express';\nimport type { ComponentType } from 'react';\nimport type { Configuration, Stats } from 'webpack';\nimport winston from 'winston';\n\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { timer } from '@dr.pogodin/js-utils';\n\nimport {\n clone,\n cloneDeep,\n defaults,\n get,\n isString,\n mapValues,\n omit,\n} from 'lodash';\n\nimport config from 'config';\nimport forge from 'node-forge';\n\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { type HelmetDataContext, HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { StaticRouter } from 'react-router';\nimport serializeJs from 'serialize-javascript';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport type { ChunkGroupsT, SsrContextT } from 'utils/globalState';\n\nimport Cache from './Cache';\n\nconst sanitizedConfig = omit(config, 'SECRET');\n\n// Note: These type definitions for logger are copied from Winston logger,\n// then simplified to make it easier to fit an alternative logger into this\n// interface.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (level: string, message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LeveledLogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface LoggerI {\n debug: LeveledLogMethodI;\n error: LeveledLogMethodI;\n info: LeveledLogMethodI;\n log: LogMethodI;\n warn: LeveledLogMethodI;\n}\n\nexport enum SCRIPT_LOCATIONS {\n BODY_OPEN = 'BODY_OPEN',\n DEFAULT = 'DEFAULT',\n HEAD_OPEN = 'HEAD_OPEN',\n}\n\nexport class ServerSsrContext<StateT>\n extends SsrContext<StateT>\n implements SsrContextT<StateT> {\n chunkGroups: ChunkGroupsT;\n\n chunks: string[] = [];\n\n redirectTo?: string;\n\n req: Request;\n\n status: number = 200;\n\n constructor(\n req: Request,\n chunkGroups: ChunkGroupsT,\n initialState?: StateT,\n ) {\n super(cloneDeep(initialState) ?? ({} as StateT));\n this.chunkGroups = chunkGroups;\n this.req = req;\n }\n}\n\ntype ScriptT = {\n code: string;\n location: SCRIPT_LOCATIONS;\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @param context Webpack context path used during the build.\n * @return Resolves to the build-time information.\n */\nfunction getBuildInfo(context: string) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url, 'utf8')) as BuildInfoT;\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @param buildDir\n * @return\n */\nfunction readChunkGroupsJson(buildDir: string) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url, 'utf8')) as Record<string, string[]>;\n } catch {\n // TODO: Should we message the error here somehow?\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @param key Encryption key (32-bit random key is expected, see\n * node-forge documentation, in case of doubts).\n * @return Resolves to the object with two fields:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nasync function prepareCipher(key: string): Promise<{\n cipher: forge.cipher.BlockCipher;\n iv: string;\n}> {\n return new Promise((resolve, reject) => {\n forge.random.getBytes(32, (err, iv) => {\n if (err) reject(err);\n else {\n const cipher = forge.cipher.createCipher('AES-CBC', key);\n cipher.start({ iv });\n resolve({ cipher, iv });\n }\n });\n });\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param req\n */\nexport function isBrotliAcceptable(req: Request): boolean {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (const op of ops) {\n const [type, priority] = op.trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts: Array<string | ScriptT> = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (const script of scripts) {\n if (isString(script)) {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (script.location in res) res[script.location] += script.code;\n else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates a new default (Winston) logger.\n * @param {object} [options={}]\n * @param {string} [options.defaultLogLevel='info']\n * @return {object}\n */\nexport function newDefaultLogger({\n defaultLogLevel = 'info',\n} = {}): winston.Logger {\n const { format, transports } = winston;\n return winston.createLogger({\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp as string}):\\t${message as string}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack as string}`;\n return res;\n },\n ),\n ),\n level: defaultLogLevel,\n transports: [new transports.Console()],\n });\n}\n\nexport type ConfigT = {\n [key: string]: ConfigT | string;\n};\n\nexport type BeforeRenderResT = {\n configToInject?: ConfigT;\n extraScripts?: Array<ScriptT | string>;\n initialState?: unknown;\n};\n\nexport type BeforeRenderT = (\n req: Request,\n config: ConfigT,\n) => BeforeRenderResT | Promise<BeforeRenderResT>;\n\ntype CacheRefT = {\n key: string;\n maxage?: number;\n};\n\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\n defaultLoggerLogLevel?: string;\n favicon?: string;\n logger?: LoggerI;\n maxSsrRounds?: number;\n noCsp?: boolean;\n staticCacheSize?: number;\n ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT | null | undefined;\n};\n\n/**\n * Creates the middleware.\n * @param webpackConfig\n * @param options Additional options:\n * @param [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` – 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 * @return Created middleware.\n */\nexport default function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): RequestHandler {\n const ops: OptionsT = defaults(clone(options), {\n beforeRender: async () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n // Note: in normal use the default logger is created and set in the root\n // server function, and this initialization is for testing uses, where\n // renderer is imported directly.\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context!);\n setBuildInfo(buildInfo);\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output!;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath as string}manifest.json\">` : '';\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface BufferWithNonce extends ArrayBuffer {\n nonce: string;\n }\n\n const cache = ops.staticCacheController\n ? new Cache<{\n buffer: BufferWithNonce;\n status: number;\n }>(ops.staticCacheSize!)\n : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath!);\n\n // TODO: Look at it later.\n // eslint-disable-next-line complexity\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n res.cookie('csrfToken', req.csrfToken());\n\n let cacheRef: CacheRefT | null | undefined;\n if (cache) {\n cacheRef = ops.staticCacheController!(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise<void>((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n\n // TODO: It should be implemented more careful.\n h = h.replace(regex, (req as unknown as {\n nonce: string;\n }).nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n const brr = ops.beforeRender!(req, sanitizedConfig as unknown as ConfigT);\n\n const [{\n configToInject,\n extraScripts,\n initialState,\n }, {\n cipher,\n iv,\n }] = await Promise.all([\n // NOTE: Written this way to avoid triggering the \"await-thenable\"\n // ESLint rule.\n brr instanceof Promise ? brr : Promise.resolve(brr),\n\n prepareCipher(buildInfo.key),\n ]);\n\n let helmet: HelmetDataContext['helmet'];\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups: ChunkGroupsT;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats') as Stats | undefined;\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets?.map(({ name }: { name: string }) => name)\n ?? [],\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n const App = ops.Application;\n let appHtmlMarkup: string = '';\n const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);\n let stream: NodeJS.ReadableStream;\n if (App) {\n const ssrStart = Date.now();\n\n // TODO: Somehow, without it TS does not realise that\n // App has been checked to exist.\n const App2 = App;\n\n const renderPass = async () => new Promise<NodeJS.ReadableStream>(\n (resolveArg, rejectArg) => {\n ssrContext.chunks = [];\n\n // NOTE: JS does not have problems if resolve() and reject() methods\n // of a Promise are called multiple times, with different arguments;\n // it only respects the first call, and ignores subsequent ones.\n // We, however, really want to assert that here, to safeguard against\n // any future problems due to unexpected internal changes in React,\n // if any.\n let error: unknown;\n\n const resolve = (arg: NodeJS.ReadableStream) => {\n if (error !== undefined) throw Error('Internal error');\n error = null;\n resolveArg(arg);\n };\n\n const reject = (arg: unknown) => {\n if (error !== undefined && error !== arg) {\n throw Error('Internal error');\n }\n error = arg;\n rejectArg(arg as Error);\n };\n\n // TODO: prerenderToNodeStream has (abort) \"signal\" option,\n // and we should wire it up to the SSR timeout below.\n const helmetContext = {} as HelmetDataContext;\n void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider context={helmetContext}>\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then((result) => {\n ({ helmet } = helmetContext);\n resolve(result.prelude);\n }).catch(reject);\n },\n );\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\n stream = await renderPass();\n\n if (!ssrContext.dirty) break;\n\n const timeout = ops.ssrTimeout! + ssrStart - Date.now();\n bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;\n } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;\n\n ops.logger!.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n if (ssrContext.redirectTo) {\n res.redirect(ssrContext.status, ssrContext.redirectTo);\n return;\n }\n\n await new Promise((ready) => {\n stream!.pipe(new Writable({\n destroy: ready,\n write: (chunk: { toString: () => string }, _, done) => {\n appHtmlMarkup += chunk.toString();\n done();\n },\n }));\n });\n }\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject ?? sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n cipher.update(forge.util.createBuffer(payload, 'utf8'));\n cipher.finish();\n const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);\n\n const chunkSet = new Set<string>();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath as string}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath as string}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon\n ? '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet?.title.toString() ?? ''}\n ${helmet?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmet?.link.toString() ?? ''}${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n <meta itemprop=\"drpruinj\" content=\"${INJ}\">\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${appHtmlMarkup}</div>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise<void>((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n if (error) failed(error);\n else {\n const b = buffer as unknown as BufferWithNonce;\n b.nonce = (req as unknown as {\n nonce: string;\n }).nonce;\n cache!.add({ buffer: b, status }, cacheRef.key, buffer.length);\n done();\n }\n });\n });\n }\n\n // Note: as caching code above may throw in some cases, sending response\n // before it completes will likely hide the error, making it difficult\n // to debug. Thus, at least for now, lets send response after it.\n res.send(html);\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":"kUAIA,IAAAA,OAAA,CAAAC,sBAAA,CAAAC,OAAA,aACA,IAAAC,SAAA,CAAAF,sBAAA,CAAAC,OAAA,eACA,IAAAE,WAAA,CAAAF,OAAA,gBACA,IAAAG,SAAA,CAAAH,OAAA,cAKA,IAAAI,QAAA,CAAAL,sBAAA,CAAAC,OAAA,aAEA,IAAAK,iBAAA,CAAAL,OAAA,mCACA,IAAAM,QAAA,CAAAN,OAAA,yBAEA,IAAAO,OAAA,CAAAP,OAAA,WAUA,IAAAQ,OAAA,CAAAT,sBAAA,CAAAC,OAAA,YACA,IAAAS,UAAA,CAAAV,sBAAA,CAAAC,OAAA,gBAEA,IAAAU,OAAA,CAAAV,OAAA,qBACA,IAAAW,YAAA,CAAAX,OAAA,6BACA,IAAAY,YAAA,CAAAZ,OAAA,iBACA,IAAAa,oBAAA,CAAAd,sBAAA,CAAAC,OAAA,0BACA,IA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AAIgG,QAAQ,EAAIhG,MAAM,CAAG,GAAG,CAAE,CAC5B;AACA;AACA,KAAM,IAAI,CAAAoB,OAAO,CAAO,CAACiF,IAAI,CAAEC,MAAM,GAAK,CACxC,GAAAgG,wBAAc,EAAC7F,IAAI,CAAE,CAACD,KAAK,CAAEN,MAAM,GAAK,CACtC,GAAIM,KAAK,CAAEF,MAAM,CAACE,KAAK,CAAC,CAAC,IACpB,CACH,KAAM,CAAA+F,CAAC,CAAGrG,MAAoC,CAC9CqG,CAAC,CAACzF,KAAK,CAAI5G,GAAG,CAEX4G,KAAK,CACRtB,KAAK,CAAEoG,GAAG,CAAC,CAAE1F,MAAM,CAAEqG,CAAC,CAAEvM,MAAO,CAAC,CAAEgG,QAAQ,CAAC7E,GAAG,CAAE+E,MAAM,CAAC/B,MAAM,CAAC,CAC9DkC,IAAI,CAAC,CACP,CACF,CAAC,CACH,CAAC,CACH,CAEA;AACA;AACA;AACApF,GAAG,CAACmF,IAAI,CAACK,IAAI,CACf,CAAE,MAAOD,KAAK,CAAE,CACdZ,IAAI,CAACY,KAAK,CACZ,CACF,CACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"renderer.js","names":["_nodeFs","_interopRequireDefault","require","_nodePath","_nodeStream","_nodeZlib","_winston","_reactGlobalState","_jsUtils","_clone","_cloneDeep","_defaults","_get","_isString","_mapValues","_omit","_config","_nodeForge","_static","_reactHelmet","_reactRouter","_serializeJavascript","_buildInfo","_Cache","_jsxRuntime","sanitizedConfig","omit","config","SCRIPT_LOCATIONS","exports","ServerSsrContext","SsrContext","chunks","status","constructor","req","chunkGroups","initialState","cloneDeep","getBuildInfo","context","url","path","resolve","JSON","parse","fs","readFileSync","readChunkGroupsJson","buildDir","res","prepareCipher","key","Promise","reject","forge","random","getBytes","err","iv","cipher","createCipher","start","isBrotliAcceptable","acceptable","get","ops","split","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","isString","code","location","Error","newDefaultLogger","defaultLogLevel","format","transports","winston","createLogger","combine","splat","timestamp","colorize","printf","level","message","stack","rest","Object","keys","length","stringify","Console","factory","webpackConfig","options","defaults","clone","beforeRender","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","setBuildInfo","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","brotliDecompress","error","html","h","toString","regex","RegExp","nonce","replace","brr","configToInject","extraScripts","all","helmet","webpackStats","locals","mapValues","toJson","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","resolveArg","rejectArg","arg","undefined","helmetContext","prerenderToNodeStream","_jsx","GlobalStateProvider","state","children","StaticRouter","HelmetProvider","onError","then","result","prelude","catch","ssrRound","bailed","dirty","timeout","race","allSettled","pending","timer","logMsg","log","redirectTo","redirect","ready","pipe","Writable","destroy","write","chunk","_","payload","serializeJs","CONFIG","ISTATE","ignoreFunction","unsafe","update","util","createBuffer","finish","INJ","encode64","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","link","brotliCompress","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { Writable } from 'node:stream';\nimport { brotliCompress, brotliDecompress } from 'node:zlib';\n\nimport type { Request, RequestHandler } from 'express';\nimport type { ComponentType } from 'react';\nimport type { Configuration, Stats } from 'webpack';\nimport winston from 'winston';\n\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { timer } from '@dr.pogodin/js-utils';\n\nimport clone from 'lodash/clone';\nimport cloneDeep from 'lodash/cloneDeep';\nimport defaults from 'lodash/defaults';\nimport get from 'lodash/get';\nimport isString from 'lodash/isString';\nimport mapValues from 'lodash/mapValues';\nimport omit from 'lodash/omit';\n\nimport config from 'config';\nimport forge from 'node-forge';\n\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { type HelmetDataContext, HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { StaticRouter } from 'react-router';\nimport serializeJs from 'serialize-javascript';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport type { ChunkGroupsT, SsrContextT } from 'utils/globalState';\n\nimport Cache from './Cache';\n\nconst sanitizedConfig = omit(config, 'SECRET');\n\n// Note: These type definitions for logger are copied from Winston logger,\n// then simplified to make it easier to fit an alternative logger into this\n// interface.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (level: string, message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LeveledLogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface LoggerI {\n debug: LeveledLogMethodI;\n error: LeveledLogMethodI;\n info: LeveledLogMethodI;\n log: LogMethodI;\n warn: LeveledLogMethodI;\n}\n\nexport enum SCRIPT_LOCATIONS {\n BODY_OPEN = 'BODY_OPEN',\n DEFAULT = 'DEFAULT',\n HEAD_OPEN = 'HEAD_OPEN',\n}\n\nexport class ServerSsrContext<StateT>\n extends SsrContext<StateT>\n implements SsrContextT<StateT> {\n chunkGroups: ChunkGroupsT;\n\n chunks: string[] = [];\n\n redirectTo?: string;\n\n req: Request;\n\n status: number = 200;\n\n constructor(\n req: Request,\n chunkGroups: ChunkGroupsT,\n initialState?: StateT,\n ) {\n super(cloneDeep(initialState) ?? ({} as StateT));\n this.chunkGroups = chunkGroups;\n this.req = req;\n }\n}\n\ntype ScriptT = {\n code: string;\n location: SCRIPT_LOCATIONS;\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @param context Webpack context path used during the build.\n * @return Resolves to the build-time information.\n */\nfunction getBuildInfo(context: string) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url, 'utf8')) as BuildInfoT;\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @param buildDir\n * @return\n */\nfunction readChunkGroupsJson(buildDir: string) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url, 'utf8')) as Record<string, string[]>;\n } catch {\n // TODO: Should we message the error here somehow?\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @param key Encryption key (32-bit random key is expected, see\n * node-forge documentation, in case of doubts).\n * @return Resolves to the object with two fields:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nasync function prepareCipher(key: string): Promise<{\n cipher: forge.cipher.BlockCipher;\n iv: string;\n}> {\n return new Promise((resolve, reject) => {\n forge.random.getBytes(32, (err, iv) => {\n if (err) reject(err);\n else {\n const cipher = forge.cipher.createCipher('AES-CBC', key);\n cipher.start({ iv });\n resolve({ cipher, iv });\n }\n });\n });\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param req\n */\nexport function isBrotliAcceptable(req: Request): boolean {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (const op of ops) {\n const [type, priority] = op.trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts: Array<string | ScriptT> = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (const script of scripts) {\n if (isString(script)) {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (script.location in res) res[script.location] += script.code;\n else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates a new default (Winston) logger.\n * @param {object} [options={}]\n * @param {string} [options.defaultLogLevel='info']\n * @return {object}\n */\nexport function newDefaultLogger({\n defaultLogLevel = 'info',\n} = {}): winston.Logger {\n const { format, transports } = winston;\n return winston.createLogger({\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp as string}):\\t${message as string}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack as string}`;\n return res;\n },\n ),\n ),\n level: defaultLogLevel,\n transports: [new transports.Console()],\n });\n}\n\nexport type ConfigT = {\n [key: string]: ConfigT | string;\n};\n\nexport type BeforeRenderResT = {\n configToInject?: ConfigT;\n extraScripts?: Array<ScriptT | string>;\n initialState?: unknown;\n};\n\nexport type BeforeRenderT = (\n req: Request,\n config: ConfigT,\n) => BeforeRenderResT | Promise<BeforeRenderResT>;\n\ntype CacheRefT = {\n key: string;\n maxage?: number;\n};\n\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\n defaultLoggerLogLevel?: string;\n favicon?: string;\n logger?: LoggerI;\n maxSsrRounds?: number;\n noCsp?: boolean;\n staticCacheSize?: number;\n ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT | null | undefined;\n};\n\n/**\n * Creates the middleware.\n * @param webpackConfig\n * @param options Additional options:\n * @param [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` – 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 * @return Created middleware.\n */\nexport default function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): RequestHandler {\n const ops: OptionsT = defaults(clone(options), {\n beforeRender: async () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n // Note: in normal use the default logger is created and set in the root\n // server function, and this initialization is for testing uses, where\n // renderer is imported directly.\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n const buildInfo = ops.buildInfo ?? getBuildInfo(webpackConfig.context!);\n setBuildInfo(buildInfo);\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output!;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath as string}manifest.json\">` : '';\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface BufferWithNonce extends ArrayBuffer {\n nonce: string;\n }\n\n const cache = ops.staticCacheController\n ? new Cache<{\n buffer: BufferWithNonce;\n status: number;\n }>(ops.staticCacheSize!)\n : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath!);\n\n // TODO: Look at it later.\n // eslint-disable-next-line complexity\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n res.cookie('csrfToken', req.csrfToken());\n\n let cacheRef: CacheRefT | null | undefined;\n if (cache) {\n cacheRef = ops.staticCacheController!(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise<void>((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n\n // TODO: It should be implemented more careful.\n h = h.replace(regex, (req as unknown as {\n nonce: string;\n }).nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n const brr = ops.beforeRender!(req, sanitizedConfig as unknown as ConfigT);\n\n const [{\n configToInject,\n extraScripts,\n initialState,\n }, {\n cipher,\n iv,\n }] = await Promise.all([\n // NOTE: Written this way to avoid triggering the \"await-thenable\"\n // ESLint rule.\n brr instanceof Promise ? brr : Promise.resolve(brr),\n\n prepareCipher(buildInfo.key),\n ]);\n\n let helmet: HelmetDataContext['helmet'];\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups: ChunkGroupsT;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats') as Stats | undefined;\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets?.map(({ name }: { name: string }) => name)\n ?? [],\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n const App = ops.Application;\n let appHtmlMarkup: string = '';\n const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);\n let stream: NodeJS.ReadableStream;\n if (App) {\n const ssrStart = Date.now();\n\n // TODO: Somehow, without it TS does not realise that\n // App has been checked to exist.\n const App2 = App;\n\n const renderPass = async () => new Promise<NodeJS.ReadableStream>(\n (resolveArg, rejectArg) => {\n ssrContext.chunks = [];\n\n // NOTE: JS does not have problems if resolve() and reject() methods\n // of a Promise are called multiple times, with different arguments;\n // it only respects the first call, and ignores subsequent ones.\n // We, however, really want to assert that here, to safeguard against\n // any future problems due to unexpected internal changes in React,\n // if any.\n let error: unknown;\n\n const resolve = (arg: NodeJS.ReadableStream) => {\n if (error !== undefined) throw Error('Internal error');\n error = null;\n resolveArg(arg);\n };\n\n const reject = (arg: unknown) => {\n if (error !== undefined && error !== arg) {\n throw Error('Internal error');\n }\n error = arg;\n rejectArg(arg as Error);\n };\n\n // TODO: prerenderToNodeStream has (abort) \"signal\" option,\n // and we should wire it up to the SSR timeout below.\n const helmetContext = {} as HelmetDataContext;\n void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider context={helmetContext}>\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then((result) => {\n ({ helmet } = helmetContext);\n resolve(result.prelude);\n }).catch(reject);\n },\n );\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\n stream = await renderPass();\n\n if (!ssrContext.dirty) break;\n\n const timeout = ops.ssrTimeout! + ssrStart - Date.now();\n bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;\n } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;\n\n ops.logger!.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n if (ssrContext.redirectTo) {\n res.redirect(ssrContext.status, ssrContext.redirectTo);\n return;\n }\n\n await new Promise((ready) => {\n stream!.pipe(new Writable({\n destroy: ready,\n write: (chunk: { toString: () => string }, _, done) => {\n appHtmlMarkup += chunk.toString();\n done();\n },\n }));\n });\n }\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject ?? sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n cipher.update(forge.util.createBuffer(payload, 'utf8'));\n cipher.finish();\n const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);\n\n const chunkSet = new Set<string>();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath as string}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath as string}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon\n ? '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet?.title.toString() ?? ''}\n ${helmet?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmet?.link.toString() ?? ''}${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n <meta itemprop=\"drpruinj\" content=\"${INJ}\">\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${appHtmlMarkup}</div>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise<void>((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n if (error) failed(error);\n else {\n const b = buffer as unknown as BufferWithNonce;\n b.nonce = (req as unknown as {\n nonce: string;\n }).nonce;\n cache!.add({ buffer: b, status }, cacheRef.key, buffer.length);\n done();\n }\n });\n });\n }\n\n // Note: as caching code above may throw in some cases, sending response\n // before it completes will likely hide the error, making it difficult\n // to debug. Thus, at least for now, lets send response after it.\n res.send(html);\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":"kUAIA,IAAAA,OAAA,CAAAC,sBAAA,CAAAC,OAAA,aACA,IAAAC,SAAA,CAAAF,sBAAA,CAAAC,OAAA,eACA,IAAAE,WAAA,CAAAF,OAAA,gBACA,IAAAG,SAAA,CAAAH,OAAA,cAKA,IAAAI,QAAA,CAAAL,sBAAA,CAAAC,OAAA,aAEA,IAAAK,iBAAA,CAAAL,OAAA,mCACA,IAAAM,QAAA,CAAAN,OAAA,yBAEA,IAAAO,MAAA,CAAAR,sBAAA,CAAAC,OAAA,kBACA,IAAAQ,UAAA,CAAAT,sBAAA,CAAAC,OAAA,sBACA,IAAAS,SAAA,CAAAV,sBAAA,CAAAC,OAAA,qBACA,IAAAU,IAAA,CAAAX,sBAAA,CAAAC,OAAA,gBACA,IAAAW,SAAA,CAAAZ,sBAAA,CAAAC,OAAA,qBACA,IAAAY,UAAA,CAAAb,sBAAA,CAAAC,OAAA,sBACA,IAAAa,KAAA,CAAAd,sBAAA,CAAAC,OAAA,iBAEA,IAAAc,OAAA,CAAAf,sBAAA,CAAAC,OAAA,YACA,IAAAe,UAAA,CAAAhB,sBAAA,CAAAC,OAAA,gBAEA,IAAAgB,OAAA,CAAAhB,OAAA,qBACA,IAAAiB,YAAA,CAAAjB,OAAA,6BACA,IAAAkB,YAAA,CAAAlB,OAAA,iBACA,IAAAmB,oBAAA,CAAApB,sBAAA,CAAAC,OAAA,0BACA,IAAAoB,UAAA,CAAApB,OAAA,wCAIA,IAAAqB,MAAA,CAAAtB,s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AACD,KAAK,CAAEN,MAAM,GAAK,CACtC,GAAIM,KAAK,CAAEF,MAAM,CAACE,KAAK,CAAC,CAAC,IACpB,CACH,KAAM,CAAA+F,CAAC,CAAGrG,MAAoC,CAC9CqG,CAAC,CAACzF,KAAK,CAAI5G,GAAG,CAEX4G,KAAK,CACRtB,KAAK,CAAEoG,GAAG,CAAC,CAAE1F,MAAM,CAAEqG,CAAC,CAAEvM,MAAO,CAAC,CAAEgG,QAAQ,CAAC7E,GAAG,CAAE+E,MAAM,CAAC/B,MAAM,CAAC,CAC9DkC,IAAI,CAAC,CACP,CACF,CAAC,CACH,CAAC,CACH,CAEA;AACA;AACA;AACApF,GAAG,CAACmF,IAAI,CAACK,IAAI,CACf,CAAE,MAAOD,KAAK,CAAE,CACdZ,IAAI,CAACY,KAAK,CACZ,CACF,CACF","ignoreList":[]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=factory;exports.getDefaultCspSettings=getDefaultCspSettings;var _nodePath=require("node:path");var _nodeUrl=require("node:url");var
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=factory;exports.getDefaultCspSettings=getDefaultCspSettings;var _nodePath=require("node:path");var _nodeUrl=require("node:url");var _cloneDeep=_interopRequireDefault(require("lodash/cloneDeep"));var _mapValues=_interopRequireDefault(require("lodash/mapValues"));var _pick=_interopRequireDefault(require("lodash/pick"));var _compression=_interopRequireDefault(require("compression"));var _cookieParser=_interopRequireDefault(require("cookie-parser"));var _csurf=_interopRequireDefault(require("@dr.pogodin/csurf"));var _express=_interopRequireDefault(require("express"));var _serveFavicon=_interopRequireDefault(require("serve-favicon"));var _helmet=_interopRequireDefault(require("helmet"));var _morgan=_interopRequireDefault(require("morgan"));var _requestIp=_interopRequireDefault(require("request-ip"));var _uuid=require("uuid");var _renderer=_interopRequireDefault(require("./renderer"));var _errors=require("./utils/errors");/**
|
|
2
2
|
* Creation of standard ExpressJS server for ReactJS apps.
|
|
3
3
|
*/// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
4
4
|
/**
|
|
5
5
|
* Default Content Security Policy settings.
|
|
6
6
|
* @ignore
|
|
7
|
-
*/const defaultCspSettings={directives:(0,
|
|
7
|
+
*/const defaultCspSettings={directives:(0,_mapValues.default)(_helmet.default.contentSecurityPolicy.getDefaultDirectives(),// 'https:' options (automatic re-write of insecure URLs to secure ones)
|
|
8
8
|
// is removed to facilitate local development with HTTP server. In cloud
|
|
9
9
|
// deployments we assume Apache or Nginx server in front of out app takes
|
|
10
10
|
// care about such re-writes.
|
|
@@ -27,11 +27,11 @@ delete defaultCspSettings.directives["upgrade-insecure-requests"];/**
|
|
|
27
27
|
* }} A deep copy of default CSP settings object used by `react-utils`,
|
|
28
28
|
* with the exception of `nonce-xxx` clause in `script-src` directive,
|
|
29
29
|
* which is added dynamically for each request.
|
|
30
|
-
*/function getDefaultCspSettings(){return(0,
|
|
30
|
+
*/function getDefaultCspSettings(){return(0,_cloneDeep.default)(defaultCspSettings)}async function factory(webpackConfig,options){const rendererOps=(0,_pick.default)(options,["Application","beforeRender","favicon","logger","maxSsrRounds","noCsp","ssrTimeout","staticCacheController","staticCacheSize"]);const renderer=(0,_renderer.default)(webpackConfig,rendererOps);const{publicPath}=webpackConfig.output;const server=(0,_express.default)();if(options.beforeExpressJsSetup){await options.beforeExpressJsSetup(server)}if(options.logger)server.logger=options.logger;if(options.httpsRedirect){server.use((req,res,next)=>{const schema=req.headers["x-forwarded-proto"];if(schema==="http"){let url=`https://${req.headers.host}`;if(req.originalUrl!=="/")url+=req.originalUrl;res.redirect(url);return}next()})}server.use((0,_compression.default)());server.use((0,_helmet.default)({contentSecurityPolicy:false,crossOriginEmbedderPolicy:false,crossOriginOpenerPolicy:false,crossOriginResourcePolicy:false}));if(!options.noCsp){server.use((req,res,next)=>{const req2=req;req2.nonce=(0,_uuid.v4)();// TODO: This is deprecated, but it is kept for now for backward
|
|
31
31
|
// compatibility. Should be removed sometime later.
|
|
32
32
|
req2.cspNonce=req2.nonce;// The deep clone is necessary here to ensure that default value can't be
|
|
33
33
|
// mutated during request processing.
|
|
34
|
-
let cspSettings=(0,
|
|
34
|
+
let cspSettings=(0,_cloneDeep.default)(defaultCspSettings);(cspSettings.directives?.["script-src"]).push(`'nonce-${req2.nonce}'`);if(options.cspSettingsHook){cspSettings=options.cspSettingsHook(cspSettings,req)}_helmet.default.contentSecurityPolicy(cspSettings)(req,res,next)})}if(options.favicon){server.use((0,_serveFavicon.default)(options.favicon))}server.use("/robots.txt",(req,res)=>{res.send("User-agent: *\nDisallow:")});server.use(_express.default.json({limit:"300kb"}));server.use(_express.default.urlencoded({extended:false}));server.use((0,_cookieParser.default)(options.cookieSignatureSecret));server.use(_requestIp.default.mw());server.use((0,_csurf.default)({cookie:true}));_morgan.default.token("ip",req=>req.clientIp);const FORMAT=":ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent";server.use((0,_morgan.default)(FORMAT,{stream:{// TODO: This implies the logger is always set. Is it on a higher level?
|
|
35
35
|
// then mark it as always present.
|
|
36
36
|
write:options.logger.info.bind(options.logger)}}));// Note: no matter the "public path", we want the service worker, if any,
|
|
37
37
|
// to be served from the root, to have all web app pages in its scope.
|