@dr.pogodin/react-utils 1.47.0-alpha.3 → 1.47.0-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/development/client/getInj.js +48 -37
- package/build/development/client/getInj.js.map +1 -1
- package/build/development/client/index.js +3 -2
- package/build/development/client/index.js.map +1 -1
- package/build/development/index.js +3 -3
- package/build/development/index.js.map +1 -1
- package/build/development/server/renderer.js +12 -30
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +2 -2
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/utils/config.js +37 -9
- package/build/development/shared/utils/config.js.map +1 -1
- package/build/development/shared/utils/index.js +2 -2
- package/build/development/shared/utils/index.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +2 -1
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/production/client/getInj.js +12 -10
- package/build/production/client/getInj.js.map +1 -1
- package/build/production/client/index.js +1 -1
- package/build/production/client/index.js.map +1 -1
- package/build/production/index.js +2 -1
- package/build/production/index.js.map +1 -1
- package/build/production/server/renderer.js +6 -9
- package/build/production/server/renderer.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/utils/config.js +8 -4
- package/build/production/shared/utils/config.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/splitComponent.js +1 -1
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/types-code/client/getInj.d.ts +1 -2
- package/build/types-code/client/index.d.ts +1 -1
- package/build/types-code/index.d.ts +1 -1
- package/build/types-code/shared/utils/config.d.ts +4 -2
- package/build/types-code/shared/utils/index.d.ts +2 -2
- package/build/types-code/shared/utils/splitComponent.d.ts +6 -4
- package/build/web/client/getInj.js +48 -37
- package/build/web/client/getInj.js.map +1 -1
- package/build/web/client/index.js +3 -2
- package/build/web/client/index.js.map +1 -1
- package/build/web/index.js +3 -3
- package/build/web/index.js.map +1 -1
- package/build/web/server/renderer.js +12 -30
- package/build/web/server/renderer.js.map +1 -1
- package/build/web/shared/components/Modal/index.js +2 -2
- package/build/web/shared/components/Modal/index.js.map +1 -1
- package/build/web/shared/utils/config.js +36 -10
- package/build/web/shared/utils/config.js.map +1 -1
- package/build/web/shared/utils/index.js +2 -2
- package/build/web/shared/utils/index.js.map +1 -1
- package/build/web/shared/utils/splitComponent.js +2 -1
- package/build/web/shared/utils/splitComponent.js.map +1 -1
- package/config/jest/setup.js +8 -1
- package/config/webpack/app-base.js +2 -2
- package/config/webpack/lib-base.js +0 -1
- package/package.json +2 -4
- package/src/client/getInj.ts +60 -40
- package/src/client/index.tsx +5 -3
- package/src/index.ts +3 -3
- package/src/server/renderer.tsx +16 -35
- package/src/shared/components/Modal/index.tsx +2 -2
- package/src/shared/utils/config.ts +48 -12
- package/src/shared/utils/index.ts +2 -2
- package/src/shared/utils/splitComponent.tsx +14 -2
- package/types.d.ts +1 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["useEffect","useMemo","useRef","
|
|
1
|
+
{"version":3,"file":"index.js","names":["useEffect","useMemo","useRef","createPortal","themed","baseTheme","S","jsx","_jsx","jsxs","_jsxs","BaseModal","cancelOnScrolling","children","containerStyle","dontDisableScrolling","onCancel","overlayStyle","style","testId","testIdForOverlay","theme","containerRef","overlayRef","window","addEventListener","removeEventListener","document","body","classList","add","scrollingDisabledByModal","remove","focusLast","onFocus","elems","current","querySelectorAll","i","length","focus","activeElement","tabIndex","className","overlay","process","env","NODE_ENV","undefined","onClick","e","stopPropagation","onKeyDown","key","ref","node","role","container","onWheel","event"],"sources":["../../../../../src/shared/components/Modal/index.tsx"],"sourcesContent":["import {\n type CSSProperties,\n type FunctionComponent,\n type ReactNode,\n useEffect,\n useMemo,\n useRef,\n} from 'react';\n\nimport { createPortal } from 'react-dom';\nimport themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport baseTheme from './base-theme.scss';\nimport S from './styles.scss';\n\ntype PropsT = {\n cancelOnScrolling?: boolean;\n children?: ReactNode;\n dontDisableScrolling?: boolean;\n onCancel?: () => void;\n overlayStyle?: CSSProperties;\n style?: CSSProperties;\n testId?: string;\n testIdForOverlay?: string;\n theme: Theme<'container' | 'overlay'>;\n\n /** @deprecated */\n containerStyle?: CSSProperties;\n};\n\n/**\n * The `<Modal>` component implements a simple themeable modal window, wrapped\n * into the default theme. `<BaseModal>` exposes the base non-themed component.\n * **Children:** Component children are rendered as the modal content.\n * @param {object} props Component properties. Beside props documented below,\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties) are supported as well.\n * @param {function} [props.onCancel] The callback to trigger when user\n * clicks outside the modal, or presses Escape. It is expected to hide the\n * modal.\n * @param {ModalTheme} [props.theme] _Ad hoc_ theme.\n */\nconst BaseModal: FunctionComponent<PropsT> = ({\n cancelOnScrolling,\n children,\n containerStyle,\n dontDisableScrolling,\n onCancel,\n overlayStyle,\n style,\n testId,\n testIdForOverlay,\n theme,\n}) => {\n const containerRef = useRef<HTMLDivElement | null>(null);\n const overlayRef = useRef<HTMLDivElement | null>(null);\n\n // Sets up modal cancellation of scrolling, if opted-in.\n useEffect(() => {\n if (cancelOnScrolling && onCancel) {\n window.addEventListener('scroll', onCancel);\n window.addEventListener('wheel', onCancel);\n }\n return () => {\n if (cancelOnScrolling && onCancel) {\n window.removeEventListener('scroll', onCancel);\n window.removeEventListener('wheel', onCancel);\n }\n };\n }, [cancelOnScrolling, onCancel]);\n\n // Disables window scrolling, if it is not opted-out.\n useEffect(() => {\n if (!dontDisableScrolling) {\n document.body.classList.add(S.scrollingDisabledByModal);\n }\n return () => {\n if (!dontDisableScrolling) {\n document.body.classList.remove(S.scrollingDisabledByModal);\n }\n };\n }, [dontDisableScrolling]);\n\n const focusLast = useMemo(() => (\n <div\n onFocus={() => {\n const elems = containerRef.current!.querySelectorAll('*');\n for (let i = elems.length - 1; i >= 0; --i) {\n (elems[i] as HTMLElement).focus();\n if (document.activeElement === elems[i]) return;\n }\n overlayRef.current?.focus();\n }}\n // TODO: Have a look at this later.\n // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex\n tabIndex={0}\n />\n ), []);\n\n return createPortal(\n (\n <div>\n {focusLast}\n <div\n aria-label=\"Cancel\"\n className={theme.overlay}\n data-testid={\n process.env.NODE_ENV === 'production'\n ? undefined : testIdForOverlay\n }\n onClick={(e) => {\n if (onCancel) {\n onCancel();\n e.stopPropagation();\n }\n }}\n onKeyDown={(e) => {\n if (e.key === 'Escape' && onCancel) {\n onCancel();\n e.stopPropagation();\n }\n }}\n ref={(node) => {\n if (node && node !== overlayRef.current) {\n overlayRef.current = node;\n node.focus();\n }\n }}\n role=\"button\"\n style={overlayStyle}\n tabIndex={0}\n />\n {\n // NOTE: These rules are disabled because our intention is to keep\n // the element non-interactive (thus not on the keyboard focus chain),\n // and it has `onClick` handler merely to stop propagation of click\n // events to its parent container. This is needed because, for example\n // when the modal is wrapped into an interactive element we don't want\n // any clicks inside the modal to bubble-up to that parent element\n // (because visually and logically the modal dialog does not belong\n // to its parent container, where it technically belongs from\n // the HTML mark-up perpective).\n }\n <div // eslint-disable-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions\n aria-modal=\"true\"\n className={theme.container}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onClick={(e) => {\n e.stopPropagation();\n }}\n onWheel={(event) => {\n event.stopPropagation();\n }}\n ref={containerRef}\n role=\"dialog\"\n style={style ?? containerStyle}\n >\n {children}\n </div>\n <div\n onFocus={() => {\n overlayRef.current?.focus();\n }}\n // TODO: Have a look at this later.\n // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex\n tabIndex={0}\n />\n {focusLast}\n </div>\n ),\n document.body,\n );\n};\n\nexport default themed(BaseModal, 'Modal', baseTheme);\n\n/* Non-themed version of the Modal. */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AG,CAAGC,IAAI,EAAK,CACb,GAAIA,IAAI,EAAIA,IAAI,GAAKhC,UAAU,CAACa,OAAO,CAAE,CACvCb,UAAU,CAACa,OAAO,CAAGmB,IAAI,CACzBA,IAAI,CAACf,KAAK,CAAC,CACb,CACF,CAAE,CACFgB,IAAI,CAAC,QAAQ,CACbtC,KAAK,CAAED,YAAa,CACpByB,QAAQ,CAAE,CAAE,CACb,CAAC,cAYFlC,IAAA,QAAK;AACH,aAAW,MAAM,CACjBmC,SAAS,CAAEtB,KAAK,CAACoC,SAAU,CAC3B,cAAaZ,OAAO,CAACC,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAGC,SAAS,CAAG7B,MAAO,CACxE8B,OAAO,CAAGC,CAAC,EAAK,CACdA,CAAC,CAACC,eAAe,CAAC,CACpB,CAAE,CACFO,OAAO,CAAGC,KAAK,EAAK,CAClBA,KAAK,CAACR,eAAe,CAAC,CACxB,CAAE,CACFG,GAAG,CAAEhC,YAAa,CAClBkC,IAAI,CAAC,QAAQ,CACbtC,KAAK,CAAEA,KAAK,EAAIJ,cAAe,CAAAD,QAAA,CAE9BA,QAAQ,CACN,CAAC,cACNL,IAAA,QACE0B,OAAO,CAAEA,CAAA,GAAM,CACbX,UAAU,CAACa,OAAO,EAAEI,KAAK,CAAC,CAC5B,CACA;AACA;AAAA,CACAE,QAAQ,CAAE,CAAE,CACb,CAAC,CACDT,SAAS,EACP,CAAC,CAERN,QAAQ,CAACC,IACX,CACF,CAAC,CAED,cAAe,CAAAxB,MAAM,CAACO,SAAS,CAAE,OAAO,CAAEN,SAAS,CAAC,CAEpD,sCACA,OAASM,SAAS","ignoreList":[]}
|
|
@@ -1,7 +1,11 @@
|
|
|
1
|
-
/* global document */import{parse}from"cookie";import clientGetInj from"../../client/getInj.js";import{IS_CLIENT_SIDE}from"./isomorphy/environment-check.js";import{requireWeak}from"./webpack.js"
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
/* global document */import{parse}from"cookie";import clientGetInj from"../../client/getInj.js";import{IS_CLIENT_SIDE}from"./isomorphy/environment-check.js";import{requireWeak}from"./webpack.js";let config;/**
|
|
2
|
+
* Injects CSRF token into config (on client-side only).
|
|
3
|
+
*
|
|
4
|
+
* BEWARE: It mutates the argument, and also returns it as the result,
|
|
5
|
+
* for chaining.
|
|
6
|
+
*/function injectCsrfToken(cfg){// The safeguard for "document" is necessary because in non-Node environments,
|
|
4
7
|
// like React Native, IS_CLIENT_SIDE is "true", however "document" and a bunch
|
|
5
8
|
// of other browser-world features are not available.
|
|
6
|
-
if(IS_CLIENT_SIDE&&typeof document!=="undefined"){
|
|
9
|
+
if(IS_CLIENT_SIDE&&typeof document!=="undefined"){// eslint-disable-next-line no-param-reassign
|
|
10
|
+
cfg.CSRF=parse(document.cookie).csrfToken}return cfg}export function getConfig(sync){if(!config){if(IS_CLIENT_SIDE){const inj=clientGetInj();config=inj instanceof Promise?inj.then(injection=>{const res=injectCsrfToken(injection.CONFIG??{});config=res;return res}):injectCsrfToken(inj.CONFIG??{})}else{const weak=requireWeak("config");if(!weak)throw Error("Internal error");config=weak}}if(sync&&config instanceof Promise){throw Error("The config is not available yet")}return config}
|
|
7
11
|
//# sourceMappingURL=config.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","names":["parse","clientGetInj","IS_CLIENT_SIDE","requireWeak","config","
|
|
1
|
+
{"version":3,"file":"config.js","names":["parse","clientGetInj","IS_CLIENT_SIDE","requireWeak","config","injectCsrfToken","cfg","document","CSRF","cookie","csrfToken","getConfig","sync","inj","Promise","then","injection","res","CONFIG","weak","Error"],"sources":["../../../../src/shared/utils/config.ts"],"sourcesContent":["/* global document */\n\nimport { parse } from 'cookie';\n\nimport clientGetInj from '../../client/getInj';\n\nimport { IS_CLIENT_SIDE } from './isomorphy/environment-check';\nimport { requireWeak } from './webpack';\n\ntype ConfigT = Record<string, unknown>;\n\nlet config: ConfigT | Promise<ConfigT> | undefined;\n\n/**\n * Injects CSRF token into config (on client-side only).\n *\n * BEWARE: It mutates the argument, and also returns it as the result,\n * for chaining.\n */\nfunction injectCsrfToken(cfg: ConfigT): ConfigT {\n // The safeguard for \"document\" is necessary because in non-Node environments,\n // like React Native, IS_CLIENT_SIDE is \"true\", however \"document\" and a bunch\n // of other browser-world features are not available.\n if (IS_CLIENT_SIDE && typeof document !== 'undefined') {\n // eslint-disable-next-line no-param-reassign\n cfg.CSRF = parse(document.cookie).csrfToken;\n }\n\n return cfg;\n}\n\nexport function getConfig(sync: true): ConfigT;\n\nexport function getConfig(sync?: boolean): ConfigT | Promise<ConfigT>;\n\nexport function getConfig(sync?: boolean): ConfigT | Promise<ConfigT> {\n if (!config) {\n if (IS_CLIENT_SIDE) {\n const inj = clientGetInj();\n config = inj instanceof Promise\n ? inj.then((injection) => {\n const res = injectCsrfToken(injection.CONFIG ?? {});\n config = res;\n return res;\n })\n : injectCsrfToken(inj.CONFIG ?? {});\n } else {\n const weak = requireWeak<ConfigT>('config');\n if (!weak) throw Error('Internal error');\n config = weak;\n }\n }\n\n if (sync && (config instanceof Promise)) {\n throw Error('The config is not available yet');\n }\n\n return config;\n}\n"],"mappings":"AAAA,qBAEA,OAASA,KAAK,KAAQ,QAAQ,OAEvB,CAAAC,YAAY,qCAEVC,cAAc,+CACdC,WAAW,oBAIpB,GAAI,CAAAC,MAA8C,CAElD;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,CAAAC,eAAeA,CAACC,GAAY,CAAW,CAC9C;AACA;AACA;AACA,GAAIJ,cAAc,EAAI,MAAO,CAAAK,QAAQ,GAAK,WAAW,CAAE,CACrD;AACAD,GAAG,CAACE,IAAI,CAAGR,KAAK,CAACO,QAAQ,CAACE,MAAM,CAAC,CAACC,SACpC,CAEA,MAAO,CAAAJ,GACT,CAMA,MAAO,SAAS,CAAAK,SAASA,CAACC,IAAc,CAA8B,CACpE,GAAI,CAACR,MAAM,CAAE,CACX,GAAIF,cAAc,CAAE,CAClB,KAAM,CAAAW,GAAG,CAAGZ,YAAY,CAAC,CAAC,CAC1BG,MAAM,CAAGS,GAAG,WAAY,CAAAC,OAAO,CAC3BD,GAAG,CAACE,IAAI,CAAEC,SAAS,EAAK,CACxB,KAAM,CAAAC,GAAG,CAAGZ,eAAe,CAACW,SAAS,CAACE,MAAM,EAAI,CAAC,CAAC,CAAC,CACnDd,MAAM,CAAGa,GAAG,CACZ,MAAO,CAAAA,GACT,CAAC,CAAC,CACAZ,eAAe,CAACQ,GAAG,CAACK,MAAM,EAAI,CAAC,CAAC,CACtC,CAAC,IAAM,CACL,KAAM,CAAAC,IAAI,CAAGhB,WAAW,CAAU,QAAQ,CAAC,CAC3C,GAAI,CAACgB,IAAI,CAAE,KAAM,CAAAC,KAAK,CAAC,gBAAgB,CAAC,CACxChB,MAAM,CAAGe,IACX,CACF,CAEA,GAAIP,IAAI,EAAKR,MAAM,WAAY,CAAAU,OAAQ,CAAE,CACvC,KAAM,CAAAM,KAAK,CAAC,iCAAiC,CAC/C,CAEA,MAAO,CAAAhB,MACT","ignoreList":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import themedImpl,{COMPOSE,PRIORITY,ThemeProvider}from"@dr.pogodin/react-themes";import
|
|
1
|
+
import themedImpl,{COMPOSE,PRIORITY,ThemeProvider}from"@dr.pogodin/react-themes";import{getConfig}from"./config.js";import*as isomorphy from"./isomorphy/index.js";import time from"./time.js";import*as webpack from"./webpack.js";export{assertEmptyObject,Barrier,Cached,Emitter,Semaphore,withRetries}from"@dr.pogodin/js-utils";export{getSsrContext}from"./globalState.js";export{default as splitComponent}from"./splitComponent.js";const themed=themedImpl;themed.COMPOSE=COMPOSE;themed.PRIORITY=PRIORITY;export{getConfig,isomorphy,themed,ThemeProvider,time,webpack};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["themedImpl","COMPOSE","PRIORITY","ThemeProvider","
|
|
1
|
+
{"version":3,"file":"index.js","names":["themedImpl","COMPOSE","PRIORITY","ThemeProvider","getConfig","isomorphy","time","webpack","assertEmptyObject","Barrier","Cached","Emitter","Semaphore","withRetries","getSsrContext","default","splitComponent","themed"],"sources":["../../../../src/shared/utils/index.ts"],"sourcesContent":["import themedImpl, {\n COMPOSE,\n PRIORITY,\n type Theme,\n ThemeProvider,\n} from '@dr.pogodin/react-themes';\n\nimport { getConfig } from './config';\nimport * as isomorphy from './isomorphy';\nimport time from './time';\nimport * as webpack from './webpack';\n\nexport {\n assertEmptyObject,\n type Listener,\n type ObjectKey,\n Barrier,\n Cached,\n Emitter,\n Semaphore,\n withRetries,\n} from '@dr.pogodin/js-utils';\n\nexport { getSsrContext } from './globalState';\nexport { default as splitComponent } from './splitComponent';\n\ntype ThemedT = typeof themedImpl & {\n COMPOSE: typeof COMPOSE;\n PRIORITY: typeof PRIORITY;\n};\n\nconst themed: ThemedT = themedImpl as ThemedT;\n\nthemed.COMPOSE = COMPOSE;\nthemed.PRIORITY = PRIORITY;\n\nexport {\n type Theme,\n getConfig,\n isomorphy,\n themed,\n ThemeProvider,\n time,\n webpack,\n};\n"],"mappings":"AAAA,MAAO,CAAAA,UAAU,EACfC,OAAO,CACPC,QAAQ,CAERC,aAAa,KACR,0BAA0B,QAExBC,SAAS,yBACX,GAAK,CAAAC,SAAS,kCACd,CAAAC,IAAI,uBACJ,GAAK,CAAAC,OAAO,oBAEnB,OACEC,iBAAiB,CAGjBC,OAAO,CACPC,MAAM,CACNC,OAAO,CACPC,SAAS,CACTC,WAAW,KACN,sBAAsB,QAEpBC,aAAa,+BACbC,OAAO,GAAI,CAAAC,cAAc,2BAOlC,KAAM,CAAAC,MAAe,CAAGjB,UAAqB,CAE7CiB,MAAM,CAAChB,OAAO,CAAGA,OAAO,CACxBgB,MAAM,CAACf,QAAQ,CAAGA,QAAQ,CAE1B,OAEEE,SAAS,CACTC,SAAS,CACTY,MAAM,CACNd,aAAa,CACbG,IAAI,CACJC,OAAO","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
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");
|
|
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");const inj=await getInj();return inj.CHUNK_GROUPS??{}})()}const refCounts={};function getPublicPath(){return getBuildInfo().publicPath}/**
|
|
2
2
|
* Client-side only! Ensures the specified CSS stylesheet is loaded into
|
|
3
3
|
* the document; loads if it is missing; and does simple reference counting
|
|
4
4
|
* to facilitate future clean-up.
|
|
@@ -1 +1 @@
|
|
|
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,MAAO,CAAC,SAAY,CAClB,KAAM,CAAEC,OAAO,CAAEC,MAAO,CAAC,CAAG,KAAM,OAAM,CAAC,2EAA4E,CAAC,CACtH,MAAO,CAAAA,MAAM,CAAC,CAAC,CAACC,YAAY,EAAI,CAAC,CACnC,CAAC,EAAE,CACL,CAEA,KAAM,CAAAC,SAAiC,CAAG,CAAC,CAAC,CAE5C,QAAS,CAAAC,aAAaA,CAAA,CAAG,CACvB,MAAO,CAAAT,YAAY,CAAC,CAAC,CAACU,UACxB,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,CAAAC,cAAcA,CACrBC,IAAY,CACZC,YAAyB,CACzBC,QAAiB,CACU,CAC3B,GAAI,CAAAC,GAA8B,CAClC,KAAM,CAAAC,IAAI,CAAG,GAAGP,aAAa,CAAC,CAAC,IAAIG,IAAI,EAAE,CACzC,KAAM,C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A,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
|
+
{"version":3,"file":"splitComponent.js","names":["Suspense","lazy","useInsertionEffect","Barrier","getSsrContext","IS_CLIENT_SIDE","IS_SERVER_SIDE","getBuildInfo","jsx","_jsx","getClientChunkGroups","undefined","default","getInj","inj","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\n const inj = await getInj();\n return inj.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\ntype GenericComponentPropsT = {\n children?: ReactNode;\n ref?: RefObject<unknown>;\n\n // NOTE: This is necessary, as without it this type (with only optional\n // fields) will be conisdered as \"weak\" by TypeScript, and it will be\n // a error to assign to it any type that does not use \"children\", or \"ref\".\n [propName: string]: unknown;\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 GenericComponentPropsT,\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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
|
* @param [options={}] Optional. Additional settings.
|
|
10
10
|
*/
|
|
11
|
-
export default function Launch(Application: ComponentType, options?: OptionsT): void
|
|
11
|
+
export default function Launch(Application: ComponentType, options?: OptionsT): Promise<void>;
|
|
12
12
|
export {};
|
|
@@ -6,5 +6,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';
|
|
9
|
-
export { assertEmptyObject,
|
|
9
|
+
export { assertEmptyObject, Barrier, Cached, Emitter, getConfig, isomorphy, getSsrContext, type Listener, type ObjectKey, Semaphore, splitComponent, type Theme, themed, ThemeProvider, time, webpack, withRetries, } from './shared/utils';
|
|
10
10
|
export { client, server };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import themedImpl, { COMPOSE, PRIORITY, type Theme, ThemeProvider } from '@dr.pogodin/react-themes';
|
|
2
|
-
import
|
|
2
|
+
import { getConfig } from './config';
|
|
3
3
|
import * as isomorphy from './isomorphy';
|
|
4
4
|
import time from './time';
|
|
5
5
|
import * as webpack from './webpack';
|
|
@@ -11,4 +11,4 @@ type ThemedT = typeof themedImpl & {
|
|
|
11
11
|
PRIORITY: typeof PRIORITY;
|
|
12
12
|
};
|
|
13
13
|
declare const themed: ThemedT;
|
|
14
|
-
export { type Theme,
|
|
14
|
+
export { type Theme, getConfig, isomorphy, themed, ThemeProvider, time, webpack, };
|
|
@@ -21,6 +21,11 @@ export declare function freeStyleSheets(chunkName: string, chunkGroups: ChunkGro
|
|
|
21
21
|
type ComponentOrModule<PropsT> = ComponentType<PropsT> | {
|
|
22
22
|
default: ComponentType<PropsT>;
|
|
23
23
|
};
|
|
24
|
+
type GenericComponentPropsT = {
|
|
25
|
+
children?: ReactNode;
|
|
26
|
+
ref?: RefObject<unknown>;
|
|
27
|
+
[propName: string]: unknown;
|
|
28
|
+
};
|
|
24
29
|
/**
|
|
25
30
|
* Given an async component retrieval function `getComponent()` it creates
|
|
26
31
|
* a special "code split" component, which uses <Suspense> to asynchronously
|
|
@@ -31,10 +36,7 @@ type ComponentOrModule<PropsT> = ComponentType<PropsT> | {
|
|
|
31
36
|
* @param {React.Element} [options.placeholder]
|
|
32
37
|
* @return {React.ElementType}
|
|
33
38
|
*/
|
|
34
|
-
export default function splitComponent<ComponentPropsT extends {
|
|
35
|
-
children?: ReactNode;
|
|
36
|
-
ref?: RefObject<unknown>;
|
|
37
|
-
}>({ chunkName, getComponent, placeholder, }: {
|
|
39
|
+
export default function splitComponent<ComponentPropsT extends GenericComponentPropsT>({ chunkName, getComponent, placeholder, }: {
|
|
38
40
|
chunkName: string;
|
|
39
41
|
getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;
|
|
40
42
|
placeholder?: ReactNode;
|
|
@@ -2,46 +2,57 @@
|
|
|
2
2
|
|
|
3
3
|
/* global document */
|
|
4
4
|
|
|
5
|
-
// Note: this way, only required part of "node-forge": AES, and some utils,
|
|
6
|
-
// is bundled into client-side code.
|
|
7
|
-
import forge from 'node-forge/lib/forge.js';
|
|
8
|
-
|
|
9
|
-
// eslint-disable-next-line import/no-unassigned-import
|
|
10
|
-
import 'node-forge/lib/aes.js';
|
|
11
5
|
import { getBuildInfo } from "../shared/utils/isomorphy/buildInfo";
|
|
6
|
+
let inj;
|
|
7
|
+
export default function getInj() {
|
|
8
|
+
inj ??= (async () => {
|
|
9
|
+
const metaElement = typeof document === 'undefined' ? null : document.querySelector('meta[itemprop="drpruinj"]');
|
|
10
|
+
if (metaElement) {
|
|
11
|
+
metaElement.remove();
|
|
12
12
|
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
|
|
16
|
-
let inj = {};
|
|
17
|
-
const metaElement = typeof document === 'undefined' ? null : document.querySelector('meta[itemprop="drpruinj"]');
|
|
18
|
-
if (metaElement) {
|
|
19
|
-
metaElement.remove();
|
|
20
|
-
let data = forge.util.decode64(metaElement.content);
|
|
21
|
-
const {
|
|
22
|
-
key
|
|
23
|
-
} = getBuildInfo();
|
|
24
|
-
const d = forge.cipher.createDecipher('AES-CBC', key);
|
|
25
|
-
d.start({
|
|
26
|
-
iv: data.slice(0, key.length)
|
|
27
|
-
});
|
|
28
|
-
d.update(forge.util.createBuffer(data.slice(key.length)));
|
|
29
|
-
d.finish();
|
|
30
|
-
data = forge.util.decodeUtf8(d.output.data);
|
|
13
|
+
// NOTE: Since 2025 there is Uint8Array.fromBase64(), which should be
|
|
14
|
+
// preferred, but it is not supported by older environments yet.
|
|
15
|
+
const data = atob(metaElement.content);
|
|
31
16
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
17
|
+
// TODO: Our current handling of this encryption / decryption follows
|
|
18
|
+
// a legacy approach, and can be enhanced by using Crypto features.
|
|
19
|
+
// Though, this is not strictly intended to be secure (it is more
|
|
20
|
+
// to obfurscate injected data, rather than really keeping them
|
|
21
|
+
// secure), thus it is fine like this for now.
|
|
22
|
+
const {
|
|
23
|
+
key
|
|
24
|
+
} = getBuildInfo();
|
|
25
|
+
const code = x => x.charCodeAt(0);
|
|
26
|
+
const dataBuffer = Uint8Array.from(data.slice(16), code);
|
|
27
|
+
const ivBuffer = Uint8Array.from(data.slice(0, 16), code);
|
|
28
|
+
const keyBuffer = Uint8Array.from(atob(key), code);
|
|
29
|
+
const cKey = await window.crypto.subtle.importKey('raw', keyBuffer, {
|
|
30
|
+
name: 'AES-CBC'
|
|
31
|
+
}, false, ['decrypt']);
|
|
32
|
+
const buffer = await window.crypto.subtle.decrypt({
|
|
33
|
+
iv: ivBuffer,
|
|
34
|
+
name: 'AES-CBC'
|
|
35
|
+
}, cKey, dataBuffer);
|
|
36
|
+
const decoder = new TextDecoder();
|
|
37
|
+
|
|
38
|
+
// eslint-disable-next-line no-eval
|
|
39
|
+
const res = eval(`(${decoder.decode(buffer)})`);
|
|
40
|
+
|
|
41
|
+
// NOTE: This is important, to be able to return the injection
|
|
42
|
+
// synchronously once it is initialized.
|
|
43
|
+
inj = res;
|
|
44
|
+
return res;
|
|
45
|
+
} else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {
|
|
46
|
+
const res = window.REACT_UTILS_INJECTION;
|
|
47
|
+
delete window.REACT_UTILS_INJECTION;
|
|
48
|
+
return res;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Otherwise, a bunch of dependent stuff will easily fail in non-standard
|
|
52
|
+
// environments, where no client-side initialization is performed. Like tests,
|
|
53
|
+
// Docusaurus examples, etc.
|
|
54
|
+
return {};
|
|
55
|
+
})();
|
|
45
56
|
return inj;
|
|
46
57
|
}
|
|
47
58
|
//# sourceMappingURL=getInj.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getInj.js","names":["
|
|
1
|
+
{"version":3,"file":"getInj.js","names":["getBuildInfo","inj","getInj","metaElement","document","querySelector","remove","data","atob","content","key","code","x","charCodeAt","dataBuffer","Uint8Array","from","slice","ivBuffer","keyBuffer","cKey","window","crypto","subtle","importKey","name","buffer","decrypt","iv","decoder","TextDecoder","res","eval","decode","REACT_UTILS_INJECTION"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nlet inj: InjT | Promise<InjT> | undefined;\n\nexport default function getInj(): InjT | Promise<InjT> {\n inj ??= (async () => {\n const metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\n if (metaElement) {\n metaElement.remove();\n\n // NOTE: Since 2025 there is Uint8Array.fromBase64(), which should be\n // preferred, but it is not supported by older environments yet.\n const data = atob(metaElement.content);\n\n // TODO: Our current handling of this encryption / decryption follows\n // a legacy approach, and can be enhanced by using Crypto features.\n // Though, this is not strictly intended to be secure (it is more\n // to obfurscate injected data, rather than really keeping them\n // secure), thus it is fine like this for now.\n const { key } = getBuildInfo();\n\n const code = (x: string) => x.charCodeAt(0);\n const dataBuffer = Uint8Array.from(data.slice(16), code);\n const ivBuffer = Uint8Array.from(data.slice(0, 16), code);\n const keyBuffer = Uint8Array.from(atob(key), code);\n\n const cKey = await window.crypto.subtle.importKey(\n 'raw',\n keyBuffer,\n { name: 'AES-CBC' },\n false,\n ['decrypt'],\n );\n\n const buffer = await window.crypto.subtle.decrypt({\n iv: ivBuffer,\n name: 'AES-CBC',\n }, cKey, dataBuffer);\n\n const decoder = new TextDecoder();\n\n // eslint-disable-next-line no-eval\n const res = eval(`(${decoder.decode(buffer)})`) as InjT;\n\n // NOTE: This is important, to be able to return the injection\n // synchronously once it is initialized.\n inj = res;\n\n return res;\n } else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n const res = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n return res;\n }\n\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 return {};\n })();\n\n return inj;\n}\n"],"mappings":"AAAA;;AAEA;;AAIA,SAASA,YAAY;AAErB,IAAIC,GAAqC;AAEzC,eAAe,SAASC,MAAMA,CAAA,EAAyB;EACrDD,GAAG,KAAK,CAAC,YAAY;IACnB,MAAME,WAAmC,GAAG,OAAOC,QAAQ,KAAK,WAAW,GACvE,IAAI,GAAGA,Q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IAAI,OAAOV,MAAM,KAAK,WAAW,IAAIA,MAAM,CAACa,qBAAqB,EAAE;MACxE,MAAMH,GAAG,GAAGV,MAAM,CAACa,qBAAqB;MACxC,OAAOb,MAAM,CAACa,qBAAqB;MACnC,OAAOH,GAAG;IACZ;;IAEA;IACA;IACA;IACA,OAAO,CAAC,CAAC;EACX,CAAC,EAAE,CAAC;EAEJ,OAAO9B,GAAG;AACZ","ignoreList":[]}
|
|
@@ -12,11 +12,12 @@ import { jsx as _jsx } from "react/jsx-runtime";
|
|
|
12
12
|
* @param Application Root application component
|
|
13
13
|
* @param [options={}] Optional. Additional settings.
|
|
14
14
|
*/
|
|
15
|
-
export default function Launch(Application, options = {}) {
|
|
15
|
+
export default async function Launch(Application, options = {}) {
|
|
16
|
+
const inj = await getInj();
|
|
16
17
|
const container = document.getElementById('react-view');
|
|
17
18
|
if (!container) throw Error('Failed to find container for React app');
|
|
18
19
|
const scene = /*#__PURE__*/_jsx(GlobalStateProvider, {
|
|
19
|
-
initialState:
|
|
20
|
+
initialState: inj.ISTATE ?? options.initialState,
|
|
20
21
|
children: /*#__PURE__*/_jsx(BrowserRouter, {
|
|
21
22
|
children: /*#__PURE__*/_jsx(HelmetProvider, {
|
|
22
23
|
children: /*#__PURE__*/_jsx(Application, {})
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["createRoot","hydrateRoot","HelmetProvider","BrowserRouter","GlobalStateProvider","getInj","jsx","_jsx","Launch","Application","options","container","document","getElementById","Error","scene","initialState","ISTATE","children","dontHydrate","root","render"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport type { ComponentType } from 'react';\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { BrowserRouter } from 'react-router';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: unknown;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport default function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n): void {\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={
|
|
1
|
+
{"version":3,"file":"index.js","names":["createRoot","hydrateRoot","HelmetProvider","BrowserRouter","GlobalStateProvider","getInj","jsx","_jsx","Launch","Application","options","inj","container","document","getElementById","Error","scene","initialState","ISTATE","children","dontHydrate","root","render"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport type { ComponentType } from 'react';\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { BrowserRouter } from 'react-router';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: unknown;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport default async function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n): Promise<void> {\n const inj = await getInj();\n\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={inj.ISTATE ?? options.initialState}>\n <BrowserRouter>\n <HelmetProvider>\n <Application />\n </HelmetProvider>\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":"AAAA;AACA;;AAGA,SAASA,UAAU,EAAEC,WAAW,QAAQ,kBAAkB;AAC1D,SAASC,cAAc,QAAQ,0BAA0B;AACzD,SAASC,aAAa,QAAQ,cAAc;AAE5C,SAASC,mBAAmB,QAAQ,gCAAgC;AAEpE,OAAOC,MAAM;AAAiB,SAAAC,GAAA,IAAAC,IAAA;AAO9B;AACA;AACA;AACA;AACA;AACA,eAAe,eAAeC,MAAMA,CAClCC,WAA0B,EAC1BC,OAAiB,GAAG,CAAC,CAAC,EACP;EACf,MAAMC,GAAG,GAAG,MAAMN,MAAM,CAAC,CAAC;EAE1B,MAAMO,SAAS,GAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC;EACvD,IAAI,CAACF,SAAS,EAAE,MAAMG,KAAK,CAAC,wCAAwC,CAAC;EACrE,MAAMC,KAAK,gBACTT,IAAA,CAACH,mBAAmB;IAACa,YAAY,EAAEN,GAAG,CAACO,MAAM,IAAIR,OAAO,CAACO,YAAa;IAAAE,QAAA,eACpEZ,IAAA,CAACJ,aAAa;MAAAgB,QAAA,eACZZ,IAAA,CAACL,cAAc;QAAAiB,QAAA,eACbZ,IAAA,CAACE,WAAW,IAAE;MAAC,CACD;IAAC,CACJ;EAAC,CACG,CACtB;EAED,IAAIC,OAAO,CAACU,WAAW,EAAE;IACvB,MAAMC,IAAI,GAAGrB,UAAU,CAACY,SAAS,CAAC;IAClCS,IAAI,CAACC,MAAM,CAACN,KAAK,CAAC;EACpB,CAAC,MAAMf,WAAW,CAACW,SAAS,EAAEI,KAAK,CAAC;AACtC","ignoreList":[]}
|
package/build/web/index.js
CHANGED
|
@@ -12,12 +12,12 @@ if (global.REACT_UTILS_LIBRARY_LOADED) {
|
|
|
12
12
|
// TODO: This is a rapid workaround to get rid of __dirname. I guess, later
|
|
13
13
|
// we'll re-implement requireWeak() to accept import.meta.url directly, and
|
|
14
14
|
// this workaround won't be needed.
|
|
15
|
-
|
|
16
|
-
dirname =
|
|
15
|
+
// eslint-disable-next-line @typescript-eslint/prefer-destructuring
|
|
16
|
+
const dirname = import.meta.dirname;
|
|
17
17
|
const server = webpack.requireWeak('./server', dirname);
|
|
18
18
|
const client = server ? undefined : clientModule;
|
|
19
19
|
export { getGlobalState, GlobalStateProvider, newAsyncDataEnvelope, useAsyncCollection, useAsyncData, useGlobalState, withGlobalStateType } from '@dr.pogodin/react-global-state';
|
|
20
20
|
export * from "./shared/components";
|
|
21
|
-
export { assertEmptyObject,
|
|
21
|
+
export { assertEmptyObject, Barrier, Cached, Emitter, getConfig, isomorphy, getSsrContext, Semaphore, splitComponent, themed, ThemeProvider, time, webpack, withRetries } from "./shared/utils";
|
|
22
22
|
export { client, server };
|
|
23
23
|
//# sourceMappingURL=index.js.map
|
package/build/web/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["clientModule","webpack","global","REACT_UTILS_LIBRARY_LOADED","Error","dirname","import","meta","
|
|
1
|
+
{"version":3,"file":"index.js","names":["clientModule","webpack","global","REACT_UTILS_LIBRARY_LOADED","Error","dirname","import","meta","server","requireWeak","client","undefined","getGlobalState","GlobalStateProvider","newAsyncDataEnvelope","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType","assertEmptyObject","Barrier","Cached","Emitter","getConfig","isomorphy","getSsrContext","Semaphore","splitComponent","themed","ThemeProvider","time","withRetries"],"sources":["../../src/index.ts"],"sourcesContent":["import 'styles/global.scss';\n\nimport clientModule from './client';\nimport { webpack } from './shared/utils';\n\nimport type * as ServerFactoryM from './server';\n\n// It is a safeguard against multiple instances / versions of the library\n// being loaded into environment by mistake (e.g. because of different\n// packages pinning down different exact versions of the lib, thus preventing\n// a proper dedupe and using a single common library version).\nif (global.REACT_UTILS_LIBRARY_LOADED) {\n throw Error('React utils library is already loaded');\n} else global.REACT_UTILS_LIBRARY_LOADED = true;\n\n// TODO: This is a rapid workaround to get rid of __dirname. I guess, later\n// we'll re-implement requireWeak() to accept import.meta.url directly, and\n// this workaround won't be needed.\n// eslint-disable-next-line @typescript-eslint/prefer-destructuring\nconst dirname = import.meta.dirname;\n\nconst server = webpack.requireWeak<typeof ServerFactoryM>('./server', dirname);\n\nconst client = server ? undefined : clientModule;\n\nexport {\n type AsyncCollectionT,\n type AsyncCollectionLoaderT,\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type ForceT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateResT,\n type ValueOrInitializerT,\n getGlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n withGlobalStateType,\n} from '@dr.pogodin/react-global-state';\n\nexport * from 'components';\n\nexport {\n type BeforeRenderResT,\n type BeforeRenderT,\n type ConfigT,\n type ServerSsrContext,\n type ServerT,\n} from './server';\n\nexport {\n assertEmptyObject,\n Barrier,\n Cached,\n Emitter,\n getConfig,\n isomorphy,\n getSsrContext,\n type Listener,\n type ObjectKey,\n Semaphore,\n splitComponent,\n type Theme,\n themed,\n ThemeProvider,\n time,\n webpack,\n withRetries,\n} from 'utils';\n\nexport { client, server };\n"],"mappings":"AAAA;AAEA,OAAOA,YAAY;AACnB,SAASC,OAAO;AAIhB;AACA;AACA;AACA;AACA,IAAIC,MAAM,CAACC,0BAA0B,EAAE;EACrC,MAAMC,KAAK,CAAC,uCAAuC,CAAC;AACtD,CAAC,MAAMF,MAAM,CAACC,0BAA0B,GAAG,IAAI;;AAE/C;AACA;AACA;AACA;AACA,MAAME,OAAO,GAAGC,MAAM,CAACC,IAAI,CAACF,OAAO;AAEnC,MAAMG,MAAM,GAAGP,OAAO,CAACQ,WAAW,CAAwB,UAAU,EAAEJ,OAAO,CAAC;AAE9E,MAAMK,MAAM,GAAGF,MAAM,GAAGG,SAAS,GAAGX,YAAY;AAEhD,SAUEY,cAAc,EACdC,mBAAmB,EACnBC,oBAAoB,EACpBC,kBAAkB,EAClBC,YAAY,EACZC,cAAc,EACdC,mBAAmB,QACd,gCAAgC;AAEvC;AAUA,SACEC,iBAAiB,EACjBC,OAAO,EACPC,MAAM,EACNC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,aAAa,EAGbC,SAAS,EACTC,cAAc,EAEdC,MAAM,EACNC,aAAa,EACbC,IAAI,EACJ7B,OAAO,EACP8B,WAAW;AAGb,SAASrB,MAAM,EAAEF,MAAM","ignoreList":[]}
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
* ExpressJS middleware for server-side rendering of a ReactJS app.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
+
import { Buffer } from 'node:buffer';
|
|
6
|
+
import { createCipheriv, randomBytes } from 'node:crypto';
|
|
5
7
|
import fs from 'node:fs';
|
|
6
8
|
import path from 'node:path';
|
|
7
9
|
import { Writable } from 'node:stream';
|
|
@@ -11,7 +13,6 @@ import { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state'
|
|
|
11
13
|
import { timer } from '@dr.pogodin/js-utils';
|
|
12
14
|
import { cloneDeep, defaults, get, mapValues } from 'lodash-es';
|
|
13
15
|
import config from 'config';
|
|
14
|
-
import forge from 'node-forge';
|
|
15
16
|
import { prerenderToNodeStream } from 'react-dom/static';
|
|
16
17
|
import { HelmetProvider } from '@dr.pogodin/react-helmet';
|
|
17
18
|
import { StaticRouter } from 'react-router';
|
|
@@ -87,27 +88,15 @@ function readChunkGroupsJson(buildDir) {
|
|
|
87
88
|
|
|
88
89
|
/**
|
|
89
90
|
* Prepares a new Cipher for data encryption.
|
|
90
|
-
* @param key Encryption key (32-bit random key is expected
|
|
91
|
-
*
|
|
92
|
-
* @return Resolves to the object with two fields:
|
|
91
|
+
* @param key Encryption key (32-bit random, Base64-encoded key is expected).
|
|
92
|
+
* @return Returns a tuple of:
|
|
93
93
|
* 1. cipher - a new Cipher, ready for encryption;
|
|
94
94
|
* 2. iv - initial vector used by the cipher.
|
|
95
95
|
*/
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
const cipher = forge.cipher.createCipher('AES-CBC', key);
|
|
101
|
-
cipher.start({
|
|
102
|
-
iv
|
|
103
|
-
});
|
|
104
|
-
resolve({
|
|
105
|
-
cipher,
|
|
106
|
-
iv
|
|
107
|
-
});
|
|
108
|
-
}
|
|
109
|
-
});
|
|
110
|
-
});
|
|
96
|
+
function prepareCipher(key) {
|
|
97
|
+
const iv = randomBytes(16);
|
|
98
|
+
const cipher = createCipheriv('AES-256-CBC', Buffer.from(key, 'base64'), iv);
|
|
99
|
+
return [cipher, iv];
|
|
111
100
|
}
|
|
112
101
|
|
|
113
102
|
/**
|
|
@@ -301,17 +290,12 @@ export default function factory(webpackConfig, options) {
|
|
|
301
290
|
}
|
|
302
291
|
}
|
|
303
292
|
const brr = ops.beforeRender(req, sanitizedConfig);
|
|
304
|
-
const
|
|
293
|
+
const {
|
|
305
294
|
configToInject,
|
|
306
295
|
extraScripts,
|
|
307
296
|
initialState
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
iv
|
|
311
|
-
}] = await Promise.all([
|
|
312
|
-
// NOTE: Written this way to avoid triggering the "await-thenable"
|
|
313
|
-
// ESLint rule.
|
|
314
|
-
brr instanceof Promise ? brr : Promise.resolve(brr), prepareCipher(buildInfo.key)]);
|
|
297
|
+
} = await brr;
|
|
298
|
+
const [cipher, iv] = prepareCipher(buildInfo.key);
|
|
315
299
|
let helmet;
|
|
316
300
|
|
|
317
301
|
// Gets the mapping between code chunk names and their asset files.
|
|
@@ -431,9 +415,7 @@ export default function factory(webpackConfig, options) {
|
|
|
431
415
|
ignoreFunction: true,
|
|
432
416
|
unsafe: true
|
|
433
417
|
});
|
|
434
|
-
cipher.update(
|
|
435
|
-
cipher.finish();
|
|
436
|
-
const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);
|
|
418
|
+
const INJ = Buffer.concat([iv, cipher.update(payload, 'utf8'), cipher.final()]).toString('base64');
|
|
437
419
|
const chunkSet = new Set();
|
|
438
420
|
|
|
439
421
|
// TODO: "main" chunk has to be added explicitly,
|