@dr.pogodin/react-utils 1.25.5 → 1.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/babel.config.js +3 -1
- package/bin/build.js +25 -5
- package/build/development/client/getInj.js +9 -8
- package/build/development/client/getInj.js.map +1 -1
- package/build/development/client/index.js +6 -3
- package/build/development/client/index.js.map +1 -1
- package/build/development/client/init.js +4 -0
- package/build/development/client/init.js.map +1 -1
- package/build/development/index.js +168 -42
- package/build/development/index.js.map +1 -1
- package/build/development/server/Cache.js +13 -13
- package/build/development/server/Cache.js.map +1 -1
- package/build/development/server/index.js +16 -24
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js +56 -44
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +9 -5
- package/build/development/server/server.js.map +1 -1
- package/build/development/server/utils/errors.js +12 -9
- package/build/development/server/utils/errors.js.map +1 -1
- package/build/development/server/utils/index.js +2 -2
- package/build/development/server/utils/index.js.map +1 -1
- package/build/development/shared/components/Button/index.js +8 -7
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +25 -28
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/Dropdown/index.js +25 -19
- package/build/development/shared/components/Dropdown/index.js.map +1 -1
- package/build/development/shared/components/GenericLink/index.js +44 -37
- package/build/development/shared/components/GenericLink/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +8 -9
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/Link.js +10 -9
- package/build/development/shared/components/Link.js.map +1 -1
- package/build/development/shared/components/MetaTags.js +22 -18
- package/build/development/shared/components/MetaTags.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +17 -18
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/NavLink.js +10 -9
- package/build/development/shared/components/NavLink.js.map +1 -1
- package/build/development/shared/components/PageLayout/index.js +17 -20
- package/build/development/shared/components/PageLayout/index.js.map +1 -1
- package/build/development/shared/components/ScalableRect/index.js +27 -7
- package/build/development/shared/components/ScalableRect/index.js.map +1 -1
- package/build/development/shared/components/Throbber/index.js +14 -23
- package/build/development/shared/components/Throbber/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/Tooltip.js +20 -24
- package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +11 -11
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js +16 -15
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/components/index.js +2 -2
- package/build/development/shared/components/index.js.map +1 -1
- package/build/development/shared/utils/config.js +1 -2
- package/build/development/shared/utils/config.js.map +1 -1
- package/build/development/shared/utils/globalState.js +15 -0
- package/build/development/shared/utils/globalState.js.map +1 -0
- package/build/development/shared/utils/index.js +13 -11
- package/build/development/shared/utils/index.js.map +1 -1
- package/build/development/shared/utils/isomorphy/buildInfo.js +7 -3
- package/build/development/shared/utils/isomorphy/buildInfo.js.map +1 -1
- package/build/development/shared/utils/isomorphy/environment-check.js +2 -4
- package/build/development/shared/utils/isomorphy/environment-check.js.map +1 -1
- package/build/development/shared/utils/isomorphy/index.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv.js +35 -28
- package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/development/shared/utils/jest/global.js +17 -0
- package/build/development/shared/utils/jest/global.js.map +1 -0
- package/build/development/shared/utils/jest/index.js +18 -11
- package/build/development/shared/utils/jest/index.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +25 -34
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/time.js +16 -13
- package/build/development/shared/utils/time.js.map +1 -1
- package/build/development/shared/utils/webpack.js +3 -3
- package/build/development/shared/utils/webpack.js.map +1 -1
- package/build/development/web.bundle.js +92 -82
- package/build/production/client/getInj.js +1 -1
- package/build/production/client/getInj.js.map +1 -1
- package/build/production/client/index.js +4 -4
- package/build/production/client/index.js.map +1 -1
- package/build/production/client/init.js +3 -1
- package/build/production/client/init.js.map +1 -1
- package/build/production/index.js +1 -1
- package/build/production/index.js.map +1 -1
- package/build/production/server/Cache.js +7 -8
- package/build/production/server/Cache.js.map +1 -1
- package/build/production/server/index.js +5 -4
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js +32 -30
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +7 -5
- package/build/production/server/server.js.map +1 -1
- package/build/production/server/utils/errors.js +9 -10
- package/build/production/server/utils/errors.js.map +1 -1
- package/build/production/server/utils/index.js +1 -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 +12 -12
- package/build/production/shared/components/Checkbox/index.js.map +1 -1
- package/build/production/shared/components/Dropdown/index.js +11 -11
- package/build/production/shared/components/Dropdown/index.js.map +1 -1
- package/build/production/shared/components/GenericLink/index.js +25 -20
- package/build/production/shared/components/GenericLink/index.js.map +1 -1
- package/build/production/shared/components/Input/index.js +7 -7
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/Link.js +2 -2
- package/build/production/shared/components/Link.js.map +1 -1
- package/build/production/shared/components/MetaTags.js +10 -10
- package/build/production/shared/components/MetaTags.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +2 -2
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/NavLink.js +1 -1
- package/build/production/shared/components/NavLink.js.map +1 -1
- package/build/production/shared/components/PageLayout/index.js +2 -2
- package/build/production/shared/components/PageLayout/index.js.map +1 -1
- package/build/production/shared/components/ScalableRect/index.js +7 -3
- package/build/production/shared/components/ScalableRect/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 +13 -13
- package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +3 -3
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js +7 -7
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/components/index.js +1 -1
- package/build/production/shared/components/index.js.map +1 -1
- package/build/production/shared/utils/config.js +1 -1
- package/build/production/shared/utils/config.js.map +1 -1
- package/build/production/shared/utils/globalState.js +3 -0
- package/build/production/shared/utils/globalState.js.map +1 -0
- package/build/production/shared/utils/index.js +3 -3
- package/build/production/shared/utils/index.js.map +1 -1
- package/build/production/shared/utils/isomorphy/buildInfo.js +7 -4
- package/build/production/shared/utils/isomorphy/buildInfo.js.map +1 -1
- package/build/production/shared/utils/isomorphy/environment-check.js +2 -2
- package/build/production/shared/utils/isomorphy/environment-check.js.map +1 -1
- package/build/production/shared/utils/isomorphy/index.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js +9 -9
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/production/shared/utils/jest/global.js +2 -0
- package/build/production/shared/utils/jest/global.js.map +1 -0
- package/build/production/shared/utils/jest/index.js +6 -6
- package/build/production/shared/utils/jest/index.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js +16 -16
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/time.js +12 -8
- package/build/production/shared/utils/time.js.map +1 -1
- package/build/production/shared/utils/webpack.js +3 -3
- package/build/production/shared/utils/webpack.js.map +1 -1
- package/build/production/web.bundle.js +1 -1
- package/build/production/web.bundle.js.map +1 -1
- package/build/types-code/client/getInj.d.ts +3 -0
- package/build/types-code/client/index.d.ts +11 -0
- package/build/types-code/client/init.d.ts +9 -0
- package/build/types-code/index.d.ts +10 -0
- package/build/types-code/server/Cache.d.ts +37 -0
- package/build/types-code/server/index.d.ts +145 -0
- package/build/types-code/server/renderer.d.ts +106 -0
- package/build/types-code/server/server.d.ts +41 -0
- package/build/types-code/server/utils/errors.d.ts +104 -0
- package/build/types-code/server/utils/index.d.ts +1 -0
- package/build/types-code/shared/components/Button/index.d.ts +27 -0
- package/build/types-code/shared/components/Checkbox/index.d.ts +21 -0
- package/build/types-code/shared/components/Dropdown/index.d.ts +23 -0
- package/build/types-code/shared/components/GenericLink/index.d.ts +61 -0
- package/build/types-code/shared/components/Input/index.d.ts +11 -0
- package/build/types-code/shared/components/Link.d.ts +12 -0
- package/build/types-code/shared/components/MetaTags.d.ts +68 -0
- package/build/types-code/shared/components/Modal/index.d.ts +26 -0
- package/build/types-code/shared/components/NavLink.d.ts +5 -0
- package/build/types-code/shared/components/PageLayout/index.d.ts +16 -0
- package/build/types-code/shared/components/ScalableRect/index.d.ts +19 -0
- package/build/types-code/shared/components/Throbber/index.d.ts +9 -0
- package/build/types-code/shared/components/WithTooltip/Tooltip.d.ts +23 -0
- package/build/types-code/shared/components/WithTooltip/index.d.ts +17 -0
- package/build/types-code/shared/components/YouTubeVideo/index.d.ts +13 -0
- package/build/types-code/shared/components/index.d.ts +16 -0
- package/build/types-code/shared/utils/config.d.ts +2 -0
- package/build/types-code/shared/utils/globalState.d.ts +20 -0
- package/build/types-code/shared/utils/index.d.ts +52 -0
- package/build/types-code/shared/utils/isomorphy/buildInfo.d.ts +23 -0
- package/build/types-code/shared/utils/isomorphy/environment-check.d.ts +11 -0
- package/build/types-code/shared/utils/isomorphy/index.d.ts +20 -0
- package/build/types-code/shared/utils/jest/E2eSsrEnv.d.ts +31 -0
- package/build/types-code/shared/utils/jest/global.d.ts +12 -0
- package/build/types-code/shared/utils/jest/index.d.ts +85 -0
- package/build/types-code/shared/utils/splitComponent.d.ts +41 -0
- package/build/types-code/shared/utils/time.d.ts +62 -0
- package/build/types-code/shared/utils/webpack.d.ts +18 -0
- package/build/types-scss/__tests__/js/config/publicPath support/__assets__/style.scss.d.ts +1 -0
- package/build/types-scss/__tests__/js/config/stylename-generation/__assets__/MockPackageA/TestComponent/style.scss.d.ts +1 -0
- package/build/types-scss/__tests__/js/config/stylename-generation/__assets__/MockPackageB/TestComponent/style.scss.d.ts +1 -0
- package/build/types-scss/__tests__/js/config/stylename-generation/__assets__/style.scss.d.ts +1 -0
- package/build/types-scss/__tests__/js/shared/components/NavLink/styles.scss.d.ts +1 -0
- package/build/types-scss/__tests__/js/shared/utils/splitComponent/__assets__/SampleScene/ComponentA/style.scss.d.ts +1 -0
- package/build/types-scss/__tests__/js/shared/utils/splitComponent/__assets__/SampleScene/ComponentB/style.scss.d.ts +1 -0
- package/build/types-scss/__tests__/js/shared/utils/splitComponent/__assets__/SampleScene/ComponentC/style.scss.d.ts +1 -0
- package/build/types-scss/__tests__/js/shared/utils/splitComponent/__assets__/SampleScene/style.scss.d.ts +1 -0
- package/build/types-scss/__tests__/ts/config/publicPath support/__assets__/style.scss.d.ts +1 -0
- package/build/types-scss/__tests__/ts/config/stylename-generation/__assets__/MockPackageA/TestComponent/style.scss.d.ts +1 -0
- package/build/types-scss/__tests__/ts/config/stylename-generation/__assets__/MockPackageB/TestComponent/style.scss.d.ts +1 -0
- package/build/types-scss/__tests__/ts/config/stylename-generation/__assets__/style.scss.d.ts +1 -0
- package/build/types-scss/__tests__/ts/shared/components/NavLink/styles.scss.d.ts +1 -0
- package/build/types-scss/__tests__/ts/shared/utils/splitComponent/__assets__/SampleScene/ComponentA/style.scss.d.ts +1 -0
- package/build/types-scss/__tests__/ts/shared/utils/splitComponent/__assets__/SampleScene/ComponentB/style.scss.d.ts +1 -0
- package/build/types-scss/__tests__/ts/shared/utils/splitComponent/__assets__/SampleScene/ComponentC/style.scss.d.ts +1 -0
- package/build/types-scss/__tests__/ts/shared/utils/splitComponent/__assets__/SampleScene/style.scss.d.ts +1 -0
- package/build/types-scss/src/shared/components/Button/style.scss.d.ts +6 -0
- package/build/types-scss/src/shared/components/Checkbox/theme.scss.d.ts +6 -0
- package/build/types-scss/src/shared/components/Dropdown/theme.scss.d.ts +9 -0
- package/build/types-scss/src/shared/components/GenericLink/style.scss.d.ts +1 -0
- package/build/types-scss/src/shared/components/Input/theme.scss.d.ts +6 -0
- package/build/types-scss/src/shared/components/Modal/base-theme.scss.d.ts +5 -0
- package/build/types-scss/src/shared/components/PageLayout/base-theme.scss.d.ts +6 -0
- package/build/types-scss/src/shared/components/ScalableRect/style.scss.d.ts +2 -0
- package/build/types-scss/src/shared/components/Throbber/theme.scss.d.ts +6 -0
- package/build/types-scss/src/shared/components/WithTooltip/default-theme.scss.d.ts +7 -0
- package/build/types-scss/src/shared/components/YouTubeVideo/base.scss.d.ts +5 -0
- package/build/types-scss/src/shared/components/YouTubeVideo/throbber.scss.d.ts +4 -0
- package/config/eslint/jest.json +3 -2
- package/config/eslint/typescript.js +34 -0
- package/config/jest/default.js +3 -3
- package/package.json +75 -33
- package/src/client/getInj.ts +43 -0
- package/src/client/index.tsx +40 -0
- package/src/client/init.ts +47 -0
- package/src/index.ts +58 -0
- package/src/server/Cache.ts +68 -0
- package/src/server/index.ts +230 -0
- package/src/server/renderer.tsx +604 -0
- package/src/server/server.ts +309 -0
- package/src/server/utils/errors.ts +135 -0
- package/src/server/utils/index.ts +3 -0
- package/src/shared/components/Button/index.tsx +146 -0
- package/src/shared/components/Button/style.scss +53 -0
- package/src/shared/components/Checkbox/index.tsx +71 -0
- package/src/shared/components/Checkbox/theme.scss +43 -0
- package/src/shared/components/Dropdown/index.tsx +144 -0
- package/src/shared/components/Dropdown/theme.scss +63 -0
- package/src/shared/components/GenericLink/index.tsx +157 -0
- package/src/shared/components/GenericLink/style.scss +3 -0
- package/src/shared/components/Input/index.tsx +59 -0
- package/src/shared/components/Input/theme.scss +27 -0
- package/src/shared/components/Link.tsx +21 -0
- package/src/shared/components/MetaTags.tsx +170 -0
- package/src/shared/components/Modal/base-theme.scss +38 -0
- package/src/shared/components/Modal/index.tsx +144 -0
- package/src/shared/components/Modal/styles.scss +5 -0
- package/src/shared/components/NavLink.tsx +13 -0
- package/src/shared/components/PageLayout/base-theme.scss +30 -0
- package/src/shared/components/PageLayout/index.tsx +76 -0
- package/src/shared/components/ScalableRect/index.tsx +84 -0
- package/src/shared/components/ScalableRect/style.scss +10 -0
- package/src/shared/components/Throbber/index.tsx +43 -0
- package/src/shared/components/Throbber/theme.scss +26 -0
- package/src/shared/components/WithTooltip/Tooltip.tsx +353 -0
- package/src/shared/components/WithTooltip/default-theme.scss +36 -0
- package/src/shared/components/WithTooltip/index.tsx +204 -0
- package/src/shared/components/YouTubeVideo/base.scss +13 -0
- package/src/shared/components/YouTubeVideo/index.tsx +96 -0
- package/src/shared/components/YouTubeVideo/throbber.scss +11 -0
- package/src/shared/components/index.ts +17 -0
- package/src/shared/utils/config.ts +21 -0
- package/src/shared/utils/globalState.ts +29 -0
- package/src/shared/utils/index.ts +105 -0
- package/src/shared/utils/isomorphy/buildInfo.ts +54 -0
- package/src/shared/utils/isomorphy/environment-check.ts +18 -0
- package/src/shared/utils/isomorphy/index.ts +38 -0
- package/src/shared/utils/jest/E2eSsrEnv.ts +250 -0
- package/src/shared/utils/jest/global.ts +19 -0
- package/src/shared/utils/jest/index.tsx +157 -0
- package/src/shared/utils/splitComponent.tsx +255 -0
- package/src/shared/utils/time.ts +118 -0
- package/src/shared/utils/webpack.ts +45 -0
- package/src/styles/_global/reset.css +52 -0
- package/src/styles/global.scss +11 -0
- package/tsconfig.configs.json +18 -0
- package/tsconfig.json +27 -0
- package/tsconfig.types.json +53 -0
- package/typed-scss-modules.config.ts +9 -0
- package/types.d.ts +37 -0
- package/{webpack.config.js → webpack.config.ts} +7 -3
- package/config/babel/node-ssr.js +0 -85
- package/config/babel/webpack.js +0 -122
- package/config/webpack/app-base.js +0 -330
- package/config/webpack/app-development.js +0 -80
- package/config/webpack/app-production.js +0 -60
- package/config/webpack/lib-base.js +0 -155
- package/config/webpack/lib-development.js +0 -45
- package/config/webpack/lib-production.js +0 -44
|
@@ -16,26 +16,26 @@
|
|
|
16
16
|
/* eslint-disable import/no-extraneous-dependencies */ /* eslint-enable import/no-extraneous-dependencies */class E2eSsrEnv extends _jestEnvironmentJsdom.default{/**
|
|
17
17
|
* Loads Webpack config, and exposes it to the environment via global
|
|
18
18
|
* webpackConfig object.
|
|
19
|
-
*/loadWebpackConfig(){
|
|
19
|
+
*/loadWebpackConfig(){const optionsString=this.pragmas["webpack-config-options"];const options=optionsString?JSON.parse(optionsString):{};(0,_lodash.defaults)(options,{context:this.testFolder,fs:this.global.webpackOutputFs});const factoryPath=this.pragmas["webpack-config-factory"];let factory=require(_path.default.resolve(this.rootDir,factoryPath));factory="default"in factory?factory.default:factory;this.global.webpackConfig=factory(options);const fs=this.global.webpackOutputFs;let buildInfo=`${options.context}/.build-info`;if(fs.existsSync(buildInfo)){buildInfo=fs.readFileSync(buildInfo,"utf8");this.global.buildInfo=JSON.parse(buildInfo)}}/**
|
|
20
20
|
* Executes Webpack build.
|
|
21
21
|
* @return {Promise}
|
|
22
|
-
*/async runWebpack(){this.loadWebpackConfig();const compiler=(0,_webpack.default)(this.global.webpackConfig);compiler.outputFileSystem=this.global.webpackOutputFs;return new Promise((done,fail)=>{compiler.run((err,stats)=>{if(err)fail(err);if(stats
|
|
22
|
+
*/async runWebpack(){this.loadWebpackConfig();const compiler=(0,_webpack.default)(this.global.webpackConfig);compiler.outputFileSystem=this.global.webpackOutputFs;return new Promise((done,fail)=>{compiler.run((err,stats)=>{if(err)fail(err);if(stats?.hasErrors()){// eslint-disable-next-line no-console
|
|
23
|
+
console.error(stats.toJson().errors);fail(Error("Webpack compilation failed"))}this.global.webpackStats=stats?.toJson();// Keeps reference to the raw Webpack stats object, which should be
|
|
23
24
|
// explicitly passed to the server-side renderer alongside the request,
|
|
24
25
|
// so that it can to pick up asset paths for different named chunks.
|
|
25
|
-
this.webpackStats=stats;done()})})}async runSsr(){
|
|
26
|
-
if(options.logger===undefined){options.logger={debug:_lodash.noop,info:_lodash.noop,log:_lodash.noop,warn:_lodash.noop}}let
|
|
27
|
-
// below, as the usual Jest Babel setup does not seem to apply to
|
|
28
|
-
// the environment code, and imports from it.
|
|
29
|
-
(0,_experimentalWorker.default)({envName:options.babelEnv,extensions:[".js",".jsx",".svg"],root});if(!options.buildInfo)options.buildInfo=this.global.buildInfo;if(options.entry){const p=_path.default.resolve(this.testFolder,options.entry);options.Application=require(p)[options.entryExportName||"default"]}const renderer=(0,_renderer.default)(this.global.webpackConfig,options);let status=200;// OK
|
|
26
|
+
this.webpackStats=stats;done()})})}async runSsr(){const optionsString=this.pragmas["ssr-options"];const options=optionsString?JSON.parse(optionsString):{};// TODO: This is temporary to shortcut the logging added to SSR.
|
|
27
|
+
if(options.logger===undefined){options.logger={debug:_lodash.noop,info:_lodash.noop,log:_lodash.noop,warn:_lodash.noop}}if(!options.buildInfo)options.buildInfo=this.global.buildInfo;let cleanup;if(options.entry){const p=_path.default.resolve(this.testFolder,options.entry);const module=require(p);cleanup=module.cleanup;options.Application=module[options.entryExportName||"default"]}const renderer=(0,_renderer.default)(this.global.webpackConfig,options);let status=200;// OK
|
|
30
28
|
const markup=await new Promise((done,fail)=>{renderer(this.ssrRequest,// TODO: This will do for now, with the current implementation of
|
|
31
29
|
// the renderer, but it will require a rework once the renderer is
|
|
32
30
|
// updated to do streaming.
|
|
33
31
|
{cookie:_lodash.noop,send:done,set:_lodash.noop,status:value=>{status=value},// This is how up-to-date Webpack stats are passed to the server in
|
|
34
32
|
// development mode, and we use this here always, instead of having
|
|
35
33
|
// to pass some information via filesystem.
|
|
36
|
-
locals:{webpack:{devMiddleware:{stats:this.webpackStats}}}},error=>{if(error)fail(error);else done("")})});this.global.ssrMarkup=markup;this.global.ssrOptions=options;this.global.ssrStatus=status}constructor(config,context){const pragmas=context.docblockPragmas;
|
|
34
|
+
locals:{webpack:{devMiddleware:{stats:this.webpackStats}}}},error=>{if(error)fail(error);else done("")})});this.global.ssrMarkup=markup;this.global.ssrOptions=options;this.global.ssrStatus=status;if(cleanup)cleanup()}constructor(config,context){const pragmas=context.docblockPragmas;const requestString=pragmas["ssr-request"];const request=requestString?JSON.parse(requestString):{};if(!request.url)request.url="/";request.csrfToken=_lodash.noop;// This ensures the initial JsDom URL matches the value we use for SSR.
|
|
37
35
|
(0,_lodash.set)(config.projectConfig,"testEnvironmentOptions.url",`http://localhost${request.url}`);super(config,context);this.global.dom=this.dom;this.global.webpackOutputFs=(0,_memfs.createFsFromVolume)(new _memfs.Volume);// Extracts necessary settings from config and context.
|
|
38
|
-
const{projectConfig}=config;this.rootDir=projectConfig.rootDir;this.testFolder=_path.default.dirname(context.testPath);this.withSsr=!pragmas["no-ssr"];this.ssrRequest=request;this.pragmas=pragmas
|
|
36
|
+
const{projectConfig}=config;this.rootDir=projectConfig.rootDir;this.testFolder=_path.default.dirname(context.testPath);this.withSsr=!pragmas["no-ssr"];this.ssrRequest=request;this.pragmas=pragmas;// The usual "babel-jest" transformation setup does not apply to
|
|
37
|
+
// the environment code and imports from it, this workaround enables it.
|
|
38
|
+
const optionsString=this.pragmas["ssr-options"];const options=optionsString?JSON.parse(optionsString):{};let root;switch(options.root){case"TEST":root=this.testFolder;break;default:root=process.cwd()}(0,_experimentalWorker.default)({envName:options.babelEnv,extensions:[".js",".jsx",".ts",".tsx",".svg"],root})}async setup(){await super.setup();await this.runWebpack();if(this.withSsr)await this.runSsr();this.global.REACT_UTILS_FORCE_CLIENT_SIDE=true}async teardown(){delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;// Resets module cache and @babel/register. Effectively this ensures that
|
|
39
39
|
// the next time an instance of this environment is set up, all modules are
|
|
40
40
|
// transformed by Babel from scratch, thus taking into account the latest
|
|
41
41
|
// Babel config (which may change between different environment instances,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"E2eSsrEnv.js","names":["_path","_interopRequireDefault","require","_lodash","_experimentalWorker","_jestEnvironmentJsdom","_memfs","_webpack","_renderer","E2eSsrEnv","JsdomEnv","loadWebpackConfig","options","pragmas","JSON","parse","defaults","context","testFolder","fs","global","webpackOutputFs","factory","path","resolve","rootDir","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","compiler","webpack","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","Error","webpackStats","runSsr","logger","undefined","debug","noop","info","log","warn","root","process","cwd","register","envName","babelEnv","extensions","entry","p","Application","entryExportName","renderer","ssrFactory","status","markup","ssrRequest","cookie","send","set","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","request","url","csrfToken","projectConfig","dom","createFsFromVolume","Volume","dirname","testPath","withSsr","setup","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","cache","forEach","key","revert","exports","default"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.js"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n/* eslint-disable global-require, import/no-dynamic-require */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\nimport path from 'path';\n\nimport { defaults, noop, set } from 'lodash';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register/experimental-worker';\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { createFsFromVolume, Volume } from 'memfs';\nimport webpack from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nimport ssrFactory from 'server/renderer';\n\nexport default class E2eSsrEnv extends JsdomEnv {\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n loadWebpackConfig() {\n let options = this.pragmas['webpack-config-options'];\n options = options ? JSON.parse(options) : {};\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n let factory = this.pragmas['webpack-config-factory'] || '';\n factory = require(path.resolve(this.rootDir, factory));\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8');\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack() {\n this.loadWebpackConfig();\n\n const compiler = webpack(this.global.webpackConfig);\n compiler.outputFileSystem = this.global.webpackOutputFs;\n return new Promise((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats.hasErrors()) {\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr() {\n let options = this.pragmas['ssr-options'];\n options = options ? JSON.parse(options) : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n if (options.logger === undefined) {\n options.logger = {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n }\n\n let root;\n switch (options.root) {\n case 'TEST': root = this.testFolder; break;\n default: root = process.cwd();\n }\n\n // Note: This enables Babel transformation for the code dynamically loaded\n // below, as the usual Jest Babel setup does not seem to apply to\n // the environment code, and imports from it.\n register({\n envName: options.babelEnv,\n extensions: ['.js', '.jsx', '.svg'],\n root,\n });\n\n if (!options.buildInfo) options.buildInfo = this.global.buildInfo;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry);\n options.Application = require(p)[options.entryExportName || 'default'];\n }\n\n const renderer = ssrFactory(this.global.webpackConfig, options);\n let status = 200; // OK\n const markup = await new Promise((done, fail) => {\n renderer(\n this.ssrRequest,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n {\n cookie: noop,\n send: done,\n set: noop,\n status: (value) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n },\n\n (error) => {\n if (error) fail(error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n }\n\n constructor(config, context) {\n const pragmas = context.docblockPragmas;\n let request = pragmas['ssr-request'];\n request = request ? JSON.parse(request) : {};\n if (!request.url) request.url = '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n }\n\n async setup() {\n await super.setup();\n await this.runWebpack();\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown() {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n super.teardown();\n }\n}\n"],"mappings":"gLAiBA,IAAAA,KAAA,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,CAACP,UAAU,CAAGK,aAAI,CAACmE,OAAO,CAACzE,OAAO,CAAC0E,QAAQ,CAAC,CAChD,IAAI,CAACC,OAAO,CAAG,CAAC/E,OAAO,CAAC,QAAQ,CAAC,CACjC,IAAI,CAACyD,UAAU,CAAGa,OAAO,CACzB,IAAI,CAACtE,OAAO,CAAGA,OACjB,CAEA,KAAM,CAAAgF,KAAKA,CAAA,CAAG,CACZ,KAAM,MAAK,CAACA,KAAK,CAAC,CAAC,CACnB,KAAM,KAAI,CAAC/D,UAAU,CAAC,CAAC,CACvB,GAAI,IAAI,CAAC8D,OAAO,CAAE,KAAM,KAAI,CAAC7C,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC3B,MAAM,CAAC0E,6BAA6B,CAAG,IAC9C,CAEA,KAAM,CAAAC,QAAQA,CAAA,CAAG,CACf,MAAO,KAAI,CAAC3E,MAAM,CAAC0E,6BAA6B,CAEhD;AACA;AACA;AACA;AACA;AACA;AACAE,MAAM,CAACC,IAAI,CAAC/F,OAAO,CAACgG,KAAK,CAAC,CAACC,OAAO,CAAEC,GAAG,EAAK,CAC1C,MAAO,CAAAlG,OAAO,CAACgG,KAAK,CAACE,GAAG,CAC1B,CAAC,CAAC,CACF1C,2BAAQ,CAAC2C,MAAM,CAAC,CAAC,CACjB,KAAK,CAACN,QAAQ,CAAC,CACjB,CACF,CAACO,OAAA,CAAAC,OAAA,CAAA9F,SAAA"}
|
|
1
|
+
{"version":3,"file":"E2eSsrEnv.js","names":["_path","_interopRequireDefault","require","_lodash","_experimentalWorker","_jestEnvironmentJsdom","_memfs","_webpack","_renderer","E2eSsrEnv","JsdomEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","defaults","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","path","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","compiler","webpack","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","Error","webpackStats","runSsr","logger","undefined","debug","noop","info","log","warn","cleanup","entry","p","module","Application","entryExportName","renderer","ssrFactory","status","markup","ssrRequest","cookie","send","set","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","createFsFromVolume","Volume","dirname","testPath","withSsr","root","process","cwd","register","envName","babelEnv","extensions","setup","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","cache","forEach","key","revert","exports"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n/* eslint-disable global-require, import/no-dynamic-require */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\nimport path from 'path';\n\nimport type { Request, Response } from 'express';\nimport { defaults, noop, set } from 'lodash';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register/experimental-worker';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { type IFs, createFsFromVolume, Volume } from 'memfs';\nimport webpack from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nimport ssrFactory from 'server/renderer';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: webpack.StatsCompilation;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString\n ? JSON.parse(optionsString) : {}) as webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n let factory = require(path.resolve(this.rootDir, factoryPath));\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs as IFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack() {\n this.loadWebpackConfig();\n\n const compiler = webpack(this.global.webpackConfig as webpack.Configuration);\n compiler.outputFileSystem = this.global.webpackOutputFs;\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr() {\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString ? JSON.parse(optionsString) : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n if (options.logger === undefined) {\n options.logger = {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n }\n\n if (!options.buildInfo) options.buildInfo = this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry);\n const module = require(p);\n cleanup = module.cleanup;\n options.Application = module[options.entryExportName || 'default'];\n }\n\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n if (error) fail(error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString ? JSON.parse(requestString) : {};\n\n if (!request.url) request.url = '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString ? JSON.parse(optionsString) : {};\n let root;\n switch (options.root) {\n case 'TEST': root = this.testFolder; break;\n default: root = process.cwd();\n }\n register({\n envName: options.babelEnv,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup() {\n await super.setup();\n await this.runWebpack();\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown() {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n super.teardown();\n }\n}\n"],"mappings":"gLAiBA,IAAAA,KAAA,CAAAC,sBAAA,CAAAC,OAAA,UAGA,IAAAC,OAAA,CAAAD,OAAA,WAKA,IAAAE,mBAAA,CAAAH,sBAAA,CAAAC,OAAA,yCAEA,IAAAG,qBAAA,CAAAJ,sBAAA,CAAAC,OAAA,4BACA,IAAAI,MAAA,CAAAJ,OAAA,UACA,IAAAK,QAAA,CAAAN,sBAAA,CAAAC,OAAA,aAGA,IAAAM,SAAA,CAAAP,sBAAA,CAAAC,OAAA,8BAhCA;AACA;AACA;AACA;AACA;AACA,GALA,CAMA,+DAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAOA;AACA;AACA,uDAMA,qDASe,KAAM,CAAAO,SAAS,QAAS,CAAAC,6BAAS,CAa9C;AACF;AACA;AACA,KACEC,iBAAiBA,CAAA,CAAG,CAClB,KAAM,CAAAC,aAAa,CAAG,IAAI,CAACC,OAAO,CAAC,wBAAwB,CAAW,CAEtE,KAAM,CAAAC,OAAO,CAAIF,aAAa,CAC1BG,IAAI,CAACC,KAAK,CAACJ,aAAa,CAAC,CAAG,CAAC,CAA2B,CAE5D,GAAAK,gBAAQ,EAACH,OAAO,CAAE,CAChBI,OAAO,CAAE,IAAI,CAACC,UAAU,CACxBC,EAAE,CAAE,IAAI,CAACC,MAAM,CAACC,eAClB,CAAC,CAAC,CAEF,KAAM,CAAAC,WAAW,CAAG,IAAI,CAACV,OAAO,CAAC,wBAAwB,CAAW,CACpE,GAAI,CA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MAAM,CAAC,CAAC,CACrC,IAAI,CAAC7B,MAAM,CAAC+E,6BAA6B,CAAG,IAC9C,CAEA,KAAM,CAAAC,QAAQA,CAAA,CAAG,CACf,MAAO,KAAI,CAAChF,MAAM,CAAC+E,6BAA6B,CAEhD;AACA;AACA;AACA;AACA;AACA;AACAE,MAAM,CAACC,IAAI,CAACrG,OAAO,CAACsG,KAAK,CAAC,CAACC,OAAO,CAAEC,GAAG,EAAK,CAC1C,MAAO,CAAAxG,OAAO,CAACsG,KAAK,CAACE,GAAG,CAC1B,CAAC,CAAC,CACFX,2BAAQ,CAACY,MAAM,CAAC,CAAC,CACjB,KAAK,CAACN,QAAQ,CAAC,CACjB,CACF,CAACO,OAAA,CAAAhF,OAAA,CAAAnB,SAAA"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=getGlobal;require("memfs");var _webpack=_interopRequireDefault(require("webpack"));/* eslint-disable import/no-extraneous-dependencies */ /* eslint-enable import/no-extraneous-dependencies */function getGlobal(){return global}
|
|
2
|
+
//# sourceMappingURL=global.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"global.js","names":["require","_webpack","_interopRequireDefault","getGlobal","global"],"sources":["../../../../../src/shared/utils/jest/global.ts"],"sourcesContent":["import { type IFs } from 'memfs';\n\n/* eslint-disable import/no-extraneous-dependencies */\nimport webpack from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\ndeclare global {\n interface Window {\n ssrMarkup: string | undefined;\n ssrStatus: number | undefined;\n webpackConfig: webpack.Configuration | undefined;\n webpackOutputFs: IFs;\n webpackStats?: webpack.StatsCompilation;\n }\n}\n\nexport default function getGlobal(): Window {\n return global as any;\n}\n"],"mappings":"mLAAAA,OAAA,UAGA,IAAAC,QAAA,CAAAC,sBAAA,CAAAF,OAAA,aADA,uDAEA,qDAYe,QAAS,CAAAG,SAASA,CAAA,CAAW,CAC1C,MAAO,CAAAC,MACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"act",{enumerable:true,get:function(){return _testUtils.act}});exports.getMockUuid=getMockUuid;exports.mockClientSide=mockClientSide;exports.mockTimer=mockTimer;exports.mount=mount;exports.render=render;exports.shallowRender=shallowRender;exports.shallowSnapshot=shallowSnapshot;exports.simulate=void 0;exports.snapshot=snapshot;exports.unmockClientSide=unmockClientSide;var _mockdate=_interopRequireDefault(require("mockdate"));var _client=require("react-dom/client");var _testUtils=_interopRequireWildcard(require("react-dom/test-utils"));var _reactTestRenderer=_interopRequireDefault(require("react-test-renderer"));var _shallow=
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"act",{enumerable:true,get:function(){return _testUtils.act}});Object.defineProperty(exports,"getGlobal",{enumerable:true,get:function(){return _global.default}});exports.getMockUuid=getMockUuid;exports.mockClientSide=mockClientSide;exports.mockTimer=mockTimer;exports.mount=mount;exports.render=render;exports.shallowRender=shallowRender;exports.shallowSnapshot=shallowSnapshot;exports.simulate=void 0;exports.snapshot=snapshot;exports.unmockClientSide=unmockClientSide;var _mockdate=_interopRequireDefault(require("mockdate"));require("react");var _client=require("react-dom/client");var _testUtils=_interopRequireWildcard(require("react-dom/test-utils"));var _reactTestRenderer=_interopRequireDefault(require("react-test-renderer"));var _shallow=require("react-test-renderer/shallow");var _global=_interopRequireDefault(require("./global"));function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var r=new WeakMap,t=new WeakMap;return(_getRequireWildcardCache=function(e){return e?t:r})(e)}function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var t=_getRequireWildcardCache(r);if(t&&t.has(e))return t.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in e)if("default"!==u&&Object.prototype.hasOwnProperty.call(e,u)){var i=a?Object.getOwnPropertyDescriptor(e,u):null;i&&(i.get||i.set)?Object.defineProperty(n,u,i):n[u]=e[u]}return n.default=e,t&&t.set(e,n),n}/* global expect, jest, document */ /* eslint-disable import/no-extraneous-dependencies */ /* eslint-disable import/no-extraneous-dependencies */ /* eslint-enable import/no-extraneous-dependencies */ /**
|
|
2
2
|
* An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)
|
|
3
3
|
* from `react-dom/test-utils`.
|
|
4
4
|
* @param {function} action
|
|
@@ -19,10 +19,10 @@
|
|
|
19
19
|
* be executed because of the mock time movement.
|
|
20
20
|
*/async function mockTimer(time){_mockdate.default.set(time+Date.now());jest.advanceTimersByTime(time)}/**
|
|
21
21
|
* Mounts `scene` to the DOM, and returns the root scene element.
|
|
22
|
-
* @param
|
|
23
|
-
* @return
|
|
22
|
+
* @param scene
|
|
23
|
+
* @return Created container DOM element with destroy() function
|
|
24
24
|
* attached.
|
|
25
|
-
*/function mount(scene){let root;const
|
|
25
|
+
*/function mount(scene){let root;const element=document.createElement("div");document.body.appendChild(element);const res=element;res.destroy=()=>{(0,_testUtils.act)(()=>root.unmount());res.remove()};(0,_testUtils.act)(()=>{root=(0,_client.createRoot)(res);root.render(scene)});return res}/* OLD STUFF BELOW THIS MARK */ /**
|
|
26
26
|
* Renders provided ReactJS component into JSON representation of the component
|
|
27
27
|
* tree, using [`react-test-renderer`](https://www.npmjs.com/package/react-test-renderer).
|
|
28
28
|
* @param {object} component ReactJS component to render.
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
* and returns the result.
|
|
37
37
|
* @param {object} component ReactJS component to render.
|
|
38
38
|
* @return {object} JSON representation of the shallow component's render tree.
|
|
39
|
-
*/function shallowRender(component){const renderer=
|
|
39
|
+
*/function shallowRender(component){const renderer=(0,_shallow.createRenderer)();renderer.render(component);return renderer.getRenderOutput()}/**
|
|
40
40
|
* Makes a shallow snapshot test of the given ReactJS component, and also
|
|
41
41
|
* returns JSON representation of the rendered component tree. Under the hood
|
|
42
42
|
* it uses {@link module:JU.shallowRender shallowRender(..)} to generate
|
|
@@ -51,5 +51,5 @@
|
|
|
51
51
|
* `expect(RENDER_RESULT).toMatchSnapshot()`, and then returns `RENDER_RESULT`.
|
|
52
52
|
* @param {object} component ReactJS component to render.
|
|
53
53
|
* @return {object} JSON render of the component.
|
|
54
|
-
*/function snapshot(component){const res=render(component);expect(res).toMatchSnapshot();return res}const simulate=_testUtils.default.Simulate;
|
|
54
|
+
*/function snapshot(component){const res=render(component);expect(res).toMatchSnapshot();return res}const simulate=exports.simulate=_testUtils.default.Simulate;
|
|
55
55
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_mockdate","_interopRequireDefault","require","_client","_testUtils","_interopRequireWildcard","_reactTestRenderer","_shallow","
|
|
1
|
+
{"version":3,"file":"index.js","names":["_mockdate","_interopRequireDefault","require","_client","_testUtils","_interopRequireWildcard","_reactTestRenderer","_shallow","_global","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","value","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockTimer","time","mockdate","Date","now","jest","advanceTimersByTime","mount","scene","root","element","document","createElement","body","appendChild","res","destroy","act","unmount","remove","createRoot","render","component","Renderer","create","toJSON","shallowRender","renderer","createRenderer","getRenderOutput","shallowSnapshot","expect","toMatchSnapshot","snapshot","simulate","exports","TU","Simulate"],"sources":["../../../../../src/shared/utils/jest/index.tsx"],"sourcesContent":["/* global expect, jest, document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\nimport TU, { act } from 'react-dom/test-utils';\n\n/* eslint-disable import/no-extraneous-dependencies */\nimport Renderer from 'react-test-renderer';\nimport { type ShallowRenderer, createRenderer } from 'react-test-renderer/shallow';\n/* eslint-enable import/no-extraneous-dependencies */\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react-dom/test-utils`.\n * @param {function} action\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\ndeclare global {\n // eslint-disable-next-line no-var, vars-on-top\n var IS_REACT_ACT_ENVIRONMENT: boolean | undefined;\n}\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide() {\n Object.defineProperty(process, 'versions', { value: null });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide() {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0) {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number) {\n mockdate.set(time + Date.now());\n jest.advanceTimersByTime(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n act(() => root.unmount());\n res.remove();\n };\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n/* OLD STUFF BELOW THIS MARK */\n\n/**\n * Renders provided ReactJS component into JSON representation of the component\n * tree, using [`react-test-renderer`](https://www.npmjs.com/package/react-test-renderer).\n * @param {object} component ReactJS component to render.\n * @return {object} JSON representation of the rendered tree.\n * @example\n * import { JU } from '@dr.pogodin/react-utils';\n * console.log(JU.render(<div>Example</div>));\n */\nexport function render(component: ReactElement) {\n return Renderer.create(component).toJSON();\n}\n\n/**\n * Generates a shallow render of given ReactJS component, using\n * [react-test-renderer/shallow](https://reactjs.org/docs/shallow-renderer.html)\n * and returns the result.\n * @param {object} component ReactJS component to render.\n * @return {object} JSON representation of the shallow component's render tree.\n */\nexport function shallowRender(component: ReactElement) {\n const renderer: ShallowRenderer = createRenderer();\n renderer.render(component);\n return renderer.getRenderOutput();\n}\n\n/**\n * Makes a shallow snapshot test of the given ReactJS component, and also\n * returns JSON representation of the rendered component tree. Under the hood\n * it uses {@link module:JU.shallowRender shallowRender(..)} to generate\n * the render, then executes `expect(RENDER_RESULT).toMatchSnapshot()`,\n * and finally returns the `RENDER_RESULT` to the caller.\n * @param {object} component ReactJS component to render.\n * @return {object} JSON representation of shallow render.\n */\nexport function shallowSnapshot(component: ReactElement) {\n const res = shallowRender(component);\n expect(res).toMatchSnapshot();\n return res;\n}\n\n/**\n * Makes snapshot test of the given ReactJS component, and also returns JSON\n * representation of the rendered component tree. Under the hood, it uses\n * {@link module:JU.render render(..)} to render it, then executes\n * `expect(RENDER_RESULT).toMatchSnapshot()`, and then returns `RENDER_RESULT`.\n * @param {object} component ReactJS component to render.\n * @return {object} JSON render of the component.\n */\nexport function snapshot(component: ReactElement) {\n const res = render(component);\n expect(res).toMatchSnapshot();\n return res;\n}\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AACJ,SAAS,CAAC,CACpCS,MAAM,CAAChB,GAAG,CAAC,CAACiB,eAAe,CAAC,CAAC,CAC7B,MAAO,CAAAjB,GACT,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAAS,CAAAkB,QAAQA,CAACX,SAAuB,CAAE,CAChD,KAAM,CAAAP,GAAG,CAAGM,MAAM,CAACC,SAAS,CAAC,CAC7BS,MAAM,CAAChB,GAAG,CAAC,CAACiB,eAAe,CAAC,CAAC,CAC7B,MAAO,CAAAjB,GACT,CAEO,KAAM,CAAAmB,QAAQ,CAAAC,OAAA,CAAAD,QAAA,CAAGE,kBAAE,CAACC,QAAQ"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.bookStyleSheets=bookStyleSheets;exports.default=splitComponent;exports.freeStyleSheets=freeStyleSheets;var _propTypes=_interopRequireDefault(require("prop-types"));var _react=require("react");var _jsUtils=require("@dr.pogodin/js-utils");var
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.bookStyleSheets=bookStyleSheets;exports.default=splitComponent;exports.freeStyleSheets=freeStyleSheets;var _propTypes=_interopRequireDefault(require("prop-types"));var _react=require("react");var _jsUtils=require("@dr.pogodin/js-utils");var _globalState=require("./globalState");var _isomorphy=require("./isomorphy");var _jsxRuntime=require("react/jsx-runtime");/* eslint-disable react/jsx-props-no-spreading */ /* global document */ // Note: At the client side we can get chunk groups immediately when loading
|
|
2
2
|
// the module; at the server-side we only can get them within React render flow.
|
|
3
3
|
// Thus, we set and use the following variable at the client-side, and then when
|
|
4
4
|
// needed on the server side, we'll fetch it differently.
|
|
@@ -7,22 +7,22 @@ clientChunkGroups=require("../../client/getInj").default().CHUNK_GROUPS||{}}cons
|
|
|
7
7
|
* Client-side only! Ensures the specified CSS stylesheet is loaded into
|
|
8
8
|
* the document; loads if it is missing; and does simple reference counting
|
|
9
9
|
* to facilitate future clean-up.
|
|
10
|
-
* @param
|
|
11
|
-
* @param
|
|
12
|
-
* @param
|
|
13
|
-
* @return
|
|
14
|
-
*/function bookStyleSheet(name,loadedSheets,refCount){let res;const path=`${getPublicPath()}/${name}`;const fullPath=`${document.location.origin}${path}`;if(!loadedSheets.has(fullPath)){let link=document.querySelector(`link[href="${path}"]`);if(!link){link=document.createElement("link");link.setAttribute("rel","stylesheet");link.setAttribute("href",path);document.head.appendChild(link)}res=new _jsUtils.Barrier;link.addEventListener("load",res.resolve);link.addEventListener("error",res.resolve)}if(refCount){const current=refCounts[path]||0;refCounts[path]=1+current}return res}/**
|
|
10
|
+
* @param name
|
|
11
|
+
* @param loadedSheets
|
|
12
|
+
* @param refCount
|
|
13
|
+
* @return
|
|
14
|
+
*/function bookStyleSheet(name,loadedSheets,refCount){let res;const path=`${getPublicPath()}/${name}`;const fullPath=`${document.location.origin}${path}`;if(!loadedSheets.has(fullPath)){let link=document.querySelector(`link[href="${path}"]`);if(!link){link=document.createElement("link");link.setAttribute("rel","stylesheet");link.setAttribute("href",path);document.head.appendChild(link)}res=new _jsUtils.Barrier;link.addEventListener("load",()=>res.resolve());link.addEventListener("error",()=>res.resolve())}if(refCount){const current=refCounts[path]||0;refCounts[path]=1+current}return res}/**
|
|
15
15
|
* Generates the set of URLs for currently loaded, linked stylesheets.
|
|
16
|
-
* @return
|
|
16
|
+
* @return
|
|
17
17
|
*/function getLoadedStyleSheets(){const res=new Set;const{styleSheets}=document;for(let i=0;i<styleSheets.length;++i){const{href}=styleSheets[i];if(href)res.add(href)}return res}function assertChunkName(chunkName,chunkGroups){if(chunkGroups[chunkName])return;throw Error(`Unknown chunk name "${chunkName}"`)}/**
|
|
18
18
|
* Client-side only! Ensures all CSS stylesheets required for the specified
|
|
19
19
|
* code chunk are loaded into the document; loads the missing ones; and does
|
|
20
20
|
* simple reference counting to facilitate future clean-up.
|
|
21
|
-
* @param
|
|
22
|
-
* @param
|
|
23
|
-
* @return
|
|
21
|
+
* @param chunkName Chunk name.
|
|
22
|
+
* @param refCount
|
|
23
|
+
* @return Resolves once all pending stylesheets, necessary for
|
|
24
24
|
* the chunk, are either loaded, or failed to load.
|
|
25
|
-
*/function bookStyleSheets(chunkName,chunkGroups,refCount){const promises=[];const assets=chunkGroups[chunkName];const loadedSheets=getLoadedStyleSheets();for(let i=0;i<assets.length;++i){const asset=assets[i];if(asset.endsWith(".css")){const promise=bookStyleSheet(asset,loadedSheets,refCount);if(promise)promises.push(promise)}}return promises.length?Promise.allSettled(promises):Promise.resolve()}/**
|
|
25
|
+
*/function bookStyleSheets(chunkName,chunkGroups,refCount){const promises=[];const assets=chunkGroups[chunkName];const loadedSheets=getLoadedStyleSheets();for(let i=0;i<assets.length;++i){const asset=assets[i];if(asset.endsWith(".css")){const promise=bookStyleSheet(asset,loadedSheets,refCount);if(promise)promises.push(promise)}}return promises.length?Promise.allSettled(promises).then():Promise.resolve()}/**
|
|
26
26
|
* Client-side only! Frees from the document all CSS stylesheets that are
|
|
27
27
|
* required by the specified chunk, and have reference counter equal to one
|
|
28
28
|
* (for chunks with larger reference counter values, it just decrements
|
|
@@ -33,19 +33,19 @@ const usedChunkNames=new Set;/**
|
|
|
33
33
|
* Given an async component retrieval function `getComponent()` it creates
|
|
34
34
|
* a special "code split" component, which uses <Suspense> to asynchronously
|
|
35
35
|
* load on demand the code required by `getComponent()`.
|
|
36
|
-
* @param
|
|
37
|
-
* @param
|
|
36
|
+
* @param options
|
|
37
|
+
* @param options.chunkName
|
|
38
38
|
* @param {function} options.getComponent
|
|
39
39
|
* @param {React.Element} [options.placeholder]
|
|
40
40
|
* @return {React.ElementType}
|
|
41
41
|
*/function splitComponent({chunkName,getComponent,placeholder}){// On the client side we can check right away if the chunk name is known.
|
|
42
42
|
if(_isomorphy.IS_CLIENT_SIDE)assertChunkName(chunkName,clientChunkGroups);// The correct usage of splitComponent() assumes a single call per chunk.
|
|
43
|
-
if(usedChunkNames.has(chunkName)){throw Error(`Repeated splitComponent() call for the chunk "${chunkName}"`)}else usedChunkNames.add(chunkName);const LazyComponent=/*#__PURE__*/(0,_react.lazy)(async()=>{
|
|
43
|
+
if(usedChunkNames.has(chunkName)){throw Error(`Repeated splitComponent() call for the chunk "${chunkName}"`)}else usedChunkNames.add(chunkName);const LazyComponent=/*#__PURE__*/(0,_react.lazy)(async()=>{const resolved=await getComponent();const Component="default"in resolved?resolved.default:resolved;// This pre-loads necessary stylesheets prior to the first mount of
|
|
44
44
|
// the component (the lazy load function is executed by React one at
|
|
45
45
|
// the frist mount).
|
|
46
46
|
if(_isomorphy.IS_CLIENT_SIDE){await bookStyleSheets(chunkName,clientChunkGroups,false)}const Wrapper=/*#__PURE__*/(0,_react.forwardRef)(({children,...rest},ref)=>{// On the server side we'll assert the chunk name here,
|
|
47
47
|
// and also push it to the SSR chunks array.
|
|
48
|
-
if(_isomorphy.IS_SERVER_SIDE){const{chunkGroups,chunks}=(0,
|
|
48
|
+
if(_isomorphy.IS_SERVER_SIDE){const{chunkGroups,chunks}=(0,_globalState.getSsrContext)();assertChunkName(chunkName,chunkGroups);if(!chunks.includes(chunkName))chunks.push(chunkName)}// This takes care about stylesheets management every time an instance of
|
|
49
49
|
// this component is mounted / unmounted.
|
|
50
|
-
(0,_react.useInsertionEffect)(()=>{bookStyleSheets(chunkName,clientChunkGroups,true);return()=>freeStyleSheets(chunkName,clientChunkGroups)},[]);return/*#__PURE__*/(0,_jsxRuntime.jsx)(Component,{ref:ref,...rest,children:children})});
|
|
50
|
+
(0,_react.useInsertionEffect)(()=>{bookStyleSheets(chunkName,clientChunkGroups,true);return()=>freeStyleSheets(chunkName,clientChunkGroups)},[]);return/*#__PURE__*/(0,_jsxRuntime.jsx)(Component,{ref:ref,...rest,children:children})});return{default:Wrapper}});const CodeSplit=({children,...rest})=>/*#__PURE__*/(0,_jsxRuntime.jsx)(_react.Suspense,{fallback:placeholder,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(LazyComponent,{...rest,children:children})});CodeSplit.propTypes={children:_propTypes.default.node};CodeSplit.defaultProps={children:undefined};return CodeSplit}
|
|
51
51
|
//# sourceMappingURL=splitComponent.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"splitComponent.js","names":["_propTypes","_interopRequireDefault","require","_react","_jsUtils","_reactGlobalState","_isomorphy","_jsxRuntime","clientChunkGroups","IS_CLIENT_SIDE","default","CHUNK_GROUPS","refCounts","getPublicPath","getBuildInfo","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","Barrier","addEventListener","resolve","current","getLoadedStyleSheets","Set","styleSheets","i","length","href","add","assertChunkName","chunkName","chunkGroups","Error","bookStyleSheets","promises","assets","asset","endsWith","promise","push","Promise","allSettled","freeStyleSheets","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","Component","Wrapper","forwardRef","children","rest","ref","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","jsx","propTypes","PT","node","defaultProps","undefined","CodeSplit","Suspense","fallback"],"sources":["../../../../src/shared/utils/splitComponent.jsx"],"sourcesContent":["/* eslint-disable react/jsx-props-no-spreading */\n/* global document */\n\nimport PT from 'prop-types';\n\nimport {\n forwardRef,\n lazy,\n Suspense,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\nimport { getSsrContext } from '@dr.pogodin/react-global-state';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from 'utils/isomorphy';\n\n// Note: At the client side we can get chunk groups immediately when loading\n// the module; at the server-side we only can get them within React render flow.\n// Thus, we set and use the following variable at the client-side, and then when\n// needed on the server side, we'll fetch it differently.\nlet clientChunkGroups;\nif (IS_CLIENT_SIDE) {\n // eslint-disable-next-line global-require\n clientChunkGroups = require('client/getInj').default().CHUNK_GROUPS || {};\n}\n\nconst refCounts = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param {string} name\n * @param {Set} loadedSheets\n * @param {boolean} refCount\n * @return {Promise}\n */\nfunction bookStyleSheet(name, loadedSheets, refCount) {\n let res;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier();\n link.addEventListener('load', res.resolve);\n link.addEventListener('error', res.resolve);\n }\n\n if (refCount) {\n const current = refCounts[path] || 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return {Set}\n */\nfunction getLoadedStyleSheets() {\n const res = new Set();\n const { styleSheets } = document;\n for (let i = 0; i < styleSheets.length; ++i) {\n const { href } = styleSheets[i];\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(chunkName, chunkGroups) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param {string} chunkName Chunk name.\n * @param {boolean} refCount\n * @return {Promise} Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport function bookStyleSheets(chunkName, chunkGroups, refCount) {\n const promises = [];\n const assets = chunkGroups[chunkName];\n const loadedSheets = getLoadedStyleSheets();\n\n for (let i = 0; i < assets.length; ++i) {\n const asset = assets[i];\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length ? Promise.allSettled(promises) : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(chunkName, chunkGroups) {\n const assets = chunkGroups[chunkName];\n for (let i = 0; i < assets.length; ++i) {\n const asset = assets[i];\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n if (--refCounts[path] <= 0) {\n document.head.querySelector(`link[href=\"${path}\"]`).remove();\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param {object} options\n * @param {string} options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent({\n chunkName,\n getComponent,\n placeholder,\n}) {\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) assertChunkName(chunkName, clientChunkGroups);\n\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n let Component = await getComponent();\n if (Component.default) Component = Component.default;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper = forwardRef(({ children, ...rest }, ref) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext();\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => freeStyleSheets(chunkName, clientChunkGroups);\n }, []);\n\n return <Component ref={ref} {...rest}>{children}</Component>;\n });\n\n Wrapper.propTypes = {\n children: PT.node,\n };\n\n Wrapper.defaultProps = {\n children: undefined,\n };\n\n return { default: Wrapper };\n });\n\n function CodeSplit({ children, ...rest }) {\n return (\n <Suspense fallback={placeholder}>\n <LazyComponent {...rest}>\n {children}\n </LazyComponent>\n </Suspense>\n );\n }\n\n CodeSplit.propTypes = {\n children: PT.node,\n };\n\n CodeSplit.defaultProps = {\n children: undefined,\n };\n\n return CodeSplit;\n}\n"],"mappings":"wQAGA,IAAAA,UAAA,CAAAC,sBAAA,CAAAC,OAAA,gBAEA,IAAAC,MAAA,CAAAD,OAAA,UAOA,IAAAE,QAAA,CAAAF,OAAA,yBACA,IAAAG,iBAAA,CAAAH,OAAA,mCAEA,IAAAI,UAAA,CAAAJ,OAAA,gBAIyB,IAAAK,WAAA,CAAAL,OAAA,sBAnBzB,kDACA,sBAoBA;AACA;AACA;AACA;AACA,GAAI,CAAAM,iBAAiB,CACrB,GAAIC,yBAAc,CAAE,CAClB;AACAD,iBAAiB,CAAGN,OAAO,sBAAgB,CAAC,CAACQ,OAAO,CAAC,CAAC,CAACC,YAAY,EAAI,CAAC,CAC1E,CAEA,KAAM,CAAAC,SAAS,CAAG,CAAC,CAAC,CAEpB,QAAS,CAAAC,aAAaA,CAAA,CAAG,CACvB,MAAO,GAAAC,uBAAY,EAAC,CAAC,CAACC,UACxB,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,CAAAC,cAAcA,CAACC,IAAI,CAAEC,YAAY,CAAEC,QAAQ,CAAE,CACpD,GAAI,CAAAC,GAAG,CACP,KAAM,CAAAC,IAAI,CAAI,GAAER,aAAa,CAAC,CAAE,IAAGI,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S,CAACF,YAAY,CAAG,CACvBZ,QAAQ,CAAEa,SACZ,CAAC,CAED,MAAO,CAAAC,SACT"}
|
|
1
|
+
{"version":3,"file":"splitComponent.js","names":["_propTypes","_interopRequireDefault","require","_react","_jsUtils","_globalState","_isomorphy","_jsxRuntime","clientChunkGroups","IS_CLIENT_SIDE","default","CHUNK_GROUPS","refCounts","getPublicPath","getBuildInfo","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","Barrier","addEventListener","resolve","current","getLoadedStyleSheets","Set","styleSheets","i","length","href","add","assertChunkName","chunkName","chunkGroups","Error","bookStyleSheets","promises","assets","asset","endsWith","promise","push","Promise","allSettled","then","freeStyleSheets","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","resolved","Component","Wrapper","forwardRef","children","rest","ref","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","jsx","CodeSplit","Suspense","fallback","propTypes","PT","node","defaultProps","undefined"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* eslint-disable react/jsx-props-no-spreading */\n/* global document */\n\nimport PT from 'prop-types';\n\nimport {\n type ComponentType,\n type ReactNode,\n forwardRef,\n lazy,\n Suspense,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\n// Note: At the client side we can get chunk groups immediately when loading\n// the module; at the server-side we only can get them within React render flow.\n// Thus, we set and use the following variable at the client-side, and then when\n// needed on the server side, we'll fetch it differently.\nlet clientChunkGroups: ChunkGroupsT;\n\nif (IS_CLIENT_SIDE) {\n // eslint-disable-next-line global-require\n clientChunkGroups = require('client/getInj').default().CHUNK_GROUPS || {};\n}\n\nconst refCounts: { [path: string]: number } = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => res!.resolve());\n link.addEventListener('error', () => res!.resolve());\n }\n\n if (refCount) {\n const current = refCounts[path] || 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (let i = 0; i < styleSheets.length; ++i) {\n const { href } = styleSheets[i];\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n const loadedSheets = getLoadedStyleSheets();\n\n for (let i = 0; i < assets.length; ++i) {\n const asset = assets[i];\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n const assets = chunkGroups[chunkName];\n for (let i = 0; i < assets.length; ++i) {\n const asset = assets[i];\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n if (--refCounts[path] <= 0) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>,\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends { children?: ReactNode },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>,\n placeholder?: ReactNode,\n}) {\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) assertChunkName(chunkName, clientChunkGroups);\n\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper = forwardRef((\n { children, ...rest }: ComponentPropsT,\n ref,\n ) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => freeStyleSheets(chunkName, clientChunkGroups);\n }, []);\n\n return (\n <Component ref={ref} {...rest as ComponentPropsT}>\n {children}\n </Component>\n );\n });\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent {...rest as Parameters<typeof LazyComponent>[0]}>\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n CodeSplit.propTypes = {\n children: PT.node,\n } as React.WeakValidationMap<ComponentPropsT>;\n\n CodeSplit.defaultProps = {\n children: undefined,\n } as Partial<ComponentPropsT>;\n\n return CodeSplit;\n}\n"],"mappings":"wQAGA,IAAAA,UAAA,CAAAC,sBAAA,CAAAC,OAAA,gBAEA,IAAAC,MAAA,CAAAD,OAAA,UASA,IAAAE,QAAA,CAAAF,OAAA,yBAEA,IAAAG,YAAA,CAAAH,OAAA,kBAEA,IAAAI,UAAA,CAAAJ,OAAA,gBAIqB,IAAAK,WAAA,CAAAL,OAAA,sBAtBrB,kDACA,sBAuBA;AACA;AACA;AACA;AACA,GAAI,CAAAM,iBAA+B,CAEnC,GAAIC,yBAAc,CAAE,CAClB;AACAD,iBAAiB,CAAGN,OAAO,sBAAgB,CAAC,CAACQ,OAAO,CAAC,CAAC,CAACC,YAAY,EAAI,CAAC,CA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,GAAAhE,WAAA,CAAAuE,GAAA,EAAC3E,MAAA,CAAA6E,QAAQ,EAACC,QAAQ,CAAElB,WAAY,CAAAO,QAAA,cAC9B,GAAA/D,WAAA,CAAAuE,GAAA,EAACd,aAAa,KAAKO,IAAI,CAAAD,QAAA,CACpBA,QAAQ,CACI,CAAC,CACR,CACX,CAEDS,SAAS,CAACG,SAAS,CAAG,CACpBZ,QAAQ,CAAEa,kBAAE,CAACC,IACf,CAA6C,CAE7CL,SAAS,CAACM,YAAY,CAAG,CACvBf,QAAQ,CAAEgB,SACZ,CAA6B,CAE7B,MAAO,CAAAP,SACT"}
|
|
@@ -1,23 +1,25 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;exports.useCurrent=useCurrent;exports.useTimezoneOffset=useTimezoneOffset;var _cookie=_interopRequireDefault(require("cookie"));var _dayjs=_interopRequireDefault(require("dayjs"));var
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;exports.useCurrent=useCurrent;exports.useTimezoneOffset=useTimezoneOffset;var _cookie=_interopRequireDefault(require("cookie"));var _dayjs=_interopRequireDefault(require("dayjs"));var _react=require("react");var _jsUtils=require("@dr.pogodin/js-utils");var _reactGlobalState=require("@dr.pogodin/react-global-state");var _globalState=require("./globalState");/* global document */ /**
|
|
2
2
|
* This react hook wraps Date.now() function in a SSR friendly way,
|
|
3
3
|
* ensuring that all calls to useCurrent() within the same render return
|
|
4
4
|
* exactly the same time (which is retrieved from Date.now() first, and
|
|
5
5
|
* then stored in the global state to be reused in all other calls), which
|
|
6
6
|
* is also passed and used in the first client side render, and then updated
|
|
7
7
|
* with a finite precision to avoid infinite re-rendering loops.
|
|
8
|
-
* @param
|
|
9
|
-
* @param
|
|
8
|
+
* @param [options] Optional settings.
|
|
9
|
+
* @param [options.globalStatePath="currentTime"] Global state path
|
|
10
10
|
* to keep the current time value.
|
|
11
|
-
* @param
|
|
11
|
+
* @param [options.precision= 5 * time.SEC_MS] Current time precision.
|
|
12
12
|
* The hook won't update the current time stored in the global state unless it
|
|
13
13
|
* is different from Date.now() result by this number (in milliseconds).
|
|
14
14
|
* Default to 5 seconds.
|
|
15
|
-
* @param
|
|
15
|
+
* @param [options.autorefresh=false] Set `true` to automatically
|
|
16
16
|
* refresh time stored in the global state with the given `precision` (and
|
|
17
17
|
* thus automatically re-rendering components dependent on this hook, or
|
|
18
18
|
* the global state with the period equal to the `precision`.
|
|
19
|
-
* @return
|
|
20
|
-
*/
|
|
19
|
+
* @return Unix timestamp in milliseconds.
|
|
20
|
+
*/ // TODO: Should we request the state type as generic parameter, to be able
|
|
21
|
+
// to verify the give globalStatePath is correct?
|
|
22
|
+
function useCurrent({autorefresh=false,globalStatePath="currentTime",precision=5*_jsUtils.SEC_MS}={}){const[now,setter]=(0,_reactGlobalState.useGlobalState)(globalStatePath,Date.now);(0,_react.useEffect)(()=>{let timerId;const update=()=>{setter(old=>{const neu=Date.now();return Math.abs(neu-old)>precision?neu:old});if(autorefresh)timerId=setTimeout(update,precision)};update();return()=>{if(timerId)clearTimeout(timerId)}},[autorefresh,precision,setter]);return now}/**
|
|
21
23
|
* Wraps the standard Date.getTimezoneOffset() method in a SSR-friendly way.
|
|
22
24
|
* This hook retrieves the offset value at the client side and uses a cookie
|
|
23
25
|
* to pass it to the server in subsequent requests from that user. At the server
|
|
@@ -35,5 +37,7 @@
|
|
|
35
37
|
* @param {string} [options.timezoneOffset="timezoneOffset"] Optional.
|
|
36
38
|
* The global state path to store the offset. Defaults "timezoneOffset".
|
|
37
39
|
* @return {number} Timezone offset.
|
|
38
|
-
*/
|
|
40
|
+
*/ // TODO: Should we request the state type as generic parameter, to be able
|
|
41
|
+
// to verify the give globalStatePath is correct?
|
|
42
|
+
function useTimezoneOffset({cookieName="timezoneOffset",globalStatePath="timezoneOffset"}={}){const ssrContext=(0,_globalState.getSsrContext)(false);const[offset,setOffset]=(0,_reactGlobalState.useGlobalState)(globalStatePath,()=>{const value=cookieName&&ssrContext?.req?.cookies?.[cookieName];return value?parseInt(value,10):0});(0,_react.useEffect)(()=>{const date=new Date;const value=date.getTimezoneOffset();setOffset(value);if(cookieName){document.cookie=_cookie.default.serialize(cookieName,value.toString(),{path:"/"})}},[cookieName,setOffset]);return offset}const time={DAY_MS:_jsUtils.DAY_MS,HOUR_MS:_jsUtils.HOUR_MS,MIN_MS:_jsUtils.MIN_MS,SEC_MS:_jsUtils.SEC_MS,YEAR_MS:_jsUtils.YEAR_MS,now:Date.now,timer:_jsUtils.timer,useCurrent,useTimezoneOffset};var _default=exports.default=Object.assign(_dayjs.default,time);
|
|
39
43
|
//# sourceMappingURL=time.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"time.js","names":["_cookie","_interopRequireDefault","require","_dayjs","
|
|
1
|
+
{"version":3,"file":"time.js","names":["_cookie","_interopRequireDefault","require","_dayjs","_react","_jsUtils","_reactGlobalState","_globalState","useCurrent","autorefresh","globalStatePath","precision","SEC_MS","now","setter","useGlobalState","Date","useEffect","timerId","update","old","neu","Math","abs","setTimeout","clearTimeout","useTimezoneOffset","cookieName","ssrContext","getSsrContext","offset","setOffset","value","req","cookies","parseInt","date","getTimezoneOffset","document","cookie","Cookie","serialize","toString","path","time","DAY_MS","HOUR_MS","MIN_MS","YEAR_MS","timer","_default","exports","default","Object","assign","dayjs"],"sources":["../../../../src/shared/utils/time.ts"],"sourcesContent":["/* global document */\n\nimport Cookie from 'cookie';\nimport dayjs from 'dayjs';\nimport { useEffect } from 'react';\n\nimport {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n timer,\n} from '@dr.pogodin/js-utils';\n\nimport { type ForceT, useGlobalState } from '@dr.pogodin/react-global-state';\n\nimport { getSsrContext } from './globalState';\n\n/**\n * This react hook wraps Date.now() function in a SSR friendly way,\n * ensuring that all calls to useCurrent() within the same render return\n * exactly the same time (which is retrieved from Date.now() first, and\n * then stored in the global state to be reused in all other calls), which\n * is also passed and used in the first client side render, and then updated\n * with a finite precision to avoid infinite re-rendering loops.\n * @param [options] Optional settings.\n * @param [options.globalStatePath=\"currentTime\"] Global state path\n * to keep the current time value.\n * @param [options.precision= 5 * time.SEC_MS] Current time precision.\n * The hook won't update the current time stored in the global state unless it\n * is different from Date.now() result by this number (in milliseconds).\n * Default to 5 seconds.\n * @param [options.autorefresh=false] Set `true` to automatically\n * refresh time stored in the global state with the given `precision` (and\n * thus automatically re-rendering components dependent on this hook, or\n * the global state with the period equal to the `precision`.\n * @return Unix timestamp in milliseconds.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useCurrent({\n autorefresh = false,\n globalStatePath = 'currentTime',\n precision = 5 * SEC_MS,\n} = {}) {\n const [now, setter] = useGlobalState<ForceT, number>(globalStatePath, Date.now);\n useEffect(() => {\n let timerId: NodeJS.Timeout;\n const update = () => {\n setter((old) => {\n const neu = Date.now();\n return Math.abs(neu - old) > precision ? neu : old;\n });\n if (autorefresh) timerId = setTimeout(update, precision);\n };\n update();\n return () => {\n if (timerId) clearTimeout(timerId);\n };\n }, [autorefresh, precision, setter]);\n return now;\n}\n\n/**\n * Wraps the standard Date.getTimezoneOffset() method in a SSR-friendly way.\n * This hook retrieves the offset value at the client side and uses a cookie\n * to pass it to the server in subsequent requests from that user. At the server\n * side the value from cookie is used in renders and passed back to the client\n * via the global state. Prior to the value being known (in the very first\n * request from the user, when the cookie is still missing), zero value is used\n * as the default value.\n *\n * @param {object} [options] Optional settings.\n * @param {string} [options.cookieName=\"timezoneOffset\"] Optional. The name of\n * cookie to use to store the timezone offset. Defaults \"timezoneOffset\". Set\n * to a falsy value to forbid using cookies altogether (in that case the hook\n * will always return zero value at the server-side, and in the first render\n * at the client-side).\n * @param {string} [options.timezoneOffset=\"timezoneOffset\"] Optional.\n * The global state path to store the offset. Defaults \"timezoneOffset\".\n * @return {number} Timezone offset.\n */\n// TODO: Should we request the state type as generic parameter, to be able\n// to verify the give globalStatePath is correct?\nexport function useTimezoneOffset({\n cookieName = 'timezoneOffset',\n globalStatePath = 'timezoneOffset',\n} = {}) {\n const ssrContext = getSsrContext(false);\n const [offset, setOffset] = useGlobalState<ForceT, number>(globalStatePath, () => {\n const value = cookieName && ssrContext?.req?.cookies?.[cookieName];\n return value ? parseInt(value, 10) : 0;\n });\n useEffect(() => {\n const date = new Date();\n const value = date.getTimezoneOffset();\n setOffset(value);\n if (cookieName) {\n document.cookie = Cookie.serialize(cookieName, value.toString(), { path: '/' });\n }\n }, [cookieName, setOffset]);\n return offset;\n}\n\nconst time = {\n DAY_MS,\n HOUR_MS,\n MIN_MS,\n SEC_MS,\n YEAR_MS,\n now: Date.now,\n timer,\n useCurrent,\n useTimezoneOffset,\n};\n\nexport default Object.assign(dayjs, time);\n"],"mappings":"0PAEA,IAAAA,OAAA,CAAAC,sBAAA,CAAAC,OAAA,YACA,IAAAC,MAAA,CAAAF,sBAAA,CAAAC,OAAA,WACA,IAAAE,MAAA,CAAAF,OAAA,UAEA,IAAAG,QAAA,CAAAH,OAAA,yBASA,IAAAI,iBAAA,CAAAJ,OAAA,mCAEA,IAAAK,YAAA,CAAAL,OAAA,kBAjBA,sBAmBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAnBA,CAoBA;AACA;AACO,QAAS,CAAAM,UAAUA,CAAC,CACzBC,WAAW,CAAG,KAAK,CACnBC,eAAe,CAAG,aAAa,CAC/BC,SAAS,CAAG,CAAC,CAAGC,eAClB,CAAC,CAAG,CAAC,CAAC,CAAE,CACN,KAAM,CAACC,GAAG,CAAEC,MAAM,CAAC,CAAG,GAAAC,gCAAc,EAAiBL,eAAe,CAAEM,IAAI,CAACH,GAAG,CAAC,CAC/E,GAAAI,gBAAS,EAAC,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B,KAAK,CAAGI,IAAI,CAACC,iBAAiB,CAAC,CAAC,CACtCN,SAAS,CAACC,KAAK,CAAC,CAChB,GAAIL,UAAU,CAAE,CACdW,QAAQ,CAACC,MAAM,CAAGC,eAAM,CAACC,SAAS,CAACd,UAAU,CAAEK,KAAK,CAACU,QAAQ,CAAC,CAAC,CAAE,CAAEC,IAAI,CAAE,GAAI,CAAC,CAChF,CACF,CAAC,CAAE,CAAChB,UAAU,CAAEI,SAAS,CAAC,CAAC,CAC3B,MAAO,CAAAD,MACT,CAEA,KAAM,CAAAc,IAAI,CAAG,CACXC,MAAM,CAANA,eAAM,CACNC,OAAO,CAAPA,gBAAO,CACPC,MAAM,CAANA,eAAM,CACNnC,MAAM,CAANA,eAAM,CACNoC,OAAO,CAAPA,gBAAO,CACPnC,GAAG,CAAEG,IAAI,CAACH,GAAG,CACboC,KAAK,CAALA,cAAK,CACLzC,UAAU,CACVkB,iBACF,CAAC,CAAC,IAAAwB,QAAA,CAAAC,OAAA,CAAAC,OAAA,CAEaC,MAAM,CAACC,MAAM,CAACC,cAAK,CAAEX,IAAI,CAAC"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireWeak=requireWeak;exports.resolveWeak=resolveWeak;var _isomorphy=require("./isomorphy");/**
|
|
2
2
|
* Requires the specified module without including it into the bundle during
|
|
3
3
|
* Webpack build.
|
|
4
|
-
* @param
|
|
5
|
-
* @param
|
|
6
|
-
* @return
|
|
4
|
+
* @param modulePath
|
|
5
|
+
* @param [basePath]
|
|
6
|
+
* @return Required module.
|
|
7
7
|
*/function requireWeak(modulePath,basePath){if(_isomorphy.IS_CLIENT_SIDE)return null;try{/* eslint-disable no-eval */const{resolve}=eval("require")("path");const path=basePath?resolve(basePath,modulePath):modulePath;const{default:def,...named}=eval("require")(path);/* eslint-enable no-eval */if(!def)return named;Object.entries(named).forEach(([key,value])=>{if(def[key])throw Error("Conflict between default and named exports");def[key]=value});return def}catch{return null}}/**
|
|
8
8
|
* Resolves specified module path with help of Babel's module resolver.
|
|
9
9
|
* Yes, the function itself just returns its argument to the caller, but Babel
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webpack.js","names":["_isomorphy","require","requireWeak","modulePath","basePath","IS_CLIENT_SIDE","resolve","eval","path","default","def","named","Object","entries","forEach","key","value","Error","resolveWeak"],"sources":["../../../../src/shared/utils/webpack.
|
|
1
|
+
{"version":3,"file":"webpack.js","names":["_isomorphy","require","requireWeak","modulePath","basePath","IS_CLIENT_SIDE","resolve","eval","path","default","def","named","Object","entries","forEach","key","value","Error","resolveWeak"],"sources":["../../../../src/shared/utils/webpack.ts"],"sourcesContent":["import { IS_CLIENT_SIDE } from './isomorphy';\n\n/**\n * Requires the specified module without including it into the bundle during\n * Webpack build.\n * @param modulePath\n * @param [basePath]\n * @return Required module.\n */\nexport function requireWeak(\n modulePath: string,\n basePath?: string,\n): NodeJS.Module | null {\n if (IS_CLIENT_SIDE) return null;\n\n try {\n /* eslint-disable no-eval */\n const { resolve } = eval('require')('path');\n const path = basePath ? resolve(basePath, modulePath) : modulePath;\n const { default: def, ...named } = eval('require')(path);\n /* eslint-enable no-eval */\n\n if (!def) return named;\n\n Object.entries(named).forEach(([key, value]) => {\n if (def[key]) throw Error('Conflict between default and named exports');\n def[key] = value;\n });\n return def;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolves specified module path with help of Babel's module resolver.\n * Yes, the function itself just returns its argument to the caller, but Babel\n * is configured to resolve the first argument of resolveWeak(..) function, thus\n * the result will be the resolved path.\n * @param {string} modulePath\n * @return {string} Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath: string): string {\n return modulePath;\n}\n"],"mappings":"sIAAA,IAAAA,UAAA,CAAAC,OAAA,gBAEA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAAS,CAAAC,WAAWA,CACzBC,UAAkB,CAClBC,QAAiB,CACK,CACtB,GAAIC,yBAAc,CAAE,MAAO,KAAI,CAE/B,GAAI,CACF,4BACA,KAAM,CAAEC,OAAQ,CAAC,CAAGC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,CAC3C,KAAM,CAAAC,IAAI,CAAGJ,QAAQ,CAAGE,OAAO,CAACF,QAAQ,CAAED,UAAU,CAAC,CAAGA,UAAU,CAClE,KAAM,CAAEM,OAAO,CAAEC,GAAG,CAAE,GAAGC,KAAM,CAAC,CAAGJ,IAAI,CAAC,SAAS,CAAC,CAACC,IAAI,CAAC,CACxD,2BAEA,GAAI,CAACE,GAAG,CAAE,MAAO,CAAAC,KAAK,CAEtBC,MAAM,CAACC,OAAO,CAACF,KAAK,CAAC,CAACG,OAAO,CAAC,CAAC,CAACC,GAAG,CAAEC,KAAK,CAAC,GAAK,CAC9C,GAAIN,GAAG,CAACK,GAAG,CAAC,CAAE,KAAM,CAAAE,KAAK,CAAC,4CAA4C,CAAC,CACvEP,GAAG,CAACK,GAAG,CAAC,CAAGC,KACb,CAAC,CAAC,CACF,MAAO,CAAAN,GACT,CAAE,KAAM,CACN,MAAO,KACT,CACF,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAAS,CAAAQ,WAAWA,CAACf,UAAkB,CAAU,CACtD,MAAO,CAAAA,UACT"}
|