@dr.pogodin/react-utils 1.40.10 → 1.40.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/bin/setup.js +38 -10
  2. package/build/development/client/index.js +2 -1
  3. package/build/development/client/index.js.map +1 -1
  4. package/build/development/server/renderer.js +2 -1
  5. package/build/development/server/renderer.js.map +1 -1
  6. package/build/development/server/utils/errors.js.map +1 -1
  7. package/build/development/shared/components/GenericLink/index.js +0 -4
  8. package/build/development/shared/components/GenericLink/index.js.map +1 -1
  9. package/build/development/shared/components/Link.js.map +1 -1
  10. package/build/development/shared/components/NavLink.js.map +1 -1
  11. package/build/development/shared/utils/webpack.js +12 -9
  12. package/build/development/shared/utils/webpack.js.map +1 -1
  13. package/build/development/style.css +0 -78
  14. package/build/development/web.bundle.js +3 -3
  15. package/build/production/client/index.js +1 -1
  16. package/build/production/client/index.js.map +1 -1
  17. package/build/production/server/renderer.js +1 -1
  18. package/build/production/server/renderer.js.map +1 -1
  19. package/build/production/server/utils/errors.js.map +1 -1
  20. package/build/production/shared/components/GenericLink/index.js +1 -1
  21. package/build/production/shared/components/GenericLink/index.js.map +1 -1
  22. package/build/production/shared/components/Link.js.map +1 -1
  23. package/build/production/shared/components/NavLink.js.map +1 -1
  24. package/build/production/shared/utils/webpack.js +1 -1
  25. package/build/production/shared/utils/webpack.js.map +1 -1
  26. package/build/production/style.css.map +1 -1
  27. package/build/production/web.bundle.js +1 -1
  28. package/build/production/web.bundle.js.map +1 -1
  29. package/build/types-code/server/utils/errors.d.ts +1 -1
  30. package/build/types-code/shared/components/GenericLink/index.d.ts +7 -7
  31. package/build/types-code/shared/components/Link.d.ts +2 -1
  32. package/build/types-code/shared/components/NavLink.d.ts +2 -1
  33. package/build/types-code/shared/utils/webpack.d.ts +1 -1
  34. package/config/stylelint/default.js +1 -0
  35. package/package.json +8 -8
  36. package/src/client/index.tsx +6 -1
  37. package/src/server/renderer.tsx +4 -1
  38. package/src/server/utils/errors.ts +1 -1
  39. package/src/shared/components/GenericLink/index.tsx +15 -11
  40. package/src/shared/components/Link.tsx +2 -2
  41. package/src/shared/components/Modal/base-theme.scss +1 -1
  42. package/src/shared/components/NavLink.tsx +2 -2
  43. package/src/shared/components/PageLayout/base-theme.scss +1 -1
  44. package/src/shared/components/TextArea/style.scss +0 -1
  45. package/src/shared/components/selectors/NativeDropdown/theme.scss +0 -2
  46. package/src/shared/utils/webpack.ts +14 -9
  47. package/src/styles/global.scss +1 -1
  48. package/src/styles/mixins.scss +3 -3
package/bin/setup.js CHANGED
@@ -47,10 +47,13 @@ program
47
47
  'Skips library installation, just fixes dependencies.',
48
48
  false,
49
49
  )
50
+ .option('--verbose', 'Do verbose logging', false)
50
51
  .parse(process.argv);
51
52
 
52
53
  const cmdLineArgs = program.opts();
53
54
 
55
+ const { verbose } = cmdLineArgs;
56
+
54
57
  /**
55
58
  * Generates a string containing name and version of the package to be
56
59
  * installed.
@@ -77,6 +80,8 @@ function generateTargetPackage(entry) {
77
80
  * @param {Object} hostData Host's package JSON data.
78
81
  */
79
82
  function adoptDevDependencies(donorData, hostData) {
83
+ if (verbose) console.log('Adopting dev dependencies...');
84
+
80
85
  /* Inits deps as a map of all donor's dev dependencies. */
81
86
  let deps = clone(donorData.devDependencies) || {};
82
87
 
@@ -94,7 +99,9 @@ function adoptDevDependencies(donorData, hostData) {
94
99
 
95
100
  deps = Object.entries(deps).map(generateTargetPackage);
96
101
  if (deps.length) {
97
- spawnSync(NPM_COMMAND, ['install', '--save-dev'].concat(deps), {
102
+ const args = ['install', '--save-dev'].concat(deps);
103
+ if (verbose) args.push('--verbose');
104
+ spawnSync(NPM_COMMAND, args, {
98
105
  stdio: 'inherit',
99
106
  });
100
107
  }
@@ -141,7 +148,14 @@ function getPackageJson(packageName = '@dr.pogodin/react-utils') {
141
148
  function install(library) {
142
149
  let name = library;
143
150
  if (!name.includes('@', 1)) name += '@latest';
144
- spawnSync(NPM_COMMAND, ['install', '--save', name], { stdio: 'inherit' });
151
+ const args = ['install', '--save', name];
152
+
153
+ if (verbose) {
154
+ console.log(`Installing "${library}"...`);
155
+ args.push('--verbose');
156
+ }
157
+
158
+ spawnSync(NPM_COMMAND, args, { stdio: 'inherit' });
145
159
  }
146
160
 
147
161
  /**
@@ -152,6 +166,7 @@ function install(library) {
152
166
  * @param {Object} hostData Data from host's `package.json`.
153
167
  */
154
168
  function updateProdDependencies(donorData, hostData) {
169
+ if (verbose) console.log('Updating prod dependencies...');
155
170
  let deps = [
156
171
  ...Object.entries(donorData.dependencies || {}),
157
172
  ...Object.entries(donorData.devDependencies || {}),
@@ -163,11 +178,9 @@ function updateProdDependencies(donorData, hostData) {
163
178
  });
164
179
  if (deps.length) {
165
180
  deps = deps.map(generateTargetPackage);
166
- spawnSync(
167
- NPM_COMMAND,
168
- ['install', '--save'].concat(deps),
169
- { stdio: 'inherit' },
170
- );
181
+ const args = ['install', '--save'].concat(deps);
182
+ if (verbose) args.push('--verbose');
183
+ spawnSync(NPM_COMMAND, args, { stdio: 'inherit' });
171
184
  }
172
185
  }
173
186
 
@@ -180,6 +193,21 @@ libs.forEach((library) => {
180
193
  adoptDevDependencies(libData, hostData);
181
194
  updateProdDependencies(libData, hostData);
182
195
  });
183
- spawnSync(NPM_COMMAND, ['install'], { stdio: 'inherit' });
184
- spawnSync(NPM_COMMAND, ['audit', 'fix'], { stdio: 'inherit' });
185
- spawnSync(NPM_COMMAND, ['dedupe'], { stdio: 'inherit' });
196
+
197
+ {
198
+ const arg = ['install'];
199
+ if (verbose) arg.push('--verbose');
200
+ spawnSync(NPM_COMMAND, arg, { stdio: 'inherit' });
201
+ }
202
+
203
+ {
204
+ const arg = ['audit', 'fix'];
205
+ if (verbose) arg.push('--verbose');
206
+ spawnSync(NPM_COMMAND, arg, { stdio: 'inherit' });
207
+ }
208
+
209
+ {
210
+ const arg = ['dedupe'];
211
+ if (verbose) arg.push('--verbose');
212
+ spawnSync(NPM_COMMAND, arg, { stdio: 'inherit' });
213
+ }
@@ -27,7 +27,8 @@ function Launch(Application) {
27
27
  initialState: (0, _getInj.default)().ISTATE || options.initialState,
28
28
  children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactRouterDom.BrowserRouter, {
29
29
  future: {
30
- v7_relativeSplatPath: true
30
+ v7_relativeSplatPath: true,
31
+ v7_startTransition: true
31
32
  },
32
33
  children: /*#__PURE__*/(0, _jsxRuntime.jsx)(Application, {})
33
34
  })
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["require","_reactGlobalState","_client","_reactRouterDom","_getInj","_interopRequireDefault","_jsxRuntime","Launch","Application","options","arguments","length","undefined","container","document","getElementById","Error","scene","jsx","GlobalStateProvider","initialState","getInj","ISTATE","children","BrowserRouter","future","v7_relativeSplatPath","dontHydrate","root","createRoot","render","hydrateRoot"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport { type ComponentType } from 'react';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { BrowserRouter } from 'react-router-dom';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: any;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport default function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n) {\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={getInj().ISTATE || options.initialState}>\n <BrowserRouter future={{ v7_relativeSplatPath: true }}>\n <Application />\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":";;;;;;;AAGAA,OAAA;AAEA,IAAAC,iBAAA,GAAAD,OAAA;AAEA,IAAAE,OAAA,GAAAF,OAAA;AACA,IAAAG,eAAA,GAAAH,OAAA;AAEA,IAAAI,OAAA,GAAAC,sBAAA,CAAAL,OAAA;AAA8B,IAAAM,WAAA,GAAAN,OAAA;AAV9B;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACe,SAASO,MAAMA,CAC5BC,WAA0B,EAE1B;EAAA,IADAC,OAAiB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAEtB,MAAMG,SAAS,GAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC;EACvD,IAAI,CAACF,SAAS,EAAE,MAAMG,KAAK,CAAC,wCAAwC,CAAC;EACrE,MAAMC,KAAK,gBACT,IAAAX,WAAA,CAAAY,GAAA,EAACjB,iBAAA,CAAAkB,mBAAmB;IAACC,YAAY,EAAE,IAAAC,eAAM,EAAC,CAAC,CAACC,MAAM,IAAIb,OAAO,CAACW,YAAa;IAAAG,QAAA,eACzE,IAAAjB,WAAA,CAAAY,GAAA,EAACf,eAAA,CAAAqB,aAAa;MAACC,MAAM,EAAE;QAAEC,oBAAoB,EAAE;MAAK,CAAE;MAAAH,QAAA,eACpD,IAAAjB,WAAA,CAAAY,GAAA,EAACV,WAAW,IAAE;IAAC,CACF;EAAC,CACG,CACtB;EAED,IAAIC,OAAO,CAACkB,WAAW,EAAE;IACvB,MAAMC,IAAI,GAAG,IAAAC,kBAAU,EAAChB,SAAS,CAAC;IAClCe,IAAI,CAACE,MAAM,CAACb,KAAK,CAAC;EACpB,CAAC,MAAM,IAAAc,mBAAW,EAAClB,SAAS,EAAEI,KAAK,CAAC;AACtC","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["require","_reactGlobalState","_client","_reactRouterDom","_getInj","_interopRequireDefault","_jsxRuntime","Launch","Application","options","arguments","length","undefined","container","document","getElementById","Error","scene","jsx","GlobalStateProvider","initialState","getInj","ISTATE","children","BrowserRouter","future","v7_relativeSplatPath","v7_startTransition","dontHydrate","root","createRoot","render","hydrateRoot"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport { type ComponentType } from 'react';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { BrowserRouter } from 'react-router-dom';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: any;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport default function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n) {\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={getInj().ISTATE || options.initialState}>\n <BrowserRouter\n future={{\n v7_relativeSplatPath: true,\n v7_startTransition: true,\n }}\n >\n <Application />\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":";;;;;;;AAGAA,OAAA;AAEA,IAAAC,iBAAA,GAAAD,OAAA;AAEA,IAAAE,OAAA,GAAAF,OAAA;AACA,IAAAG,eAAA,GAAAH,OAAA;AAEA,IAAAI,OAAA,GAAAC,sBAAA,CAAAL,OAAA;AAA8B,IAAAM,WAAA,GAAAN,OAAA;AAV9B;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACe,SAASO,MAAMA,CAC5BC,WAA0B,EAE1B;EAAA,IADAC,OAAiB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAEtB,MAAMG,SAAS,GAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC;EACvD,IAAI,CAACF,SAAS,EAAE,MAAMG,KAAK,CAAC,wCAAwC,CAAC;EACrE,MAAMC,KAAK,gBACT,IAAAX,WAAA,CAAAY,GAAA,EAACjB,iBAAA,CAAAkB,mBAAmB;IAACC,YAAY,EAAE,IAAAC,eAAM,EAAC,CAAC,CAACC,MAAM,IAAIb,OAAO,CAACW,YAAa;IAAAG,QAAA,eACzE,IAAAjB,WAAA,CAAAY,GAAA,EAACf,eAAA,CAAAqB,aAAa;MACZC,MAAM,EAAE;QACNC,oBAAoB,EAAE,IAAI;QAC1BC,kBAAkB,EAAE;MACtB,CAAE;MAAAJ,QAAA,eAEF,IAAAjB,WAAA,CAAAY,GAAA,EAACV,WAAW,IAAE;IAAC,CACF;EAAC,CACG,CACtB;EAED,IAAIC,OAAO,CAACmB,WAAW,EAAE;IACvB,MAAMC,IAAI,GAAG,IAAAC,kBAAU,EAACjB,SAAS,CAAC;IAClCgB,IAAI,CAACE,MAAM,CAACd,KAAK,CAAC;EACpB,CAAC,MAAM,IAAAe,mBAAW,EAACnB,SAAS,EAAEI,KAAK,CAAC;AACtC","ignoreList":[]}
@@ -347,7 +347,8 @@ function factory(webpackConfig, options) {
347
347
  ssrContext: ssrContext,
348
348
  children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_server2.StaticRouter, {
349
349
  future: {
350
- v7_relativeSplatPath: true
350
+ v7_relativeSplatPath: true,
351
+ v7_startTransition: true
351
352
  },
352
353
  location: req.url,
353
354
  children: /*#__PURE__*/(0, _jsxRuntime.jsx)(App2, {})
@@ -1 +1 @@
1
- {"version":3,"file":"renderer.js","names":["_fs","_interopRequireDefault","require","_path","_stream","_zlib","_winston","_reactGlobalState","_jsUtils","_lodash","_config","_nodeForge","_server","_reactHelmet","_server2","_serializeJavascript","_buildInfo","_Cache","_jsxRuntime","sanitizedConfig","omit","config","SCRIPT_LOCATIONS","exports","ServerSsrContext","SsrContext","chunks","status","constructor","req","chunkGroups","initialState","cloneDeep","getBuildInfo","context","url","path","resolve","JSON","parse","fs","readFileSync","readChunkGroupsJson","buildDir","res","err","prepareCipher","key","Promise","reject","forge","random","getBytes","iv","cipher","createCipher","start","isBrotliAcceptable","acceptable","get","ops","split","i","length","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","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","setBuildInfo","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","brotliDecompress","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","all","helmet","webpackStats","locals","mapValues","toJson","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","pipeableStream","renderToPipeableStream","jsx","GlobalStateProvider","state","children","StaticRouter","future","v7_relativeSplatPath","onAllReady","onError","ssrRound","bailed","dirty","timeout","race","allSettled","pending","timer","then","logMsg","log","pipe","Writable","write","chunk","_","Helmet","renderStatic","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","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport fs from 'fs';\nimport path from 'path';\n\nimport { type Request, type RequestHandler } from 'express';\nimport { type ComponentType } from 'react';\nimport { Writable } from 'stream';\nimport { brotliCompress, brotliDecompress } from 'zlib';\nimport winston from 'winston';\n\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { timer } from '@dr.pogodin/js-utils';\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';\n\nimport { type PipeableStream, renderToPipeableStream } from 'react-dom/server';\nimport { Helmet } from 'react-helmet';\nimport { StaticRouter } from 'react-router-dom/server';\nimport serializeJs from 'serialize-javascript';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport { type ChunkGroupsT, type SsrContextT } from 'utils/globalState';\n\nimport { type Configuration } from 'webpack';\n\nimport Cache from './Cache';\n\nconst sanitizedConfig = omit(config, 'SECRET');\n\n// Note: These type definitions for logger are copied from Winston logger,\n// then simplified to make it easier to fit an alternative logger into this\n// interface.\ninterface LogMethodI {\n (level: string, message: string, ...meta: any[]): void;\n}\ninterface LeveledLogMethodI {\n (message: string, ...meta: any[]): void;\n}\n\nexport interface LoggerI {\n debug: LeveledLogMethodI;\n error: LeveledLogMethodI;\n info: LeveledLogMethodI;\n log: LogMethodI;\n warn: LeveledLogMethodI;\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport enum SCRIPT_LOCATIONS {\n BODY_OPEN = 'BODY_OPEN',\n DEFAULT = 'DEFAULT',\n HEAD_OPEN = 'HEAD_OPEN',\n}\n\nexport class ServerSsrContext<StateT>\n extends SsrContext<StateT>\n implements SsrContextT<StateT> {\n chunkGroups: ChunkGroupsT;\n\n chunks: string[] = [];\n\n req: Request;\n\n status: number = 200;\n\n constructor(\n req: Request,\n chunkGroups: ChunkGroupsT,\n initialState?: StateT,\n ) {\n super(cloneDeep(initialState) || ({} as StateT));\n this.chunkGroups = chunkGroups;\n this.req = req;\n }\n}\n\ntype ScriptT = {\n code: string;\n location: SCRIPT_LOCATIONS;\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @param context Webpack context path used during the build.\n * @return Resolves to the build-time information.\n */\nfunction getBuildInfo(context: string) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url, 'utf8'));\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @param buildDir\n * @return\n */\nfunction readChunkGroupsJson(buildDir: string) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url, 'utf8'));\n } catch (err) {\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @param key Encryption key (32-bit random key is expected, see\n * node-forge documentation, in case of doubts).\n * @return Resolves to the object with two fields:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key: string) {\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: Request) {\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 op = ops[i];\n if (op) {\n const [type, priority] = op.trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts: Array<string | ScriptT> = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (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\nexport type ConfigT = {\n [key: string]: ConfigT | string;\n};\n\nexport type BeforeRenderResT = {\n configToInject?: ConfigT;\n extraScripts?: Array<ScriptT | string>;\n initialState?: any;\n};\n\nexport type BeforeRenderT =\n(req: Request, config: ConfigT) => BeforeRenderResT | Promise<BeforeRenderResT>;\n\ntype CacheRefT = {\n key: string;\n maxage?: number;\n};\n\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\n defaultLoggerLogLevel?: string;\n favicon?: string;\n logger?: LoggerI;\n maxSsrRounds?: number;\n noCsp?: boolean;\n staticCacheSize?: number;\n ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT | null | undefined;\n};\n\n/**\n * Creates the middleware.\n * @param webpackConfig\n * @param options Additional options:\n * @param [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &ndash; the cache key for the response;\n * - `maxage?: number` &ndash; the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @return Created middleware.\n */\nexport default function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): RequestHandler {\n const ops: OptionsT = defaults(clone(options), {\n beforeRender: () => 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 setBuildInfo(buildInfo);\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output!;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath}manifest.json\">` : '';\n\n interface BufferWithNonce extends Buffer {\n nonce: string;\n }\n\n const cache = ops.staticCacheController\n ? new Cache<{\n buffer: BufferWithNonce;\n status: number;\n }>(ops.staticCacheSize!)\n : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath!);\n\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n res.cookie('csrfToken', req.csrfToken());\n\n let cacheRef: CacheRefT | null | undefined;\n if (cache) {\n cacheRef = ops.staticCacheController!(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise<void>((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n h = h.replace(regex, (req as any).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 as any),\n prepareCipher(buildInfo.key) as Promise<any>,\n ]);\n\n let helmet;\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups: ChunkGroupsT;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats');\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets.map(({ name }: { name: string }) => name),\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n const App = ops.Application;\n let appHtmlMarkup: string = '';\n const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);\n let stream: PipeableStream;\n if (App) {\n const ssrStart = Date.now();\n\n // TODO: Somehow, without it TS does not realise that\n // App has been checked to exist.\n const App2 = App;\n\n const renderPass = async () => {\n ssrContext.chunks = [];\n return new Promise<PipeableStream>((resolve, reject) => {\n const pipeableStream = renderToPipeableStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter\n future={{ v7_relativeSplatPath: true }}\n location={req.url}\n >\n <App2 />\n </StaticRouter>\n </GlobalStateProvider>,\n {\n onAllReady: () => resolve(pipeableStream),\n onError: reject,\n },\n );\n });\n };\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\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 bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n /* eslint-enable no-await-in-loop */\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;\n } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;\n\n ops.logger!.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n stream!.pipe(new Writable({\n write: (chunk, _, done) => {\n appHtmlMarkup += 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 /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject || sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n cipher.update(forge.util.createBuffer(payload, 'utf8'));\n cipher.finish();\n const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);\n\n const chunkSet = new Set<string>();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath}${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 <meta itemprop=\"drpruinj\" content=\"${INJ}\">\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${appHtmlMarkup}</div>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise<void>((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n const b = buffer as BufferWithNonce;\n if (error) failed(error);\n else {\n b.nonce = (req as any).nonce; // eslint-disable-line no-param-reassign\n cache!.add({ buffer: b, status }, cacheRef!.key, buffer.length);\n done();\n }\n });\n });\n }\n\n // Note: as caching code above may throw in some cases, sending response\n // before it completes will likely hide the error, making it difficult\n // to debug. Thus, at least for now, lets send response after it.\n res.send(html);\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":";;;;;;;;;;AAIA,IAAAA,GAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,KAAA,GAAAF,sBAAA,CAAAC,OAAA;AAEAA,OAAA;AACAA,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AACA,IAAAG,KAAA,GAAAH,OAAA;AACA,IAAAI,QAAA,GAAAL,sBAAA,CAAAC,OAAA;AAEA,IAAAK,iBAAA,GAAAL,OAAA;AACA,IAAAM,QAAA,GAAAN,OAAA;AAEA,IAAAO,OAAA,GAAAP,OAAA;AAUA,IAAAQ,OAAA,GAAAT,sBAAA,CAAAC,OAAA;AACA,IAAAS,UAAA,GAAAV,sBAAA,CAAAC,OAAA;AAEA,IAAAU,OAAA,GAAAV,OAAA;AACA,IAAAW,YAAA,GAAAX,OAAA;AACA,IAAAY,QAAA,GAAAZ,OAAA;AACA,IAAAa,oBAAA,GAAAd,sBAAA,CAAAC,OAAA;AACA,IAAAc,UAAA,GAAAd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AcU,oBAAoB,CAAC/L,gBAAgB,CAACiD,SAAS,CAAC;AAC9D,mCAAmCqF,aAAa;AAChD,cAAcuD,iBAAiB;AAC/B,cAAcE,oBAAoB,CAAC/L,gBAAgB,CAACkD,OAAO,CAAC;AAC5D;AACA,gBAAgB;MAEV,MAAM7C,MAAM,GAAGkI,UAAU,CAAClI,MAAM,IAAI,GAAG;MACvC,IAAIA,MAAM,KAAK,GAAG,EAAEiB,GAAG,CAACjB,MAAM,CAACA,MAAM,CAAC;MAEtC,IAAIkG,QAAQ,IAAIlG,MAAM,GAAG,GAAG,EAAE;QAC5B;QACA;QACA,MAAM,IAAIqB,OAAO,CAAO,CAACkF,IAAI,EAAEC,MAAM,KAAK;UACxC,IAAAuF,oBAAc,EAACpF,IAAI,EAAE,CAACD,KAAK,EAAEN,MAAM,KAAK;YACtC,MAAM4F,CAAC,GAAG5F,MAAyB;YACnC,IAAIM,KAAK,EAAEF,MAAM,CAACE,KAAK,CAAC,CAAC,KACpB;cACHsF,CAAC,CAAChF,KAAK,GAAI9G,GAAG,CAAS8G,KAAK,CAAC,CAAC;cAC9BtB,KAAK,CAAE4F,GAAG,CAAC;gBAAElF,MAAM,EAAE4F,CAAC;gBAAEhM;cAAO,CAAC,EAAEkG,QAAQ,CAAE9E,GAAG,EAAEgF,MAAM,CAAChE,MAAM,CAAC;cAC/DmE,IAAI,CAAC,CAAC;YACR;UACF,CAAC,CAAC;QACJ,CAAC,CAAC;MACJ;;MAEA;MACA;MACA;MACAtF,GAAG,CAACqF,IAAI,CAACK,IAAI,CAAC;IAChB,CAAC,CAAC,OAAOD,KAAK,EAAE;MACdZ,IAAI,CAACY,KAAK,CAAC;IACb;EACF,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"file":"renderer.js","names":["_fs","_interopRequireDefault","require","_path","_stream","_zlib","_winston","_reactGlobalState","_jsUtils","_lodash","_config","_nodeForge","_server","_reactHelmet","_server2","_serializeJavascript","_buildInfo","_Cache","_jsxRuntime","sanitizedConfig","omit","config","SCRIPT_LOCATIONS","exports","ServerSsrContext","SsrContext","chunks","status","constructor","req","chunkGroups","initialState","cloneDeep","getBuildInfo","context","url","path","resolve","JSON","parse","fs","readFileSync","readChunkGroupsJson","buildDir","res","err","prepareCipher","key","Promise","reject","forge","random","getBytes","iv","cipher","createCipher","start","isBrotliAcceptable","acceptable","get","ops","split","i","length","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","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","setBuildInfo","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","Cache","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","brotliDecompress","error","html","h","toString","regex","RegExp","nonce","replace","configToInject","extraScripts","all","helmet","webpackStats","locals","mapValues","toJson","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","pipeableStream","renderToPipeableStream","jsx","GlobalStateProvider","state","children","StaticRouter","future","v7_relativeSplatPath","v7_startTransition","onAllReady","onError","ssrRound","bailed","dirty","timeout","race","allSettled","pending","timer","then","logMsg","log","pipe","Writable","write","chunk","_","Helmet","renderStatic","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","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport fs from 'fs';\nimport path from 'path';\n\nimport { type Request, type RequestHandler } from 'express';\nimport { type ComponentType } from 'react';\nimport { Writable } from 'stream';\nimport { brotliCompress, brotliDecompress } from 'zlib';\nimport winston from 'winston';\n\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { timer } from '@dr.pogodin/js-utils';\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';\n\nimport { type PipeableStream, renderToPipeableStream } from 'react-dom/server';\nimport { Helmet } from 'react-helmet';\nimport { StaticRouter } from 'react-router-dom/server';\nimport serializeJs from 'serialize-javascript';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport { type ChunkGroupsT, type SsrContextT } from 'utils/globalState';\n\nimport { type Configuration } from 'webpack';\n\nimport Cache from './Cache';\n\nconst sanitizedConfig = omit(config, 'SECRET');\n\n// Note: These type definitions for logger are copied from Winston logger,\n// then simplified to make it easier to fit an alternative logger into this\n// interface.\ninterface LogMethodI {\n (level: string, message: string, ...meta: any[]): void;\n}\ninterface LeveledLogMethodI {\n (message: string, ...meta: any[]): void;\n}\n\nexport interface LoggerI {\n debug: LeveledLogMethodI;\n error: LeveledLogMethodI;\n info: LeveledLogMethodI;\n log: LogMethodI;\n warn: LeveledLogMethodI;\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport enum SCRIPT_LOCATIONS {\n BODY_OPEN = 'BODY_OPEN',\n DEFAULT = 'DEFAULT',\n HEAD_OPEN = 'HEAD_OPEN',\n}\n\nexport class ServerSsrContext<StateT>\n extends SsrContext<StateT>\n implements SsrContextT<StateT> {\n chunkGroups: ChunkGroupsT;\n\n chunks: string[] = [];\n\n req: Request;\n\n status: number = 200;\n\n constructor(\n req: Request,\n chunkGroups: ChunkGroupsT,\n initialState?: StateT,\n ) {\n super(cloneDeep(initialState) || ({} as StateT));\n this.chunkGroups = chunkGroups;\n this.req = req;\n }\n}\n\ntype ScriptT = {\n code: string;\n location: SCRIPT_LOCATIONS;\n};\n\n/**\n * Reads build-time information about the app. This information is generated\n * by our standard Webpack config for apps, and it is written into\n * \".build-info\" file in the context folder specified in Webpack config.\n * At the moment, that file contains build timestamp and a random 32-bit key,\n * suitable for cryptographical use.\n * @param context Webpack context path used during the build.\n * @return Resolves to the build-time information.\n */\nfunction getBuildInfo(context: string) {\n const url = path.resolve(context, '.build-info');\n return JSON.parse(fs.readFileSync(url, 'utf8'));\n}\n\n/**\n * Attempts to read from disk the named chunk groups mapping generated\n * by Webpack during the compilation.\n * It will not work for development builds, where these stats should be captured\n * via compilator callback.\n * @param buildDir\n * @return\n */\nfunction readChunkGroupsJson(buildDir: string) {\n const url = path.resolve(buildDir, '__chunk_groups__.json');\n let res;\n try {\n res = JSON.parse(fs.readFileSync(url, 'utf8'));\n } catch (err) {\n res = null;\n }\n return res;\n}\n\n/**\n * Prepares a new Cipher for data encryption.\n * @param key Encryption key (32-bit random key is expected, see\n * node-forge documentation, in case of doubts).\n * @return Resolves to the object with two fields:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key: string) {\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: Request) {\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 op = ops[i];\n if (op) {\n const [type, priority] = op.trim().split(';q=');\n if ((type === '*' || type === 'br')\n && (!priority || parseFloat(priority) > 0)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Given an array of extra script strings / objects, it returns an object with\n * arrays of scripts to inject in different HTML template locations. During\n * the script groupping it also filters out any empty scripts.\n * @param {({\n * code: string;\n * location: string;\n * }|string)[]} [scripts=[]]\n * @return {{\n * BODY_OPEN: string[];\n * DEFAULT: string[];\n * HEAD_OPEN: string[];\n * }}\n */\nfunction groupExtraScripts(scripts: Array<string | ScriptT> = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (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\nexport type ConfigT = {\n [key: string]: ConfigT | string;\n};\n\nexport type BeforeRenderResT = {\n configToInject?: ConfigT;\n extraScripts?: Array<ScriptT | string>;\n initialState?: any;\n};\n\nexport type BeforeRenderT =\n(req: Request, config: ConfigT) => BeforeRenderResT | Promise<BeforeRenderResT>;\n\ntype CacheRefT = {\n key: string;\n maxage?: number;\n};\n\nexport type OptionsT = {\n Application?: ComponentType;\n beforeRender?: BeforeRenderT;\n buildInfo?: BuildInfoT;\n defaultLoggerLogLevel?: string;\n favicon?: string;\n logger?: LoggerI;\n maxSsrRounds?: number;\n noCsp?: boolean;\n staticCacheSize?: number;\n ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT | null | undefined;\n};\n\n/**\n * Creates the middleware.\n * @param webpackConfig\n * @param options Additional options:\n * @param [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param [options.buildInfo] \"Build info\" object to use. If provided,\n * it will be used, instead of trying to load from the filesystem the one\n * generated by the Webpack build. It is intended for test environments,\n * where passing this stuff via file system is no bueno.\n * @param [options.favicon] `true` will include favicon\n * link into the rendered HTML templates.\n * @param [options.noCsp] `true` means that no\n * Content-Security-Policy (CSP) is used by server, thus the renderer\n * may cut a few corners.\n * @param [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @param [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &ndash; the cache key for the response;\n * - `maxage?: number` &ndash; the maximum age of cached result in ms.\n * If undefined - infinite age is assumed.\n * @return Created middleware.\n */\nexport default function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): RequestHandler {\n const ops: OptionsT = defaults(clone(options), {\n beforeRender: () => 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 setBuildInfo(buildInfo);\n\n // publicPath from webpack.output has a trailing slash at the end.\n const { publicPath, path: outputPath } = webpackConfig.output!;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath}manifest.json\">` : '';\n\n interface BufferWithNonce extends Buffer {\n nonce: string;\n }\n\n const cache = ops.staticCacheController\n ? new Cache<{\n buffer: BufferWithNonce;\n status: number;\n }>(ops.staticCacheSize!)\n : null;\n\n const CHUNK_GROUPS = readChunkGroupsJson(outputPath!);\n\n return async (req, res, next) => {\n try {\n // Ensures any caches always revalidate HTML markup before reuse.\n res.set('Cache-Control', 'no-cache');\n\n res.cookie('csrfToken', req.csrfToken());\n\n let cacheRef: CacheRefT | null | undefined;\n if (cache) {\n cacheRef = ops.staticCacheController!(req);\n if (cacheRef) {\n const data = cache.get(cacheRef);\n if (data !== null) {\n const { buffer, status } = data;\n if (ops.noCsp && isBrotliAcceptable(req)) {\n res.set('Content-Type', 'text/html');\n res.set('Content-Encoding', 'br');\n if (status !== 200) res.status(status);\n res.send(buffer);\n } else {\n await new Promise<void>((done, failed) => {\n brotliDecompress(buffer, (error, html) => {\n if (error) failed(error);\n else {\n let h = html.toString();\n if (!ops.noCsp) {\n // TODO: Starting from Node v15 we'll be able to use string's\n // .replaceAll() method instead relying on reg. expression for\n // global matching.\n const regex = new RegExp(buffer.nonce, 'g');\n h = h.replace(regex, (req as any).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 as any),\n prepareCipher(buildInfo.key) as Promise<any>,\n ]);\n\n let helmet;\n\n // Gets the mapping between code chunk names and their asset files.\n // These data come from the Webpack compilation, either from the stats\n // attached to the request (in dev mode), or from a file output during\n // the build (in prod mode).\n let chunkGroups: ChunkGroupsT;\n const webpackStats = get(res.locals, 'webpack.devMiddleware.stats');\n if (webpackStats) {\n chunkGroups = mapValues(\n webpackStats.toJson({\n all: false,\n chunkGroups: true,\n }).namedChunkGroups,\n (item) => item.assets.map(({ name }: { name: string }) => name),\n );\n } else if (CHUNK_GROUPS) chunkGroups = CHUNK_GROUPS;\n else chunkGroups = {};\n\n /* Optional server-side rendering. */\n const App = ops.Application;\n let appHtmlMarkup: string = '';\n const ssrContext = new ServerSsrContext(req, chunkGroups, initialState);\n let stream: PipeableStream;\n if (App) {\n const ssrStart = Date.now();\n\n // TODO: Somehow, without it TS does not realise that\n // App has been checked to exist.\n const App2 = App;\n\n const renderPass = async () => {\n ssrContext.chunks = [];\n return new Promise<PipeableStream>((resolve, reject) => {\n const pipeableStream = renderToPipeableStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter\n future={{\n v7_relativeSplatPath: true,\n v7_startTransition: true,\n }}\n location={req.url}\n >\n <App2 />\n </StaticRouter>\n </GlobalStateProvider>,\n {\n onAllReady: () => resolve(pipeableStream),\n onError: reject,\n },\n );\n });\n };\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\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 bailed = timeout <= 0 || !await Promise.race([\n Promise.allSettled(ssrContext.pending),\n timer(timeout).then(() => false),\n ]);\n if (bailed) break;\n /* eslint-enable no-await-in-loop */\n }\n\n let logMsg;\n if (ssrContext.dirty) {\n // NOTE: In the case of incomplete SSR one more round is necessary\n // to ensure the correct hydration when some pending promises have\n // resolved and placed their data into the initial global state.\n stream = await renderPass();\n\n logMsg = bailed ? `SSR timed out after ${ops.ssrTimeout} second(s)`\n : `SSR bailed out after ${ops.maxSsrRounds} round(s)`;\n } else logMsg = `SSR completed in ${ssrRound + 1} round(s)`;\n\n ops.logger!.log(ssrContext.dirty ? 'warn' : 'info', logMsg);\n\n stream!.pipe(new Writable({\n write: (chunk, _, done) => {\n appHtmlMarkup += 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 /* Encrypts data to be injected into HTML.\n * Keep in mind, that this encryption is no way secure: as the JS bundle\n * contains decryption key and is able to decode it at the client side.\n * Hovewer, for a number of reasons, encryption of injected data is still\n * better than injection of a plain text. */\n const payload = serializeJs({\n CHUNK_GROUPS: chunkGroups,\n CONFIG: configToInject || sanitizedConfig,\n ISTATE: ssrContext.state,\n }, {\n ignoreFunction: true,\n unsafe: true,\n });\n cipher.update(forge.util.createBuffer(payload, 'utf8'));\n cipher.finish();\n const INJ = forge.util.encode64(`${iv}${cipher.output.data}`);\n\n const chunkSet = new Set<string>();\n\n // TODO: \"main\" chunk has to be added explicitly,\n // because unlike all other chunks they are not managed by <CodeSplit>\n // component, thus they are not added to the ssrContext.chunks\n // automatically. Actually, names of these entry chunks should be\n // read from Wepback config, as the end user may customize them,\n // remove or add other entry points, but it requires additional\n // efforts to figure out how to automatically order them right,\n // thus for now this handles the default config.\n [\n 'main',\n ...ssrContext.chunks,\n ].forEach((chunk) => {\n const assets = chunkGroups[chunk];\n if (assets) assets.forEach((asset) => chunkSet.add(asset));\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath}${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 <meta itemprop=\"drpruinj\" content=\"${INJ}\">\n </head>\n <body>\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.BODY_OPEN]}\n <div id=\"react-view\">${appHtmlMarkup}</div>\n ${scriptChunkString}\n ${grouppedExtraScripts[SCRIPT_LOCATIONS.DEFAULT]}\n </body>\n </html>`;\n\n const status = ssrContext.status || 200;\n if (status !== 200) res.status(status);\n\n if (cacheRef && status < 500) {\n // Note: waiting for the caching to complete is not strictly necessary,\n // but it greately simplifies testing, and error reporting.\n await new Promise<void>((done, failed) => {\n brotliCompress(html, (error, buffer) => {\n const b = buffer as BufferWithNonce;\n if (error) failed(error);\n else {\n b.nonce = (req as any).nonce; // eslint-disable-line no-param-reassign\n cache!.add({ buffer: b, status }, cacheRef!.key, buffer.length);\n done();\n }\n });\n });\n }\n\n // Note: as caching code above may throw in some cases, sending response\n // before it completes will likely hide the error, making it difficult\n // to debug. Thus, at least for now, lets send response after it.\n res.send(html);\n } catch (error) {\n next(error);\n }\n };\n}\n"],"mappings":";;;;;;;;;;AAIA,IAAAA,GAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,KAAA,GAAAF,sBAAA,CAAAC,OAAA;AAEAA,OAAA;AACAA,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AACA,IAAAG,KAAA,GAAAH,OAAA;AACA,IAAAI,QAAA,GAAAL,sBAAA,CAAAC,OAAA;AAEA,IAAAK,iBAAA,GAAAL,OAAA;AACA,IAAAM,QAAA,GAAAN,OAAA;AAEA,IAAAO,OAAA,GA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CAACqF,IAAI,CAACK,IAAI,CAAC;IAChB,CAAC,CAAC,OAAOD,KAAK,EAAE;MACdZ,IAAI,CAACY,KAAK,CAAC;IACb;EACF,CAAC;AACH","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":["_httpStatusCodes","require","_joi","_interopRequireDefault","ErrorWithStatus","Error","status","CODES","INTERNAL_SERVER_ERROR","newError","message","statusCode","error","fail","assert","value","schema","BAD_REQUEST","validate","abortEarly","concat"],"sources":["../../../../src/server/utils/errors.ts"],"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// TODO: It could accept the status code as a constructor argument.\nclass ErrorWithStatus extends Error {\n status: number = CODES.INTERNAL_SERVER_ERROR;\n}\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: string, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n const error = new ErrorWithStatus(message);\n error.status = statusCode;\n return error;\n}\n\n/**\n * Throws an error with given message and HTTP status code.\n */\nexport function fail(\n message: string,\n statusCode: CODES = CODES.INTERNAL_SERVER_ERROR,\n): never {\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 value\n * @param schema\n * @param [message] Error message.\n * @param [statusCode=500] HTTP status code. Defaults to 400 (Bad\n * Request).\n */\nexport function assert(\n value: any,\n schema: joi.AnySchema,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,IAAAA,gBAAA,GAAAC,OAAA;AAMA,IAAAC,IAAA,GAAAC,sBAAA,CAAAF,OAAA;AAjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA,MAAMG,eAAe,SAASC,KAAK,CAAC;EAClCC,MAAM,GAAWC,4BAAK,CAACC,qBAAqB;AAC9C;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,QAAQA,CAACC,OAAe,EAAEC,UAAU,GAAGJ,4BAAK,CAACC,qBAAqB,EAAE;EAClF,MAAMI,KAAK,GAAG,IAAIR,eAAe,CAACM,OAAO,CAAC;EAC1CE,KAAK,CAACN,MAAM,GAAGK,UAAU;EACzB,OAAOC,KAAK;AACd;;AAEA;AACA;AACA;AACO,SAASC,IAAIA,CAClBH,OAAe,EACfC,UAAiB,GAAGJ,4BAAK,CAACC,qBAAqB,EACxC;EACP,MAAMC,QAAQ,CAACC,OAAO,EAAEC,UAAU,CAAC;AACrC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASG,MAAMA,CACpBC,KAAU,EACVC,MAAqB,EACrBN,OAAO,GAAG,EAAE,EACZC,UAAU,GAAGJ,4BAAK,CAACU,WAAW,EAC9B;EACA,MAAM;IAAEL;EAAM,CAAC,GAAGI,MAAM,CAACE,QAAQ,CAACH,KAAK,EAAE;IAAEI,UAAU,EAAE;EAAM,CAAC,CAAC;EAC/D,IAAIP,KAAK,EAAE;IACTC,IAAI,CAACH,OAAO,CAACU,MAAM,CAACV,OAAO,GAAG,IAAI,GAAG,EAAE,EAAEE,KAAK,CAACF,OAAO,CAAC,EAAEC,UAAU,CAAC;EACtE;AACF","ignoreList":[]}
1
+ {"version":3,"file":"errors.js","names":["_httpStatusCodes","require","_joi","_interopRequireDefault","ErrorWithStatus","Error","status","CODES","INTERNAL_SERVER_ERROR","newError","message","statusCode","error","fail","assert","value","schema","BAD_REQUEST","validate","abortEarly","concat"],"sources":["../../../../src/server/utils/errors.ts"],"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// TODO: It could accept the status code as a constructor argument.\nclass ErrorWithStatus extends Error {\n status: number = CODES.INTERNAL_SERVER_ERROR;\n}\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: string, statusCode = CODES.INTERNAL_SERVER_ERROR) {\n const error = new ErrorWithStatus(message);\n error.status = statusCode;\n return error;\n}\n\n/**\n * Throws an error with given message and HTTP status code.\n */\nexport function fail(\n message: string,\n statusCode: CODES = CODES.INTERNAL_SERVER_ERROR,\n): 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 value\n * @param schema\n * @param [message] Error message.\n * @param [statusCode=500] HTTP status code. Defaults to 400 (Bad\n * Request).\n */\nexport function assert(\n value: any,\n schema: joi.AnySchema,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,IAAAA,gBAAA,GAAAC,OAAA;AAMA,IAAAC,IAAA,GAAAC,sBAAA,CAAAF,OAAA;AAjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA,MAAMG,eAAe,SAASC,KAAK,CAAC;EAClCC,MAAM,GAAWC,4BAAK,CAACC,qBAAqB;AAC9C;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,QAAQA,CAACC,OAAe,EAAEC,UAAU,GAAGJ,4BAAK,CAACC,qBAAqB,EAAE;EAClF,MAAMI,KAAK,GAAG,IAAIR,eAAe,CAACM,OAAO,CAAC;EAC1CE,KAAK,CAACN,MAAM,GAAGK,UAAU;EACzB,OAAOC,KAAK;AACd;;AAEA;AACA;AACA;AACO,SAASC,IAAIA,CAClBH,OAAe,EACfC,UAAiB,GAAGJ,4BAAK,CAACC,qBAAqB,EACxC;EACP,MAAMC,QAAQ,CAACC,OAAO,EAAEC,UAAU,CAAC;AACrC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASG,MAAMA,CACpBC,KAAU,EACVC,MAAqB,EACrBN,OAAO,GAAG,EAAE,EACZC,UAAU,GAAGJ,4BAAK,CAACU,WAAW,EAC9B;EACA,MAAM;IAAEL;EAAM,CAAC,GAAGI,MAAM,CAACE,QAAQ,CAACH,KAAK,EAAE;IAAEI,UAAU,EAAE;EAAM,CAAC,CAAC;EAC/D,IAAIP,KAAK,EAAE;IACTC,IAAI,CAACH,OAAO,CAACU,MAAM,CAACV,OAAO,GAAG,IAAI,GAAG,EAAE,EAAEE,KAAK,CAACF,OAAO,CAAC,EAAEC,UAAU,CAAC;EACtE;AACF","ignoreList":[]}
@@ -4,11 +4,7 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
- require("react");
8
- require("react-router-dom");
9
7
  var _jsxRuntime = require("react/jsx-runtime");
10
- /* global window */
11
-
12
8
  /**
13
9
  * The `<Link>` component, and almost identical `<NavLink>` component, are
14
10
  * auxiliary wrappers around
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["require","_jsxRuntime","GenericLink","children","className","disabled","enforceA","keepScrollPosition","onClick","onMouseDown","openNewTab","replace","routerLinkType","to","rest","match","jsx","href","e","preventDefault","rel","target","L","window","scroll","_default","exports","default"],"sources":["../../../../../src/shared/components/GenericLink/index.tsx"],"sourcesContent":["/* global window */\n\nimport { type ReactNode } from 'react';\n\nimport { type Link, type NavLink } from 'react-router-dom';\n\nimport './style.scss';\n\ntype ToT = Parameters<typeof Link>[0]['to'];\n\ninterface LinkI {}\n\nexport type PropsT = {\n children?: ReactNode;\n className?: string;\n disabled?: boolean;\n enforceA?: boolean;\n keepScrollPosition?: boolean;\n onClick?: React.MouseEventHandler<HTMLAnchorElement>;\n onMouseDown?: React.MouseEventHandler<HTMLAnchorElement>;\n openNewTab?: boolean;\n replace?: boolean;\n routerLinkType: LinkI;\n to?: ToT;\n};\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 [props] Component properties.\n * @param [props.className] CSS classes to apply to the link.\n * @param [props.disabled] Disables the link.\n * @param [props.enforceA] `true` enforces rendering of the link as\n * a simple `<a>` element.\n * @param [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 [props.onClick] Event handler to trigger upon click.\n * @param [props.onMouseDown] Event handler to trigger on MouseDown\n * event.\n * @param [props.openNewTab] If `true` the link opens in a new tab.\n * @param [props.replace] When `true`, the link will replace current\n * entry in the history stack instead of adding a new one.\n * @param [props.to] Link URL.\n * @param [props.activeClassName] **`<NavLink>`** only: CSS class(es)\n * to apply to rendered link when it is active.\n * @param [props.activeStyle] **`<NavLink>`** only: CSS styles\n * to apply to the rendered link when it is active.\n * @param [props.exact] **`<NavLink>`** only: if `true`, the active\n * class/style will only be applied if the location is matched exactly.\n * @param [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 [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 [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 */\nconst GenericLink: React.FunctionComponent<PropsT> = ({\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 as string)?.match(/^(#|(https?|mailto):)/)) {\n return (\n <a\n className={className}\n // TODO: This requires a fix: disabled is not really an attribute of <a>\n // tag, thus for disabled option we rather should render a plain text\n // styled as a link.\n // disabled={disabled}\n href={to as string}\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 const L = routerLinkType as typeof NavLink;\n\n return (\n <L\n className={className}\n // disabled\n onMouseDown={onMouseDown}\n replace={replace}\n to={to!}\n onClick={(e: React.MouseEvent<HTMLAnchorElement>) => {\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} // eslint-disable-line react/jsx-props-no-spreading\n >\n {children}\n </L>\n );\n};\n\nexport default GenericLink;\n"],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,EAAI;IACRL,OAAO,EAAGU,CAAsC,IAAK;MACnD;MACA,IAAIV,OAAO,EAAEA,OAAO,CAACU,CAAC,CAAC;;MAEvB;MACA,IAAI,CAACX,kBAAkB,EAAEgB,MAAM,CAACC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC;IAC9C,CAAE;IAAA,GACEV,IAAI;IAAAX,QAAA,EAEPA;EAAQ,CACR,CAAC;AAER,CAAC;AAAC,IAAAsB,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEazB,WAAW","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["GenericLink","children","className","disabled","enforceA","keepScrollPosition","onClick","onMouseDown","openNewTab","replace","routerLinkType","to","rest","match","_jsxRuntime","jsx","href","e","preventDefault","rel","target","L","window","scroll","_default","exports","default"],"sources":["../../../../../src/shared/components/GenericLink/index.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport type {\n Link,\n LinkProps,\n NavLink,\n NavLinkProps,\n} from 'react-router-dom';\n\nimport './style.scss';\n\ntype LinkT = typeof Link;\ntype NavLinkT = typeof NavLink;\n\ntype ToT = Parameters<typeof Link>[0]['to'];\n\nexport type PropsT = {\n children?: ReactNode;\n className?: string;\n disabled?: boolean;\n enforceA?: boolean;\n keepScrollPosition?: boolean;\n onClick?: React.MouseEventHandler<HTMLAnchorElement>;\n onMouseDown?: React.MouseEventHandler<HTMLAnchorElement>;\n openNewTab?: boolean;\n replace?: boolean;\n routerLinkType: LinkT | NavLinkT;\n to: ToT;\n};\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 [props] Component properties.\n * @param [props.className] CSS classes to apply to the link.\n * @param [props.disabled] Disables the link.\n * @param [props.enforceA] `true` enforces rendering of the link as\n * a simple `<a>` element.\n * @param [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 [props.onClick] Event handler to trigger upon click.\n * @param [props.onMouseDown] Event handler to trigger on MouseDown\n * event.\n * @param [props.openNewTab] If `true` the link opens in a new tab.\n * @param [props.replace] When `true`, the link will replace current\n * entry in the history stack instead of adding a new one.\n * @param [props.to] Link URL.\n * @param [props.activeClassName] **`<NavLink>`** only: CSS class(es)\n * to apply to rendered link when it is active.\n * @param [props.activeStyle] **`<NavLink>`** only: CSS styles\n * to apply to the rendered link when it is active.\n * @param [props.exact] **`<NavLink>`** only: if `true`, the active\n * class/style will only be applied if the location is matched exactly.\n * @param [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 [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 [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 */\nconst 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}: (LinkProps | NavLinkProps) & PropsT): ReactNode => {\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 as string)?.match(/^(#|(https?|mailto):)/)) {\n return (\n <a\n className={className}\n // TODO: This requires a fix: disabled is not really an attribute of <a>\n // tag, thus for disabled option we rather should render a plain text\n // styled as a link.\n // disabled={disabled}\n href={to as string}\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 const L = routerLinkType;\n\n return (\n <L\n className={className}\n // disabled\n onMouseDown={onMouseDown}\n replace={replace}\n to={to!}\n onClick={(e: React.MouseEvent<HTMLAnchorElement>) => {\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} // eslint-disable-line react/jsx-props-no-spreading\n >\n {children}\n </L>\n );\n};\n\nexport default GenericLink;\n"],"mappings":";;;;;;;AA8BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMA,WAAW,GAAGA,CAAC;EACnBC,QAAQ;EACRC,SAAS;EACTC,QAAQ;EACRC,QAAQ;EACRC,kBAAkB;EAClBC,OAAO;EACPC,WAAW;EACXC,UAAU;EACVC,OAAO;EACPC,cAAc;EACdC,EAAE;EACF,GAAGC;AACgC,CAAC,KAAgB;EACpD;AACF;AACA;AACA;AACA;EACE,IAAIT,QAAQ,IAAIC,QAAQ,IAAII,UAAU,IAAKG,EAAE,EAAaE,KAAK,CAAC,uBAAuB,CAAC,EAAE;IACxF,oBACE,IAAAC,WAAA,CAAAC,GAAA;MACEb,SAAS,GAAEA,SAAS,GAATA,SAAS;MACpB;MACA;MACA;MACA;MAAA;MACAc,IAAI,EAAEL,EAAa;MACnBL,OAAO,EAAEH,QAAQ,GAAIc,CAAC,IAAKA,CAAC,CAACC,cAAc,CAAC,CAAC,GAAGZ,OAAQ;MACxDC,WAAW,EAAEJ,QAAQ,GAAIc,CAAC,IAAKA,CAAC,CAACC,cAAc,CAAC,CAAC,GAAGX,WAAY;MAChEY,GAAG,EAAC,qBAAqB;MAEzBC,MAAM,EAAEZ,UAAU,GAAG,QAAQ,GAAG,EAAG;MAAAP,QAAA,EAElCA;IAAQ,CACR,CAAC;EAER;EAEA,MAAMoB,CAAC,GAAGX,cAAc;EAExB,oBACE,IAAAI,WAAA,CAAAC,GAAA,EAACM,CAAC;IACAnB,SAAS,EAAEA;IACX;IAAA;IACAK,WAAW,EAAEA,WAAY;IACzBE,OAAO,EAAEA,OAAQ;IACjBE,EAAE,EAAEA,EAAI;IACRL,OAAO,EAAGW,CAAsC,IAAK;MACnD;MACA,IAAIX,OAAO,EAAEA,OAAO,CAACW,CAAC,CAAC;;MAEvB;MACA,IAAI,CAACZ,kBAAkB,EAAEiB,MAAM,CAACC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC;IAC9C,CAAE;IAAA,GACEX,IAAI;IAAAX,QAAA,EAEPA;EAAQ,CACR,CAAC;AAER,CAAC;AAAC,IAAAuB,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEa1B,WAAW","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"Link.js","names":["_reactRouterDom","require","_GenericLink","_interopRequireDefault","_jsxRuntime","Link","props","jsx","default","routerLinkType","RrLink","_default","exports"],"sources":["../../../../src/shared/components/Link.tsx"],"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, { type PropsT as GenericLinkPropsT } from './GenericLink';\n\ntype PropsT = Omit<GenericLinkPropsT, 'routerLinkType'>;\n\nconst Link: React.FunctionComponent<PropsT> = (props) => (\n /* eslint-disable react/jsx-props-no-spreading */\n <GenericLink {...props} routerLinkType={RrLink} />\n /* eslint-enable react/jsx-props-no-spreading */\n);\n\nexport default Link;\n"],"mappings":";;;;;;;AAQA,IAAAA,eAAA,GAAAC,OAAA;AAEA,IAAAC,YAAA,GAAAC,sBAAA,CAAAF,OAAA;AAA8E,IAAAG,WAAA,GAAAH,OAAA;AAV9E;AACA;AACA;AACA;AACA;AACA;AACA;;AAQA,MAAMI,IAAqC,GAAIC,KAAK;AAAA;AAClD;AACA,IAAAF,WAAA,CAAAG,GAAA,EAACL,YAAA,CAAAM,OAAW;EAAA,GAAKF,KAAK;EAAEG,cAAc,EAAEC;AAAO,CAAE;AACjD,gDACD;AAAC,IAAAC,QAAA,GAAAC,OAAA,CAAAJ,OAAA,GAEaH,IAAI","ignoreList":[]}
1
+ {"version":3,"file":"Link.js","names":["_reactRouterDom","require","_GenericLink","_interopRequireDefault","_jsxRuntime","Link","props","jsx","default","routerLinkType","RrLink","_default","exports"],"sources":["../../../../src/shared/components/Link.tsx"],"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 { type LinkProps, Link as RrLink } from 'react-router-dom';\n\nimport GenericLink, { type PropsT as GenericLinkPropsT } from './GenericLink';\n\ntype PropsT = Omit<GenericLinkPropsT, 'routerLinkType'> & LinkProps;\n\nconst Link: React.FunctionComponent<PropsT> = (props) => (\n /* eslint-disable react/jsx-props-no-spreading */\n <GenericLink {...props} routerLinkType={RrLink} />\n /* eslint-enable react/jsx-props-no-spreading */\n);\n\nexport default Link;\n"],"mappings":";;;;;;;AAQA,IAAAA,eAAA,GAAAC,OAAA;AAEA,IAAAC,YAAA,GAAAC,sBAAA,CAAAF,OAAA;AAA8E,IAAAG,WAAA,GAAAH,OAAA;AAV9E;AACA;AACA;AACA;AACA;AACA;AACA;;AAQA,MAAMI,IAAqC,GAAIC,KAAK;AAAA;AAClD;AACA,IAAAF,WAAA,CAAAG,GAAA,EAACL,YAAA,CAAAM,OAAW;EAAA,GAAKF,KAAK;EAAEG,cAAc,EAAEC;AAAO,CAAE;AACjD,gDACD;AAAC,IAAAC,QAAA,GAAAC,OAAA,CAAAJ,OAAA,GAEaH,IAAI","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"NavLink.js","names":["_reactRouterDom","require","_GenericLink","_interopRequireDefault","_jsxRuntime","NavLink","props","jsx","default","routerLinkType","RrNavLink","_default","exports"],"sources":["../../../../src/shared/components/NavLink.tsx"],"sourcesContent":["import { NavLink as RrNavLink } from 'react-router-dom';\n\nimport GenericLink, { type PropsT as GenericLinkPropsT } from './GenericLink';\n\ntype PropsT = Omit<GenericLinkPropsT, 'routerLinkType'>;\n\nconst NavLink: React.FunctionComponent<PropsT> = (props) => (\n /* eslint-disable react/jsx-props-no-spreading */\n <GenericLink {...props} routerLinkType={RrNavLink} />\n /* eslint-enable react/jsx-props-no-spreading */\n);\n\nexport default NavLink;\n"],"mappings":";;;;;;;AAAA,IAAAA,eAAA,GAAAC,OAAA;AAEA,IAAAC,YAAA,GAAAC,sBAAA,CAAAF,OAAA;AAA8E,IAAAG,WAAA,GAAAH,OAAA;AAI9E,MAAMI,OAAwC,GAAIC,KAAK;AAAA;AACrD;AACA,IAAAF,WAAA,CAAAG,GAAA,EAACL,YAAA,CAAAM,OAAW;EAAA,GAAKF,KAAK;EAAEG,cAAc,EAAEC;AAAU,CAAE;AACpD,gDACD;AAAC,IAAAC,QAAA,GAAAC,OAAA,CAAAJ,OAAA,GAEaH,OAAO","ignoreList":[]}
1
+ {"version":3,"file":"NavLink.js","names":["_reactRouterDom","require","_GenericLink","_interopRequireDefault","_jsxRuntime","NavLink","props","jsx","default","routerLinkType","RrNavLink","_default","exports"],"sources":["../../../../src/shared/components/NavLink.tsx"],"sourcesContent":["import { type NavLinkProps, NavLink as RrNavLink } from 'react-router-dom';\n\nimport GenericLink, { type PropsT as GenericLinkPropsT } from './GenericLink';\n\ntype PropsT = Omit<GenericLinkPropsT, 'routerLinkType'> & NavLinkProps;\n\nconst NavLink: React.FunctionComponent<PropsT> = (props) => (\n /* eslint-disable react/jsx-props-no-spreading */\n <GenericLink {...props} routerLinkType={RrNavLink} />\n /* eslint-enable react/jsx-props-no-spreading */\n);\n\nexport default NavLink;\n"],"mappings":";;;;;;;AAAA,IAAAA,eAAA,GAAAC,OAAA;AAEA,IAAAC,YAAA,GAAAC,sBAAA,CAAAF,OAAA;AAA8E,IAAAG,WAAA,GAAAH,OAAA;AAI9E,MAAMI,OAAwC,GAAIC,KAAK;AAAA;AACrD;AACA,IAAAF,WAAA,CAAAG,GAAA,EAACL,YAAA,CAAAM,OAAW;EAAA,GAAKF,KAAK;EAAEG,cAAc,EAAEC;AAAU,CAAE;AACpD,gDACD;AAAC,IAAAC,QAAA,GAAAC,OAAA,CAAAJ,OAAA,GAEaH,OAAO","ignoreList":[]}
@@ -21,21 +21,24 @@ function requireWeak(modulePath, basePath) {
21
21
  resolve
22
22
  } = eval('require')('path');
23
23
  const path = basePath ? resolve(basePath, modulePath) : modulePath;
24
+ const module = eval('require')(path);
25
+ /* eslint-enable no-eval */
26
+
27
+ if (!('default' in module)) return module;
24
28
  const {
25
29
  default: def,
26
30
  ...named
27
- } = eval('require')(path);
28
- /* eslint-enable no-eval */
29
-
30
- if (!def) return named;
31
- Object.entries(named).forEach(([key, value]) => {
32
- if (def[key]) {
33
- if (def[key] !== value) {
31
+ } = module;
32
+ const res = def;
33
+ Object.entries(named).forEach(([name, value]) => {
34
+ const assigned = res[name];
35
+ if (assigned !== undefined) {
36
+ if (assigned !== value) {
34
37
  throw Error('Conflict between default and named exports');
35
38
  }
36
- } else def[key] = value;
39
+ } else res[name] = value;
37
40
  });
38
- return def;
41
+ return res;
39
42
  } catch {
40
43
  return null;
41
44
  }
@@ -1 +1 @@
1
- {"version":3,"file":"webpack.js","names":["_isomorphy","require","requireWeak","modulePath","basePath","IS_CLIENT_SIDE","resolve","eval","path","default","def","named","Object","entries","forEach","key","value","Error","resolveWeak"],"sources":["../../../../src/shared/utils/webpack.ts"],"sourcesContent":["import { IS_CLIENT_SIDE } from './isomorphy';\n\n/**\n * Requires the specified module without including it into the bundle during\n * Webpack build.\n * @param modulePath\n * @param [basePath]\n * @return Required module.\n */\nexport function requireWeak(\n modulePath: string,\n basePath?: string,\n): NodeJS.Module | null {\n if (IS_CLIENT_SIDE) return null;\n\n try {\n /* eslint-disable no-eval */\n const { resolve } = eval('require')('path');\n const path = basePath ? resolve(basePath, modulePath) : modulePath;\n const { default: def, ...named } = eval('require')(path);\n /* eslint-enable no-eval */\n\n if (!def) return named;\n\n Object.entries(named).forEach(([key, value]) => {\n if (def[key]) {\n if (def[key] !== value) {\n throw Error('Conflict between default and named exports');\n }\n } else def[key] = value;\n });\n return def;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolves specified module path with help of Babel's module resolver.\n * Yes, the function itself just returns its argument to the caller, but Babel\n * is configured to resolve the first argument of resolveWeak(..) function, thus\n * the result will be the resolved path.\n * @param {string} modulePath\n * @return {string} Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath: string): string {\n return modulePath;\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,UAAA,GAAAC,OAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,WAAWA,CACzBC,UAAkB,EAClBC,QAAiB,EACK;EACtB,IAAIC,yBAAc,EAAE,OAAO,IAAI;EAE/B,IAAI;IACF;IACA,MAAM;MAAEC;IAAQ,CAAC,GAAGC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC;IAC3C,MAAMC,IAAI,GAAGJ,QAAQ,GAAGE,OAAO,CAACF,QAAQ,EAAED,UAAU,CAAC,GAAGA,UAAU;IAClE,MAAM;MAAEM,OAAO,EAAEC,GAAG;MAAE,GAAGC;IAAM,CAAC,GAAGJ,IAAI,CAAC,SAAS,CAAC,CAACC,IAAI,CAAC;IACxD;;IAEA,IAAI,CAACE,GAAG,EAAE,OAAOC,KAAK;IAEtBC,MAAM,CAACC,OAAO,CAACF,KAAK,CAAC,CAACG,OAAO,CAAC,CAAC,CAACC,GAAG,EAAEC,KAAK,CAAC,KAAK;MAC9C,IAAIN,GAAG,CAACK,GAAG,CAAC,EAAE;QACZ,IAAIL,GAAG,CAACK,GAAG,CAAC,KAAKC,KAAK,EAAE;UACtB,MAAMC,KAAK,CAAC,4CAA4C,CAAC;QAC3D;MACF,CAAC,MAAMP,GAAG,CAACK,GAAG,CAAC,GAAGC,KAAK;IACzB,CAAC,CAAC;IACF,OAAON,GAAG;EACZ,CAAC,CAAC,MAAM;IACN,OAAO,IAAI;EACb;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASQ,WAAWA,CAACf,UAAkB,EAAU;EACtD,OAAOA,UAAU;AACnB","ignoreList":[]}
1
+ {"version":3,"file":"webpack.js","names":["_isomorphy","require","requireWeak","modulePath","basePath","IS_CLIENT_SIDE","resolve","eval","path","module","default","def","named","res","Object","entries","forEach","name","value","assigned","undefined","Error","resolveWeak"],"sources":["../../../../src/shared/utils/webpack.ts"],"sourcesContent":["import { IS_CLIENT_SIDE } from './isomorphy';\n\n/**\n * Requires the specified module without including it into the bundle during\n * Webpack build.\n * @param modulePath\n * @param [basePath]\n * @return Required module.\n */\nexport function requireWeak<Module extends NodeJS.Module>(\n modulePath: string,\n basePath?: string,\n): Module | null {\n if (IS_CLIENT_SIDE) return null;\n\n try {\n /* eslint-disable no-eval */\n const { resolve } = eval('require')('path');\n const path = basePath ? resolve(basePath, modulePath) : modulePath;\n const module = eval('require')(path) as Module;\n /* eslint-enable no-eval */\n\n if (!('default' in module)) return module;\n\n const { default: def, ...named } = module;\n\n const res = def as Module;\n\n Object.entries(named).forEach(([name, value]) => {\n const assigned = res[name as keyof Module];\n if (assigned !== undefined) {\n if (assigned !== value) {\n throw Error('Conflict between default and named exports');\n }\n } else res[name as keyof Module] = value;\n });\n return res;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolves specified module path with help of Babel's module resolver.\n * Yes, the function itself just returns its argument to the caller, but Babel\n * is configured to resolve the first argument of resolveWeak(..) function, thus\n * the result will be the resolved path.\n * @param {string} modulePath\n * @return {string} Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath: string): string {\n return modulePath;\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,UAAA,GAAAC,OAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,WAAWA,CACzBC,UAAkB,EAClBC,QAAiB,EACF;EACf,IAAIC,yBAAc,EAAE,OAAO,IAAI;EAE/B,IAAI;IACF;IACA,MAAM;MAAEC;IAAQ,CAAC,GAAGC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC;IAC3C,MAAMC,IAAI,GAAGJ,QAAQ,GAAGE,OAAO,CAACF,QAAQ,EAAED,UAAU,CAAC,GAAGA,UAAU;IAClE,MAAMM,MAAM,GAAGF,IAAI,CAAC,SAAS,CAAC,CAACC,IAAI,CAAW;IAC9C;;IAEA,IAAI,EAAE,SAAS,IAAIC,MAAM,CAAC,EAAE,OAAOA,MAAM;IAEzC,MAAM;MAAEC,OAAO,EAAEC,GAAG;MAAE,GAAGC;IAAM,CAAC,GAAGH,MAAM;IAEzC,MAAMI,GAAG,GAAGF,GAAa;IAEzBG,MAAM,CAACC,OAAO,CAACH,KAAK,CAAC,CAACI,OAAO,CAAC,CAAC,CAACC,IAAI,EAAEC,KAAK,CAAC,KAAK;MAC/C,MAAMC,QAAQ,GAAGN,GAAG,CAACI,IAAI,CAAiB;MAC1C,IAAIE,QAAQ,KAAKC,SAAS,EAAE;QAC1B,IAAID,QAAQ,KAAKD,KAAK,EAAE;UACtB,MAAMG,KAAK,CAAC,4CAA4C,CAAC;QAC3D;MACF,CAAC,MAAMR,GAAG,CAACI,IAAI,CAAiB,GAAGC,KAAK;IAC1C,CAAC,CAAC;IACF,OAAOL,GAAG;EACZ,CAAC,CAAC,MAAM;IACN,OAAO,IAAI;EACb;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASS,WAAWA,CAACnB,UAAkB,EAAU;EACtD,OAAOA,UAAU;AACnB","ignoreList":[]}
@@ -275,45 +275,6 @@ body {
275
275
  !*** css ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!./node_modules/resolve-url-loader/index.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[4]!./src/shared/components/selectors/NativeDropdown/theme.scss ***!
276
276
  \*****************************************************************************************************************************************************************************************************************************************************************************************************************************/
277
277
  @charset "UTF-8";
278
- /* Collection of standard mixins, being used all around. */
279
- /* Auxiliary mixins for fonts inclusion. */
280
- /**
281
- * Includes a font, provided as a set of alternative files in EOT, WOFF, TTF,
282
- * SVG formats into the app.
283
- * $font-name {String}
284
- * $font-weight {Number}
285
- * $font-style {String}
286
- * $font-url {String} Path to the font file, without the filename itself.
287
- * $font-file {String} Font filename, without extension (should be the same for
288
- * each version of the font in different formats.
289
- */
290
- /**
291
- * Includes a font, provided in the TTF format only.
292
- * $font-name {String}
293
- * $font-weight {Number}
294
- * $font-style {String}
295
- * $font-url {String}
296
- */
297
- /**
298
- * Mixins for different layout sizes: xs, sm, md, lg.
299
- * Breaking points are defined in _variables.scss
300
- * The range mixins A-to-B all means "for the sizes from A to B, both
301
- * inclusive", in particular it means that mixin A-to-lg is equivalent to
302
- * all sizes from A (inclusive) and larger.
303
- *
304
- * NOTE: For convenience, these mixins are sorted not alphabetically, but,
305
- * first, by increase of the first size; second, by increase of the second size.
306
- */
307
- /* Break points. */
308
- /* XS */
309
- /* SM */
310
- /* MM */
311
- /* MD */
312
- /* LG */
313
- /* XL */
314
- /**
315
- * A simple drop-in typography mixin.
316
- */
317
278
  *.-dr-pogodin-react-utils___src-shared-components-selectors-NativeDropdown-theme___dropdown___kI9A9U,
318
279
  .-dr-pogodin-react-utils___src-shared-components-selectors-NativeDropdown-theme___context___xHyZo4.-dr-pogodin-react-utils___src-shared-components-selectors-NativeDropdown-theme___dropdown___kI9A9U,
319
280
  .-dr-pogodin-react-utils___src-shared-components-selectors-NativeDropdown-theme___ad___ADu59e.-dr-pogodin-react-utils___src-shared-components-selectors-NativeDropdown-theme___hoc___FTP2bb.-dr-pogodin-react-utils___src-shared-components-selectors-NativeDropdown-theme___dropdown___kI9A9U {
@@ -814,45 +775,6 @@ body {
814
775
  /*!*************************************************************************************************************************************************************************************************************************************************************************************************************!*\
815
776
  !*** css ./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[3].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[3].use[2]!./node_modules/resolve-url-loader/index.js!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[3].use[4]!./src/shared/components/TextArea/style.scss ***!
816
777
  \*************************************************************************************************************************************************************************************************************************************************************************************************************/
817
- /* Collection of standard mixins, being used all around. */
818
- /* Auxiliary mixins for fonts inclusion. */
819
- /**
820
- * Includes a font, provided as a set of alternative files in EOT, WOFF, TTF,
821
- * SVG formats into the app.
822
- * $font-name {String}
823
- * $font-weight {Number}
824
- * $font-style {String}
825
- * $font-url {String} Path to the font file, without the filename itself.
826
- * $font-file {String} Font filename, without extension (should be the same for
827
- * each version of the font in different formats.
828
- */
829
- /**
830
- * Includes a font, provided in the TTF format only.
831
- * $font-name {String}
832
- * $font-weight {Number}
833
- * $font-style {String}
834
- * $font-url {String}
835
- */
836
- /**
837
- * Mixins for different layout sizes: xs, sm, md, lg.
838
- * Breaking points are defined in _variables.scss
839
- * The range mixins A-to-B all means "for the sizes from A to B, both
840
- * inclusive", in particular it means that mixin A-to-lg is equivalent to
841
- * all sizes from A (inclusive) and larger.
842
- *
843
- * NOTE: For convenience, these mixins are sorted not alphabetically, but,
844
- * first, by increase of the first size; second, by increase of the second size.
845
- */
846
- /* Break points. */
847
- /* XS */
848
- /* SM */
849
- /* MM */
850
- /* MD */
851
- /* LG */
852
- /* XL */
853
- /**
854
- * A simple drop-in typography mixin.
855
- */
856
778
  *.-dr-pogodin-react-utils___src-shared-components-TextArea-style___container___dzMVIB,
857
779
  .-dr-pogodin-react-utils___src-shared-components-TextArea-style___context___KVPc7g.-dr-pogodin-react-utils___src-shared-components-TextArea-style___container___dzMVIB,
858
780
  .-dr-pogodin-react-utils___src-shared-components-TextArea-style___ad___z2GQ0Z.-dr-pogodin-react-utils___src-shared-components-TextArea-style___hoc___8R1Qdj.-dr-pogodin-react-utils___src-shared-components-TextArea-style___container___dzMVIB {