@dr.pogodin/react-utils 1.47.0-alpha.1 → 1.47.0-alpha.11
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 -1
- package/babel.module.config.js +11 -0
- package/bin/build.js +8 -4
- package/bin/setup.js +2 -3
- package/build/development/client/getInj.js +57 -44
- package/build/development/client/getInj.js.map +1 -1
- package/build/development/client/index.js +15 -21
- package/build/development/client/index.js.map +1 -1
- package/build/development/client/init.js +2 -6
- package/build/development/client/init.js.map +1 -1
- package/build/development/index.js +3 -183
- package/build/development/index.js.map +1 -1
- package/build/development/server/Cache.js +1 -8
- package/build/development/server/Cache.js.map +1 -1
- package/build/development/server/index.js +22 -50
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js +83 -92
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +58 -62
- package/build/development/server/server.js.map +1 -1
- package/build/development/server/utils/errors.js +8 -31
- package/build/development/server/utils/errors.js.map +1 -1
- package/build/development/server/utils/index.js +2 -9
- package/build/development/server/utils/index.js.map +1 -1
- package/build/development/shared/components/Button/index.js +9 -16
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +6 -13
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/GenericLink/index.js +4 -10
- package/build/development/shared/components/GenericLink/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +11 -18
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/Link.js +6 -13
- package/build/development/shared/components/Link.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +16 -22
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/NavLink.js +6 -13
- package/build/development/shared/components/NavLink.js.map +1 -1
- package/build/development/shared/components/PageLayout/index.js +7 -14
- package/build/development/shared/components/PageLayout/index.js.map +1 -1
- package/build/development/shared/components/TextArea/index.js +15 -22
- package/build/development/shared/components/TextArea/index.js.map +1 -1
- package/build/development/shared/components/Throbber/index.js +7 -14
- package/build/development/shared/components/Throbber/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/Tooltip.js +12 -18
- package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +16 -23
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js +10 -17
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/components/index.js +16 -130
- package/build/development/shared/components/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +18 -19
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js +24 -28
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js +19 -19
- package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/Switch/index.js +12 -17
- package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/development/shared/components/selectors/common.js +1 -7
- package/build/development/shared/components/selectors/common.js.map +1 -1
- package/build/development/shared/components/selectors/index.js +3 -27
- package/build/development/shared/components/selectors/index.js.map +1 -1
- package/build/development/shared/utils/config.js +40 -21
- package/build/development/shared/utils/config.js.map +1 -1
- package/build/development/shared/utils/globalState.js +3 -8
- package/build/development/shared/utils/globalState.js.map +1 -1
- package/build/development/shared/utils/index.js +12 -89
- package/build/development/shared/utils/index.js.map +1 -1
- package/build/development/shared/utils/isomorphy/buildInfo.js +2 -9
- package/build/development/shared/utils/isomorphy/buildInfo.js.map +1 -1
- package/build/development/shared/utils/isomorphy/environment-check.js +2 -8
- package/build/development/shared/utils/isomorphy/environment-check.js.map +1 -1
- package/build/development/shared/utils/isomorphy/index.js +7 -32
- package/build/development/shared/utils/isomorphy/index.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv.js +24 -31
- package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/development/shared/utils/jest/global.js +1 -7
- package/build/development/shared/utils/jest/global.js.map +1 -1
- package/build/development/shared/utils/jest/index.js +20 -44
- package/build/development/shared/utils/jest/index.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +54 -46
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/time.js +22 -31
- package/build/development/shared/utils/time.js.map +1 -1
- package/build/development/shared/utils/webpack.js +17 -16
- package/build/development/shared/utils/webpack.js.map +1 -1
- package/build/production/client/getInj.js +13 -11
- package/build/production/client/getInj.js.map +1 -1
- package/build/production/client/index.js +3 -3
- package/build/production/client/index.js.map +1 -1
- package/build/production/client/init.js +2 -2
- package/build/production/client/init.js.map +1 -1
- package/build/production/index.js +2 -6
- package/build/production/index.js.map +1 -1
- package/build/production/server/Cache.js +3 -3
- package/build/production/server/Cache.js.map +1 -1
- package/build/production/server/index.js +8 -8
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js +24 -25
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +9 -11
- package/build/production/server/server.js.map +1 -1
- package/build/production/server/utils/errors.js +9 -9
- package/build/production/server/utils/errors.js.map +1 -1
- package/build/production/server/utils/index.js +2 -1
- package/build/production/server/utils/index.js.map +1 -1
- package/build/production/shared/components/Button/index.js +4 -4
- 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 +4 -4
- package/build/production/shared/components/GenericLink/index.js.map +1 -1
- package/build/production/shared/components/Input/index.js +5 -5
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/Link.js +3 -3
- package/build/production/shared/components/Link.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +7 -7
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/NavLink.js +2 -2
- package/build/production/shared/components/NavLink.js.map +1 -1
- package/build/production/shared/components/PageLayout/index.js +2 -2
- package/build/production/shared/components/PageLayout/index.js.map +1 -1
- package/build/production/shared/components/TextArea/index.js +5 -5
- package/build/production/shared/components/TextArea/index.js.map +1 -1
- package/build/production/shared/components/Throbber/index.js +2 -2
- package/build/production/shared/components/Throbber/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js +4 -4
- package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +4 -4
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js +4 -4
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/components/index.js +3 -1
- package/build/production/shared/components/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +2 -2
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js +2 -2
- package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/NativeDropdown/index.js +4 -4
- 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/components/selectors/common.js +2 -2
- package/build/production/shared/components/selectors/common.js.map +1 -1
- package/build/production/shared/components/selectors/index.js +1 -1
- package/build/production/shared/components/selectors/index.js.map +1 -1
- package/build/production/shared/utils/config.js +8 -6
- package/build/production/shared/utils/config.js.map +1 -1
- package/build/production/shared/utils/globalState.js +2 -2
- package/build/production/shared/utils/globalState.js.map +1 -1
- package/build/production/shared/utils/index.js +1 -1
- package/build/production/shared/utils/index.js.map +1 -1
- package/build/production/shared/utils/isomorphy/buildInfo.js +3 -3
- package/build/production/shared/utils/isomorphy/buildInfo.js.map +1 -1
- package/build/production/shared/utils/isomorphy/environment-check.js +3 -3
- package/build/production/shared/utils/isomorphy/environment-check.js.map +1 -1
- package/build/production/shared/utils/isomorphy/index.js +4 -4
- package/build/production/shared/utils/isomorphy/index.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js +14 -14
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/production/shared/utils/jest/global.js +1 -1
- package/build/production/shared/utils/jest/global.js.map +1 -1
- package/build/production/shared/utils/jest/index.js +11 -11
- package/build/production/shared/utils/jest/index.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js +11 -22
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/time.js +3 -3
- package/build/production/shared/utils/time.js.map +1 -1
- package/build/production/shared/utils/webpack.js +6 -6
- package/build/production/shared/utils/webpack.js.map +1 -1
- package/build/types-code/client/getInj.d.ts +1 -2
- package/build/types-code/client/index.d.ts +1 -1
- package/build/types-code/index.d.ts +1 -7
- package/build/types-code/server/index.d.ts +6 -11
- package/build/types-code/server/utils/index.d.ts +1 -1
- package/build/types-code/shared/utils/config.d.ts +4 -2
- package/build/types-code/shared/utils/index.d.ts +2 -2
- package/build/types-code/shared/utils/splitComponent.d.ts +6 -4
- package/build/web/client/getInj.js +55 -44
- package/build/web/client/getInj.js.map +1 -1
- package/build/web/client/index.js +15 -21
- package/build/web/client/index.js.map +1 -1
- package/build/web/client/init.js +2 -4
- package/build/web/client/init.js.map +1 -1
- package/build/web/index.js +1 -15
- package/build/web/index.js.map +1 -1
- package/build/web/server/index.js +12 -21
- package/build/web/server/index.js.map +1 -1
- package/build/web/server/renderer.js +34 -40
- package/build/web/server/renderer.js.map +1 -1
- package/build/web/server/server.js +14 -11
- package/build/web/server/server.js.map +1 -1
- package/build/web/server/utils/index.js +1 -1
- package/build/web/server/utils/index.js.map +1 -1
- package/build/web/shared/components/Button/index.js +1 -1
- package/build/web/shared/components/Button/index.js.map +1 -1
- package/build/web/shared/components/Checkbox/index.js +1 -1
- package/build/web/shared/components/Checkbox/index.js.map +1 -1
- package/build/web/shared/components/Input/index.js +1 -1
- package/build/web/shared/components/Input/index.js.map +1 -1
- package/build/web/shared/components/Modal/index.js +3 -3
- package/build/web/shared/components/Modal/index.js.map +1 -1
- package/build/web/shared/components/PageLayout/index.js +1 -1
- package/build/web/shared/components/PageLayout/index.js.map +1 -1
- package/build/web/shared/components/TextArea/index.js +1 -1
- package/build/web/shared/components/TextArea/index.js.map +1 -1
- package/build/web/shared/components/Throbber/index.js +1 -1
- package/build/web/shared/components/Throbber/index.js.map +1 -1
- package/build/web/shared/components/WithTooltip/index.js +1 -1
- package/build/web/shared/components/WithTooltip/index.js.map +1 -1
- package/build/web/shared/components/YouTubeVideo/index.js +1 -1
- package/build/web/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +3 -0
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js +3 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/NativeDropdown/index.js +4 -1
- package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/Switch/index.js +2 -1
- package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/web/shared/utils/config.js +38 -14
- package/build/web/shared/utils/config.js.map +1 -1
- package/build/web/shared/utils/index.js +2 -2
- package/build/web/shared/utils/index.js.map +1 -1
- package/build/web/shared/utils/jest/E2eSsrEnv.js +3 -2
- package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/web/shared/utils/splitComponent.js +27 -20
- package/build/web/shared/utils/splitComponent.js.map +1 -1
- package/build/web/shared/utils/webpack.js +13 -7
- package/build/web/shared/utils/webpack.js.map +1 -1
- package/config/babel/node-ssr.js +12 -6
- package/config/babel/webpack.js +6 -1
- package/config/jest/default.js +8 -2
- package/config/jest/setup.js +8 -1
- package/config/webpack/app-base.js +23 -15
- package/config/webpack/app-development.js +2 -3
- package/config/webpack/lib-base.js +1 -2
- package/package.json +35 -25
- package/types.d.ts +1 -6
- package/node-entry.js +0 -15
- package/src/client/getInj.ts +0 -51
- package/src/client/index.tsx +0 -43
- package/src/client/init.ts +0 -52
- package/src/index.ts +0 -79
- package/src/server/Cache.ts +0 -61
- package/src/server/index.ts +0 -249
- package/src/server/renderer.tsx +0 -653
- package/src/server/server.ts +0 -332
- package/src/server/utils/errors.ts +0 -122
- package/src/server/utils/index.ts +0 -3
- package/src/shared/components/Button/index.tsx +0 -130
- package/src/shared/components/Button/style.scss +0 -54
- package/src/shared/components/Checkbox/index.tsx +0 -53
- package/src/shared/components/Checkbox/theme.scss +0 -63
- package/src/shared/components/GenericLink/index.tsx +0 -141
- package/src/shared/components/GenericLink/style.scss +0 -3
- package/src/shared/components/Input/index.tsx +0 -96
- package/src/shared/components/Input/theme.scss +0 -52
- package/src/shared/components/Link.tsx +0 -25
- package/src/shared/components/Modal/base-theme.scss +0 -38
- package/src/shared/components/Modal/index.tsx +0 -177
- package/src/shared/components/Modal/styles.scss +0 -3
- package/src/shared/components/NavLink.tsx +0 -18
- package/src/shared/components/PageLayout/base-theme.scss +0 -30
- package/src/shared/components/PageLayout/index.tsx +0 -51
- package/src/shared/components/TextArea/index.tsx +0 -139
- package/src/shared/components/TextArea/style.scss +0 -68
- package/src/shared/components/Throbber/index.tsx +0 -28
- package/src/shared/components/Throbber/theme.scss +0 -26
- package/src/shared/components/WithTooltip/Tooltip.tsx +0 -274
- package/src/shared/components/WithTooltip/default-theme.scss +0 -36
- package/src/shared/components/WithTooltip/index.tsx +0 -186
- package/src/shared/components/YouTubeVideo/base.scss +0 -15
- package/src/shared/components/YouTubeVideo/index.tsx +0 -73
- package/src/shared/components/YouTubeVideo/throbber.scss +0 -11
- package/src/shared/components/index.ts +0 -20
- package/src/shared/components/selectors/CustomDropdown/Options/index.tsx +0 -124
- package/src/shared/components/selectors/CustomDropdown/Options/style.scss +0 -6
- package/src/shared/components/selectors/CustomDropdown/index.tsx +0 -146
- package/src/shared/components/selectors/CustomDropdown/theme.scss +0 -118
- package/src/shared/components/selectors/NativeDropdown/index.tsx +0 -90
- package/src/shared/components/selectors/NativeDropdown/theme.scss +0 -81
- package/src/shared/components/selectors/Switch/index.tsx +0 -74
- package/src/shared/components/selectors/Switch/theme.scss +0 -39
- package/src/shared/components/selectors/common.ts +0 -57
- package/src/shared/components/selectors/index.ts +0 -8
- package/src/shared/utils/config.ts +0 -28
- package/src/shared/utils/globalState.ts +0 -44
- package/src/shared/utils/index.ts +0 -45
- package/src/shared/utils/isomorphy/buildInfo.ts +0 -50
- package/src/shared/utils/isomorphy/environment-check.ts +0 -18
- package/src/shared/utils/isomorphy/index.ts +0 -36
- package/src/shared/utils/jest/E2eSsrEnv.ts +0 -305
- package/src/shared/utils/jest/global.ts +0 -17
- package/src/shared/utils/jest/index.ts +0 -215
- package/src/shared/utils/splitComponent.tsx +0 -275
- package/src/shared/utils/time.ts +0 -101
- package/src/shared/utils/webpack.ts +0 -74
- package/src/styles/_global/reset.css +0 -52
- package/src/styles/_mixins/fonts.scss +0 -40
- package/src/styles/_mixins/media.scss +0 -150
- package/src/styles/_mixins/typography.scss +0 -83
- package/src/styles/global.scss +0 -11
- package/src/styles/mixins.scss +0 -6
|
@@ -1 +1 @@
|
|
|
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,MAAAC,OAAA,CAAAV,CAAA,YAAAA,CAAA,mBAAAA,CAAA,qBAAAA,CAAA,QAAAQ,CAAA,IAAAF,CAAA,CAAAL,CAAA,CAAAG,CAAA,CAAAD,CAAA,KAAAG,CAAA,CAAAK,GA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,GAAAC,iBAAQ,EAACvB,GAAG,CAACP,IAAI,CAAC,CAAG,QAAQO,GAAG,CAACP,IAAI,EAAE,CAAG,QAAQO,GAAG,CAACP,IAAI,EAAE,CAEzE,6DACA,OAAS2B,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,iBAAQ,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":["http","https","cloneDeep","defaults","serverFactory","getDefaultCspSettings","SCRIPT_LOCATIONS","newDefaultLogger","normalizePort","value","port","parseInt","Number","isFinite","launchServer","webpackConfig","options","ops","process","env","PORT","httpsRedirect","logger","defaultLogLevel","defaultLoggerLogLevel","expressServer","httpServer","createServer","cert","key","on","error","syscall","bind","code","exit","undefined","addr","address","info","NODE_ENV","listen"],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register.js';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport { cloneDeep, defaults } from 'lodash-es';\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.js';\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\nexport * from './utils';\n\nexport type {\n BeforeRenderResT,\n BeforeRenderT,\n ConfigT,\n ServerSsrContext,\n} from './renderer';\n\nexport {\n getDefaultCspSettings,\n SCRIPT_LOCATIONS,\n type ServerT,\n};\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).\n */\nfunction normalizePort(value: number | string) {\n const port = typeof value === 'string' ? parseInt(value) : value;\n if (Number.isFinite(port)) return port; /* port number */\n return value; /* named pipe */\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 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 = typeof ops.port === 'string' ? `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 = typeof addr === 'string' ? `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"],"mappings":"AAAA;AACA,MAAO,gCAAgC,CAEvC,MAAO,CAAAA,IAAI,KAAM,WAAW,CAC5B,MAAO,CAAAC,KAAK,KAAM,YAAY,CAE9B,OAASC,SAAS,CAAEC,QAAQ,KAAQ,WAAW,CAE/C;AACA;AACA;AACA,MAAO,iBAAiB,OAIjB,CAAAC,aAAa,EAGlBC,qBAAqB,0BAGdC,gBAAgB,CAAEC,gBAAgB,mDAW3C,OACEF,qBAAqB,CACrBC,gBAAgB,EAIlB;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,CAAAE,aAAaA,CAACC,KAAsB,CAAE,CAC7C,KAAM,CAAAC,IAAI,CAAG,MAAO,CAAAD,KAAK,GAAK,QAAQ,CAAGE,QAAQ,CAACF,KAAK,CAAC,CAAGA,KAAK,CAChE,GAAIG,MAAM,CAACC,QAAQ,CAACH,IAAI,CAAC,CAAE,MAAO,CAAAA,IAAI,CAAE,iBACxC,MAAO,CAAAD,KAAK,CAAE,gBAChB,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;A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AG,CAACP,IAAI,EAAE,CAAG,QAAQO,GAAG,CAACP,IAAI,EAAE,CAEnF,6DACA,OAASqB,KAAK,CAAuBG,IAAI,EACvC,IAAK,QAAQ,CACXjB,GAAG,CAACK,MAAM,CAAES,KAAK,CAAC,GAAGE,IAAI,+BAA+B,CAAC,CACzD,MAAO,CAAAf,OAAO,CAACiB,IAAI,CAAC,CAAC,CAAC,CACxB,IAAK,YAAY,CACflB,GAAG,CAACK,MAAM,CAAES,KAAK,CAAC,GAAGE,IAAI,oBAAoB,CAAC,CAC9C,MAAO,CAAAf,OAAO,CAACiB,IAAI,CAAC,CAAC,CAAC,CACxB,IAAK,CAAAC,SAAS,CACd,QACE,KAAM,CAAAL,KACV,CACF,CAAC,CAAC,CAEF,iDACAL,UAAU,CAACI,EAAE,CAAC,WAAW,CAAE,IAAM,CAC/B,KAAM,CAAAO,IAAI,CAAGX,UAAU,CAACY,OAAO,CAAC,CAAE,CAClC,KAAM,CAAAL,IAAI,CAAG,MAAO,CAAAI,IAAI,GAAK,QAAQ,CAAG,QAAQA,IAAI,EAAE,CAAG,QAAQA,IAAI,CAAC3B,IAAI,EAAE,CAC5EO,GAAG,CAACK,MAAM,CAAEiB,IAAI,CAAC,uBAAuBN,IAAI,OAC1Cf,OAAO,CAACC,GAAG,CAACqB,QAAQ,OAAO,CAC/B,CAAC,CAAC,CAEFd,UAAU,CAACe,MAAM,CAACxB,GAAG,CAACP,IAAI,CAAC,CAE3B,MAAO,CACLe,aAAa,CACbC,UACF,CACF","ignoreList":[]}
|
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
"
|
|
1
|
+
import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.iterator.map.js";import"core-js/modules/es.set.difference.v2.js";import"core-js/modules/es.set.intersection.v2.js";import"core-js/modules/es.set.is-disjoint-from.v2.js";import"core-js/modules/es.set.is-subset-of.v2.js";import"core-js/modules/es.set.is-superset-of.v2.js";import"core-js/modules/es.set.symmetric-difference.v2.js";import"core-js/modules/es.set.union.v2.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.iterator.map.js";import"core-js/modules/es.set.difference.v2.js";import"core-js/modules/es.set.intersection.v2.js";import"core-js/modules/es.set.is-disjoint-from.v2.js";import"core-js/modules/es.set.is-subset-of.v2.js";import"core-js/modules/es.set.is-superset-of.v2.js";import"core-js/modules/es.set.symmetric-difference.v2.js";import"core-js/modules/es.set.union.v2.js";/**
|
|
2
2
|
* ExpressJS middleware for server-side rendering of a ReactJS app.
|
|
3
|
-
*/
|
|
3
|
+
*/import{Buffer}from"node:buffer";import{createCipheriv,randomBytes}from"node:crypto";import fs from"node:fs";import path from"node:path";import{Writable}from"node:stream";import{brotliCompress,brotliDecompress}from"node:zlib";import winston from"winston";import{GlobalStateProvider,SsrContext}from"@dr.pogodin/react-global-state";import{timer}from"@dr.pogodin/js-utils";import{cloneDeep,defaults,get,mapValues}from"lodash-es";import config from"config";import{prerenderToNodeStream}from"react-dom/static";import{HelmetProvider}from"@dr.pogodin/react-helmet";import{StaticRouter}from"react-router";import serializeJs from"serialize-javascript";import{setBuildInfo}from"../shared/utils/isomorphy/buildInfo.js";import Cache from"./Cache.js";// @ts-expect-error "Property 'SECRET' does not exist on type 'IConfig'."
|
|
4
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
5
|
+
import{jsx as _jsx}from"react/jsx-runtime";const{SECRET,...sanitizedConfig}=config;// Note: These type definitions for logger are copied from Winston logger,
|
|
4
6
|
// then simplified to make it easier to fit an alternative logger into this
|
|
5
7
|
// interface.
|
|
6
8
|
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
7
9
|
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
8
10
|
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
9
|
-
let SCRIPT_LOCATIONS
|
|
11
|
+
export let 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}({});export class ServerSsrContext extends SsrContext{chunks=[];status=200;constructor(req,chunkGroups,initialState){super(cloneDeep(initialState)??{});this.chunkGroups=chunkGroups;this.req=req}}/**
|
|
10
12
|
* Reads build-time information about the app. This information is generated
|
|
11
13
|
* by our standard Webpack config for apps, and it is written into
|
|
12
14
|
* ".build-info" file in the context folder specified in Webpack config.
|
|
@@ -14,26 +16,25 @@ let SCRIPT_LOCATIONS=exports.SCRIPT_LOCATIONS=/*#__PURE__*/function(SCRIPT_LOCAT
|
|
|
14
16
|
* suitable for cryptographical use.
|
|
15
17
|
* @param context Webpack context path used during the build.
|
|
16
18
|
* @return Resolves to the build-time information.
|
|
17
|
-
*/
|
|
19
|
+
*/function getBuildInfo(context){const url=path.resolve(context,".build-info");return JSON.parse(fs.readFileSync(url,"utf8"))}/**
|
|
18
20
|
* Attempts to read from disk the named chunk groups mapping generated
|
|
19
21
|
* by Webpack during the compilation.
|
|
20
22
|
* It will not work for development builds, where these stats should be captured
|
|
21
23
|
* via compilator callback.
|
|
22
24
|
* @param buildDir
|
|
23
25
|
* @return
|
|
24
|
-
*/function readChunkGroupsJson(buildDir){const url=
|
|
26
|
+
*/function readChunkGroupsJson(buildDir){const url=path.resolve(buildDir,"__chunk_groups__.json");let res;try{res=JSON.parse(fs.readFileSync(url,"utf8"))}catch{// TODO: Should we message the error here somehow?
|
|
25
27
|
res=null}return res}/**
|
|
26
28
|
* Prepares a new Cipher for data encryption.
|
|
27
|
-
* @param key Encryption key (32-bit random key is expected
|
|
28
|
-
*
|
|
29
|
-
* @return Resolves to the object with two fields:
|
|
29
|
+
* @param key Encryption key (32-bit random, Base64-encoded key is expected).
|
|
30
|
+
* @return Returns a tuple of:
|
|
30
31
|
* 1. cipher - a new Cipher, ready for encryption;
|
|
31
32
|
* 2. iv - initial vector used by the cipher.
|
|
32
|
-
*/
|
|
33
|
+
*/function prepareCipher(key){const iv=randomBytes(16);const cipher=createCipheriv("AES-256-CBC",Buffer.from(key,"base64"),iv);return[cipher,iv]}/**
|
|
33
34
|
* Given an incoming HTTP requests, it deduces whether Brotli-encoded responses
|
|
34
35
|
* are acceptable to the caller.
|
|
35
36
|
* @param req
|
|
36
|
-
*/function isBrotliAcceptable(req){const acceptable=req.get("accept-encoding");if(acceptable){const ops=acceptable.split(",");for(const op of ops){const[type,priority]=op.trim().split(";q=");if((type==="*"||type==="br")&&(!priority||parseFloat(priority)>0)){return true}}}return false}/**
|
|
37
|
+
*/export function isBrotliAcceptable(req){const acceptable=req.get("accept-encoding");if(acceptable){const ops=acceptable.split(",");for(const op of ops){const[type,priority]=op.trim().split(";q=");if((type==="*"||type==="br")&&(!priority||parseFloat(priority)>0)){return true}}}return false}/**
|
|
37
38
|
* Given an array of extra script strings / objects, it returns an object with
|
|
38
39
|
* arrays of scripts to inject in different HTML template locations. During
|
|
39
40
|
* the script groupping it also filters out any empty scripts.
|
|
@@ -46,12 +47,12 @@ res=null}return res}/**
|
|
|
46
47
|
* DEFAULT: string[];
|
|
47
48
|
* HEAD_OPEN: string[];
|
|
48
49
|
* }}
|
|
49
|
-
*/function groupExtraScripts(scripts=[]){const res={[SCRIPT_LOCATIONS.BODY_OPEN]:"",[SCRIPT_LOCATIONS.DEFAULT]:"",[SCRIPT_LOCATIONS.HEAD_OPEN]:""};for(const script of scripts){if(
|
|
50
|
+
*/function groupExtraScripts(scripts=[]){const res={[SCRIPT_LOCATIONS.BODY_OPEN]:"",[SCRIPT_LOCATIONS.DEFAULT]:"",[SCRIPT_LOCATIONS.HEAD_OPEN]:""};for(const script of scripts){if(typeof script==="string"){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
51
|
* Creates a new default (Winston) logger.
|
|
51
52
|
* @param {object} [options={}]
|
|
52
53
|
* @param {string} [options.defaultLogLevel='info']
|
|
53
54
|
* @return {object}
|
|
54
|
-
*/function newDefaultLogger({defaultLogLevel="info"}={}){const{format,transports}=
|
|
55
|
+
*/export function newDefaultLogger({defaultLogLevel="info"}={}){const{format,transports}=winston;return winston.createLogger({format:format.combine(format.splat(),format.timestamp(),format.colorize(),format.printf(({level,message,timestamp,stack,...rest})=>{let res=`${level}\t(at ${timestamp}):\t${message}`;if(Object.keys(rest).length){res+=`\n${JSON.stringify(rest,null,2)}`}if(stack)res+=`\n${stack}`;return res})),level:defaultLogLevel,transports:[new transports.Console]})}/**
|
|
55
56
|
* Creates the middleware.
|
|
56
57
|
* @param webpackConfig
|
|
57
58
|
* @param options Additional options:
|
|
@@ -81,25 +82,23 @@ res=null}return res}/**
|
|
|
81
82
|
* - `maxage?: number` – the maximum age of cached result in ms.
|
|
82
83
|
* If undefined - infinite age is assumed.
|
|
83
84
|
* @return Created middleware.
|
|
84
|
-
*/function factory(webpackConfig,options){const ops=(
|
|
85
|
+
*/export default function factory(webpackConfig,options){const ops=defaults({...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
86
|
// server function, and this initialization is for testing uses, where
|
|
86
87
|
// renderer is imported directly.
|
|
87
|
-
ops.logger??=newDefaultLogger({defaultLogLevel:ops.defaultLoggerLogLevel});const buildInfo=ops.buildInfo??getBuildInfo(webpackConfig.context);
|
|
88
|
-
const{publicPath,path:outputPath}=webpackConfig.output;const manifestLink=
|
|
89
|
-
const cache=ops.staticCacheController?new
|
|
88
|
+
ops.logger??=newDefaultLogger({defaultLogLevel:ops.defaultLoggerLogLevel});const buildInfo=ops.buildInfo??getBuildInfo(webpackConfig.context);setBuildInfo(buildInfo);// publicPath from webpack.output has a trailing slash at the end.
|
|
89
|
+
const{publicPath,path:outputPath}=webpackConfig.output;const manifestLink=fs.existsSync(`${outputPath}/manifest.json`)?`<link rel="manifest" href="${publicPath}manifest.json">`:"";// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
90
|
+
const cache=ops.staticCacheController?new Cache(ops.staticCacheSize):null;const CHUNK_GROUPS=readChunkGroupsJson(outputPath);// TODO: Look at it later.
|
|
90
91
|
// eslint-disable-next-line complexity
|
|
91
92
|
return async(req,res,next)=>{try{// Ensures any caches always revalidate HTML markup before reuse.
|
|
92
|
-
res.set("Cache-Control","no-cache");res.cookie("csrfToken",req.csrfToken());let cacheRef;if(cache){cacheRef=ops.staticCacheController(req);if(cacheRef){const data=cache.get(cacheRef);if(data!==null){const{buffer,status}=data;if(ops.noCsp&&isBrotliAcceptable(req)){res.set("Content-Type","text/html");res.set("Content-Encoding","br");if(status!==200)res.status(status);res.send(buffer)}else{await new Promise((done,failed)=>{
|
|
93
|
+
res.set("Cache-Control","no-cache");res.cookie("csrfToken",req.csrfToken());let cacheRef;if(cache){cacheRef=ops.staticCacheController(req);if(cacheRef){const data=cache.get(cacheRef);if(data!==null){const{buffer,status}=data;if(ops.noCsp&&isBrotliAcceptable(req)){res.set("Content-Type","text/html");res.set("Content-Encoding","br");if(status!==200)res.status(status);res.send(buffer)}else{await new Promise((done,failed)=>{brotliDecompress(buffer,(error,html)=>{if(error)failed(error);else{let h=html.toString();if(!ops.noCsp){// TODO: Starting from Node v15 we'll be able to use string's
|
|
93
94
|
// .replaceAll() method instead relying on reg. expression for
|
|
94
95
|
// global matching.
|
|
95
96
|
const regex=new RegExp(buffer.nonce,"g");// TODO: It should be implemented more careful.
|
|
96
|
-
h=h.replace(regex,req.nonce)}if(status!==200)res.status(status);res.send(h);done()}})})}return}}}const brr=ops.beforeRender(req,sanitizedConfig);const
|
|
97
|
-
// ESLint rule.
|
|
98
|
-
brr instanceof Promise?brr:Promise.resolve(brr),prepareCipher(buildInfo.key)]);let helmet;// Gets the mapping between code chunk names and their asset files.
|
|
97
|
+
h=h.replace(regex,req.nonce)}if(status!==200)res.status(status);res.send(h);done()}})})}return}}}const brr=ops.beforeRender(req,sanitizedConfig);const{configToInject,extraScripts,initialState}=await brr;const[cipher,iv]=prepareCipher(buildInfo.key);let helmet;// Gets the mapping between code chunk names and their asset files.
|
|
99
98
|
// These data come from the Webpack compilation, either from the stats
|
|
100
99
|
// attached to the request (in dev mode), or from a file output during
|
|
101
100
|
// the build (in prod mode).
|
|
102
|
-
let chunkGroups;const webpackStats=(
|
|
101
|
+
let chunkGroups;const webpackStats=get(res.locals,"webpack.devMiddleware.stats");if(webpackStats){chunkGroups=mapValues(webpackStats.toJson({all:false,chunkGroups:true}).namedChunkGroups,item=>item.assets?.map(({name})=>name)??[])}else if(CHUNK_GROUPS)chunkGroups=CHUNK_GROUPS;else chunkGroups={};/* Optional server-side rendering. */const App=ops.Application;let appHtmlMarkup="";const ssrContext=new ServerSsrContext(req,chunkGroups,initialState);let stream;if(App){const ssrStart=Date.now();// TODO: Somehow, without it TS does not realise that
|
|
103
102
|
// App has been checked to exist.
|
|
104
103
|
const App2=App;const renderPass=async()=>new Promise((resolveArg,rejectArg)=>{ssrContext.chunks=[];// NOTE: JS does not have problems if resolve() and reject() methods
|
|
105
104
|
// of a Promise are called multiple times, with different arguments;
|
|
@@ -109,14 +108,14 @@ const App2=App;const renderPass=async()=>new Promise((resolveArg,rejectArg)=>{ss
|
|
|
109
108
|
// if any.
|
|
110
109
|
let error;const resolve=arg=>{if(error!==undefined)throw Error("Internal error");error=null;resolveArg(arg)};const reject=arg=>{if(error!==undefined&&error!==arg){throw Error("Internal error")}error=arg;rejectArg(arg)};// TODO: prerenderToNodeStream has (abort) "signal" option,
|
|
111
110
|
// and we should wire it up to the SSR timeout below.
|
|
112
|
-
const helmetContext={};void
|
|
111
|
+
const helmetContext={};void prerenderToNodeStream(/*#__PURE__*/_jsx(GlobalStateProvider,{initialState:ssrContext.state,ssrContext:ssrContext,children:/*#__PURE__*/_jsx(StaticRouter,{location:req.url,children:/*#__PURE__*/_jsx(HelmetProvider,{context:helmetContext,children:/*#__PURE__*/_jsx(App2,{})})})}),{onError:reject}).then(result=>{({helmet}=helmetContext);resolve(result.prelude)}).catch(reject)});let ssrRound=0;let bailed=false;for(;ssrRound<ops.maxSsrRounds;++ssrRound){stream=await renderPass();if(!ssrContext.dirty)break;const timeout=ops.ssrTimeout+ssrStart-Date.now();bailed=timeout<=0||!(await Promise.race([Promise.allSettled(ssrContext.pending),timer(timeout).then(()=>false)]));if(bailed)break}let logMsg;if(ssrContext.dirty){// NOTE: In the case of incomplete SSR one more round is necessary
|
|
113
112
|
// to ensure the correct hydration when some pending promises have
|
|
114
113
|
// resolved and placed their data into the initial global state.
|
|
115
|
-
stream=await renderPass();logMsg=bailed?`SSR timed out after ${ops.ssrTimeout} second(s)`:`SSR bailed out after ${ops.maxSsrRounds} round(s)`}else logMsg=`SSR completed in ${ssrRound+1} round(s)`;ops.logger.log(ssrContext.dirty?"warn":"info",logMsg);if(ssrContext.redirectTo){res.redirect(ssrContext.status,ssrContext.redirectTo);return}await new Promise(ready=>{stream.pipe(new
|
|
114
|
+
stream=await renderPass();logMsg=bailed?`SSR timed out after ${ops.ssrTimeout} second(s)`:`SSR bailed out after ${ops.maxSsrRounds} round(s)`}else logMsg=`SSR completed in ${ssrRound+1} round(s)`;ops.logger.log(ssrContext.dirty?"warn":"info",logMsg);if(ssrContext.redirectTo){res.redirect(ssrContext.status,ssrContext.redirectTo);return}await new Promise(ready=>{stream.pipe(new Writable({destroy:ready,write:(chunk,_,done)=>{appHtmlMarkup+=chunk.toString();done()}}))})}/* Encrypts data to be injected into HTML.
|
|
116
115
|
* Keep in mind, that this encryption is no way secure: as the JS bundle
|
|
117
116
|
* contains decryption key and is able to decode it at the client side.
|
|
118
117
|
* Hovewer, for a number of reasons, encryption of injected data is still
|
|
119
|
-
* better than injection of a plain text. */const payload=(
|
|
118
|
+
* better than injection of a plain text. */const payload=serializeJs({CHUNK_GROUPS:chunkGroups,CONFIG:configToInject??sanitizedConfig,ISTATE:ssrContext.state},{ignoreFunction:true,unsafe:true});const INJ=Buffer.concat([iv,cipher.update(payload,"utf8"),cipher.final()]).toString("base64");const chunkSet=new Set;// TODO: "main" chunk has to be added explicitly,
|
|
120
119
|
// because unlike all other chunks they are not managed by <CodeSplit>
|
|
121
120
|
// component, thus they are not added to the ssrContext.chunks
|
|
122
121
|
// automatically. Actually, names of these entry chunks should be
|
|
@@ -151,7 +150,7 @@ stream=await renderPass();logMsg=bailed?`SSR timed out after ${ops.ssrTimeout} s
|
|
|
151
150
|
</body>
|
|
152
151
|
</html>`;const status=ssrContext.status||200;if(status!==200)res.status(status);if(cacheRef&&status<500){// Note: waiting for the caching to complete is not strictly necessary,
|
|
153
152
|
// but it greately simplifies testing, and error reporting.
|
|
154
|
-
await new Promise((done,failed)=>{
|
|
153
|
+
await new Promise((done,failed)=>{brotliCompress(html,(error,buffer)=>{if(error)failed(error);else{const b=buffer;b.nonce=req.nonce;cache.add({buffer:b,status},cacheRef.key,buffer.length);done()}})})}// Note: as caching code above may throw in some cases, sending response
|
|
155
154
|
// before it completes will likely hide the error, making it difficult
|
|
156
155
|
// to debug. Thus, at least for now, lets send response after it.
|
|
157
156
|
res.send(html)}catch(error){next(error)}}}
|
|
@@ -1 +1 @@
|
|
|
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,iBAC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A,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":["Buffer","createCipheriv","randomBytes","fs","path","Writable","brotliCompress","brotliDecompress","winston","GlobalStateProvider","SsrContext","timer","cloneDeep","defaults","get","mapValues","config","prerenderToNodeStream","HelmetProvider","StaticRouter","serializeJs","setBuildInfo","Cache","jsx","_jsx","SECRET","sanitizedConfig","SCRIPT_LOCATIONS","ServerSsrContext","chunks","status","constructor","req","chunkGroups","initialState","getBuildInfo","context","url","resolve","JSON","parse","readFileSync","readChunkGroupsJson","buildDir","res","prepareCipher","key","iv","cipher","from","isBrotliAcceptable","acceptable","ops","split","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","code","location","Error","newDefaultLogger","defaultLogLevel","format","transports","createLogger","combine","splat","timestamp","colorize","printf","level","message","stack","rest","Object","keys","length","stringify","Console","factory","webpackConfig","options","beforeRender","Promise","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","error","html","h","toString","regex","RegExp","nonce","replace","brr","configToInject","extraScripts","helmet","webpackStats","locals","toJson","all","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","resolveArg","rejectArg","arg","undefined","reject","helmetContext","state","children","onError","then","result","prelude","catch","ssrRound","bailed","dirty","timeout","race","allSettled","pending","logMsg","log","redirectTo","redirect","ready","pipe","destroy","write","chunk","_","payload","CONFIG","ISTATE","ignoreFunction","unsafe","INJ","concat","update","final","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","link","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { type Cipheriv, createCipheriv, randomBytes } from 'node:crypto';\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 cloneDeep,\n defaults,\n get,\n mapValues,\n} from 'lodash-es';\n\nimport config from 'config';\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\n// @ts-expect-error \"Property 'SECRET' does not exist on type 'IConfig'.\"\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst { SECRET, ...sanitizedConfig } = config;\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, Base64-encoded key is expected).\n * @return Returns a tuple of:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key: string): [cipher: Cipheriv, iv: Buffer] {\n const iv = randomBytes(16);\n const cipher = createCipheriv('AES-256-CBC', Buffer.from(key, 'base64'), iv);\n return [cipher, iv];\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 (typeof script === 'string') {\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({ ...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 const { configToInject, extraScripts, initialState } = await brr;\n\n const [cipher, iv] = prepareCipher(buildInfo.key);\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\n const INJ = Buffer.concat([\n iv,\n cipher.update(payload, 'utf8'),\n cipher.final(),\n ]).toString('base64');\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":"k+BAAA;AACA;AACA,GAEA,OAASA,MAAM,KAAQ,aAAa,CACpC,OAAwBC,cAAc,CAAEC,WAAW,KAAQ,aAAa,CACxE,MAAO,CAAAC,EAAE,KAAM,SAA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KAAM,CAAAoF,CAAC,CAAGzF,MAAoC,CAC9CyF,CAAC,CAAC9E,KAAK,CAAI3F,GAAG,CAEX2F,KAAK,CACRpB,KAAK,CAAEwF,GAAG,CAAC,CAAE/E,MAAM,CAAEyF,CAAC,CAAE3K,MAAO,CAAC,CAAEgF,QAAQ,CAAChE,GAAG,CAAEkE,MAAM,CAAC5B,MAAM,CAAC,CAC9D+B,IAAI,CAAC,CACP,CACF,CAAC,CACH,CAAC,CACH,CAEA;AACA;AACA;AACAvE,GAAG,CAACsE,IAAI,CAACI,IAAI,CACf,CAAE,MAAOD,KAAK,CAAE,CACdX,IAAI,CAACW,KAAK,CACZ,CACF,CACF","ignoreList":[]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"
|
|
1
|
+
import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";/**
|
|
2
2
|
* Creation of standard ExpressJS server for ReactJS apps.
|
|
3
|
-
|
|
3
|
+
*/import{sep}from"node:path";import{pathToFileURL}from"node:url";import{cloneDeep,mapValues,pick}from"lodash-es";import compression from"compression";import cookieParser from"cookie-parser";import csrf from"@dr.pogodin/csurf";import express from"express";import favicon from"serve-favicon";import helmet from"helmet";import loggerMiddleware from"morgan";import requestIp from"request-ip";import{v4 as uuid}from"uuid";import rendererFactory from"./renderer.js";import{CODES,ERRORS,getErrorForCode,newError}from"./utils/errors.js";// 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:(
|
|
7
|
+
*/const defaultCspSettings={directives:mapValues(helmet.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,17 +27,17 @@ 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(
|
|
30
|
+
*/export function getDefaultCspSettings(){return cloneDeep(defaultCspSettings)}export default async function factory(webpackConfig,options){const rendererOps=pick(options,["Application","beforeRender","favicon","logger","maxSsrRounds","noCsp","ssrTimeout","staticCacheController","staticCacheSize"]);const renderer=rendererFactory(webpackConfig,rendererOps);const{publicPath}=webpackConfig.output;const server=express();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(compression());server.use(helmet({contentSecurityPolicy:false,crossOriginEmbedderPolicy:false,crossOriginOpenerPolicy:false,crossOriginResourcePolicy:false}));if(!options.noCsp){server.use((req,res,next)=>{const req2=req;req2.nonce=uuid();// 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=(
|
|
34
|
+
let cspSettings=cloneDeep(defaultCspSettings);(cspSettings.directives?.["script-src"]).push(`'nonce-${req2.nonce}'`);if(options.cspSettingsHook){cspSettings=options.cspSettingsHook(cspSettings,req)}helmet.contentSecurityPolicy(cspSettings)(req,res,next)})}if(options.favicon){server.use(favicon(options.favicon))}server.use("/robots.txt",(req,res)=>{res.send("User-agent: *\nDisallow:")});server.use(express.json({limit:"300kb"}));server.use(express.urlencoded({extended:false}));server.use(cookieParser(options.cookieSignatureSecret));server.use(requestIp.mw());server.use(csrf({cookie:true}));loggerMiddleware.token("ip",req=>req.clientIp);const FORMAT=":ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent";server.use(loggerMiddleware(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.
|
|
38
38
|
// Thus, this setup to serve it. Probably, need some more configuration
|
|
39
39
|
// for special cases, but this will do for now.
|
|
40
|
-
server.get("/__service-worker.js",
|
|
40
|
+
server.get("/__service-worker.js",express.static(webpackConfig.output?.path??"",{setHeaders:res=>res.set("Cache-Control","no-cache")}));/* Setup of Hot Module Reloading for development environment.
|
|
41
41
|
* These dependencies are not used, nor installed for production use,
|
|
42
42
|
* hence we should violate some import-related lint rules. *//* eslint-disable import/no-extraneous-dependencies */if(options.devMode){// This is a workaround for SASS bug:
|
|
43
43
|
// https://github.com/dart-lang/sdk/issues/27979
|
|
@@ -45,9 +45,7 @@ server.get("/__service-worker.js",_express.default.static(webpackConfig.output?.
|
|
|
45
45
|
// (in dev mode), and app modules are imported in some unfortunate ways.
|
|
46
46
|
// TODO: Double-check, what is going on here.
|
|
47
47
|
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
48
|
-
if(!global.location){global.location={href:`${
|
|
49
|
-
// right now.
|
|
50
|
-
const webpackDevMiddleware=require("webpack-dev-middleware");const webpackHotMiddleware=require("webpack-hot-middleware");const compiler=webpack(webpackConfig);server.use(webpackDevMiddleware(compiler,{publicPath,serverSideRender:true}));server.use(webpackHotMiddleware(compiler))}/* eslint-enable import/no-extraneous-dependencies */server.use(publicPath,_express.default.static(webpackConfig.output.path));if(options.onExpressJsSetup){await options.onExpressJsSetup(server)}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use((req,res,next)=>{next((0,_errors.newError)(_errors.ERRORS.NOT_FOUND,_errors.CODES.NOT_FOUND))});let dontAttachDefaultErrorHandler;if(options.beforeExpressJsError){dontAttachDefaultErrorHandler=await options.beforeExpressJsError(server)}/* Error handler. */if(!dontAttachDefaultErrorHandler){// TODO: Do we need this error handler at all? It actually seems to do
|
|
48
|
+
if(!global.location){global.location={href:`${pathToFileURL(process.cwd()).href}${sep}`}}const{default:webpack}=await import(/* webpackChunkName: "server-side-code" */"webpack");const{default:webpackDevMiddleware}=await import(/* webpackChunkName: "server-side-code" */"webpack-dev-middleware");const{default:webpackHotMiddleware}=await import(/* webpackChunkName: "server-side-code" */"webpack-hot-middleware");const compiler=webpack(webpackConfig);if(!compiler)throw Error("Internal error");server.use(webpackDevMiddleware(compiler,{publicPath,serverSideRender:true}));server.use(webpackHotMiddleware(compiler))}/* eslint-enable import/no-extraneous-dependencies */server.use(publicPath,express.static(webpackConfig.output.path));if(options.onExpressJsSetup){await options.onExpressJsSetup(server)}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use((req,res,next)=>{next(newError(ERRORS.NOT_FOUND,CODES.NOT_FOUND))});let dontAttachDefaultErrorHandler;if(options.beforeExpressJsError){dontAttachDefaultErrorHandler=await options.beforeExpressJsError(server)}/* Error handler. */if(!dontAttachDefaultErrorHandler){// TODO: Do we need this error handler at all? It actually seems to do
|
|
51
49
|
// what the default ExpressJS error handler does anyway, see:
|
|
52
50
|
// https://expressjs.com/en/guide/error-handling.html
|
|
53
51
|
//
|
|
@@ -57,6 +55,6 @@ const webpackDevMiddleware=require("webpack-dev-middleware");const webpackHotMid
|
|
|
57
55
|
// though.
|
|
58
56
|
server.use((error,req,res,next)=>{// TODO: This is needed to correctly handled any errors thrown after
|
|
59
57
|
// sending initial response to the client.
|
|
60
|
-
if(res.headersSent){next(error);return}const status=error.status??
|
|
61
|
-
options.logger.log(serverSide?"error":"debug",error.toString());let message=error.message||
|
|
58
|
+
if(res.headersSent){next(error);return}const status=error.status??CODES.INTERNAL_SERVER_ERROR;const serverSide=status>=CODES.INTERNAL_SERVER_ERROR;// Log server-side errors always, client-side at debug level only.
|
|
59
|
+
options.logger.log(serverSide?"error":"debug",error.toString());let message=error.message||getErrorForCode(status);if(serverSide&&process.env.NODE_ENV==="production"){message=ERRORS.INTERNAL_SERVER_ERROR}res.status(status).send(message)})}return server}
|
|
62
60
|
//# sourceMappingURL=server.js.map
|