@dr.pogodin/react-utils 1.17.4 → 1.17.7
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/index.js.map +1 -1
- package/build/development/client/init.js.map +1 -1
- package/build/development/index.js +7 -0
- package/build/development/index.js.map +1 -1
- package/build/development/server/index.js +6 -31
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js +105 -24
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +4 -2
- package/build/development/server/server.js.map +1 -1
- package/build/development/server/utils/errors.js.map +1 -1
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/CodeSplit/index.js.map +1 -1
- package/build/development/shared/components/Dropdown/index.js.map +1 -1
- package/build/development/shared/components/GenericLink/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/MetaTags.js.map +1 -1
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/PageLayout/index.js.map +1 -1
- package/build/development/shared/components/ScalableRect/index.js.map +1 -1
- package/build/development/shared/components/Throbber/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/utils/Semaphore.js.map +1 -1
- package/build/development/shared/utils/config.js.map +1 -1
- package/build/development/shared/utils/index.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv.js +26 -7
- package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/development/shared/utils/jest/index.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/time.js.map +1 -1
- package/build/development/web.bundle.js +1 -1
- package/build/production/client/index.js.map +1 -1
- package/build/production/client/init.js.map +1 -1
- package/build/production/index.js +1 -1
- package/build/production/index.js.map +1 -1
- package/build/production/server/Cache.js.map +1 -1
- package/build/production/server/index.js +3 -3
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js +18 -8
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +2 -2
- package/build/production/server/server.js.map +1 -1
- package/build/production/server/utils/errors.js.map +1 -1
- package/build/production/shared/components/Button/index.js.map +1 -1
- package/build/production/shared/components/Checkbox/index.js.map +1 -1
- package/build/production/shared/components/CodeSplit/index.js.map +1 -1
- package/build/production/shared/components/Dropdown/index.js.map +1 -1
- package/build/production/shared/components/GenericLink/index.js.map +1 -1
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/Link.js.map +1 -1
- package/build/production/shared/components/MetaTags.js.map +1 -1
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/NavLink.js.map +1 -1
- package/build/production/shared/components/PageLayout/index.js.map +1 -1
- package/build/production/shared/components/ScalableRect/index.js.map +1 -1
- package/build/production/shared/components/Throbber/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/utils/Barrier.js.map +1 -1
- package/build/production/shared/utils/Emitter.js.map +1 -1
- package/build/production/shared/utils/Semaphore.js.map +1 -1
- package/build/production/shared/utils/config.js.map +1 -1
- package/build/production/shared/utils/index.js.map +1 -1
- package/build/production/shared/utils/isomorphy.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js +9 -7
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/production/shared/utils/jest/index.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/time.js.map +1 -1
- package/build/production/shared/utils/webpack.js.map +1 -1
- package/build/production/web.bundle.js +1 -1
- package/build/production/web.bundle.js.map +1 -1
- package/config/webpack/app-base.js +8 -2
- package/config/webpack/app-development.js +0 -1
- package/config/webpack/app-production.js +0 -1
- package/package.json +21 -21
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.SCRIPT_LOCATIONS=void 0;exports.default=factory;exports.isBrotliAcceptable=isBrotliAcceptable;var _stream=require("stream");var _reactGlobalState=require("@dr.pogodin/react-global-state");var _lodash=require("lodash");var _config=_interopRequireDefault(require("config"));var _nodeForge=_interopRequireDefault(require("node-forge"));var _fs=_interopRequireDefault(require("fs"));var _path=_interopRequireDefault(require("path"));var _zlib=require("zlib");var _server=require("react-dom/server");var _reactHelmet=require("react-helmet");var _server2=require("react-router-dom/server");var _serializeJavascript=_interopRequireDefault(require("serialize-javascript"));var _time=_interopRequireDefault(require("../shared/utils/time"));var _Cache=_interopRequireDefault(require("./Cache"));var _jsxRuntime=require("react/jsx-runtime");/**
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.SCRIPT_LOCATIONS=void 0;exports.default=factory;exports.isBrotliAcceptable=isBrotliAcceptable;exports.newDefaultLogger=newDefaultLogger;var _stream=require("stream");var _reactGlobalState=require("@dr.pogodin/react-global-state");var _lodash=require("lodash");var _config=_interopRequireDefault(require("config"));var _nodeForge=_interopRequireDefault(require("node-forge"));var _fs=_interopRequireDefault(require("fs"));var _path=_interopRequireDefault(require("path"));var _zlib=require("zlib");var _server=require("react-dom/server");var _reactHelmet=require("react-helmet");var _server2=require("react-router-dom/server");var _serializeJavascript=_interopRequireDefault(require("serialize-javascript"));var _time=_interopRequireDefault(require("../shared/utils/time"));var _winston=_interopRequireDefault(require("winston"));var _Cache=_interopRequireDefault(require("./Cache"));var _jsxRuntime=require("react/jsx-runtime");/**
|
|
2
2
|
* ExpressJS middleware for server-side rendering of a ReactJS app.
|
|
3
3
|
*/const sanitizedConfig=(0,_lodash.omit)(_config.default,"SECRET");const SCRIPT_LOCATIONS={BODY_OPEN:"BODY_OPEN",DEFAULT:"DEFAULT",HEAD_OPEN:"HEAD_OPEN"};/**
|
|
4
4
|
* Reads build-time information about the app. This information is generated
|
|
@@ -45,6 +45,11 @@
|
|
|
45
45
|
* HEAD_OPEN: string[];
|
|
46
46
|
* }}
|
|
47
47
|
*/function groupExtraScripts(scripts=[]){const res={[SCRIPT_LOCATIONS.BODY_OPEN]:"",[SCRIPT_LOCATIONS.DEFAULT]:"",[SCRIPT_LOCATIONS.HEAD_OPEN]:""};for(let i=0;i<scripts.length;++i){const script=scripts[i];if((0,_lodash.isString)(script)){if(script)res[SCRIPT_LOCATIONS.DEFAULT]+=script}else if(script.code){if(res[script.location]!==undefined){res[script.location]+=script.code}else throw Error(`Invalid location "${script.location}"`)}}return res}/**
|
|
48
|
+
* Creates a new default (Winston) logger.
|
|
49
|
+
* @param {object} [options={}]
|
|
50
|
+
* @param {string} [options.defaultLogLevel='info']
|
|
51
|
+
* @return {object}
|
|
52
|
+
*/function newDefaultLogger({defaultLogLevel="info"}={}){const{format,transports}=_winston.default;return _winston.default.createLogger({level:defaultLogLevel,format:format.combine(format.splat(),format.timestamp(),format.colorize(),format.printf(({level,message,timestamp,stack,...rest})=>{let res=`${level}\t(at ${timestamp}):\t${message}`;if(Object.keys(rest).length){res+=`\n${JSON.stringify(rest,null,2)}`}if(stack)res+=`\n${stack}`;return res})),transports:[new transports.Console]})}/**
|
|
48
53
|
* Creates the middleware.
|
|
49
54
|
* @param {object} webpackConfig
|
|
50
55
|
* @param {object} options Additional options:
|
|
@@ -74,19 +79,22 @@
|
|
|
74
79
|
* - `maxage?: number` – the maximum age of cached result in ms.
|
|
75
80
|
* If undefined - infinite age is assumed.
|
|
76
81
|
* @return {function} Created middleware.
|
|
77
|
-
*/function factory(webpackConfig,options){const ops=(0,_lodash.defaults)((0,_lodash.clone)(options),{beforeRender:()=>Promise.resolve({}),maxSsrRounds:10,ssrTimeout:1000,staticCacheSize:1.e7})
|
|
82
|
+
*/function factory(webpackConfig,options){const ops=(0,_lodash.defaults)((0,_lodash.clone)(options),{beforeRender:()=>Promise.resolve({}),maxSsrRounds:10,ssrTimeout:1000,staticCacheSize:1.e7});// Note: in normal use the default logger is created and set in the root
|
|
83
|
+
// server function, and this initialization is for testing uses, where
|
|
84
|
+
// renderer is imported directly.
|
|
85
|
+
if(ops.logger===undefined){ops.logger=newDefaultLogger({defaultLogLevel:ops.defaultLoggerLogLevel})}const buildInfo=ops.buildInfo||getBuildInfo(webpackConfig.context);global.TRU_BUILD_INFO=buildInfo;// publicPath from webpack.output has a trailing slash at the end.
|
|
78
86
|
const{publicPath,path:outputPath}=webpackConfig.output;const manifestLink=_fs.default.existsSync(`${outputPath}/manifest.json`)?`<link rel="manifest" href="${publicPath}manifest.json">`:"";const cache=ops.staticCacheController?new _Cache.default(ops.staticCacheSize):null;const CHUNK_GROUPS=readChunkGroupsJson(outputPath);return async(req,res,next)=>{try{// Ensures any caches always revalidate HTML markup before reuse.
|
|
79
|
-
res.set("Cache-Control","no-cache");let cacheRef;if(cache){cacheRef=ops.staticCacheController(req);if(cacheRef){const data=cache.get(cacheRef);if(data!==null){if(ops.noCsp&&isBrotliAcceptable(req)){res.set("Content-Type","text/html");res.set("Content-Encoding","br");res.send(
|
|
87
|
+
res.set("Cache-Control","no-cache");let cacheRef;if(cache){cacheRef=ops.staticCacheController(req);if(cacheRef){const data=cache.get(cacheRef);if(data!==null){const{buffer,status}=data;if(ops.noCsp&&isBrotliAcceptable(req)){res.set("Content-Type","text/html");res.set("Content-Encoding","br");if(status!==200)res.status(status);res.send(buffer)}else{await new Promise((done,failed)=>{(0,_zlib.brotliDecompress)(buffer,(error,html)=>{if(error)failed(error);else{let h=html.toString();if(!ops.noCsp){// TODO: Starting from Node v15 we'll be able to use string's
|
|
80
88
|
// .replaceAll() method instead relying on reg. expression for
|
|
81
89
|
// global matching.
|
|
82
|
-
const regex=new RegExp(
|
|
90
|
+
const regex=new RegExp(buffer.nonce,"g");h=h.replace(regex,req.nonce)}if(status!==200)res.status(status);res.send(h);done()}})})}return}}}const[{configToInject,extraScripts,initialState},{cipher,iv}]=await Promise.all([ops.beforeRender(req,sanitizedConfig),prepareCipher(buildInfo.key)]);let helmet;/* Optional server-side rendering. */let App=ops.Application;const ssrContext={req,state:(0,_lodash.cloneDeep)(initialState||{}),// Array of chunk names encountered during the rendering.
|
|
83
91
|
chunks:[]};let stream;if(App){const ssrStart=Date.now();const renderPass=async()=>{ssrContext.chunks=[];return new Promise((resolve,reject)=>{const pipeableStream=(0,_server.renderToPipeableStream)(/*#__PURE__*/(0,_jsxRuntime.jsx)(_reactGlobalState.GlobalStateProvider,{initialState:ssrContext.state,ssrContext:ssrContext,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(_server2.StaticRouter,{location:req.url,children:/*#__PURE__*/(0,_jsxRuntime.jsx)(App,{})})}),{onAllReady:()=>resolve(pipeableStream),onError:reject})})};for(let round=0;round<ops.maxSsrRounds;++round){stream=await renderPass();// eslint-disable-line no-await-in-loop
|
|
84
|
-
if(!ssrContext.dirty)break
|
|
92
|
+
if(!ssrContext.dirty){ops.logger.info(`SSR completed in ${round+1} rounds`);break}/* eslint-disable no-await-in-loop */const timeout=ops.ssrTimeout+ssrStart-Date.now();const ok=timeout>0&&(await Promise.race([Promise.allSettled(ssrContext.pending),_time.default.timer(timeout).then(()=>false)]));if(!ok){ops.logger.warn(`SSR timed out (${ops.ssrTimeout}sec)`);break}/* eslint-enable no-await-in-loop */if(round+1===ops.maxSsrRounds){ops.logger.warn(`SSR reached max number of rounds ${ops.maxSsrRounds}`)}}App="";stream.pipe(new _stream.Writable({write:(chunk,_,done)=>{App+=chunk.toString();done()}}));/* This takes care about server-side rendering of page title and meta tags
|
|
85
93
|
* (still demands injection into HTML template, which happens below). */helmet=_reactHelmet.Helmet.renderStatic()}let chunkGroups;const webpackStats=(0,_lodash.get)(res.locals,"webpack.devMiddleware.stats");if(webpackStats){chunkGroups=(0,_lodash.mapValues)(webpackStats.toJson({all:false,chunkGroups:true}).namedChunkGroups,item=>item.assets.map(({name})=>name))}else if(CHUNK_GROUPS)chunkGroups=CHUNK_GROUPS;else chunkGroups={};/* Encrypts data to be injected into HTML.
|
|
86
94
|
* Keep in mind, that this encryption is no way secure: as the JS bundle
|
|
87
95
|
* contains decryption key and is able to decode it at the client side.
|
|
88
96
|
* Hovewer, for a number of reasons, encryption of injected data is still
|
|
89
|
-
* better than injection of a plain text. */delete ssrContext.state.dr_pogodin_react_utils___split_components;const payload=(0,_serializeJavascript.default)({CHUNK_GROUPS:chunkGroups,CONFIG:configToInject||sanitizedConfig,ISTATE:ssrContext.state},{ignoreFunction:true,unsafe:true});cipher.update(_nodeForge.default.util.createBuffer(payload,"utf8"));cipher.finish();const INJ=_nodeForge.default.util.encode64(`${iv}${cipher.output.data}`);
|
|
97
|
+
* better than injection of a plain text. */delete ssrContext.state.dr_pogodin_react_utils___split_components;const payload=(0,_serializeJavascript.default)({CHUNK_GROUPS:chunkGroups,CONFIG:configToInject||sanitizedConfig,ISTATE:ssrContext.state},{ignoreFunction:true,unsafe:true});cipher.update(_nodeForge.default.util.createBuffer(payload,"utf8"));cipher.finish();const INJ=_nodeForge.default.util.encode64(`${iv}${cipher.output.data}`);const status=ssrContext.status||200;if(status!==200)res.status(status);const chunkSet=new Set;// TODO: "main" chunk has to be added explicitly,
|
|
90
98
|
// because unlike all other chunks they are not managed by <CodeSplit>
|
|
91
99
|
// component, thus they are not added to the ssrContext.chunks
|
|
92
100
|
// automatically. Actually, names of these entry chunks should be
|
|
@@ -125,6 +133,8 @@ if(!ssrContext.dirty)break;/* eslint-disable no-await-in-loop */const timeout=op
|
|
|
125
133
|
${scriptChunkString}
|
|
126
134
|
${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}
|
|
127
135
|
</body>
|
|
128
|
-
</html>`;res.send(html);if(cacheRef){
|
|
129
|
-
|
|
136
|
+
</html>`;res.send(html);if(cacheRef&&status<500){// Note: waiting for the caching to complete is not strictly necessary,
|
|
137
|
+
// but it greately simplifies testing, and error reporting.
|
|
138
|
+
await new Promise((done,failed)=>{(0,_zlib.brotliCompress)(html,(error,buffer)=>{if(error)failed(error);else{buffer.nonce=req.nonce;// eslint-disable-line no-param-reassign
|
|
139
|
+
cache.add({buffer,status},cacheRef.key);done()}})})}}catch(error){next(error)}}}
|
|
130
140
|
//# sourceMappingURL=renderer.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderer.js","names":["sanitizedConfig","config","SCRIPT_LOCATIONS","BODY_OPEN","DEFAULT","HEAD_OPEN","getBuildInfo","context","url","path","resolve","JSON","parse","fs","readFileSync","readChunkGroupsJson","buildDir","res","err","prepareCipher","key","Promise","reject","forge","random","getBytes","iv","cipher","createCipher","start","isBrotliAcceptable","req","acceptable","get","ops","split","i","length","type","priority","trim","parseFloat","groupExtraScripts","scripts","script","code","location","undefined","Error","factory","webpackConfig","options","beforeRender","maxSsrRounds","ssrTimeout","staticCacheSize","buildInfo","global","TRU_BUILD_INFO","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","CHUNK_GROUPS","next","set","cacheRef","data","noCsp","send","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","initialState","all","helmet","App","Application","ssrContext","state","chunks","stream","ssrStart","Date","now","renderPass","pipeableStream","onAllReady","onError","round","dirty","timeout","ok","race","allSettled","pending","time","timer","then","pipe","Writable","write","chunk","_","done","Helmet","renderStatic","chunkGroups","webpackStats","locals","toJson","namedChunkGroups","item","assets","map","name","dr_pogodin_react_utils___split_components","payload","CONFIG","ISTATE","ignoreFunction","unsafe","update","util","createBuffer","finish","INJ","encode64","status","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","buffer"],"sources":["../../../src/server/renderer.jsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Writable } from 'stream';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport {\n clone,\n cloneDeep,\n defaults,\n isString,\n get,\n mapValues,\n omit,\n} from 'lodash';\n\nimport config from 'config';\nimport forge from 'node-forge';\nimport fs from 'fs';\nimport path from 'path';\nimport { brotliCompress, brotliDecompress } from 'zlib';\n\nimport { renderToPipeableStream } from 'react-dom/server';\nimport { Helmet } from 'react-helmet';\nimport { StaticRouter } from 'react-router-dom/server';\nimport serializeJs from 'serialize-javascript';\n\nimport time from 'utils/time';\n\nimport Cache from './Cache';\n\nconst sanitizedConfig = omit(config, 'SECRET');\n\nexport const SCRIPT_LOCATIONS = {\n BODY_OPEN: 'BODY_OPEN',\n DEFAULT: 'DEFAULT',\n HEAD_OPEN: 'HEAD_OPEN',\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @ignore\n * @param {String} context Webpack context path used during the build.\n * @return {Object} Resolves to the build-time information.\n */\nfunction getBuildInfo(context) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url));\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @ignore\n * @param {string} buildDir\n * @return {object}\n */\nfunction readChunkGroupsJson(buildDir) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url));\n } catch (err) {\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @ignore\n * @param {String} key Encryption key (32-bit random key is expected, see\n * node-forge documentation, in case of doubts).\n * @return {Promise} Resolves to the object with two fields:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key) {\n return new Promise((resolve, reject) => {\n forge.random.getBytes(32, (err, iv) => {\n if (err) reject(err);\n else {\n const cipher = forge.cipher.createCipher('AES-CBC', key);\n cipher.start({ iv });\n resolve({ cipher, iv });\n }\n });\n });\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param {object} req\n * @return {boolean}\n * @ignore\n */\nexport function isBrotliAcceptable(req) {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (let i = 0; i < ops.length; ++i) {\n const [type, priority] = ops[i].trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (let i = 0; i < scripts.length; ++i) {\n const script = scripts[i];\n if (isString(script)) {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (res[script.location] !== undefined) {\n res[script.location] += script.code;\n } else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates the middleware.\n * @param {object} webpackConfig\n * @param {object} options Additional options:\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {object} [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param {boolean} [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param {boolean} [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` – the cache key for the response;\n * - `maxage?: number` – the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @return {function} Created middleware.\n */\nexport default function factory(webpackConfig, options) {\n const ops = defaults(clone(options), {\n beforeRender: () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n const buildInfo = ops.buildInfo || getBuildInfo(webpackConfig.context);\n global.TRU_BUILD_INFO = buildInfo;\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath}manifest.json\">` : '';\n\n const cache = ops.staticCacheController\n ? new Cache(ops.staticCacheSize) : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath);\n\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n let cacheRef;\n if (cache) {\n cacheRef = ops.staticCacheController(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n res.send(data);\n } else {\n brotliDecompress(data, (error, html) => {\n if (error) next(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(data.nonce, 'g');\n h = h.replace(regex, req.nonce);\n }\n res.send(h);\n }\n });\n }\n return;\n }\n }\n }\n\n const [{\n configToInject,\n extraScripts,\n initialState,\n }, {\n cipher,\n iv,\n }] = await Promise.all([\n ops.beforeRender(req, sanitizedConfig),\n prepareCipher(buildInfo.key),\n ]);\n\n let helmet;\n\n /* Optional server-side rendering. */\n let App = ops.Application;\n const ssrContext = {\n req,\n state: cloneDeep(initialState || {}),\n\n // Array of chunk names encountered during the rendering.\n chunks: [],\n };\n let stream;\n if (App) {\n const ssrStart = Date.now();\n\n const renderPass = async () => {\n ssrContext.chunks = [];\n return new Promise((resolve, reject) => {\n const pipeableStream = renderToPipeableStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <App />\n </StaticRouter>\n </GlobalStateProvider>,\n {\n onAllReady: () => resolve(pipeableStream),\n onError: reject,\n },\n );\n });\n };\n\n for (let round = 0; round < ops.maxSsrRounds; ++round) {\n stream = await renderPass(); // eslint-disable-line no-await-in-loop\n\n if (!ssrContext.dirty) break;\n\n /* eslint-disable no-await-in-loop */\n const timeout = ops.ssrTimeout + ssrStart - Date.now();\n const ok = timeout > 0 && await Promise.race([\n Promise.allSettled(ssrContext.pending),\n time.timer(timeout).then(() => false),\n ]);\n if (!ok) break;\n /* eslint-enable no-await-in-loop */\n }\n\n App = '';\n stream.pipe(new Writable({\n write: (chunk, _, done) => {\n App += chunk.toString();\n done();\n },\n }));\n\n /* This takes care about server-side rendering of page title and meta tags\n * (still demands injection into HTML template, which happens below). */\n helmet = Helmet.renderStatic();\n }\n\n let chunkGroups;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats');\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets.map(({ name }) => name),\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n delete ssrContext.state.dr_pogodin_react_utils___split_components;\n\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject || sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n cipher.update(forge.util.createBuffer(payload, 'utf8'));\n cipher.finish();\n const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);\n\n if (ssrContext.status) res.status(ssrContext.status);\n\n const chunkSet = new Set();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon ? (\n '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n ) : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet ? helmet.title.toString() : ''}\n ${helmet ? helmet.meta.toString() : ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${App || ''}</div>\n <script\n id=\"inj\"\n type=\"application/javascript\"\n ${ops.noCsp ? '' : `nonce=\"${req.nonce}\"`}\n >\n window.INJ=\"${INJ}\"\n </script>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n res.send(html);\n\n if (cacheRef) {\n brotliCompress(html, (error, buffer) => {\n if (error) throw error;\n buffer.nonce = req.nonce; // eslint-disable-line no-param-reassign\n cache.add(buffer, cacheRef.key);\n });\n }\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":"+PAIA,8BAEA,gEAEA,8BAUA,sDACA,6DACA,8CACA,kDACA,0BAEA,wCACA,yCACA,gDACA,iFAEA,kEAEA,sD,6CA/BA;AACA;AACA,GA+BA,KAAMA,CAAAA,eAAe,CAAG,iBAAKC,eAAL,CAAa,QAAb,CAAxB,CAEO,KAAMC,CAAAA,gBAAgB,CAAG,CAC9BC,SAAS,CAAE,WADmB,CAE9BC,OAAO,CAAE,SAFqB,CAG9BC,SAAS,CAAE,WAHmB,CAAzB,CAMP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,G,0CACA,QAASC,CAAAA,YAAT,CAAsBC,OAAtB,CAA+B,CAC7B,KAAMC,CAAAA,GAAG,CAAGC,cAAKC,OAAL,CAAaH,OAAb,CAAsB,aAAtB,CAAZ,CACA,MAAOI,CAAAA,IAAI,CAAC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AAD,CACL,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"renderer.js","names":["sanitizedConfig","omit","config","SCRIPT_LOCATIONS","BODY_OPEN","DEFAULT","HEAD_OPEN","getBuildInfo","context","url","path","resolve","JSON","parse","fs","readFileSync","readChunkGroupsJson","buildDir","res","err","prepareCipher","key","Promise","reject","forge","random","getBytes","iv","cipher","createCipher","start","isBrotliAcceptable","req","acceptable","get","ops","split","i","length","type","priority","trim","parseFloat","groupExtraScripts","scripts","script","isString","code","location","undefined","Error","newDefaultLogger","defaultLogLevel","format","transports","winston","createLogger","level","combine","splat","timestamp","colorize","printf","message","stack","rest","Object","keys","stringify","Console","factory","webpackConfig","options","defaults","clone","beforeRender","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","global","TRU_BUILD_INFO","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","CHUNK_GROUPS","next","set","cacheRef","data","buffer","status","noCsp","send","done","failed","brotliDecompress","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","initialState","all","helmet","App","Application","ssrContext","state","cloneDeep","chunks","stream","ssrStart","Date","now","renderPass","pipeableStream","renderToPipeableStream","onAllReady","onError","round","dirty","info","timeout","ok","race","allSettled","pending","time","timer","then","warn","pipe","Writable","write","chunk","_","Helmet","renderStatic","chunkGroups","webpackStats","locals","mapValues","toJson","namedChunkGroups","item","assets","map","name","dr_pogodin_react_utils___split_components","payload","serializeJs","CONFIG","ISTATE","ignoreFunction","unsafe","update","util","createBuffer","finish","INJ","encode64","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","brotliCompress"],"sources":["../../../src/server/renderer.jsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Writable } from 'stream';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport {\n clone,\n cloneDeep,\n defaults,\n isString,\n get,\n mapValues,\n omit,\n} from 'lodash';\n\nimport config from 'config';\nimport forge from 'node-forge';\nimport fs from 'fs';\nimport path from 'path';\nimport { brotliCompress, brotliDecompress } from 'zlib';\n\nimport { renderToPipeableStream } from 'react-dom/server';\nimport { Helmet } from 'react-helmet';\nimport { StaticRouter } from 'react-router-dom/server';\nimport serializeJs from 'serialize-javascript';\nimport time from 'utils/time';\nimport winston from 'winston';\n\nimport Cache from './Cache';\n\nconst sanitizedConfig = omit(config, 'SECRET');\n\nexport const SCRIPT_LOCATIONS = {\n BODY_OPEN: 'BODY_OPEN',\n DEFAULT: 'DEFAULT',\n HEAD_OPEN: 'HEAD_OPEN',\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @ignore\n * @param {String} context Webpack context path used during the build.\n * @return {Object} Resolves to the build-time information.\n */\nfunction getBuildInfo(context) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url));\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @ignore\n * @param {string} buildDir\n * @return {object}\n */\nfunction readChunkGroupsJson(buildDir) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url));\n } catch (err) {\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @ignore\n * @param {String} key Encryption key (32-bit random key is expected, see\n * node-forge documentation, in case of doubts).\n * @return {Promise} Resolves to the object with two fields:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key) {\n return new Promise((resolve, reject) => {\n forge.random.getBytes(32, (err, iv) => {\n if (err) reject(err);\n else {\n const cipher = forge.cipher.createCipher('AES-CBC', key);\n cipher.start({ iv });\n resolve({ cipher, iv });\n }\n });\n });\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param {object} req\n * @return {boolean}\n * @ignore\n */\nexport function isBrotliAcceptable(req) {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (let i = 0; i < ops.length; ++i) {\n const [type, priority] = ops[i].trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (let i = 0; i < scripts.length; ++i) {\n const script = scripts[i];\n if (isString(script)) {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (res[script.location] !== undefined) {\n res[script.location] += script.code;\n } else throw Error(`Invalid location \"${script.location}\"`);\n }\n }\n return res;\n}\n\n/**\n * Creates a new default (Winston) logger.\n * @param {object} [options={}]\n * @param {string} [options.defaultLogLevel='info']\n * @return {object}\n */\nexport function newDefaultLogger({\n defaultLogLevel = 'info',\n} = {}) {\n const { format, transports } = winston;\n return winston.createLogger({\n level: defaultLogLevel,\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n timestamp,\n stack,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp}):\\t${message}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack}`;\n return res;\n },\n ),\n ),\n transports: [new transports.Console()],\n });\n}\n\n/**\n * Creates the middleware.\n * @param {object} webpackConfig\n * @param {object} options Additional options:\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {object} [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param {boolean} [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param {boolean} [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` – the cache key for the response;\n * - `maxage?: number` – the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @return {function} Created middleware.\n */\nexport default function factory(webpackConfig, options) {\n const ops = defaults(clone(options), {\n beforeRender: () => Promise.resolve({}),\n maxSsrRounds: 10,\n ssrTimeout: 1000,\n staticCacheSize: 1.e7,\n });\n\n // Note: in normal use the default logger is created and set in the root\n // server function, and this initialization is for testing uses, where\n // renderer is imported directly.\n if (ops.logger === undefined) {\n ops.logger = newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n }\n\n const buildInfo = ops.buildInfo || getBuildInfo(webpackConfig.context);\n global.TRU_BUILD_INFO = buildInfo;\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath}manifest.json\">` : '';\n\n const cache = ops.staticCacheController\n ? new Cache(ops.staticCacheSize) : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath);\n\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n let cacheRef;\n if (cache) {\n cacheRef = ops.staticCacheController(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n h = h.replace(regex, req.nonce);\n }\n if (status !== 200) res.status(status);\n res.send(h);\n done();\n }\n });\n });\n }\n return;\n }\n }\n }\n\n const [{\n configToInject,\n extraScripts,\n initialState,\n }, {\n cipher,\n iv,\n }] = await Promise.all([\n ops.beforeRender(req, sanitizedConfig),\n prepareCipher(buildInfo.key),\n ]);\n\n let helmet;\n\n /* Optional server-side rendering. */\n let App = ops.Application;\n const ssrContext = {\n req,\n state: cloneDeep(initialState || {}),\n\n // Array of chunk names encountered during the rendering.\n chunks: [],\n };\n let stream;\n if (App) {\n const ssrStart = Date.now();\n\n const renderPass = async () => {\n ssrContext.chunks = [];\n return new Promise((resolve, reject) => {\n const pipeableStream = renderToPipeableStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <App />\n </StaticRouter>\n </GlobalStateProvider>,\n {\n onAllReady: () => resolve(pipeableStream),\n onError: reject,\n },\n );\n });\n };\n\n for (let round = 0; round < ops.maxSsrRounds; ++round) {\n stream = await renderPass(); // eslint-disable-line no-await-in-loop\n\n if (!ssrContext.dirty) {\n ops.logger.info(`SSR completed in ${round + 1} rounds`);\n break;\n }\n\n /* eslint-disable no-await-in-loop */\n const timeout = ops.ssrTimeout + ssrStart - Date.now();\n const ok = timeout > 0 && await Promise.race([\n Promise.allSettled(ssrContext.pending),\n time.timer(timeout).then(() => false),\n ]);\n if (!ok) {\n ops.logger.warn(`SSR timed out (${ops.ssrTimeout}sec)`);\n break;\n }\n /* eslint-enable no-await-in-loop */\n\n if (round + 1 === ops.maxSsrRounds) {\n ops.logger.warn(\n `SSR reached max number of rounds ${ops.maxSsrRounds}`,\n );\n }\n }\n\n App = '';\n stream.pipe(new Writable({\n write: (chunk, _, done) => {\n App += chunk.toString();\n done();\n },\n }));\n\n /* This takes care about server-side rendering of page title and meta tags\n * (still demands injection into HTML template, which happens below). */\n helmet = Helmet.renderStatic();\n }\n\n let chunkGroups;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats');\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets.map(({ name }) => name),\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n delete ssrContext.state.dr_pogodin_react_utils___split_components;\n\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject || sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n cipher.update(forge.util.createBuffer(payload, 'utf8'));\n cipher.finish();\n const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n const chunkSet = new Set();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath}${chunk}\" rel=\"stylesheet\">`;\n } else if (\n chunk.endsWith('.js')\n // In dev mode HMR adds JS updates into asset arrays,\n // and they (updates) should be ignored.\n && !chunk.endsWith('.hot-update.js')\n ) {\n scriptChunkString += `<script src=\"${publicPath}${chunk}\" type=\"application/javascript\"></script>`;\n }\n });\n\n const grouppedExtraScripts = groupExtraScripts(extraScripts);\n\n const faviconLink = ops.favicon ? (\n '<link rel=\"shortcut icon\" href=\"/favicon.ico\">'\n ) : '';\n\n const html = `<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.HEAD_OPEN]}\n ${helmet ? helmet.title.toString() : ''}\n ${helmet ? helmet.meta.toString() : ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${styleChunkString}\n ${faviconLink}\n <meta charset=\"utf-8\">\n <meta\n content=\"width=device-width,initial-scale=1.0\"\n name=\"viewport\"\n >\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${App || ''}</div>\n <script\n id=\"inj\"\n type=\"application/javascript\"\n ${ops.noCsp ? '' : `nonce=\"${req.nonce}\"`}\n >\n window.INJ=\"${INJ}\"\n </script>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n res.send(html);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n if (error) failed(error);\n else {\n buffer.nonce = req.nonce; // eslint-disable-line no-param-reassign\n cache.add({ buffer, status }, cacheRef.key);\n done();\n }\n });\n });\n }\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":"ySAIA,8BAEA,gEAEA,8BAUA,sDACA,6DACA,8CACA,kDACA,0BAEA,wCACA,yCACA,gDACA,iFACA,kEACA,wDAEA,sD,6CA/BA;AACA;AACA,GA+BA,KAAMA,gBAAe,CAAG,GAAAC,YAAA,EAAKC,eAAL,CAAa,QAAb,CAAxB,CAEO,KAAMC,iBAAgB,CAAG,CAC9BC,SAAS,CAAE,WADmB,CAE9BC,OAAO,CAAE,SAFqB,CAG9BC,SAAS,CAAE,WAHmB,CAAzB,CAMP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,G,0CACA,QAASC,aAAT,CAAsBC,OAAtB,CAA+B,CAC7B,KAAMC,IAAG,CAAGC,aAAA,CAAKC,OAAL,CAAaH,OAAb,CAAsB,aAAtB,CAAZ,CACA,MAAOI,KAAI,CAACC,KAAL,CAAWC,WAAA,CAAGC,YAAH,CAAgBN,GAAhB,CAAX,CACR,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAASO,oBAAT,CAA6BC,QAA7B,CAAuC,CACrC,KAAMR,IAAG,CAAGC,aAAA,CAAKC,OAAL,CAAaM,QAAb,CAAuB,uBAAvB,CAAZ,CACA,GAAIC,IAAJ,CACA,GAAI,CACFA,GAAG,CAAGN,IAAI,CAACC,KAAL,CAAWC,WAAA,CAAGC,YAAH,CAAgBN,GAAhB,CAAX,CACP,CAAC,MAAOU,GAAP,CAAY,CACZD,GAAG,CAAG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QAAQ,CAAC1E,GAAvC,EACAgF,IAAI,EACL,CACF,CAPD,CAQD,CATK,CAUP,CACF,CAAC,MAAOG,KAAP,CAAc,CACdX,IAAI,CAACW,KAAD,CACL,CACF,CACF"}
|
|
@@ -26,7 +26,7 @@ delete defaultCspSettings.directives["upgrade-insecure-requests"];/**
|
|
|
26
26
|
* }} A deep copy of default CSP settings object used by `react-utils`,
|
|
27
27
|
* with the exception of `nonce-xxx` clause in `script-src` directive,
|
|
28
28
|
* which is added dynamically for each request.
|
|
29
|
-
*/function getDefaultCspSettings(){return(0,_lodash.cloneDeep)(defaultCspSettings)}async function factory(webpackConfig,options){const rendererOps=(0,_lodash.pick)(options,["Application","beforeRender","favicon","maxSsrRounds","noCsp","ssrTimeout","staticCacheController","staticCacheSize"]);const renderer=(0,_renderer.default)(webpackConfig,rendererOps);const{publicPath}=webpackConfig.output;const server=(0,_express.default)();if(options.beforeExpressJsSetup){await options.beforeExpressJsSetup(server)}server.logger=options.logger;if(options.httpsRedirect){server.use((req,res,next)=>{const schema=req.headers["x-forwarded-proto"];if(schema==="http"){let url=`https://${req.headers.host}`;if(req.originalUrl!=="/")url+=req.originalUrl;return res.redirect(url)}return next()})}server.use((0,_compression.default)());server.use((0,_helmet.default)({contentSecurityPolicy:false,crossOriginEmbedderPolicy:false,crossOriginOpenerPolicy:false,crossOriginResourcePolicy:false}));if(!options.noCsp){server.use((req,res,next)=>{req.nonce=(0,_uuid.v4)();// TODO: This is deprecated, but it is kept for now for backward
|
|
29
|
+
*/function getDefaultCspSettings(){return(0,_lodash.cloneDeep)(defaultCspSettings)}async function factory(webpackConfig,options){const rendererOps=(0,_lodash.pick)(options,["Application","beforeRender","favicon","logger","maxSsrRounds","noCsp","ssrTimeout","staticCacheController","staticCacheSize"]);const renderer=(0,_renderer.default)(webpackConfig,rendererOps);const{publicPath}=webpackConfig.output;const server=(0,_express.default)();if(options.beforeExpressJsSetup){await options.beforeExpressJsSetup(server)}server.logger=options.logger;if(options.httpsRedirect){server.use((req,res,next)=>{const schema=req.headers["x-forwarded-proto"];if(schema==="http"){let url=`https://${req.headers.host}`;if(req.originalUrl!=="/")url+=req.originalUrl;return res.redirect(url)}return next()})}server.use((0,_compression.default)());server.use((0,_helmet.default)({contentSecurityPolicy:false,crossOriginEmbedderPolicy:false,crossOriginOpenerPolicy:false,crossOriginResourcePolicy:false}));if(!options.noCsp){server.use((req,res,next)=>{req.nonce=(0,_uuid.v4)();// TODO: This is deprecated, but it is kept for now for backward
|
|
30
30
|
// compatibility. Should be removed sometime later.
|
|
31
31
|
req.cspNonce=req.nonce;// The deep clone is necessary here to ensure that default value can't be
|
|
32
32
|
// mutated during request processing.
|
|
@@ -36,7 +36,7 @@ let cspSettings=(0,_lodash.cloneDeep)(defaultCspSettings);cspSettings.directives
|
|
|
36
36
|
// https://github.com/dart-lang/sdk/issues/27979
|
|
37
37
|
// which manifests itself sometimes when webpack dev middleware is used
|
|
38
38
|
// (in dev mode), and app modules are imported in some unfortunate ways.
|
|
39
|
-
if(!global.location){global.location={href:`${(0,_url.pathToFileURL)(process.cwd()).href}${_path.sep}`}}const webpack=require("webpack");const webpackDevMiddleware=require("webpack-dev-middleware");const webpackHotMiddleware=require("webpack-hot-middleware");const compiler=webpack(webpackConfig);server.use(webpackDevMiddleware(compiler,{publicPath,serverSideRender:true}));server.use(webpackHotMiddleware(compiler))}/* eslint-enable global-require */ /* eslint-enable import/no-extraneous-dependencies */ /* eslint-enable import/no-unresolved */server.use(publicPath,_express.default.static(webpackConfig.output.path));if(options.onExpressJsSetup){await options.onExpressJsSetup(server)}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use(()=>(0,_errors.
|
|
39
|
+
if(!global.location){global.location={href:`${(0,_url.pathToFileURL)(process.cwd()).href}${_path.sep}`}}const webpack=require("webpack");const webpackDevMiddleware=require("webpack-dev-middleware");const webpackHotMiddleware=require("webpack-hot-middleware");const compiler=webpack(webpackConfig);server.use(webpackDevMiddleware(compiler,{publicPath,serverSideRender:true}));server.use(webpackHotMiddleware(compiler))}/* eslint-enable global-require */ /* eslint-enable import/no-extraneous-dependencies */ /* eslint-enable import/no-unresolved */server.use(publicPath,_express.default.static(webpackConfig.output.path));if(options.onExpressJsSetup){await options.onExpressJsSetup(server)}server.use(renderer);/* Detects 404 errors, and forwards them to the error handler. */server.use((req,res,next)=>{next((0,_errors.newError)(_errors.ERRORS.NOT_FOUND,_errors.CODES.NOT_FOUND))});let dontAttachDefaultErrorHandler;if(options.beforeExpressJsError){dontAttachDefaultErrorHandler=await options.beforeExpressJsError(server)}/* Error handler. */if(!dontAttachDefaultErrorHandler){// TODO: It is better to move the default error handler definition
|
|
40
40
|
// to a stand-alone function at top-level, but the use of options.logger
|
|
41
41
|
// prevents to do it without some extra refactoring. Should be done sometime
|
|
42
42
|
// though.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","names":["defaultCspSettings","directives","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","factory","webpackConfig","options","rendererOps","renderer","publicPath","output","server","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","nonce","cspNonce","cspSettings","cspSettingsHook","favicon","send","express","json","limit","urlencoded","extended","requestIp","mw","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","header","devMode","global","location","href","process","cwd","sep","webpack","require","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","static","path","onExpressJsSetup","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","status","INTERNAL_SERVER_ERROR","serverSide","log","message","env","NODE_ENV"],"sources":["../../../src/server/server.js"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport express from 'express';\nimport favicon from 'serve-favicon';\nimport helmet from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport rendererFactory from './renderer';\n\nimport {\n CODES,\n ERRORS,\n fail,\n getErrorForCode,\n} from './utils/errors';\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => array.filter((item) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\ndefaultCspSettings.directives['script-src'].push(\"'unsafe-eval'\");\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings() {\n return cloneDeep(defaultCspSettings);\n}\n\nexport default async function factory(webpackConfig, options) {\n const rendererOps = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output;\n\n const server = express();\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n return res.redirect(url);\n }\n return next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use((req, res, next) => {\n req.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req.cspNonce = req.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings = cloneDeep(defaultCspSettings);\n cspSettings.directives['script-src'].push(`'nonce-${req.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n });\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => res.send('User-agent: *\\nDisallow:'));\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser());\n server.use(requestIp.mw());\n\n loggerMiddleware.token('ip', (req) => req.clientIp);\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n write: options.logger.info.bind(options.logger),\n },\n }));\n\n /* Ensures no caching for the service worker script. */\n server.use(`${publicPath}service-worker.js`, (req, res, next) => {\n res.header('Cache-Control', 'no-cache');\n next();\n });\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable global-require */\n /* eslint-disable import/no-extraneous-dependencies */\n /* eslint-disable import/no-unresolved */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n };\n }\n\n const webpack = require('webpack');\n const webpackDevMiddleware = require('webpack-dev-middleware');\n const webpackHotMiddleware = require('webpack-hot-middleware');\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable global-require */\n /* eslint-enable import/no-extraneous-dependencies */\n /* eslint-enable import/no-unresolved */\n\n server.use(publicPath, express.static(webpackConfig.output.path));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use(() => fail(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n /* eslint-disable no-unused-vars */\n server.use((error, req, res, next) => {\n /* eslint-enable no-unused-vars */\n const status = error.status || CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;\n\n // Log server-side errors always, client-side at debug level only.\n options.logger.log(serverSide ? 'error' : 'debug', error);\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":"qOAIA,0BACA,wBAEA,8BAMA,gEACA,mEACA,wDACA,mE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M,CAACI,GAAP,CAAW,CAACyD,KAAD,CAAQxD,GAAR,CAAaC,GAAb,CAAkBC,IAAlB,GAA2B,CACtC,kCACE,KAAMuD,CAAAA,MAAM,CAAGD,KAAK,CAACC,MAAN,EAAgBJ,cAAMK,qBAArC,CACA,KAAMC,CAAAA,UAAU,CAAGF,MAAM,EAAIJ,cAAMK,qBAAnC,CAEA;AACApE,OAAO,CAACO,MAAR,CAAe+D,GAAf,CAAmBD,UAAU,CAAG,OAAH,CAAa,OAA1C,CAAmDH,KAAnD,EAEA,GAAIK,CAAAA,OAAO,CAAGL,KAAK,CAACK,OAAN,EAAiB,4BAAgBJ,MAAhB,CAA/B,CACA,GAAIE,UAAU,EAAIpB,OAAO,CAACuB,GAAR,CAAYC,QAAZ,GAAyB,YAA3C,CAAyD,CACvDF,OAAO,CAAGV,eAAOO,qBAClB,CAEDzD,GAAG,CAACwD,MAAJ,CAAWA,MAAX,EAAmBvC,IAAnB,CAAwB2C,OAAxB,CACD,CAdD,CAeD,CAED,MAAOlE,CAAAA,MACR"}
|
|
1
|
+
{"version":3,"file":"server.js","names":["defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","requestIp","mw","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","header","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","require","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","static","path","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","status","INTERNAL_SERVER_ERROR","serverSide","log","message","getErrorForCode","env","NODE_ENV"],"sources":["../../../src/server/server.js"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport express from 'express';\nimport favicon from 'serve-favicon';\nimport helmet from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport rendererFactory from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => array.filter((item) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\ndefaultCspSettings.directives['script-src'].push(\"'unsafe-eval'\");\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings() {\n return cloneDeep(defaultCspSettings);\n}\n\nexport default async function factory(webpackConfig, options) {\n const rendererOps = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output;\n\n const server = express();\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n return res.redirect(url);\n }\n return next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use((req, res, next) => {\n req.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req.cspNonce = req.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings = cloneDeep(defaultCspSettings);\n cspSettings.directives['script-src'].push(`'nonce-${req.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n });\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => res.send('User-agent: *\\nDisallow:'));\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser());\n server.use(requestIp.mw());\n\n loggerMiddleware.token('ip', (req) => req.clientIp);\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n write: options.logger.info.bind(options.logger),\n },\n }));\n\n /* Ensures no caching for the service worker script. */\n server.use(`${publicPath}service-worker.js`, (req, res, next) => {\n res.header('Cache-Control', 'no-cache');\n next();\n });\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable global-require */\n /* eslint-disable import/no-extraneous-dependencies */\n /* eslint-disable import/no-unresolved */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n };\n }\n\n const webpack = require('webpack');\n const webpackDevMiddleware = require('webpack-dev-middleware');\n const webpackHotMiddleware = require('webpack-hot-middleware');\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable global-require */\n /* eslint-enable import/no-extraneous-dependencies */\n /* eslint-enable import/no-unresolved */\n\n server.use(publicPath, express.static(webpackConfig.output.path));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n /* eslint-disable no-unused-vars */\n server.use((error, req, res, next) => {\n /* eslint-enable no-unused-vars */\n const status = error.status || CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= CODES.INTERNAL_SERVER_ERROR;\n\n // Log server-side errors always, client-side at debug level only.\n options.logger.log(serverSide ? 'error' : 'debug', error);\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":"qOAIA,0BACA,wBAEA,8BAMA,gEACA,mEACA,wDACA,mEACA,sDACA,sDACA,6DACA,0BAEA,4DAEA,sCAxBA;AACA;AACA,G,CA6BA;AACA;AACA;AACA,GACA,KAAMA,mBAAkB,CAAG,CACzBC,UAAU,CAAE,GAAAC,iBAAA,EACVC,eAAA,CAAOC,qBAAP,CAA6BC,oBAA7B,EADU,CAGV;AACA;AACA;AACA;AACCC,KAAD,EAAWA,KAAK,CAACC,MAAN,CAAcC,IAAD,EAAUA,IAAI,GAAK,QAAhC,CAPD,CADa,CAA3B,CAWAR,kBAAkB,CAACC,UAAnB,CAA8B,WAA9B,EAA6C,CAC3C,QAD2C,CAG3C;AACA;AACA,uBAL2C,CAA7C,CAOAD,kBAAkB,CAACC,UAAnB,CAA8B,YAA9B,EAA4CQ,IAA5C,CAAiD,eAAjD,EAEA;AACA;AACA;AACA,MAAOT,mBAAkB,CAACC,UAAnB,CAA8B,2BAA9B,CAAP,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAASS,sBAAT,EAAiC,CACtC,MAAO,GAAAC,iBAAA,EAAUX,kBAAV,CACR,CAEc,cAAeY,QAAf,CAAuBC,aAAvB,CAAsCC,OAAtC,CAA+C,CAC5D,KAAMC,YAAW,CAAG,GAAAC,YAAA,EAAKF,OAAL,CAAc,CAChC,aADgC,CAEhC,cAFgC,CAGhC,SAHgC,CAIhC,QAJgC,CAKhC,cALgC,CAMhC,OANgC,CAOhC,YAPgC,CAQhC,uBARgC,CAShC,iBATgC,CAAd,CAApB,CAWA,KAAMG,SAAQ,CAAG,GAAAC,iBAAA,EAAgBL,aAAhB,CAA+BE,WAA/B,C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ACK,GAAP,CAAW,CAACC,GAAD,CAAMC,GAAN,CAAWC,IAAX,GAAoB,CAC7BA,IAAI,CAAC,GAAAoD,gBAAA,EAASC,cAAA,CAAOC,SAAhB,CAA2BC,aAAA,CAAMD,SAAjC,CAAD,CACL,CAFD,EAIA,GAAIE,8BAAJ,CACA,GAAIvE,OAAO,CAACwE,oBAAZ,CAAkC,CAChCD,6BAA6B,CAAG,KAAMvE,QAAO,CAACwE,oBAAR,CAA6BjE,MAA7B,CACvC,CAED,oBACA,GAAI,CAACgE,6BAAL,CAAoC,CAClC;AACA;AACA;AACA;AACA,mCACAhE,MAAM,CAACK,GAAP,CAAW,CAAC6D,KAAD,CAAQ5D,GAAR,CAAaC,GAAb,CAAkBC,IAAlB,GAA2B,CACtC,kCACE,KAAM2D,OAAM,CAAGD,KAAK,CAACC,MAAN,EAAgBJ,aAAA,CAAMK,qBAArC,CACA,KAAMC,WAAU,CAAGF,MAAM,EAAIJ,aAAA,CAAMK,qBAAnC,CAEA;AACA3E,OAAO,CAACU,MAAR,CAAemE,GAAf,CAAmBD,UAAU,CAAG,OAAH,CAAa,OAA1C,CAAmDH,KAAnD,EAEA,GAAIK,QAAO,CAAGL,KAAK,CAACK,OAAN,EAAiB,GAAAC,uBAAA,EAAgBL,MAAhB,CAA/B,CACA,GAAIE,UAAU,EAAIrB,OAAO,CAACyB,GAAR,CAAYC,QAAZ,GAAyB,YAA3C,CAAyD,CACvDH,OAAO,CAAGV,cAAA,CAAOO,qBAClB,CAED7D,GAAG,CAAC4D,MAAJ,CAAWA,MAAX,EAAmBzC,IAAnB,CAAwB6C,OAAxB,CACD,CAdD,CAeD,CAED,MAAOvE,OACR"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":["newError","message","statusCode","CODES","INTERNAL_SERVER_ERROR","error","Error","status","fail","assert","value","schema","BAD_REQUEST","validate","abortEarly","concat"],"sources":["../../../../src/server/utils/errors.js"],"sourcesContent":["/**\n * @category Utilities\n * @module server/errors\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { errors } = server;\n * ```\n * Server-side helpers for error handling.\n */\n\nimport {\n StatusCodes as CODES,\n ReasonPhrases as ERRORS,\n getReasonPhrase as getErrorForCode,\n} from 'http-status-codes';\n\nimport joi from 'joi';\n\n/**\n * @static\n * @const CODES\n * @desc An alias for\n * [StatusCodes object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and corresponding numeric codes.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { CODES } = server.errors;\n * console.log(CODES.BAD_REQUEST); // Prints: 400\n */\nexport { CODES };\n\n/**\n * @static\n * @const ERRORS\n * @desc An alias for\n * [ReasonPhrases object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and their pretty-printed forms.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { ERRORS } = server.errors;\n * console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request\n */\nexport { ERRORS };\n\n/**\n * @static\n * @func getErrorForCode\n * @desc An alias for\n * [getReasonPhrase() function from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * Given an HTTP code it returns the corresponding error text.\n * @param {number} code HTTP code.\n * @return {string} HTTP error text.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request\n */\nexport { getErrorForCode };\n\n/**\n * @static\n * @const joi\n * @desc An alias for [Joi library](https://joi.dev/api/?v=17.4.0),\n * which provides tooling for HTTP request validation. You can use it in any\n * way you would use that library import.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { joi } = server.errors;\n * const requestBodySchema = joi.object({\n * sampleKey: joi.string().max(16).required(),\n * });\n */\nexport { joi };\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { newError } = server.errors;\n * ```\n * Creates a new `Error` object with given message, and HTTP status code\n * attached as `status` field.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal\n * Server Error).\n * @return {Error}\n */\nexport function newError(message, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n const error = new Error(message);\n error.status = statusCode;\n return error;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { fail } = server.errors;\n * ```\n * Throws an error with given message and HTTP status code.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP error code. Defaults to 500 (Internal\n * Server Error).\n * @throws {Error}\n */\nexport function fail(message, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n throw newError(message, statusCode);\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { assert } = server.errors;\n * ```\n * Validates a value using given Joi schema, and throws an error with given\n * message and HTTP status code in case of the validation failure.\n * @param {any} value\n * @param {object} schema\n * @param {string} [message] Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 400 (Bad\n * Request).\n * @throws {Error}\n */\nexport function assert(\n value,\n schema,\n message = '',\n statusCode = CODES.BAD_REQUEST,\n) {\n const { error } = schema.validate(value, { abortEarly: false });\n if (error) {\n fail(message.concat(message ? '\\n' : '', error.message), statusCode);\n }\n}\n"],"mappings":"8oBAWA,kDAMA,gDAjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,G,CAUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,G,CAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,G,CAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,G,CAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,G,CAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAASA,
|
|
1
|
+
{"version":3,"file":"errors.js","names":["newError","message","statusCode","CODES","INTERNAL_SERVER_ERROR","error","Error","status","fail","assert","value","schema","BAD_REQUEST","validate","abortEarly","concat"],"sources":["../../../../src/server/utils/errors.js"],"sourcesContent":["/**\n * @category Utilities\n * @module server/errors\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { errors } = server;\n * ```\n * Server-side helpers for error handling.\n */\n\nimport {\n StatusCodes as CODES,\n ReasonPhrases as ERRORS,\n getReasonPhrase as getErrorForCode,\n} from 'http-status-codes';\n\nimport joi from 'joi';\n\n/**\n * @static\n * @const CODES\n * @desc An alias for\n * [StatusCodes object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and corresponding numeric codes.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { CODES } = server.errors;\n * console.log(CODES.BAD_REQUEST); // Prints: 400\n */\nexport { CODES };\n\n/**\n * @static\n * @const ERRORS\n * @desc An alias for\n * [ReasonPhrases object from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * It is a map between HTTP status code names and their pretty-printed forms.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { ERRORS } = server.errors;\n * console.log(ERRORS.BAD_REQUEST); // Prints: Bad Request\n */\nexport { ERRORS };\n\n/**\n * @static\n * @func getErrorForCode\n * @desc An alias for\n * [getReasonPhrase() function from **http-status-codes** library](https://www.npmjs.com/package/http-status-codes).\n * Given an HTTP code it returns the corresponding error text.\n * @param {number} code HTTP code.\n * @return {string} HTTP error text.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * console.log(server.errors.getErrorForCode(400)); // Prints: Bad Request\n */\nexport { getErrorForCode };\n\n/**\n * @static\n * @const joi\n * @desc An alias for [Joi library](https://joi.dev/api/?v=17.4.0),\n * which provides tooling for HTTP request validation. You can use it in any\n * way you would use that library import.\n * @example\n * import { server } from '@dr.pogodin/react-utils';\n * const { joi } = server.errors;\n * const requestBodySchema = joi.object({\n * sampleKey: joi.string().max(16).required(),\n * });\n */\nexport { joi };\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { newError } = server.errors;\n * ```\n * Creates a new `Error` object with given message, and HTTP status code\n * attached as `status` field.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 500 (Internal\n * Server Error).\n * @return {Error}\n */\nexport function newError(message, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n const error = new Error(message);\n error.status = statusCode;\n return error;\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { fail } = server.errors;\n * ```\n * Throws an error with given message and HTTP status code.\n * @param {string} message Error message.\n * @param {number} [statusCode=500] HTTP error code. Defaults to 500 (Internal\n * Server Error).\n * @throws {Error}\n */\nexport function fail(message, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n throw newError(message, statusCode);\n}\n\n/**\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { assert } = server.errors;\n * ```\n * Validates a value using given Joi schema, and throws an error with given\n * message and HTTP status code in case of the validation failure.\n * @param {any} value\n * @param {object} schema\n * @param {string} [message] Error message.\n * @param {number} [statusCode=500] HTTP status code. Defaults to 400 (Bad\n * Request).\n * @throws {Error}\n */\nexport function assert(\n value,\n schema,\n message = '',\n statusCode = CODES.BAD_REQUEST,\n) {\n const { error } = schema.validate(value, { abortEarly: false });\n if (error) {\n fail(message.concat(message ? '\\n' : '', error.message), statusCode);\n }\n}\n"],"mappings":"8oBAWA,kDAMA,gDAjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,G,CAUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,G,CAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,G,CAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,G,CAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,G,CAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAASA,SAAT,CAAkBC,OAAlB,CAA2BC,UAAU,CAAGC,4BAAA,CAAMC,qBAA9C,CAAqE,CAC1E,KAAMC,MAAK,CAAG,GAAIC,MAAJ,CAAUL,OAAV,CAAd,CACAI,KAAK,CAACE,MAAN,CAAeL,UAAf,CACA,MAAOG,MACR,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAASG,KAAT,CAAcP,OAAd,CAAuBC,UAAU,CAAGC,4BAAA,CAAMC,qBAA1C,CAAiE,CACtE,KAAMJ,SAAQ,CAACC,OAAD,CAAUC,UAAV,CACf,CAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACO,QAASO,OAAT,CACLC,KADK,CAELC,MAFK,CAGLV,OAAO,CAAG,EAHL,CAILC,UAAU,CAAGC,4BAAA,CAAMS,WAJd,CAKL,CACA,KAAM,CAAEP,KAAF,EAAYM,MAAM,CAACE,QAAP,CAAgBH,KAAhB,CAAuB,CAAEI,UAAU,CAAE,KAAd,CAAvB,CAAlB,CACA,GAAIT,KAAJ,CAAW,CACTG,IAAI,CAACP,OAAO,CAACc,MAAR,CAAed,OAAO,CAAG,IAAH,CAAU,EAAhC,CAAoCI,KAAK,CAACJ,OAA1C,CAAD,CAAqDC,UAArD,CACL,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["BaseButton","active","children","disabled","enforceA","onClick","onMouseDown","openNewTab","replace","theme","to","className","button","ThemedButton","defaultTheme","defaultProps","undefined","propTypes","PT","bool","node","func","themeType","isRequired","oneOfType","object","string"],"sources":["../../../../../src/shared/components/Button/index.jsx"],"sourcesContent":["// The <Button> component implements a standard button / button-like link.\n\nimport PT from 'prop-types';\n\nimport Link from 'components/Link';\n\nimport { themed } from 'utils';\n\nimport defaultTheme from './style.scss';\n\nfunction BaseButton({\n active,\n children,\n disabled,\n enforceA,\n onClick,\n onMouseDown,\n openNewTab,\n replace,\n theme,\n to,\n}) {\n let className = theme.button;\n if (active && theme.active) className += ` ${theme.active}`;\n if (disabled) {\n if (theme.disabled) className += ` ${theme.disabled}`;\n return (\n <div className={className}>\n {children}\n </div>\n );\n }\n if (to) {\n return (\n <Link\n className={className}\n enforceA={enforceA}\n onClick={onClick}\n onMouseDown={onMouseDown}\n openNewTab={openNewTab}\n replace={replace}\n to={to}\n >\n {children}\n </Link>\n );\n }\n return (\n <div\n className={className}\n onClick={onClick}\n onKeyPress={onClick}\n onMouseDown={onMouseDown}\n role=\"button\"\n tabIndex={0}\n >\n {children}\n </div>\n );\n}\n\n/**\n * Button component theme: a map of CSS\n * class names to append to button elements:\n * @prop {string} [active] to the root element of active button.\n * @prop {string} [button] to the root element of any button.\n * @prop {string} [disabled] to the root element of disabled button.\n */\nconst ThemedButton = themed('Button', [\n 'active',\n 'button',\n 'disabled',\n], defaultTheme)(BaseButton);\n\n/**\n * Implements themeable buttons, and button-line links (elements which look\n * like buttons, but behave as links) in the same uniform manner.\n * @param {object} [props] Component props.\n * @param {boolean} [props.active] Set `true` to render the button as\n * active, even if it is not active otherwise.\n * @param {boolean} [props.disabled] Set `true` to disable the button.\n * @param {boolean} [props.enforceA] When the button is rendered as `<Link>`\n * component, this prop enforces it to be rendered as a simple `<a>` element\n * (external link), rather than the React router's internal link.\n * See `<Link>` documentation to learn when links are rendered as `<a>`\n * by default.\n * @param {function} [props.onClick] Click event handler.\n * @param {function} [props.onMouseDown] Mouse down event handler.\n * @param {boolean} [props.openNewTab] Set `true` to open link in the new tab.\n * @param {boolean} [props.replace] When the button is rendered as\n * `<Link>`, and the target URL is internal, this property tells that\n * the new route should replace the last record in the browser's history,\n * rather than to be pushed as a new entry into the history stack.\n * @param {ButtonTheme} [props.theme] _Ad hoc_ button theme.\n * @param {object|string} [props.to] If specified, the button will be rendered\n * as `<Link>` (if not disabled), and it will point to the specified location\n * or URL.\n * @param {...any} [props....]\n * [Other properties of themeable components](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nBaseButton.defaultProps = {\n active: false,\n children: undefined,\n disabled: false,\n enforceA: false,\n onClick: undefined,\n onMouseDown: undefined,\n openNewTab: false,\n replace: false,\n to: undefined,\n};\n\nBaseButton.propTypes = {\n active: PT.bool,\n children: PT.node,\n disabled: PT.bool,\n enforceA: PT.bool,\n onClick: PT.func,\n onMouseDown: PT.func,\n openNewTab: PT.bool,\n replace: PT.bool,\n theme: ThemedButton.themeType.isRequired,\n to: PT.oneOfType([PT.object, PT.string]),\n};\n\nexport default ThemedButton;\n"],"mappings":"gLAEA,6DAEA,qDAEA,kC,6CANA;+HAUA,QAASA,
|
|
1
|
+
{"version":3,"file":"index.js","names":["BaseButton","active","children","disabled","enforceA","onClick","onMouseDown","openNewTab","replace","theme","to","className","button","ThemedButton","themed","defaultTheme","defaultProps","undefined","propTypes","PT","bool","node","func","themeType","isRequired","oneOfType","object","string"],"sources":["../../../../../src/shared/components/Button/index.jsx"],"sourcesContent":["// The <Button> component implements a standard button / button-like link.\n\nimport PT from 'prop-types';\n\nimport Link from 'components/Link';\n\nimport { themed } from 'utils';\n\nimport defaultTheme from './style.scss';\n\nfunction BaseButton({\n active,\n children,\n disabled,\n enforceA,\n onClick,\n onMouseDown,\n openNewTab,\n replace,\n theme,\n to,\n}) {\n let className = theme.button;\n if (active && theme.active) className += ` ${theme.active}`;\n if (disabled) {\n if (theme.disabled) className += ` ${theme.disabled}`;\n return (\n <div className={className}>\n {children}\n </div>\n );\n }\n if (to) {\n return (\n <Link\n className={className}\n enforceA={enforceA}\n onClick={onClick}\n onMouseDown={onMouseDown}\n openNewTab={openNewTab}\n replace={replace}\n to={to}\n >\n {children}\n </Link>\n );\n }\n return (\n <div\n className={className}\n onClick={onClick}\n onKeyPress={onClick}\n onMouseDown={onMouseDown}\n role=\"button\"\n tabIndex={0}\n >\n {children}\n </div>\n );\n}\n\n/**\n * Button component theme: a map of CSS\n * class names to append to button elements:\n * @prop {string} [active] to the root element of active button.\n * @prop {string} [button] to the root element of any button.\n * @prop {string} [disabled] to the root element of disabled button.\n */\nconst ThemedButton = themed('Button', [\n 'active',\n 'button',\n 'disabled',\n], defaultTheme)(BaseButton);\n\n/**\n * Implements themeable buttons, and button-line links (elements which look\n * like buttons, but behave as links) in the same uniform manner.\n * @param {object} [props] Component props.\n * @param {boolean} [props.active] Set `true` to render the button as\n * active, even if it is not active otherwise.\n * @param {boolean} [props.disabled] Set `true` to disable the button.\n * @param {boolean} [props.enforceA] When the button is rendered as `<Link>`\n * component, this prop enforces it to be rendered as a simple `<a>` element\n * (external link), rather than the React router's internal link.\n * See `<Link>` documentation to learn when links are rendered as `<a>`\n * by default.\n * @param {function} [props.onClick] Click event handler.\n * @param {function} [props.onMouseDown] Mouse down event handler.\n * @param {boolean} [props.openNewTab] Set `true` to open link in the new tab.\n * @param {boolean} [props.replace] When the button is rendered as\n * `<Link>`, and the target URL is internal, this property tells that\n * the new route should replace the last record in the browser's history,\n * rather than to be pushed as a new entry into the history stack.\n * @param {ButtonTheme} [props.theme] _Ad hoc_ button theme.\n * @param {object|string} [props.to] If specified, the button will be rendered\n * as `<Link>` (if not disabled), and it will point to the specified location\n * or URL.\n * @param {...any} [props....]\n * [Other properties of themeable components](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nBaseButton.defaultProps = {\n active: false,\n children: undefined,\n disabled: false,\n enforceA: false,\n onClick: undefined,\n onMouseDown: undefined,\n openNewTab: false,\n replace: false,\n to: undefined,\n};\n\nBaseButton.propTypes = {\n active: PT.bool,\n children: PT.node,\n disabled: PT.bool,\n enforceA: PT.bool,\n onClick: PT.func,\n onMouseDown: PT.func,\n openNewTab: PT.bool,\n replace: PT.bool,\n theme: ThemedButton.themeType.isRequired,\n to: PT.oneOfType([PT.object, PT.string]),\n};\n\nexport default ThemedButton;\n"],"mappings":"gLAEA,6DAEA,qDAEA,kC,6CANA;+HAUA,QAASA,WAAT,CAAoB,CAClBC,MADkB,CAElBC,QAFkB,CAGlBC,QAHkB,CAIlBC,QA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Q,CAAE,KAHc,CAIxBC,QAAQ,CAAE,KAJc,CAKxBC,OAAO,CAAEY,SALe,CAMxBX,WAAW,CAAEW,SANW,CAOxBV,UAAU,CAAE,KAPY,CAQxBC,OAAO,CAAE,KARe,CASxBE,EAAE,CAAEO,SAToB,CAA1B,CAYAjB,UAAU,CAACkB,SAAX,CAAuB,CACrBjB,MAAM,CAAEkB,kBAAA,CAAGC,IADU,CAErBlB,QAAQ,CAAEiB,kBAAA,CAAGE,IAFQ,CAGrBlB,QAAQ,CAAEgB,kBAAA,CAAGC,IAHQ,CAIrBhB,QAAQ,CAAEe,kBAAA,CAAGC,IAJQ,CAKrBf,OAAO,CAAEc,kBAAA,CAAGG,IALS,CAMrBhB,WAAW,CAAEa,kBAAA,CAAGG,IANK,CAOrBf,UAAU,CAAEY,kBAAA,CAAGC,IAPM,CAQrBZ,OAAO,CAAEW,kBAAA,CAAGC,IARS,CASrBX,KAAK,CAAEI,YAAY,CAACU,SAAb,CAAuBC,UATT,CAUrBd,EAAE,CAAES,kBAAA,CAAGM,SAAH,CAAa,CAACN,kBAAA,CAAGO,MAAJ,CAAYP,kBAAA,CAAGQ,MAAf,CAAb,CAViB,CAAvB,C,aAaed,Y"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["Checkbox","checked","label","onChange","theme","container","undefined","checkbox","ThemedCheckbox","defaultTheme","propTypes","PT","bool","string","func","themeType","isRequired","defaultProps"],"sources":["../../../../../src/shared/components/Checkbox/index.jsx"],"sourcesContent":["import PT from 'prop-types';\n\nimport { themed } from 'utils';\n\nimport defaultTheme from './theme.scss';\n\nfunction Checkbox({\n checked,\n label,\n onChange,\n theme,\n}) {\n return (\n <div className={theme.container}>\n { label === undefined ? null : <p className={theme.label}>{label}</p> }\n <input\n checked={checked}\n className={theme.checkbox}\n onChange={onChange}\n type=\"checkbox\"\n />\n </div>\n );\n}\n\n/**\n * Checkbox component theme: a map of\n * CSS classes to append to its elements:\n * @prop {string} [checkbox] to the underlying checkbox `<input>` element.\n * @prop {string} [container] to the root checkbox element.\n * @prop {string} [label] to the checkbox label element.\n */\nconst ThemedCheckbox = themed('Checkbox', [\n 'checkbox',\n 'container',\n 'label',\n], defaultTheme)(Checkbox);\n\n/**\n * The `<Checkbox>` component implements themeable checkboxes.\n * @param {object} [props] Component properties.\n * @param {boolean} [props.checked] Checkbox value.\n * @param {string} [props.label] Checkbox label.\n * @param {function} [props.onChange] State change handler.\n * @param {CheckboxTheme} [props.theme] _Ad hoc_ theme.\n * @param {...any} [props....]\n * [Other properties of themeable components](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties).\n */\nCheckbox.propTypes = {\n checked: PT.bool,\n label: PT.string,\n onChange: PT.func,\n theme: ThemedCheckbox.themeType.isRequired,\n};\n\nCheckbox.defaultProps = {\n checked: undefined,\n label: undefined,\n onChange: undefined,\n};\n\nexport default ThemedCheckbox;\n"],"mappings":"gLAAA,6DAEA,kC,6KAIA,QAASA,
|
|
1
|
+
{"version":3,"file":"index.js","names":["Checkbox","checked","label","onChange","theme","container","undefined","checkbox","ThemedCheckbox","themed","defaultTheme","propTypes","PT","bool","string","func","themeType","isRequired","defaultProps"],"sources":["../../../../../src/shared/components/Checkbox/index.jsx"],"sourcesContent":["import PT from 'prop-types';\n\nimport { themed } from 'utils';\n\nimport defaultTheme from './theme.scss';\n\nfunction Checkbox({\n checked,\n label,\n onChange,\n theme,\n}) {\n return (\n <div className={theme.container}>\n { label === undefined ? null : <p className={theme.label}>{label}</p> }\n <input\n checked={checked}\n className={theme.checkbox}\n onChange={onChange}\n type=\"checkbox\"\n />\n </div>\n );\n}\n\n/**\n * Checkbox component theme: a map of\n * CSS classes to append to its elements:\n * @prop {string} [checkbox] to the underlying checkbox `<input>` element.\n * @prop {string} [container] to the root checkbox element.\n * @prop {string} [label] to the checkbox label element.\n */\nconst ThemedCheckbox = themed('Checkbox', [\n 'checkbox',\n 'container',\n 'label',\n], defaultTheme)(Checkbox);\n\n/**\n * The `<Checkbox>` component implements themeable checkboxes.\n * @param {object} [props] Component properties.\n * @param {boolean} [props.checked] Checkbox value.\n * @param {string} [props.label] Checkbox label.\n * @param {function} [props.onChange] State change handler.\n * @param {CheckboxTheme} [props.theme] _Ad hoc_ theme.\n * @param {...any} [props....]\n * [Other properties of themeable components](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties).\n */\nCheckbox.propTypes = {\n checked: PT.bool,\n label: PT.string,\n onChange: PT.func,\n theme: ThemedCheckbox.themeType.isRequired,\n};\n\nCheckbox.defaultProps = {\n checked: undefined,\n label: undefined,\n onChange: undefined,\n};\n\nexport default ThemedCheckbox;\n"],"mappings":"gLAAA,6DAEA,kC,6KAIA,QAASA,SAAT,CAAkB,CAChBC,OADgB,CAEhBC,KAFgB,CAGhBC,QAHgB,CAIhBC,KAJgB,CAAlB,CAKG,CACD,mBACE,4BAAK,SAAS,CAAEA,KAAK,CAACC,SAAtB,WACIH,KAAK,GAAKI,SAAV,CAAsB,IAAtB,cAA6B,yBAAG,SAAS,CAAEF,KAAK,CAACF,KAApB,UAA4BA,KAA5B,EADjC,cAEE,6BACE,OAAO,CAAED,OADX,CAEE,SAAS,CAAEG,KAAK,CAACG,QAFnB,CAGE,QAAQ,CAAEJ,QAHZ,CAIE,IAAI,CAAC,UAJP,EAFF,GAUH,CAED;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAMK,eAAc,CAAG,GAAAC,aAAA,EAAO,UAAP,CAAmB,CACxC,UADwC,CAExC,WAFwC,CAGxC,OAHwC,CAAnB,CAIpBC,YAJoB,EAINV,QAJM,CAAvB,CAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACAA,QAAQ,CAACW,SAAT,CAAqB,CACnBV,OAAO,CAAEW,kBAAA,CAAGC,IADO,CAEnBX,KAAK,CAAEU,kBAAA,CAAGE,MAFS,CAGnBX,QAAQ,CAAES,kBAAA,CAAGG,IAHM,CAInBX,KAAK,CAAEI,cAAc,CAACQ,SAAf,CAAyBC,UAJb,CAArB,CAOAjB,QAAQ,CAACkB,YAAT,CAAwB,CACtBjB,OAAO,CAAEK,SADa,CAEtBJ,KAAK,CAAEI,SAFe,CAGtBH,QAAQ,CAAEG,SAHY,CAAxB,C,aAMeE,c"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["CodeSplit","children","chunkName","getComponent","placeholder","props","current","heap","mounted","pendingStyles","publicPath","LazyComponent","res","length","Promise","all","default","IS_SERVER_SIDE","chunks","ssrContext","includes","Error","push","window","CHUNK_GROUPS","forEach","asset","endsWith","path","link","document","querySelector","createElement","setAttribute","barrier","onload","resolve","onerror","head","appendChild","STYLESHEET_USAGE_COUNTERS","item","removeChild","propTypes","PT","node","string","isRequired","func","defaultProps","undefined"],"sources":["../../../../../src/shared/components/CodeSplit/index.jsx"],"sourcesContent":["/* eslint-disable react/jsx-props-no-spreading */\n/* global document, window */\n\nimport PT from 'prop-types';\n\nimport {\n lazy,\n Suspense,\n useEffect,\n useRef,\n} from 'react';\n\nimport { getGlobalState } from '@dr.pogodin/react-global-state';\nimport { newBarrier } from 'utils/Barrier';\nimport { getBuildInfo, IS_SERVER_SIDE } from 'utils/isomorphy';\n\nexport default function CodeSplit({\n children,\n chunkName,\n getComponent,\n placeholder,\n ...props\n}) {\n const { current: heap } = useRef({\n mounted: false,\n pendingStyles: [],\n });\n const { publicPath } = getBuildInfo();\n\n // TODO: Not sure whether it is fine for the inner React.lazy() mechanics\n // if we dynamically create the lazy component inside a render of another\n // component, or does it expect we only create it once on outside of any\n // component.\n const LazyComponent = lazy(async () => {\n const res = await getComponent();\n if (heap.pendingStyles.length) await Promise.all(heap.pendingStyles);\n return res.default ? res : { default: res };\n });\n\n if (IS_SERVER_SIDE) {\n const { chunks } = getGlobalState().ssrContext;\n if (chunks.includes(chunkName)) {\n throw Error(`Chunk name clash for \"${chunkName}\"`);\n } else chunks.push(chunkName);\n } else if (!heap.mounted) {\n heap.mounted = true;\n\n window.CHUNK_GROUPS[chunkName].forEach((asset) => {\n if (!asset.endsWith('.css')) return;\n const path = `${publicPath}/${asset}`;\n let link = document.querySelector(`link[href=\"${path}\"]`);\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('href', path);\n link.setAttribute('rel', 'stylesheet');\n\n const barrier = newBarrier();\n link.onload = barrier.resolve;\n\n // Even if the style load failed, still allow to mount the component,\n // abeit with broken styling.\n link.onerror = barrier.resolve;\n\n heap.pendingStyles.push(barrier);\n\n const head = document.querySelector('head');\n head.appendChild(link);\n }\n window.STYLESHEET_USAGE_COUNTERS ||= {};\n window.STYLESHEET_USAGE_COUNTERS[path] ||= 0;\n ++window.STYLESHEET_USAGE_COUNTERS[path];\n });\n }\n\n // This effectively fires only once, just before the component unmounts.\n useEffect(() => () => {\n heap.mounted = false;\n window.CHUNK_GROUPS[chunkName].forEach((item) => {\n if (!item.endsWith('.css')) return;\n const path = `${publicPath}/${item}`;\n if (--window.STYLESHEET_USAGE_COUNTERS[path] <= 0) {\n const link = document.querySelector(`link[href=\"${path}\"]`);\n const head = document.querySelector('head');\n head.removeChild(link);\n }\n });\n }, [chunkName, heap, publicPath]);\n\n return (\n <Suspense fallback={placeholder}>\n <LazyComponent {...props}>\n {children}\n </LazyComponent>\n </Suspense>\n );\n}\n\nCodeSplit.propTypes = {\n children: PT.node,\n chunkName: PT.string.isRequired,\n getComponent: PT.func.isRequired,\n placeholder: PT.node,\n};\n\nCodeSplit.defaultProps = {\n children: undefined,\n placeholder: undefined,\n};\n"],"mappings":"mLAGA,6DAEA,4BAOA,gEACA,4CACA,gD,6CAdA,iD,CACA,6BAee,QAASA,
|
|
1
|
+
{"version":3,"file":"index.js","names":["CodeSplit","children","chunkName","getComponent","placeholder","props","current","heap","useRef","mounted","pendingStyles","publicPath","getBuildInfo","LazyComponent","lazy","res","length","Promise","all","default","IS_SERVER_SIDE","chunks","getGlobalState","ssrContext","includes","Error","push","window","CHUNK_GROUPS","forEach","asset","endsWith","path","link","document","querySelector","createElement","setAttribute","barrier","newBarrier","onload","resolve","onerror","head","appendChild","STYLESHEET_USAGE_COUNTERS","useEffect","item","removeChild","propTypes","PT","node","string","isRequired","func","defaultProps","undefined"],"sources":["../../../../../src/shared/components/CodeSplit/index.jsx"],"sourcesContent":["/* eslint-disable react/jsx-props-no-spreading */\n/* global document, window */\n\nimport PT from 'prop-types';\n\nimport {\n lazy,\n Suspense,\n useEffect,\n useRef,\n} from 'react';\n\nimport { getGlobalState } from '@dr.pogodin/react-global-state';\nimport { newBarrier } from 'utils/Barrier';\nimport { getBuildInfo, IS_SERVER_SIDE } from 'utils/isomorphy';\n\nexport default function CodeSplit({\n children,\n chunkName,\n getComponent,\n placeholder,\n ...props\n}) {\n const { current: heap } = useRef({\n mounted: false,\n pendingStyles: [],\n });\n const { publicPath } = getBuildInfo();\n\n // TODO: Not sure whether it is fine for the inner React.lazy() mechanics\n // if we dynamically create the lazy component inside a render of another\n // component, or does it expect we only create it once on outside of any\n // component.\n const LazyComponent = lazy(async () => {\n const res = await getComponent();\n if (heap.pendingStyles.length) await Promise.all(heap.pendingStyles);\n return res.default ? res : { default: res };\n });\n\n if (IS_SERVER_SIDE) {\n const { chunks } = getGlobalState().ssrContext;\n if (chunks.includes(chunkName)) {\n throw Error(`Chunk name clash for \"${chunkName}\"`);\n } else chunks.push(chunkName);\n } else if (!heap.mounted) {\n heap.mounted = true;\n\n window.CHUNK_GROUPS[chunkName].forEach((asset) => {\n if (!asset.endsWith('.css')) return;\n const path = `${publicPath}/${asset}`;\n let link = document.querySelector(`link[href=\"${path}\"]`);\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('href', path);\n link.setAttribute('rel', 'stylesheet');\n\n const barrier = newBarrier();\n link.onload = barrier.resolve;\n\n // Even if the style load failed, still allow to mount the component,\n // abeit with broken styling.\n link.onerror = barrier.resolve;\n\n heap.pendingStyles.push(barrier);\n\n const head = document.querySelector('head');\n head.appendChild(link);\n }\n window.STYLESHEET_USAGE_COUNTERS ||= {};\n window.STYLESHEET_USAGE_COUNTERS[path] ||= 0;\n ++window.STYLESHEET_USAGE_COUNTERS[path];\n });\n }\n\n // This effectively fires only once, just before the component unmounts.\n useEffect(() => () => {\n heap.mounted = false;\n window.CHUNK_GROUPS[chunkName].forEach((item) => {\n if (!item.endsWith('.css')) return;\n const path = `${publicPath}/${item}`;\n if (--window.STYLESHEET_USAGE_COUNTERS[path] <= 0) {\n const link = document.querySelector(`link[href=\"${path}\"]`);\n const head = document.querySelector('head');\n head.removeChild(link);\n }\n });\n }, [chunkName, heap, publicPath]);\n\n return (\n <Suspense fallback={placeholder}>\n <LazyComponent {...props}>\n {children}\n </LazyComponent>\n </Suspense>\n );\n}\n\nCodeSplit.propTypes = {\n children: PT.node,\n chunkName: PT.string.isRequired,\n getComponent: PT.func.isRequired,\n placeholder: PT.node,\n};\n\nCodeSplit.defaultProps = {\n children: undefined,\n placeholder: undefined,\n};\n"],"mappings":"mLAGA,6DAEA,4BAOA,gEACA,4CACA,gD,6CAdA,iD,CACA,6BAee,QAASA,UAAT,CAAmB,CAChCC,QADgC,CAEhCC,SAFgC,CAGhCC,YAHgC,CAIhCC,WAJgC,CAKhC,GAAGC,KAL6B,CAAnB,CAMZ,CACD,KAAM,CAAEC,OAAO,CAAEC,IAAX,EAAoB,GAAAC,aAAA,EAAO,CAC/BC,OAAO,CAAE,KADsB,CAE/BC,aAAa,CAAE,EAFgB,CAAP,CAA1B,CAIA,KAAM,CAAEC,UAAF,EAAiB,GAAAC,uBAAA,GAAvB,CAEA;AACA;AACA;AACA;AACA,KAAMC,cAAa,cAAG,GAAAC,WAAA,EAAK,SAAY,CACrC,KAAMC,IAAG,CAAG,KAAMZ,aAAY,EAA9B,CACA,GAAII,IAAI,CAACG,aAAL,CAAmBM,MAAvB,CAA+B,KAAMC,QAAO,CAACC,GAAR,CAAYX,IAAI,CAACG,aAAjB,CAAN,CAC/B,MAAOK,IAAG,CAACI,OAAJ,CAAcJ,GAAd,CAAoB,CAAEI,O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@@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["Dropdown","filter","label","onChange","options","theme","value","optionArray","hiddenOption","i","length","op","push","option","name","undefined","container","select","arrow","ThemedDropdown","defaultTheme","propTypes","PT","func","string","arrayOf","oneOfType","shape","node","isRequired","themeType","defaultProps"],"sources":["../../../../../src/shared/components/Dropdown/index.jsx"],"sourcesContent":["import { isString } from 'lodash';\nimport PT from 'prop-types';\n\nimport { themed } from 'utils';\n\nimport defaultTheme from './theme.scss';\n\n/**\n * Implements a themeable dropdown list. Internally it is rendered with help of\n * the standard HTML `<select>` element, thus the styling support is somewhat\n * limited.\n * @param {object} [props] Component properties.\n * @param {function} [props.filter] Options filter function. If provided, only\n * those elements of `options` list will be used by the dropdown, for which this\n * filter returns `true`.\n * @param {string} [props.label] Dropdown label.\n * @param {string} [props.onChange] Selection event handler.\n * @param {DropdownOption[]|string[]} [props.options=[]] Array of dropdown\n * options. For string elements the option value and name will be the same.\n * It is allowed to mix DropdownOption and string elements in the same option\n * list.\n * @param {DropdownTheme} [props.theme] _Ad hoc_ theme.\n * @param {string} [props.value] Currently selected value.\n * @param {...any} [props....]\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nfunction Dropdown({\n filter,\n label,\n onChange,\n options,\n theme,\n value,\n}) {\n const optionArray = [(\n <option\n className={theme.hiddenOption}\n key=\"__reactUtilsHiddenOption\"\n >\n ‌\n </option>\n )];\n for (let i = 0; i < options.length; ++i) {\n let op = options[i];\n if (!filter || filter(op)) {\n if (isString(op)) op = { value: op };\n optionArray.push((\n <option className={theme.option} key={op.value} value={op.value}>\n {op.name === undefined ? op.value : op.name }\n </option>\n ));\n }\n }\n return (\n <div className={theme.container}>\n { label === undefined ? null : <p className={theme.label}>{label}</p> }\n <select\n className={theme.select}\n onChange={onChange}\n value={value}\n >\n {optionArray}\n </select>\n <div className={theme.arrow}>▼</div>\n </div>\n );\n}\n\nconst ThemedDropdown = themed('Dropdown', [\n 'arrow',\n 'container',\n 'hiddenOption',\n 'label',\n 'option',\n 'select',\n], defaultTheme)(Dropdown);\n\nDropdown.propTypes = {\n filter: PT.func,\n label: PT.string,\n onChange: PT.func,\n options: PT.arrayOf(\n PT.oneOfType([\n PT.shape({\n name: PT.node,\n value: PT.string.isRequired,\n }),\n PT.string,\n ]).isRequired,\n ),\n theme: ThemedDropdown.themeType.isRequired,\n value: PT.string,\n};\n\nDropdown.defaultProps = {\n filter: undefined,\n label: undefined,\n onChange: undefined,\n options: [],\n value: undefined,\n};\n\nexport default ThemedDropdown;\n"],"mappings":"gLAAA,8BACA,6DAEA,kC,sOAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAASA,
|
|
1
|
+
{"version":3,"file":"index.js","names":["Dropdown","filter","label","onChange","options","theme","value","optionArray","hiddenOption","i","length","op","isString","push","option","name","undefined","container","select","arrow","ThemedDropdown","themed","defaultTheme","propTypes","PT","func","string","arrayOf","oneOfType","shape","node","isRequired","themeType","defaultProps"],"sources":["../../../../../src/shared/components/Dropdown/index.jsx"],"sourcesContent":["import { isString } from 'lodash';\nimport PT from 'prop-types';\n\nimport { themed } from 'utils';\n\nimport defaultTheme from './theme.scss';\n\n/**\n * Implements a themeable dropdown list. Internally it is rendered with help of\n * the standard HTML `<select>` element, thus the styling support is somewhat\n * limited.\n * @param {object} [props] Component properties.\n * @param {function} [props.filter] Options filter function. If provided, only\n * those elements of `options` list will be used by the dropdown, for which this\n * filter returns `true`.\n * @param {string} [props.label] Dropdown label.\n * @param {string} [props.onChange] Selection event handler.\n * @param {DropdownOption[]|string[]} [props.options=[]] Array of dropdown\n * options. For string elements the option value and name will be the same.\n * It is allowed to mix DropdownOption and string elements in the same option\n * list.\n * @param {DropdownTheme} [props.theme] _Ad hoc_ theme.\n * @param {string} [props.value] Currently selected value.\n * @param {...any} [props....]\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nfunction Dropdown({\n filter,\n label,\n onChange,\n options,\n theme,\n value,\n}) {\n const optionArray = [(\n <option\n className={theme.hiddenOption}\n key=\"__reactUtilsHiddenOption\"\n >\n ‌\n </option>\n )];\n for (let i = 0; i < options.length; ++i) {\n let op = options[i];\n if (!filter || filter(op)) {\n if (isString(op)) op = { value: op };\n optionArray.push((\n <option className={theme.option} key={op.value} value={op.value}>\n {op.name === undefined ? op.value : op.name }\n </option>\n ));\n }\n }\n return (\n <div className={theme.container}>\n { label === undefined ? null : <p className={theme.label}>{label}</p> }\n <select\n className={theme.select}\n onChange={onChange}\n value={value}\n >\n {optionArray}\n </select>\n <div className={theme.arrow}>▼</div>\n </div>\n );\n}\n\nconst ThemedDropdown = themed('Dropdown', [\n 'arrow',\n 'container',\n 'hiddenOption',\n 'label',\n 'option',\n 'select',\n], defaultTheme)(Dropdown);\n\nDropdown.propTypes = {\n filter: PT.func,\n label: PT.string,\n onChange: PT.func,\n options: PT.arrayOf(\n PT.oneOfType([\n PT.shape({\n name: PT.node,\n value: PT.string.isRequired,\n }),\n PT.string,\n ]).isRequired,\n ),\n theme: ThemedDropdown.themeType.isRequired,\n value: PT.string,\n};\n\nDropdown.defaultProps = {\n filter: undefined,\n label: undefined,\n onChange: undefined,\n options: [],\n value: undefined,\n};\n\nexport default ThemedDropdown;\n"],"mappings":"gLAAA,8BACA,6DAEA,kC,sOAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAASA,SAAT,CAAkB,CAChBC,MADgB,CAEhBC,KAFgB,CAGhBC,QAHgB,CAIhBC,OAJgB,CAKhBC,KALgB,CAMhBC,KANgB,CAAlB,CAOG,CACD,KAAMC,YAAW,CAAG,cAClB,8BACE,SAAS,CAAEF,KAAK,CAACG,YADnB,oBAEM,0BAFN,CADkB,CAApB,CAQA,IAAK,GAAIC,EAAC,CAAG,CAAb,CAA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AAGG,OAAH,CACPH,kBAAA,CAAGI,SAAH,CAAa,CACXJ,kBAAA,CAAGK,KAAH,CAAS,CACPd,IAAI,CAAES,kBAAA,CAAGM,IADF,CAEPxB,KAAK,CAAEkB,kBAAA,CAAGE,MAAH,CAAUK,UAFV,CAAT,CADW,CAKXP,kBAAA,CAAGE,MALQ,CAAb,EAMGK,UAPI,CAJU,CAanB1B,KAAK,CAAEe,cAAc,CAACY,SAAf,CAAyBD,UAbb,CAcnBzB,KAAK,CAAEkB,kBAAA,CAAGE,MAdS,CAArB,CAiBA1B,QAAQ,CAACiC,YAAT,CAAwB,CACtBhC,MAAM,CAAEe,SADc,CAEtBd,KAAK,CAAEc,SAFe,CAGtBb,QAAQ,CAAEa,SAHY,CAItBZ,OAAO,CAAE,EAJa,CAKtBE,KAAK,CAAEU,SALe,CAAxB,C,aAQeI,c"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["GenericLink","children","className","disabled","enforceA","keepScrollPosition","onClick","onMouseDown","openNewTab","replace","routerLinkType","to","rest","match","e","preventDefault","window","scroll","defaultProps","propTypes","PT","node","string","bool","func","elementType","isRequired","oneOfType","object"],"sources":["../../../../../src/shared/components/GenericLink/index.jsx"],"sourcesContent":["/* global window */\n\nimport PT from 'prop-types';\nimport { createElement } from 'react';\n\nimport './style.scss';\n\n/**\n * The `<Link>` component, and almost identical `<NavLink>` component, are\n * auxiliary wrappers around\n * [React Router](https://github.com/ReactTraining/react-router)'s\n * `<Link>` and `<NavLink>` components; they help to handle external and\n * internal links in uniform manner.\n *\n * @param {object} [props] Component properties.\n * @param {string} [props.className] CSS classes to apply to the link.\n * @param {boolean} [props.disabled] Disables the link.\n * @param {boolean} [props.enforceA] `true` enforces rendering of the link as\n * a simple `<a>` element.\n * @param {boolean} [props.keepScrollPosition] If `true`, and the link is\n * rendered as a React Router's component, it won't reset the viewport scrolling\n * position to the origin when clicked.\n * @param {function} [props.onClick] Event handler to trigger upon click.\n * @param {function} [props.onMouseDown] Event handler to trigger on MouseDown\n * event.\n * @param {boolean} [props.openNewTab] If `true` the link opens in a new tab.\n * @param {boolean} [props.replace] When `true`, the link will replace current\n * entry in the history stack instead of adding a new one.\n * @param {string} [props.to] Link URL.\n * @param {string} [props.activeClassName] **`<NavLink>`** only: CSS class(es)\n * to apply to rendered link when it is active.\n * @param {string} [props.activeStyle] **`<NavLink>`** only: CSS styles\n * to apply to the rendered link when it is active.\n * @param {boolean} [props.exact] **`<NavLink>`** only: if `true`, the active\n * class/style will only be applied if the location is matched exactly.\n * @param {function} [props.isActive] **`<NavLink>`** only: Add extra\n * logic for determining whether the link is active. This should be used if you\n * want to do more than verify that the link’s pathname matches the current URL\n * pathname.\n * @param {object} [props.location] **`<NavLink>`** only: `isActive` compares\n * current history location (usually the current browser URL). To compare to\n * a different location, a custom `location` can be passed.\n * @param {boolean} [props.strict] **`<NavLink>`** only: . When `true`, trailing\n * slash on a location’s pathname will be taken into consideration when\n * determining if the location matches the current URL. See the `<Route strict>`\n * documentation for more information.\n */\nexport default function GenericLink({\n children,\n className,\n disabled,\n enforceA,\n keepScrollPosition,\n onClick,\n onMouseDown,\n openNewTab,\n replace,\n routerLinkType,\n to,\n ...rest\n}) {\n /* Renders Link as <a> element if:\n * - It is opted explicitely by `enforceA` prop;\n * - It should be opened in a new tab;\n * - It is an absolte URL (starts with http:// or https://);\n * - It is anchor link (starts with #). */\n if (disabled || enforceA || openNewTab || to.match(/^(#|(https?|mailto):)/)) {\n return (\n <a\n className={className}\n disabled={disabled}\n href={to}\n onClick={disabled ? (e) => e.preventDefault() : onClick}\n onMouseDown={disabled ? (e) => e.preventDefault() : onMouseDown}\n rel=\"noopener noreferrer\"\n styleName=\"link\"\n target={openNewTab ? '_blank' : ''}\n >\n {children}\n </a>\n );\n }\n\n /* Otherwise we render the link as React Router's Link or NavLink element. */\n return createElement(routerLinkType, {\n className,\n disabled,\n onMouseDown,\n replace,\n to,\n onClick: (e) => {\n // Executes the user-provided event handler, if any.\n if (onClick) onClick(e);\n\n // By default, clicking the link scrolls the page to beginning.\n if (!keepScrollPosition) window.scroll(0, 0);\n },\n ...rest,\n }, children);\n}\n\nGenericLink.defaultProps = {\n children: null,\n className: null,\n disabled: false,\n enforceA: false,\n keepScrollPosition: false,\n onClick: null,\n onMouseDown: null,\n openNewTab: false,\n replace: false,\n to: '',\n};\n\nGenericLink.propTypes = {\n children: PT.node,\n className: PT.string,\n disabled: PT.bool,\n enforceA: PT.bool,\n keepScrollPosition: PT.bool,\n onClick: PT.func,\n onMouseDown: PT.func,\n openNewTab: PT.bool,\n replace: PT.bool,\n routerLinkType: PT.elementType.isRequired,\n to: PT.oneOfType([PT.object, PT.string]),\n};\n"],"mappings":"qLAEA,6DACA,4B,6CAHA,mB,CAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACe,QAASA,
|
|
1
|
+
{"version":3,"file":"index.js","names":["GenericLink","children","className","disabled","enforceA","keepScrollPosition","onClick","onMouseDown","openNewTab","replace","routerLinkType","to","rest","match","e","preventDefault","createElement","window","scroll","defaultProps","propTypes","PT","node","string","bool","func","elementType","isRequired","oneOfType","object"],"sources":["../../../../../src/shared/components/GenericLink/index.jsx"],"sourcesContent":["/* global window */\n\nimport PT from 'prop-types';\nimport { createElement } from 'react';\n\nimport './style.scss';\n\n/**\n * The `<Link>` component, and almost identical `<NavLink>` component, are\n * auxiliary wrappers around\n * [React Router](https://github.com/ReactTraining/react-router)'s\n * `<Link>` and `<NavLink>` components; they help to handle external and\n * internal links in uniform manner.\n *\n * @param {object} [props] Component properties.\n * @param {string} [props.className] CSS classes to apply to the link.\n * @param {boolean} [props.disabled] Disables the link.\n * @param {boolean} [props.enforceA] `true` enforces rendering of the link as\n * a simple `<a>` element.\n * @param {boolean} [props.keepScrollPosition] If `true`, and the link is\n * rendered as a React Router's component, it won't reset the viewport scrolling\n * position to the origin when clicked.\n * @param {function} [props.onClick] Event handler to trigger upon click.\n * @param {function} [props.onMouseDown] Event handler to trigger on MouseDown\n * event.\n * @param {boolean} [props.openNewTab] If `true` the link opens in a new tab.\n * @param {boolean} [props.replace] When `true`, the link will replace current\n * entry in the history stack instead of adding a new one.\n * @param {string} [props.to] Link URL.\n * @param {string} [props.activeClassName] **`<NavLink>`** only: CSS class(es)\n * to apply to rendered link when it is active.\n * @param {string} [props.activeStyle] **`<NavLink>`** only: CSS styles\n * to apply to the rendered link when it is active.\n * @param {boolean} [props.exact] **`<NavLink>`** only: if `true`, the active\n * class/style will only be applied if the location is matched exactly.\n * @param {function} [props.isActive] **`<NavLink>`** only: Add extra\n * logic for determining whether the link is active. This should be used if you\n * want to do more than verify that the link’s pathname matches the current URL\n * pathname.\n * @param {object} [props.location] **`<NavLink>`** only: `isActive` compares\n * current history location (usually the current browser URL). To compare to\n * a different location, a custom `location` can be passed.\n * @param {boolean} [props.strict] **`<NavLink>`** only: . When `true`, trailing\n * slash on a location’s pathname will be taken into consideration when\n * determining if the location matches the current URL. See the `<Route strict>`\n * documentation for more information.\n */\nexport default function GenericLink({\n children,\n className,\n disabled,\n enforceA,\n keepScrollPosition,\n onClick,\n onMouseDown,\n openNewTab,\n replace,\n routerLinkType,\n to,\n ...rest\n}) {\n /* Renders Link as <a> element if:\n * - It is opted explicitely by `enforceA` prop;\n * - It should be opened in a new tab;\n * - It is an absolte URL (starts with http:// or https://);\n * - It is anchor link (starts with #). */\n if (disabled || enforceA || openNewTab || to.match(/^(#|(https?|mailto):)/)) {\n return (\n <a\n className={className}\n disabled={disabled}\n href={to}\n onClick={disabled ? (e) => e.preventDefault() : onClick}\n onMouseDown={disabled ? (e) => e.preventDefault() : onMouseDown}\n rel=\"noopener noreferrer\"\n styleName=\"link\"\n target={openNewTab ? '_blank' : ''}\n >\n {children}\n </a>\n );\n }\n\n /* Otherwise we render the link as React Router's Link or NavLink element. */\n return createElement(routerLinkType, {\n className,\n disabled,\n onMouseDown,\n replace,\n to,\n onClick: (e) => {\n // Executes the user-provided event handler, if any.\n if (onClick) onClick(e);\n\n // By default, clicking the link scrolls the page to beginning.\n if (!keepScrollPosition) window.scroll(0, 0);\n },\n ...rest,\n }, children);\n}\n\nGenericLink.defaultProps = {\n children: null,\n className: null,\n disabled: false,\n enforceA: false,\n keepScrollPosition: false,\n onClick: null,\n onMouseDown: null,\n openNewTab: false,\n replace: false,\n to: '',\n};\n\nGenericLink.propTypes = {\n children: PT.node,\n className: PT.string,\n disabled: PT.bool,\n enforceA: PT.bool,\n keepScrollPosition: PT.bool,\n onClick: PT.func,\n onMouseDown: PT.func,\n openNewTab: PT.bool,\n replace: PT.bool,\n routerLinkType: PT.elementType.isRequired,\n to: PT.oneOfType([PT.object, PT.string]),\n};\n"],"mappings":"qLAEA,6DACA,4B,6CAHA,mB,CAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACe,QAASA,YAAT,CAAqB,CAClCC,QADkC,CAElCC,SAFkC,CAGlCC,QAHkC,CAIlCC,QAJkC,CAKlCC,kBALkC,CAMlCC,OANkC,CAOlCC,WAPkC,CAQlCC,UARkC,CASlCC,OATkC,CAUlCC,cAVkC,CAWlCC,EAXkC,CAYlC,GAAGC,IAZ+B,CAArB,CAaZ,CACD;AACF;AACA;AACA;AACA,4CACE,GAAIT,QAAQ,EAAIC,QAAZ,EAAwBI,UAAxB,EAAsCG,EAAE,CAACE,KAAH,CAAS,uBAAT,CAA1C,CAA6E,CAC3E,mBACE,yBACE,SAAS,EAAEX,SAAF,CAAEA,SAAF,iBADX,CAEE,QAAQ,CAAEC,QAF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,OAAO,CAAEe,kBAAA,CAAGI,IANU,CAOtBlB,WAAW,CAAEc,kBAAA,CAAGI,IAPM,CAQtBjB,UAAU,CAAEa,kBAAA,CAAGG,IARO,CAStBf,OAAO,CAAEY,kBAAA,CAAGG,IATU,CAUtBd,cAAc,CAAEW,kBAAA,CAAGK,WAAH,CAAeC,UAVT,CAWtBhB,EAAE,CAAEU,kBAAA,CAAGO,SAAH,CAAa,CAACP,kBAAA,CAAGQ,MAAJ,CAAYR,kBAAA,CAAGE,MAAf,CAAb,CAXkB,CAAxB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["Input","label","theme","rest","container","undefined","input","ThemedInput","defaultTheme","propTypes","PT","string","themeType","isRequired","defaultProps"],"sources":["../../../../../src/shared/components/Input/index.jsx"],"sourcesContent":["import PT from 'prop-types';\n\nimport { themed } from 'utils';\n\nimport defaultTheme from './theme.scss';\n\n/**\n * Themeable input field, based on the standard HTML `<input>` element.\n * @param {object} [props]\n * @param {string} [props.label] Input label.\n * @param {InputTheme} [props.theme] _Ad hoc_ theme.\n * @param {...any} [props....] [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n * @param {...any} [props....] Any other properties are passed to the underlying\n * `<input>` element.\n */\nfunction Input({\n label,\n theme,\n ...rest\n}) {\n return (\n <div className={theme.container}>\n { label === undefined ? null : <p className={theme.label}>{label}</p> }\n <input\n className={theme.input}\n {...rest} // eslint-disable-line react/jsx-props-no-spreading\n />\n </div>\n );\n}\n\nconst ThemedInput = themed('Input', [\n 'container',\n 'input',\n 'label',\n], defaultTheme)(Input);\n\nInput.propTypes = {\n label: PT.string,\n theme: ThemedInput.themeType.isRequired,\n};\n\nInput.defaultProps = {\n label: undefined,\n};\n\nexport default ThemedInput;\n"],"mappings":"gLAAA,6DAEA,kC,0KAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAASA,
|
|
1
|
+
{"version":3,"file":"index.js","names":["Input","label","theme","rest","container","undefined","input","ThemedInput","themed","defaultTheme","propTypes","PT","string","themeType","isRequired","defaultProps"],"sources":["../../../../../src/shared/components/Input/index.jsx"],"sourcesContent":["import PT from 'prop-types';\n\nimport { themed } from 'utils';\n\nimport defaultTheme from './theme.scss';\n\n/**\n * Themeable input field, based on the standard HTML `<input>` element.\n * @param {object} [props]\n * @param {string} [props.label] Input label.\n * @param {InputTheme} [props.theme] _Ad hoc_ theme.\n * @param {...any} [props....] [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n * @param {...any} [props....] Any other properties are passed to the underlying\n * `<input>` element.\n */\nfunction Input({\n label,\n theme,\n ...rest\n}) {\n return (\n <div className={theme.container}>\n { label === undefined ? null : <p className={theme.label}>{label}</p> }\n <input\n className={theme.input}\n {...rest} // eslint-disable-line react/jsx-props-no-spreading\n />\n </div>\n );\n}\n\nconst ThemedInput = themed('Input', [\n 'container',\n 'input',\n 'label',\n], defaultTheme)(Input);\n\nInput.propTypes = {\n label: PT.string,\n theme: ThemedInput.themeType.isRequired,\n};\n\nInput.defaultProps = {\n label: undefined,\n};\n\nexport default ThemedInput;\n"],"mappings":"gLAAA,6DAEA,kC,0KAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAASA,MAAT,CAAe,CACbC,KADa,CAEbC,KAFa,CAGb,GAAGC,IAHU,CAAf,CAIG,CACD,mBACE,4BAAK,SAAS,CAAED,KAAK,CAACE,SAAtB,WACIH,KAAK,GAAKI,SAAV,CAAsB,IAAtB,cAA6B,yBAAG,SAAS,CAAEH,KAAK,CAACD,KAApB,UAA4BA,KAA5B,EADjC,cAEE,6BACE,SAAS,CAAEC,KAAK,CAACI,KADnB,IAEMH,IAFN,EAFF,GAQH,CAED,KAAMI,YAAW,CAAG,GAAAC,aAAA,EAAO,OAAP,CAAgB,CAClC,WADkC,CAElC,OAFkC,CAGlC,OAHkC,CAAhB,CAIjBC,YAJiB,EAIHT,KAJG,CAApB,CAMAA,KAAK,CAACU,SAAN,CAAkB,CAChBT,KAAK,CAAEU,kBAAA,CAAGC,MADM,CAEhBV,KAAK,CAAEK,WAAW,CAACM,SAAZ,CAAsBC,UAFb,CAAlB,CAKAd,KAAK,CAACe,YAAN,CAAqB,CACnBd,KAAK,CAAEI,SADY,CAArB,C,aAIeE,W"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Link.js","names":["Link","props","RrLink"],"sources":["../../../../src/shared/components/Link.jsx"],"sourcesContent":["/**\n * The Link wraps around React Router's Link component, to automatically replace\n * it by the regular <a> element when:\n * - The target reference points to another domain;\n * - User opts to open the reference in a new tab;\n * - User explicitely opts to use <a>.\n */\n\nimport { Link as RrLink } from 'react-router-dom';\n\nimport GenericLink from './GenericLink';\n\nexport default function Link(props) {\n /* eslint-disable react/jsx-props-no-spreading */\n return <GenericLink {...props} routerLinkType={RrLink} />;\n /* eslint-enable react/jsx-props-no-spreading */\n}\n"],"mappings":"8KAQA,gDAEA,kE,6CAVA;AACA;AACA;AACA;AACA;AACA;AACA,GAMe,QAASA,
|
|
1
|
+
{"version":3,"file":"Link.js","names":["Link","props","RrLink"],"sources":["../../../../src/shared/components/Link.jsx"],"sourcesContent":["/**\n * The Link wraps around React Router's Link component, to automatically replace\n * it by the regular <a> element when:\n * - The target reference points to another domain;\n * - User opts to open the reference in a new tab;\n * - User explicitely opts to use <a>.\n */\n\nimport { Link as RrLink } from 'react-router-dom';\n\nimport GenericLink from './GenericLink';\n\nexport default function Link(props) {\n /* eslint-disable react/jsx-props-no-spreading */\n return <GenericLink {...props} routerLinkType={RrLink} />;\n /* eslint-enable react/jsx-props-no-spreading */\n}\n"],"mappings":"8KAQA,gDAEA,kE,6CAVA;AACA;AACA;AACA;AACA;AACA;AACA,GAMe,QAASA,KAAT,CAAcC,KAAd,CAAqB,CAClC,iDACA,mBAAO,oBAAC,oBAAD,KAAiBA,KAAjB,CAAwB,cAAc,CAAEC,oBAAxC,EAAP,CACA,gDACD"}
|