@dr.pogodin/react-utils 1.47.0-alpha.1 → 1.47.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/babel.config.js +1 -1
- package/babel.module.config.js +11 -0
- package/bin/build.js +8 -4
- package/bin/setup.js +2 -3
- package/build/development/client/getInj.js +9 -18
- package/build/development/client/getInj.js.map +1 -1
- package/build/development/client/index.js +14 -21
- package/build/development/client/index.js.map +1 -1
- package/build/development/client/init.js +2 -6
- package/build/development/client/init.js.map +1 -1
- package/build/development/index.js +9 -179
- package/build/development/index.js.map +1 -1
- package/build/development/server/Cache.js +1 -8
- package/build/development/server/Cache.js.map +1 -1
- package/build/development/server/index.js +25 -50
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js +56 -67
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +52 -62
- package/build/development/server/server.js.map +1 -1
- package/build/development/server/utils/errors.js +8 -31
- package/build/development/server/utils/errors.js.map +1 -1
- package/build/development/server/utils/index.js +2 -9
- package/build/development/server/utils/index.js.map +1 -1
- package/build/development/shared/components/Button/index.js +9 -16
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +6 -13
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/GenericLink/index.js +4 -10
- package/build/development/shared/components/GenericLink/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +11 -18
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/Link.js +6 -13
- package/build/development/shared/components/Link.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +16 -22
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/NavLink.js +6 -13
- package/build/development/shared/components/NavLink.js.map +1 -1
- package/build/development/shared/components/PageLayout/index.js +7 -14
- package/build/development/shared/components/PageLayout/index.js.map +1 -1
- package/build/development/shared/components/TextArea/index.js +15 -22
- package/build/development/shared/components/TextArea/index.js.map +1 -1
- package/build/development/shared/components/Throbber/index.js +7 -14
- package/build/development/shared/components/Throbber/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/Tooltip.js +12 -18
- package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +16 -23
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js +10 -17
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/components/index.js +16 -130
- package/build/development/shared/components/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +12 -19
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js +20 -28
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js +13 -19
- package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/Switch/index.js +10 -17
- package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/development/shared/components/selectors/common.js +1 -7
- package/build/development/shared/components/selectors/common.js.map +1 -1
- package/build/development/shared/components/selectors/index.js +3 -27
- package/build/development/shared/components/selectors/index.js.map +1 -1
- package/build/development/shared/utils/config.js +8 -17
- package/build/development/shared/utils/config.js.map +1 -1
- package/build/development/shared/utils/globalState.js +3 -8
- package/build/development/shared/utils/globalState.js.map +1 -1
- package/build/development/shared/utils/index.js +12 -89
- package/build/development/shared/utils/index.js.map +1 -1
- package/build/development/shared/utils/isomorphy/buildInfo.js +2 -9
- package/build/development/shared/utils/isomorphy/buildInfo.js.map +1 -1
- package/build/development/shared/utils/isomorphy/environment-check.js +2 -8
- package/build/development/shared/utils/isomorphy/environment-check.js.map +1 -1
- package/build/development/shared/utils/isomorphy/index.js +7 -32
- package/build/development/shared/utils/isomorphy/index.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv.js +20 -31
- package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/development/shared/utils/jest/global.js +1 -7
- package/build/development/shared/utils/jest/global.js.map +1 -1
- package/build/development/shared/utils/jest/index.js +20 -44
- package/build/development/shared/utils/jest/index.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +35 -46
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/time.js +22 -31
- package/build/development/shared/utils/time.js.map +1 -1
- package/build/development/shared/utils/webpack.js +13 -16
- package/build/development/shared/utils/webpack.js.map +1 -1
- package/build/production/client/getInj.js +5 -5
- package/build/production/client/getInj.js.map +1 -1
- package/build/production/client/index.js +3 -3
- package/build/production/client/index.js.map +1 -1
- package/build/production/client/init.js +2 -2
- package/build/production/client/init.js.map +1 -1
- package/build/production/index.js +2 -3
- package/build/production/index.js.map +1 -1
- package/build/production/server/Cache.js +3 -3
- package/build/production/server/Cache.js.map +1 -1
- package/build/production/server/index.js +8 -8
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js +21 -19
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +9 -11
- package/build/production/server/server.js.map +1 -1
- package/build/production/server/utils/errors.js +9 -9
- package/build/production/server/utils/errors.js.map +1 -1
- package/build/production/server/utils/index.js +2 -1
- package/build/production/server/utils/index.js.map +1 -1
- package/build/production/shared/components/Button/index.js +4 -4
- package/build/production/shared/components/Button/index.js.map +1 -1
- package/build/production/shared/components/Checkbox/index.js +1 -1
- package/build/production/shared/components/Checkbox/index.js.map +1 -1
- package/build/production/shared/components/GenericLink/index.js +4 -4
- package/build/production/shared/components/GenericLink/index.js.map +1 -1
- package/build/production/shared/components/Input/index.js +5 -5
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/Link.js +3 -3
- package/build/production/shared/components/Link.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +7 -7
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/NavLink.js +2 -2
- package/build/production/shared/components/NavLink.js.map +1 -1
- package/build/production/shared/components/PageLayout/index.js +2 -2
- package/build/production/shared/components/PageLayout/index.js.map +1 -1
- package/build/production/shared/components/TextArea/index.js +5 -5
- package/build/production/shared/components/TextArea/index.js.map +1 -1
- package/build/production/shared/components/Throbber/index.js +2 -2
- package/build/production/shared/components/Throbber/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js +4 -4
- package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +4 -4
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js +4 -4
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/components/index.js +3 -1
- package/build/production/shared/components/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +2 -2
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js +2 -2
- package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/NativeDropdown/index.js +4 -4
- package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/Switch/index.js +1 -1
- package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/production/shared/components/selectors/common.js +2 -2
- package/build/production/shared/components/selectors/common.js.map +1 -1
- package/build/production/shared/components/selectors/index.js +1 -1
- package/build/production/shared/components/selectors/index.js.map +1 -1
- package/build/production/shared/utils/config.js +3 -5
- package/build/production/shared/utils/config.js.map +1 -1
- package/build/production/shared/utils/globalState.js +2 -2
- package/build/production/shared/utils/globalState.js.map +1 -1
- package/build/production/shared/utils/index.js +1 -1
- package/build/production/shared/utils/index.js.map +1 -1
- package/build/production/shared/utils/isomorphy/buildInfo.js +3 -3
- package/build/production/shared/utils/isomorphy/buildInfo.js.map +1 -1
- package/build/production/shared/utils/isomorphy/environment-check.js +3 -3
- package/build/production/shared/utils/isomorphy/environment-check.js.map +1 -1
- package/build/production/shared/utils/isomorphy/index.js +4 -4
- package/build/production/shared/utils/isomorphy/index.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js +14 -14
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/production/shared/utils/jest/global.js +1 -1
- package/build/production/shared/utils/jest/global.js.map +1 -1
- package/build/production/shared/utils/jest/index.js +11 -11
- package/build/production/shared/utils/jest/index.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js +11 -22
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/time.js +3 -3
- package/build/production/shared/utils/time.js.map +1 -1
- package/build/production/shared/utils/webpack.js +6 -6
- package/build/production/shared/utils/webpack.js.map +1 -1
- package/build/types-code/client/getInj.d.ts +1 -1
- package/build/types-code/index.d.ts +2 -2
- package/build/types-code/server/index.d.ts +2 -2
- package/build/web/client/getInj.js +9 -16
- package/build/web/client/getInj.js.map +1 -1
- package/build/web/client/index.js +14 -21
- package/build/web/client/index.js.map +1 -1
- package/build/web/client/init.js +2 -4
- package/build/web/client/init.js.map +1 -1
- package/build/web/index.js +2 -4
- package/build/web/index.js.map +1 -1
- package/build/web/server/index.js +9 -15
- package/build/web/server/index.js.map +1 -1
- package/build/web/server/renderer.js +12 -10
- package/build/web/server/renderer.js.map +1 -1
- package/build/web/server/server.js +11 -11
- package/build/web/server/server.js.map +1 -1
- package/build/web/shared/utils/config.js +4 -6
- package/build/web/shared/utils/config.js.map +1 -1
- package/build/web/shared/utils/jest/E2eSsrEnv.js +1 -2
- package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/web/shared/utils/splitComponent.js +17 -20
- package/build/web/shared/utils/splitComponent.js.map +1 -1
- package/build/web/shared/utils/webpack.js +11 -7
- package/build/web/shared/utils/webpack.js.map +1 -1
- package/config/babel/node-ssr.js +5 -5
- package/config/jest/default.js +8 -2
- package/config/webpack/app-base.js +11 -10
- package/config/webpack/app-development.js +3 -3
- package/config/webpack/lib-base.js +1 -1
- package/package.json +15 -12
- package/src/client/getInj.ts +2 -2
- package/src/index.ts +3 -7
- package/src/server/index.ts +9 -15
- package/src/server/renderer.tsx +11 -10
- package/src/server/server.ts +11 -13
- package/src/shared/utils/config.ts +5 -10
- package/src/shared/utils/jest/E2eSsrEnv.ts +1 -2
- package/src/shared/utils/splitComponent.tsx +17 -20
- package/src/shared/utils/webpack.ts +14 -8
- package/types.d.ts +1 -1
- package/node-entry.js +0 -15
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
export default function getGlobal(){return global}
|
|
2
2
|
//# sourceMappingURL=global.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"global.js","names":["getGlobal","global"],"sources":["../../../../../src/shared/utils/jest/global.ts"],"sourcesContent":["import type { IFs } from 'memfs';\nimport type { Configuration, StatsCompilation } from 'webpack';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n ssrMarkup: string | undefined;\n ssrStatus: number | undefined;\n webpackConfig: Configuration | undefined;\n webpackOutputFs: IFs;\n webpackStats?: StatsCompilation;\n }\n}\n\nexport default function getGlobal(): Window {\n return global as unknown as Window;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"global.js","names":["getGlobal","global"],"sources":["../../../../../src/shared/utils/jest/global.ts"],"sourcesContent":["import type { IFs } from 'memfs';\nimport type { Configuration, StatsCompilation } from 'webpack';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n ssrMarkup: string | undefined;\n ssrStatus: number | undefined;\n webpackConfig: Configuration | undefined;\n webpackOutputFs: IFs;\n webpackStats?: StatsCompilation;\n }\n}\n\nexport default function getGlobal(): Window {\n return global as unknown as Window;\n}\n"],"mappings":"AAcA,cAAe,SAAS,CAAAA,SAASA,CAAA,CAAW,CAC1C,MAAO,CAAAC,MACT","ignoreList":[]}
|
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
|
|
1
|
+
/* global jest, document *//* eslint-disable import/no-extraneous-dependencies */import mockdate from"mockdate";import{act}from"react";import{createRoot}from"react-dom/client";import{render}from"@testing-library/react";/**
|
|
2
2
|
* An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)
|
|
3
3
|
* from `react`.
|
|
4
|
-
*/global.IS_REACT_ACT_ENVIRONMENT=true;const originalProcessVersions=process.versions;/**
|
|
4
|
+
*/export{act};export{default as getGlobal}from"./global.js";global.IS_REACT_ACT_ENVIRONMENT=true;const originalProcessVersions=process.versions;/**
|
|
5
5
|
* Tricks **react-utils** into thinking the test is running within client-side
|
|
6
6
|
* (browser) environment.
|
|
7
|
-
*/function mockClientSide(){Object.defineProperty(process,"versions",{value:undefined})}/**
|
|
7
|
+
*/export function mockClientSide(){Object.defineProperty(process,"versions",{value:undefined})}/**
|
|
8
8
|
* Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.
|
|
9
|
-
*/function unmockClientSide(){Object.defineProperty(process,"versions",{value:originalProcessVersions,writable:false})}/**
|
|
9
|
+
*/export function unmockClientSide(){Object.defineProperty(process,"versions",{value:originalProcessVersions,writable:false})}/**
|
|
10
10
|
* Generates a mock UUID, or better said it determenistically transforms given
|
|
11
11
|
* `seed` number into a UUID-formatted string.
|
|
12
12
|
* @param {number} seed
|
|
13
13
|
* @return {string}
|
|
14
|
-
*/function getMockUuid(seed=0){const x=seed.toString(16).padStart(32,"0");return`${x.slice(0,8)}-${x.slice(8,12)}-${x.slice(12,16)}-${x.slice(16,20)}-${x.slice(20)}`}function mockAxios(handlers){const axios=jest.requireActual("axios");axios.defaults.adapter=async config=>{for(const handler of handlers){const res=handler(config);if(res){return{config:config,data:null,headers:{},status:200,statusText:"OK",...res}}}// Fallback to the regular network request.
|
|
14
|
+
*/export function getMockUuid(seed=0){const x=seed.toString(16).padStart(32,"0");return`${x.slice(0,8)}-${x.slice(8,12)}-${x.slice(12,16)}-${x.slice(16,20)}-${x.slice(20)}`}export function mockAxios(handlers){const axios=jest.requireActual("axios");axios.defaults.adapter=async config=>{for(const handler of handlers){const res=handler(config);if(res){return{config:config,data:null,headers:{},status:200,statusText:"OK",...res}}}// Fallback to the regular network request.
|
|
15
15
|
let res;try{res=await axios({...config,adapter:["xhr","http","fetch"]});// eslint-disable-next-line no-console
|
|
16
16
|
console.warn("Network request has not been mocked for a test.\n\nConfig:\n",config,"\n\nResult:\n",JSON.stringify(res,null,2))}catch(e){// eslint-disable-next-line no-console
|
|
17
17
|
console.warn("Network request has not been mocked for a test, and failed.\n\nConfig:\n",config,"\n\nError\n",JSON.stringify(e,null,2));throw e}return res};return axios}/**
|
|
@@ -19,25 +19,25 @@ console.warn("Network request has not been mocked for a test, and failed.\n\nCon
|
|
|
19
19
|
* @param {number} time Time step [ms].
|
|
20
20
|
* @returns {Promise} Wait for this to "jump after" any async code which should
|
|
21
21
|
* be executed because of the mock time movement.
|
|
22
|
-
*/async function mockTimer(time){
|
|
22
|
+
*/export async function mockTimer(time){mockdate.set(time+Date.now());await jest.advanceTimersByTimeAsync(time)}/**
|
|
23
23
|
* Mounts `scene` to the DOM, and returns the root scene element.
|
|
24
24
|
* @param scene
|
|
25
25
|
* @return Created container DOM element with destroy() function
|
|
26
26
|
* attached.
|
|
27
|
-
*/function mount(scene){let root;const element=document.createElement("div");document.body.appendChild(element);const res=element;res.destroy=()=>{// NOTE: As it seems @testing-library may reset this flag to false
|
|
27
|
+
*/export function mount(scene){let root;const element=document.createElement("div");document.body.appendChild(element);const res=element;res.destroy=()=>{// NOTE: As it seems @testing-library may reset this flag to false
|
|
28
28
|
// when it is simulating user events.
|
|
29
|
-
global.IS_REACT_ACT_ENVIRONMENT=true;
|
|
29
|
+
global.IS_REACT_ACT_ENVIRONMENT=true;act(()=>{root.unmount()});res.remove()};res.snapshot=()=>{expect(res).toMatchSnapshot()};// NOTE: As it seems @testing-library may reset this flag to false
|
|
30
30
|
// when it is simulating user events.
|
|
31
|
-
global.IS_REACT_ACT_ENVIRONMENT=true;
|
|
31
|
+
global.IS_REACT_ACT_ENVIRONMENT=true;act(()=>{root=createRoot(res);root.render(scene)});return res}// NOTE: If in future we have additional options here, they should be distributed
|
|
32
32
|
// across two objects, depending whether they are applicable to the sync, or async
|
|
33
33
|
// versions of snapshot(), or both.
|
|
34
|
-
function snapshot(element,options){let res;// TODO: Just adding async to the actor function breaks stuff, as it makes
|
|
34
|
+
export function snapshot(element,options){let res;// TODO: Just adding async to the actor function breaks stuff, as it makes
|
|
35
35
|
// act() asynchronous no matter the `options.await` value, thus breaking all
|
|
36
36
|
// calls that do not await for snapshot() result... thus... perhaps we need
|
|
37
37
|
// to have a more complex typing to ensure it all works as intended in all
|
|
38
38
|
// cases, and while being correctly enforced by TypeScript.
|
|
39
39
|
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
40
|
-
const promise=
|
|
40
|
+
const promise=act(()=>{res=render(element);return options?.await});if(res===undefined)throw Error("Render failed");if(options?.await){// BEWARE: Although `promise` is thenable (i.e. it has .then() method),
|
|
41
41
|
// it is not an instance of proper Promise class, and returning it directly
|
|
42
42
|
// breaks some async logic in Jest test or React test functions... thus, we
|
|
43
43
|
// wrap it into Promise instance here.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_mockdate","_interopRequireDefault","require","_react","_client","_react2","_global","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","undefined","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockAxios","handlers","axios","jest","requireActual","defaults","adapter","config","handler","res","data","headers","status","statusText","console","warn","JSON","stringify","e","mockTimer","time","mockdate","set","Date","now","advanceTimersByTimeAsync","mount","scene","root","element","document","createElement","body","appendChild","destroy","act","unmount","remove","snapshot","expect","toMatchSnapshot","createRoot","render","options","promise","await","Error","Promise","resolve","then","nodes","asFragment","childNodes","length"],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global jest, document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): string {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: React.ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve) => {\n void promise.then(() => {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n const nodes = res!.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res!);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"4iBAUA,IAAAA,SAAA,CAAAC,sBAAA,CAAAC,OAAA,cACA,IAAAC,MAAA,CAAAD,OAAA,UACA,IAAAE,OAAA,CAAAF,OAAA,qBAEA,IAAAG,OAAA,CAAAH,OAAA,2BAQA,IAAAI,OAAA,CAAAL,sBAAA,CAAAC,OAAA,cAtBA,2BACA,sDAeA;AACA;AACA;AACA,GAKAK,MAAM,CAACC,wBAAwB,CAAG,IAAI,CAEtC,KAAM,CAAAC,uBAAuB,CAAGC,OAAO,CAACC,QAAQ,CAEhD;AACA;AACA;AACA,GACO,QAAS,CAAAC,cAAcA,CAAA,CAAS,CACrCC,MAAM,CAACC,cAAc,CAACJ,OAAO,CAAE,UAAU,CAAE,CAA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CACzCb,MAAM,CAACW,KAAK,CAACG,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGH,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACV,eAAe,CAAC,CAAC,CAClE,MAAO,CAAA/B,GACT","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":["mockdate","act","createRoot","render","default","getGlobal","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","undefined","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockAxios","handlers","axios","jest","requireActual","defaults","adapter","config","handler","res","data","headers","status","statusText","console","warn","JSON","stringify","e","mockTimer","time","set","Date","now","advanceTimersByTimeAsync","mount","scene","root","element","document","createElement","body","appendChild","destroy","unmount","remove","snapshot","expect","toMatchSnapshot","options","promise","await","Error","Promise","resolve","then","nodes","asFragment","childNodes","length"],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global jest, document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): string {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: React.ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve) => {\n void promise.then(() => {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n const nodes = res!.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res!);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"AAAA,2BACA,sDASA,MAAO,CAAAA,QAAQ,KAAM,UAAU,CAC/B,OAA4CC,GAAG,KAAQ,OAAO,CAC9D,OAAoBC,UAAU,KAAQ,kBAAkB,CAExD,OAA4BC,MAAM,KAAQ,wBAAwB,CAElE;AACA;AACA;AACA,GACA,OAASF,GAAG,SAEHG,OAAO,GAAI,CAAAC,SAAS,mBAE7BC,MAAM,CAACC,wBAAwB,CAAG,IAAI,CAEtC,KAAM,CAAAC,uBAAuB,CAAGC,OAAO,CAACC,QAAQ,CAEhD;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,cAAcA,CAAA,CAAS,CACrCC,MAAM,CAACC,cAAc,CAACJ,OAAO,CAAE,UAAU,CAAE,CAAEK,KAAK,CAAEC,SAAU,CAAC,CACjE,CAEA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,gBAAgBA,CAAA,CAAS,CACvCJ,MAAM,CAACC,cAAc,CAACJ,OAAO,CAAE,UAAU,CAAE,CACzCK,KAAK,CAAEN,uBAAuB,CAC9BS,QAAQ,CAAE,KACZ,CAAC,CACH,CAEA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,WAAWA,CAACC,IAAI,CAAG,CAAC,CAAU,CAC5C,KAAM,CAAAC,CAAC,CAAGD,IAAI,CAACE,QAAQ,CAAC,EAAE,CAAC,CAACC,QAAQ,CAAC,EAAE,CAAE,GAAG,CAAC,CAC7C,MAAO,GAAGF,CAAC,CAACG,KAAK,CAAC,CAAC,CAAE,CAAC,CAAC,IAAIH,CAAC,CAACG,KAAK,CAAC,CAAC,CAAE,EAAE,CAAC,IAAIH,CAAC,CAACG,KAAK,CAAC,EAAE,CAAE,EAAE,CAAC,IAAIH,CAAC,CAACG,KAAK,CAAC,EAAE,CAAE,EAAE,CAAC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G,GAAKlB,SAAS,CAAE,KAAM,CAAAmD,KAAK,CAAC,eAAe,CAAC,CACnD,GAAIH,OAAO,EAAEE,KAAK,CAAE,CAClB;AACA;AACA;AACA;AACA,MAAO,IAAI,CAAAE,OAAO,CAAEC,OAAO,EAAK,CAC9B,IAAK,CAAAJ,OAAO,CAACK,IAAI,CAAC,IAAM,CACtB;AACA;AACA,KAAM,CAAAC,KAAK,CAAGrC,GAAG,CAAEsC,UAAU,CAAC,CAAC,CAACC,UAAU,CAC1CX,MAAM,CAACS,KAAK,CAACG,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGH,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC,CAClEM,OAAO,CAACnC,GAAI,CACd,CAAC,CACH,CAAC,CACH,CAEA,KAAM,CAAAqC,KAAK,CAAGrC,GAAG,CAACsC,UAAU,CAAC,CAAC,CAACC,UAAU,CACzCX,MAAM,CAACS,KAAK,CAACG,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGH,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC,CAClE,MAAO,CAAA7B,GACT","ignoreList":[]}
|
|
@@ -1,15 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
// the module; at the server-side we only can get them within React render flow.
|
|
3
|
-
// Thus, we set and use the following variable at the client-side, and then when
|
|
4
|
-
// needed on the server side, we'll fetch it differently.
|
|
5
|
-
let clientChunkGroups;if(_isomorphy.IS_CLIENT_SIDE){// TODO: Rewrite to avoid these overrides of ESLint rules.
|
|
6
|
-
/* eslint-disable @typescript-eslint/no-unsafe-assignment,
|
|
7
|
-
@typescript-eslint/no-require-imports,
|
|
8
|
-
@typescript-eslint/no-unsafe-call,
|
|
9
|
-
@typescript-eslint/no-unsafe-member-access */clientChunkGroups=require("../../client/getInj").default().CHUNK_GROUPS??{};/* eslint-enable @typescript-eslint/no-unsafe-assignment,
|
|
10
|
-
@typescript-eslint/no-require-imports,
|
|
11
|
-
@typescript-eslint/no-unsafe-call,
|
|
12
|
-
@typescript-eslint/no-unsafe-member-access */}const refCounts={};function getPublicPath(){return(0,_isomorphy.getBuildInfo)().publicPath}/**
|
|
1
|
+
/* global document */import{Suspense,lazy,useInsertionEffect}from"react";import{Barrier}from"@dr.pogodin/js-utils";import{getSsrContext}from"./globalState.js";import{IS_CLIENT_SIDE,IS_SERVER_SIDE,getBuildInfo}from"./isomorphy/index.js";import{jsx as _jsx}from"react/jsx-runtime";function getClientChunkGroups(){if(!IS_CLIENT_SIDE)return undefined;return(async()=>{const{default:getInj}=await import(/* webpackChunkName: "react-utils-client-side-code" */"../../client/getInj");return getInj().CHUNK_GROUPS??{}})()}const refCounts={};function getPublicPath(){return getBuildInfo().publicPath}/**
|
|
13
2
|
* Client-side only! Ensures the specified CSS stylesheet is loaded into
|
|
14
3
|
* the document; loads if it is missing; and does simple reference counting
|
|
15
4
|
* to facilitate future clean-up.
|
|
@@ -17,7 +6,7 @@ let clientChunkGroups;if(_isomorphy.IS_CLIENT_SIDE){// TODO: Rewrite to avoid th
|
|
|
17
6
|
* @param loadedSheets
|
|
18
7
|
* @param refCount
|
|
19
8
|
* @return
|
|
20
|
-
*/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
|
|
9
|
+
*/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 Barrier;link.addEventListener("load",()=>{if(!res)throw Error("Internal error");void res.resolve()});link.addEventListener("error",()=>{if(!res)throw Error("Internal error");void res.resolve()})}if(refCount){const current=refCounts[path]??0;refCounts[path]=1+current}return res}/**
|
|
21
10
|
* Generates the set of URLs for currently loaded, linked stylesheets.
|
|
22
11
|
* @return
|
|
23
12
|
*/function getLoadedStyleSheets(){const res=new Set;const{styleSheets}=document;for(const{href}of styleSheets){if(href)res.add(href)}return res}function assertChunkName(chunkName,chunkGroups){if(chunkGroups[chunkName])return;throw Error(`Unknown chunk name "${chunkName}"`)}/**
|
|
@@ -28,13 +17,13 @@ let clientChunkGroups;if(_isomorphy.IS_CLIENT_SIDE){// TODO: Rewrite to avoid th
|
|
|
28
17
|
* @param refCount
|
|
29
18
|
* @return Resolves once all pending stylesheets, necessary for
|
|
30
19
|
* the chunk, are either loaded, or failed to load.
|
|
31
|
-
*/async function bookStyleSheets(chunkName,chunkGroups,refCount){const promises=[];const assets=chunkGroups[chunkName];if(!assets)return Promise.resolve();const loadedSheets=getLoadedStyleSheets();for(const asset of assets){if(asset.endsWith(".css")){const promise=bookStyleSheet(asset,loadedSheets,refCount);if(promise)promises.push(promise)}}return promises.length?Promise.allSettled(promises).then():Promise.resolve()}/**
|
|
20
|
+
*/export async function bookStyleSheets(chunkName,chunkGroups,refCount){const promises=[];const assets=chunkGroups[chunkName];if(!assets)return Promise.resolve();const loadedSheets=getLoadedStyleSheets();for(const asset of assets){if(asset.endsWith(".css")){const promise=bookStyleSheet(asset,loadedSheets,refCount);if(promise)promises.push(promise)}}return promises.length?Promise.allSettled(promises).then():Promise.resolve()}/**
|
|
32
21
|
* Client-side only! Frees from the document all CSS stylesheets that are
|
|
33
22
|
* required by the specified chunk, and have reference counter equal to one
|
|
34
23
|
* (for chunks with larger reference counter values, it just decrements
|
|
35
24
|
* the reference counter).
|
|
36
25
|
* @param {string} chunkName
|
|
37
|
-
*/function freeStyleSheets(chunkName,chunkGroups){const assets=chunkGroups[chunkName];if(!assets)return;for(const asset of assets){if(asset.endsWith(".css")){const path=`${getPublicPath()}/${asset}`;const pathRefCount=refCounts[path];if(pathRefCount){if(pathRefCount<=1){document.head.querySelector(`link[href="${path}"]`).remove();delete refCounts[path]}else refCounts[path]=pathRefCount-1}}}}// Holds the set of chunk names already used for splitComponent() calls.
|
|
26
|
+
*/export function freeStyleSheets(chunkName,chunkGroups){const assets=chunkGroups[chunkName];if(!assets)return;for(const asset of assets){if(asset.endsWith(".css")){const path=`${getPublicPath()}/${asset}`;const pathRefCount=refCounts[path];if(pathRefCount){if(pathRefCount<=1){document.head.querySelector(`link[href="${path}"]`).remove();delete refCounts[path]}else refCounts[path]=pathRefCount-1}}}}// Holds the set of chunk names already used for splitComponent() calls.
|
|
38
27
|
const usedChunkNames=new Set;/**
|
|
39
28
|
* Given an async component retrieval function `getComponent()` it creates
|
|
40
29
|
* a special "code split" component, which uses <Suspense> to asynchronously
|
|
@@ -44,16 +33,16 @@ const usedChunkNames=new Set;/**
|
|
|
44
33
|
* @param {function} options.getComponent
|
|
45
34
|
* @param {React.Element} [options.placeholder]
|
|
46
35
|
* @return {React.ElementType}
|
|
47
|
-
*/function splitComponent({chunkName,getComponent,placeholder}){//
|
|
48
|
-
if(
|
|
49
|
-
if(
|
|
36
|
+
*/export default function splitComponent({chunkName,getComponent,placeholder}){// The correct usage of splitComponent() assumes a single call per chunk.
|
|
37
|
+
if(usedChunkNames.has(chunkName)){throw Error(`Repeated splitComponent() call for the chunk "${chunkName}"`)}else usedChunkNames.add(chunkName);const LazyComponent=/*#__PURE__*/lazy(async()=>{const clientChunkGroups=await getClientChunkGroups();// On the client side we can check right away if the chunk name is known.
|
|
38
|
+
if(IS_CLIENT_SIDE){if(!clientChunkGroups)throw Error("Internal error");assertChunkName(chunkName,clientChunkGroups)}const resolved=await getComponent();const Component="default"in resolved?resolved.default:resolved;// This pre-loads necessary stylesheets prior to the first mount of
|
|
50
39
|
// the component (the lazy load function is executed by React one at
|
|
51
40
|
// the frist mount).
|
|
52
|
-
if(
|
|
41
|
+
if(IS_CLIENT_SIDE){if(!clientChunkGroups)throw Error("Internal error");await bookStyleSheets(chunkName,clientChunkGroups,false)}const Wrapper=({children,ref,...rest})=>{// On the server side we'll assert the chunk name here,
|
|
53
42
|
// and also push it to the SSR chunks array.
|
|
54
|
-
if(
|
|
43
|
+
if(IS_SERVER_SIDE){const{chunkGroups,chunks}=getSsrContext();assertChunkName(chunkName,chunkGroups);if(!chunks.includes(chunkName))chunks.push(chunkName)}// This takes care about stylesheets management every time an instance of
|
|
55
44
|
// this component is mounted / unmounted.
|
|
56
|
-
|
|
57
|
-
,{...rest,ref:ref,children:children})};return{default:Wrapper}});const CodeSplit=({children,...rest})=>/*#__PURE__*/(
|
|
45
|
+
useInsertionEffect(()=>{if(!clientChunkGroups)throw Error("Internal error");void bookStyleSheets(chunkName,clientChunkGroups,true);return()=>{freeStyleSheets(chunkName,clientChunkGroups)}},[]);return/*#__PURE__*/_jsx(Component// eslint-disable-next-line react/jsx-props-no-spreading
|
|
46
|
+
,{...rest,ref:ref,children:children})};return{default:Wrapper}});const CodeSplit=({children,...rest})=>/*#__PURE__*/_jsx(Suspense,{fallback:placeholder,children:/*#__PURE__*/_jsx(LazyComponent// eslint-disable-next-line react/jsx-props-no-spreading
|
|
58
47
|
,{...rest,children:children})});return CodeSplit}
|
|
59
48
|
//# sourceMappingURL=splitComponent.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"splitComponent.js","names":["_react","require","_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","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","resolved","Component","Wrapper","children","ref","rest","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","_jsx","CodeSplit","Suspense","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\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 // TODO: Rewrite to avoid these overrides of ESLint rules.\n /* eslint-disable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n clientChunkGroups = require('client/getInj').default().CHUNK_GROUPS ?? {};\n /* eslint-enable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n}\n\nconst refCounts: Record<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', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\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 (const { href } of styleSheets) {\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 async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\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): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\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; ref?: RefObject<unknown> },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\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: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\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 void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\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\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":"qLAEA,IAAAA,MAAA,CAAAC,OAAA,UAUA,IAAAC,QAAA,CAAAD,OAAA,yBAEA,IAAAE,YAAA,CAAAF,OAAA,kBAEA,IAAAG,UAAA,CAAAH,OAAA,gBASA,IAAAI,WAAA,CAAAJ,OAAA,sBAzBA,qBAsBA;AACA;AACA;AACA;AACA,GAAI,CAAAK,iBAA+B,CAEnC,GAAIC,yBAAc,CAAE,CAClB;AACA;AACF;AACA;AACA,iDACED,iBAAiB,CAAGL,OAAO,sBAAgB,CAAC,CAACO,OAAO,CAAC,CAAC,CAACC,YAAY,EAAI,CAAC,CAAC,CACzE;AACF;AACA;AACA,iDACA,CAEA,KAAM,CAAAC,SAAiC,CAAG,CAAC,CAAC,CAE5C,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,CACrBC,I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EAACb,aACC;AAAA,KACIO,IAAI,CAAAF,QAAA,CAEPA,QAAQ,CACI,CAAC,CACR,CACX,CAED,MAAO,CAAAS,SACT","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"splitComponent.js","names":["Suspense","lazy","useInsertionEffect","Barrier","getSsrContext","IS_CLIENT_SIDE","IS_SERVER_SIDE","getBuildInfo","jsx","_jsx","getClientChunkGroups","undefined","default","getInj","CHUNK_GROUPS","refCounts","getPublicPath","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","clientChunkGroups","resolved","Component","Wrapper","children","ref","rest","chunks","includes","CodeSplit","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\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\nfunction getClientChunkGroups(): Promise<ChunkGroupsT> | undefined {\n if (!IS_CLIENT_SIDE) return undefined;\n\n return (async () => {\n const { default: getInj } = await import(/* webpackChunkName: \"react-utils-client-side-code\" */ '../../client/getInj');\n return getInj().CHUNK_GROUPS ?? {};\n })();\n}\n\nconst refCounts: Record<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', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\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 (const { href } of styleSheets) {\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 async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\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): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\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; ref?: RefObject<unknown> },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\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 clientChunkGroups = await getClientChunkGroups();\n\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n assertChunkName(chunkName, clientChunkGroups);\n }\n\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 if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\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 if (!clientChunkGroups) throw Error('Internal error');\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\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\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":"AAAA,qBAEA,OAKEA,QAAQ,CACRC,IAAI,CACJC,kBAAkB,KACb,OAAO,CAEd,OAASC,OAAO,KAAQ,sBAAsB,QAElBC,aAAa,+BAGvCC,cAAc,CACdC,cAAc,CACdC,YAAY,4BACO,OAAAC,GAAA,IAAAC,IAAA,yBAErB,QAAS,CAAAC,oBAAoBA,CAAA,CAAsC,CACjE,GAAI,CAACL,cAAc,CAAE,MAAO,CAAAM,SAAS,CAErC,MA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AAS,CAAC,CAAE4B,MAAM,CAACnB,IAAI,CAACT,SAAS,CACxD,CAEA;AACA;AACA3C,kBAAkB,CAAC,IAAM,CACvB,GAAI,CAACgE,iBAAiB,CAAE,KAAM,CAAA9B,KAAK,CAAC,gBAAgB,CAAC,CACrD,IAAK,CAAAW,eAAe,CAACF,SAAS,CAAEqB,iBAAiB,CAAE,IAAI,CAAC,CACxD,MAAO,IAAM,CACXR,eAAe,CAACb,SAAS,CAAEqB,iBAAiB,CAC9C,CACF,CAAC,CAAE,EAAE,CAAC,CAEN,mBACEzD,IAAA,CAAC2D,SACC;AAAA,KACKI,IAAI,CACTD,GAAG,CAAEA,GAAI,CAAAD,QAAA,CAERA,QAAQ,CACA,CAEf,CAAC,CAED,MAAO,CAAE1D,OAAO,CAAEyD,OAAQ,CAC5B,CAAC,CAAC,CAEF,KAAM,CAAAM,SAAmD,CAAGA,CAAC,CAC3DL,QAAQ,CACR,GAAGE,IACY,CAAC,gBAChB/D,IAAA,CAACT,QAAQ,EAAC4E,QAAQ,CAAEZ,WAAY,CAAAM,QAAA,cAC9B7D,IAAA,CAACwD,aACC;AAAA,KACIO,IAAI,CAAAF,QAAA,CAEPA,QAAQ,CACI,CAAC,CACR,CACX,CAED,MAAO,CAAAK,SACT","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import{serialize}from"cookie";import{useEffect}from"react";import dayjs from"dayjs";import{DAY_MS,HOUR_MS,MIN_MS,SEC_MS,YEAR_MS,timer}from"@dr.pogodin/js-utils";import{useGlobalState}from"@dr.pogodin/react-global-state";import{getSsrContext}from"./globalState.js";/**
|
|
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
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* with a finite precision to avoid infinite re-rendering loops.
|
|
8
8
|
*/// TODO: Should we request the state type as generic parameter, to be able
|
|
9
9
|
// to verify the give globalStatePath is correct?
|
|
10
|
-
function useCurrent({autorefresh=false,globalStatePath="currentTime",precision=5*
|
|
10
|
+
export function useCurrent({autorefresh=false,globalStatePath="currentTime",precision=5*SEC_MS}={}){const[now,setter]=useGlobalState(globalStatePath,Date.now);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}/**
|
|
11
11
|
* Wraps the standard Date.getTimezoneOffset() method in a SSR-friendly way.
|
|
12
12
|
* This hook retrieves the offset value at the client side and uses a cookie
|
|
13
13
|
* to pass it to the server in subsequent requests from that user. At the server
|
|
@@ -17,5 +17,5 @@ function useCurrent({autorefresh=false,globalStatePath="currentTime",precision=5
|
|
|
17
17
|
* as the default value.
|
|
18
18
|
*/// TODO: Should we request the state type as generic parameter, to be able
|
|
19
19
|
// to verify the give globalStatePath is correct?
|
|
20
|
-
function useTimezoneOffset({cookieName="timezoneOffset",globalStatePath="timezoneOffset"}={}){const ssrContext=
|
|
20
|
+
export function useTimezoneOffset({cookieName="timezoneOffset",globalStatePath="timezoneOffset"}={}){const ssrContext=getSsrContext(false);const[offset,setOffset]=useGlobalState(globalStatePath,()=>{const value=cookieName&&ssrContext?.req.cookies[cookieName];return value?parseInt(value):0});useEffect(()=>{const date=new Date;const value=date.getTimezoneOffset();setOffset(value);if(cookieName){document.cookie=serialize(cookieName,value.toString(),{path:"/"})}},[cookieName,setOffset]);return offset}const time={DAY_MS,HOUR_MS,MIN_MS,SEC_MS,YEAR_MS,now:Date.now,timer,useCurrent,useTimezoneOffset};export default Object.assign(dayjs,time);
|
|
21
21
|
//# sourceMappingURL=time.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"time.js","names":["
|
|
1
|
+
{"version":3,"file":"time.js","names":["serialize","useEffect","dayjs","DAY_MS","HOUR_MS","MIN_MS","SEC_MS","YEAR_MS","timer","useGlobalState","getSsrContext","useCurrent","autorefresh","globalStatePath","precision","now","setter","Date","timerId","update","old","neu","Math","abs","setTimeout","clearTimeout","useTimezoneOffset","cookieName","ssrContext","offset","setOffset","value","req","cookies","parseInt","date","getTimezoneOffset","document","cookie","toString","path","time","Object","assign"],"sources":["../../../../src/shared/utils/time.ts"],"sourcesContent":["import { serialize } from 'cookie';\nimport { useEffect } from 'react';\nimport dayjs from 'dayjs';\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 */\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} = {}): number {\n const [now, setter] = useGlobalState<ForceT, number>(\n globalStatePath,\n Date.now,\n );\n useEffect(() => {\n let timerId: NodeJS.Timeout | undefined;\n const update = (): void => {\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 (): void => {\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// 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} = {}): number {\n const ssrContext = getSsrContext(false);\n const [offset, setOffset] = useGlobalState<ForceT, number>(\n globalStatePath,\n () => {\n const value = cookieName\n && ssrContext?.req.cookies[cookieName] as string;\n return value ? parseInt(value) : 0;\n },\n );\n useEffect(() => {\n const date = new Date();\n const value = date.getTimezoneOffset();\n setOffset(value);\n if (cookieName) {\n document.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":"AAAA,OAASA,SAAS,KAAQ,QAAQ,CAClC,OAASC,SAAS,KAAQ,OAAO,CACjC,MAAO,CAAAC,KAAK,KAAM,OAAO,CAEzB,OACEC,MAAM,CACNC,OAAO,CACPC,MAAM,CACNC,MAAM,CACNC,OAAO,CACPC,KAAK,KACA,sBAAsB,CAE7B,OAAsBC,cAAc,KAAQ,gCAAgC,QAEnEC,aAAa,wBAEtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA;AACA;AACA,MAAO,SAAS,CAAAC,UAAUA,CAAC,CACzBC,WAAW,CAAG,KAAK,CACnBC,eAAe,CAAG,aAAa,CAC/BC,SAAS,CAAG,CAAC,CAAGR,MAClB,CAAC,CAAG,CAAC,CAAC,CAAU,CACd,KAAM,CAACS,GAAG,CAAEC,MAAM,CAAC,CAAGP,cAAc,CAClCI,eAAe,CACfI,IAAI,CAACF,GACP,CAAC,CACDd,SAAS,CAAC,IAAM,CACd,GAAI,CAAAiB,OAAmC,CACvC,KAAM,CAAAC,MAAM,CAAGA,CAAA,GAAY,CACzBH,MAAM,CAAEI,GAAG,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CAAC,CAAC,CAAE,CAAEC,IAAI,CAAE,GAAI,CAAC,CACzE,CACF,CAAC,CAAE,CAACb,UAAU,CAAEG,SAAS,CAAC,CAAC,CAC3B,MAAO,CAAAD,MACT,CAEA,KAAM,CAAAY,IAAI,CAAG,CACXtC,MAAM,CACNC,OAAO,CACPC,MAAM,CACNC,MAAM,CACNC,OAAO,CACPQ,GAAG,CAAEE,IAAI,CAACF,GAAG,CACbP,KAAK,CACLG,UAAU,CACVe,iBACF,CAAC,CAED,cAAe,CAAAgB,MAAM,CAACC,MAAM,CAACzC,KAAK,CAAEuC,IAAI,CAAC","ignoreList":[]}
|
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
|
|
1
|
+
// eslint-disable-next-line import/enforce-node-protocol-usage
|
|
2
|
+
import{createRequire}from"module";import{IS_CLIENT_SIDE,IS_SERVER_SIDE}from"./isomorphy/index.js";let require;if(IS_SERVER_SIDE)require=createRequire(import.meta.url);/**
|
|
2
3
|
* Requires the specified module without including it into the bundle during
|
|
3
4
|
* Webpack build.
|
|
4
5
|
* @param modulePath
|
|
5
6
|
* @param [basePath]
|
|
6
7
|
* @return Required module.
|
|
7
|
-
*/function requireWeak(modulePath,// TODO: For now `basePath` can be provided directly as a string here,
|
|
8
|
+
*/export function requireWeak(modulePath,// TODO: For now `basePath` can be provided directly as a string here,
|
|
8
9
|
// for backward compatibility. Deprecate it in future, if any other
|
|
9
10
|
// breaking changes are done for requireWeak().
|
|
10
|
-
basePathOrOptions){if(
|
|
11
|
-
const
|
|
12
|
-
const{resolve}=req("path");const path=basePath?resolve(basePath,modulePath):modulePath;const module=req(path);if(!("default"in module)||!module.default)return module;const{default:def,...named}=module;const res=def;Object.entries(named).forEach(([name,value])=>{const assigned=res[name];if(assigned)res[name]=value;else if(assigned!==value){throw Error("Conflict between default and named exports")}});return res}/**
|
|
11
|
+
basePathOrOptions){if(IS_CLIENT_SIDE)return null;let basePath;let ops;if(typeof basePathOrOptions==="string"){basePath=basePathOrOptions}else{ops=basePathOrOptions??{};({basePath}=ops)}// eslint-disable-next-line @typescript-eslint/unbound-method
|
|
12
|
+
const{resolve}=require("node:path");const path=basePath?resolve(basePath,modulePath):modulePath;const module=require(path);if(!("default"in module)||!module.default)return module;const{default:def,...named}=module;const res=def;Object.entries(named).forEach(([name,value])=>{const assigned=res[name];if(assigned===undefined){res[name]=value}else if(assigned!==value){throw Error("Conflict between default and named exports")}});return res}/**
|
|
13
13
|
* Resolves specified module path with help of Babel's module resolver.
|
|
14
14
|
* Yes, the function itself just returns its argument to the caller, but Babel
|
|
15
15
|
* is configured to resolve the first argument of resolveWeak(..) function, thus
|
|
16
16
|
* the result will be the resolved path.
|
|
17
17
|
* @param {string} modulePath
|
|
18
18
|
* @return {string} Absolute or relative path to the module.
|
|
19
|
-
*/function resolveWeak(modulePath){return modulePath}
|
|
19
|
+
*/export function resolveWeak(modulePath){return modulePath}
|
|
20
20
|
//# sourceMappingURL=webpack.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webpack.js","names":["
|
|
1
|
+
{"version":3,"file":"webpack.js","names":["createRequire","IS_CLIENT_SIDE","IS_SERVER_SIDE","require","import","meta","url","requireWeak","modulePath","basePathOrOptions","basePath","ops","resolve","path","module","default","def","named","res","Object","entries","forEach","name","value","assigned","undefined","Error","resolveWeak"],"sources":["../../../../src/shared/utils/webpack.ts"],"sourcesContent":["import type PathNS from 'node:path';\n\n// eslint-disable-next-line import/enforce-node-protocol-usage\nimport { createRequire } from 'module';\n\nimport { IS_CLIENT_SIDE, IS_SERVER_SIDE } from './isomorphy';\n\ntype RequireWeakOptionsT = {\n basePath?: string;\n};\n\ntype RequireWeakResT<T> = T extends { default: infer D }\n ? (D extends null | undefined ? T : D & Omit<T, 'default'>)\n : T;\n\nlet require: ((url: string) => unknown) | undefined;\n\nif (IS_SERVER_SIDE) require = createRequire(import.meta.url);\n\n/**\n * Requires the specified module without including it into the bundle during\n * Webpack build.\n * @param modulePath\n * @param [basePath]\n * @return Required module.\n */\nexport function requireWeak<T extends object>(\n modulePath: string,\n\n // TODO: For now `basePath` can be provided directly as a string here,\n // for backward compatibility. Deprecate it in future, if any other\n // breaking changes are done for requireWeak().\n basePathOrOptions?: string | RequireWeakOptionsT,\n): RequireWeakResT<T> | null {\n if (IS_CLIENT_SIDE) return null;\n\n let basePath: string | undefined;\n let ops: RequireWeakOptionsT;\n if (typeof basePathOrOptions === 'string') {\n basePath = basePathOrOptions;\n } else {\n ops = basePathOrOptions ?? {};\n ({ basePath } = ops);\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { resolve } = require!('node:path') as typeof PathNS;\n\n const path = basePath ? resolve(basePath, modulePath) : modulePath;\n\n const module = require!(path) as T;\n\n if (!('default' in module) || !module.default) return module as RequireWeakResT<T>;\n\n const { default: def, ...named } = module;\n\n const res = def as RequireWeakResT<T>;\n\n Object.entries(named).forEach(([name, value]) => {\n const assigned = res[name as keyof RequireWeakResT<T>];\n if (assigned === undefined) {\n (res[name as keyof RequireWeakResT<T>] as unknown) = value;\n } else if (assigned !== value) {\n throw Error('Conflict between default and named exports');\n }\n });\n return res;\n}\n\n/**\n * Resolves specified module path with help of Babel's module resolver.\n * Yes, the function itself just returns its argument to the caller, but Babel\n * is configured to resolve the first argument of resolveWeak(..) function, thus\n * the result will be the resolved path.\n * @param {string} modulePath\n * @return {string} Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath: string): string {\n return modulePath;\n}\n"],"mappings":"AAEA;AACA,OAASA,aAAa,KAAQ,QAAQ,QAE7BC,cAAc,CAAEC,cAAc,4BAUvC,GAAI,CAAAC,OAA+C,CAEnD,GAAID,cAAc,CAAEC,OAAO,CAAGH,aAAa,CAACI,MAAM,CAACC,IAAI,CAACC,GAAG,CAAC,CAE5D;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,WAAWA,CACzBC,UAAkB,CAElB;AACA;AACA;AACAC,iBAAgD,CACrB,CAC3B,GAAIR,cAA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
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import 'styles/global.scss';
|
|
2
|
-
import
|
|
2
|
+
import clientModule from './client';
|
|
3
3
|
import type * as ServerFactoryM from './server';
|
|
4
4
|
declare const server: (typeof ServerFactoryM.default & Omit<typeof ServerFactoryM, "default">) | null;
|
|
5
|
-
declare const client: typeof
|
|
5
|
+
declare const client: typeof clientModule | undefined;
|
|
6
6
|
export { type AsyncCollectionT, type AsyncCollectionLoaderT, type AsyncDataEnvelopeT, type AsyncDataLoaderT, type ForceT, type UseAsyncDataOptionsT, type UseAsyncDataResT, type UseGlobalStateResT, type ValueOrInitializerT, getGlobalState, GlobalStateProvider, newAsyncDataEnvelope, useAsyncCollection, useAsyncData, useGlobalState, withGlobalStateType, } from '@dr.pogodin/react-global-state';
|
|
7
7
|
export * from './shared/components';
|
|
8
8
|
export { type BeforeRenderResT, type BeforeRenderT, type ConfigT, type ServerSsrContext, type ServerT, } from './server';
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import 'source-map-support/register';
|
|
1
|
+
import 'source-map-support/register.js';
|
|
2
2
|
import http from 'node:http';
|
|
3
|
-
import 'raf/polyfill';
|
|
3
|
+
import 'raf/polyfill.js';
|
|
4
4
|
import type { Configuration } from 'webpack';
|
|
5
5
|
import { type OptionsT as ServerOptionsT, type ServerT, getDefaultCspSettings } from './server';
|
|
6
6
|
import { errors } from './utils';
|
|
@@ -1,21 +1,14 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
|
4
|
-
Object.defineProperty(exports, "__esModule", {
|
|
5
|
-
value: true
|
|
6
|
-
});
|
|
7
|
-
exports.default = getInj;
|
|
8
|
-
var _forge = _interopRequireDefault(require("node-forge/lib/forge"));
|
|
9
|
-
require("node-forge/lib/aes");
|
|
10
|
-
var _buildInfo = require("../shared/utils/isomorphy/buildInfo");
|
|
11
1
|
// Encapsulates retrieval of server-side data injection into HTML template.
|
|
12
2
|
|
|
13
3
|
/* global document */
|
|
14
4
|
|
|
15
5
|
// Note: this way, only required part of "node-forge": AES, and some utils,
|
|
16
6
|
// is bundled into client-side code.
|
|
7
|
+
import forge from 'node-forge/lib/forge.js';
|
|
17
8
|
|
|
18
9
|
// eslint-disable-next-line import/no-unassigned-import
|
|
10
|
+
import 'node-forge/lib/aes.js';
|
|
11
|
+
import { getBuildInfo } from "../shared/utils/isomorphy/buildInfo";
|
|
19
12
|
|
|
20
13
|
// Safeguard is needed here, because the server-side version of Docusaurus docs
|
|
21
14
|
// is compiled (at least now) with settings suggesting it is a client-side
|
|
@@ -24,17 +17,17 @@ let inj = {};
|
|
|
24
17
|
const metaElement = typeof document === 'undefined' ? null : document.querySelector('meta[itemprop="drpruinj"]');
|
|
25
18
|
if (metaElement) {
|
|
26
19
|
metaElement.remove();
|
|
27
|
-
let data =
|
|
20
|
+
let data = forge.util.decode64(metaElement.content);
|
|
28
21
|
const {
|
|
29
22
|
key
|
|
30
|
-
} =
|
|
31
|
-
const d =
|
|
23
|
+
} = getBuildInfo();
|
|
24
|
+
const d = forge.cipher.createDecipher('AES-CBC', key);
|
|
32
25
|
d.start({
|
|
33
26
|
iv: data.slice(0, key.length)
|
|
34
27
|
});
|
|
35
|
-
d.update(
|
|
28
|
+
d.update(forge.util.createBuffer(data.slice(key.length)));
|
|
36
29
|
d.finish();
|
|
37
|
-
data =
|
|
30
|
+
data = forge.util.decodeUtf8(d.output.data);
|
|
38
31
|
|
|
39
32
|
// TODO: Double-check, if there is a safer alternative to parse it?
|
|
40
33
|
// eslint-disable-next-line no-eval
|
|
@@ -48,7 +41,7 @@ if (metaElement) {
|
|
|
48
41
|
// Docusaurus examples, etc.
|
|
49
42
|
inj = {};
|
|
50
43
|
}
|
|
51
|
-
function getInj() {
|
|
44
|
+
export default function getInj() {
|
|
52
45
|
return inj;
|
|
53
46
|
}
|
|
54
47
|
//# sourceMappingURL=getInj.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getInj.js","names":["
|
|
1
|
+
{"version":3,"file":"getInj.js","names":["forge","getBuildInfo","inj","metaElement","document","querySelector","remove","data","util","decode64","content","key","d","cipher","createDecipher","start","iv","slice","length","update","createBuffer","finish","decodeUtf8","output","eval","window","REACT_UTILS_INJECTION","getInj"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\n// Note: this way, only required part of \"node-forge\": AES, and some utils,\n// is bundled into client-side code.\nimport forge from 'node-forge/lib/forge.js';\n\n// eslint-disable-next-line import/no-unassigned-import\nimport 'node-forge/lib/aes.js';\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\n// Safeguard is needed here, because the server-side version of Docusaurus docs\n// is compiled (at least now) with settings suggesting it is a client-side\n// environment, but there is no document.\nlet inj: InjT = {};\n\nconst metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\nif (metaElement) {\n metaElement.remove();\n let data = forge.util.decode64(metaElement.content);\n\n const { key } = getBuildInfo();\n const d = forge.cipher.createDecipher('AES-CBC', key);\n d.start({ iv: data.slice(0, key.length) });\n d.update(forge.util.createBuffer(data.slice(key.length)));\n d.finish();\n\n data = forge.util.decodeUtf8(d.output.data);\n\n // TODO: Double-check, if there is a safer alternative to parse it?\n // eslint-disable-next-line no-eval\n inj = eval(`(${data})`) as InjT;\n} else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n inj = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n} else {\n // Otherwise, a bunch of dependent stuff will easily fail in non-standard\n // environments, where no client-side initialization is performed. Like tests,\n // Docusaurus examples, etc.\n inj = {};\n}\n\nexport default function getInj(): InjT {\n return inj;\n}\n"],"mappings":"AAAA;;AAEA;;AAEA;AACA;AACA,OAAOA,KAAK,MAAM,yBAAyB;;AAE3C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ACrC,OAAOzB,GAAG;AACZ","ignoreList":[]}
|
|
@@ -1,38 +1,31 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
|
4
|
-
Object.defineProperty(exports, "__esModule", {
|
|
5
|
-
value: true
|
|
6
|
-
});
|
|
7
|
-
exports.default = Launch;
|
|
8
|
-
var _client = require("react-dom/client");
|
|
9
|
-
var _reactHelmet = require("@dr.pogodin/react-helmet");
|
|
10
|
-
var _reactRouter = require("react-router");
|
|
11
|
-
var _reactGlobalState = require("@dr.pogodin/react-global-state");
|
|
12
|
-
var _getInj = _interopRequireDefault(require("./getInj"));
|
|
13
|
-
var _jsxRuntime = require("react/jsx-runtime");
|
|
14
1
|
// Initialization of client-side code.
|
|
15
2
|
/* global document */
|
|
16
3
|
|
|
4
|
+
import { createRoot, hydrateRoot } from 'react-dom/client';
|
|
5
|
+
import { HelmetProvider } from '@dr.pogodin/react-helmet';
|
|
6
|
+
import { BrowserRouter } from 'react-router';
|
|
7
|
+
import { GlobalStateProvider } from '@dr.pogodin/react-global-state';
|
|
8
|
+
import getInj from "./getInj";
|
|
9
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
17
10
|
/**
|
|
18
11
|
* Prepares and launches the app at client side.
|
|
19
12
|
* @param Application Root application component
|
|
20
13
|
* @param [options={}] Optional. Additional settings.
|
|
21
14
|
*/
|
|
22
|
-
function Launch(Application, options = {}) {
|
|
15
|
+
export default function Launch(Application, options = {}) {
|
|
23
16
|
const container = document.getElementById('react-view');
|
|
24
17
|
if (!container) throw Error('Failed to find container for React app');
|
|
25
|
-
const scene = /*#__PURE__*/(
|
|
26
|
-
initialState: (
|
|
27
|
-
children: /*#__PURE__*/(
|
|
28
|
-
children: /*#__PURE__*/(
|
|
29
|
-
children: /*#__PURE__*/(
|
|
18
|
+
const scene = /*#__PURE__*/_jsx(GlobalStateProvider, {
|
|
19
|
+
initialState: getInj().ISTATE ?? options.initialState,
|
|
20
|
+
children: /*#__PURE__*/_jsx(BrowserRouter, {
|
|
21
|
+
children: /*#__PURE__*/_jsx(HelmetProvider, {
|
|
22
|
+
children: /*#__PURE__*/_jsx(Application, {})
|
|
30
23
|
})
|
|
31
24
|
})
|
|
32
25
|
});
|
|
33
26
|
if (options.dontHydrate) {
|
|
34
|
-
const root =
|
|
27
|
+
const root = createRoot(container);
|
|
35
28
|
root.render(scene);
|
|
36
|
-
} else
|
|
29
|
+
} else hydrateRoot(container, scene);
|
|
37
30
|
}
|
|
38
31
|
//# sourceMappingURL=index.js.map
|