@dr.pogodin/react-utils 1.48.9 → 1.48.12

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 (111) hide show
  1. package/build/development/client/index.js +1 -1
  2. package/build/development/client/index.js.map +1 -1
  3. package/build/development/index.js +2 -2
  4. package/build/development/index.js.map +1 -1
  5. package/build/development/server/index.js +1 -1
  6. package/build/development/server/index.js.map +1 -1
  7. package/build/development/server/renderer.js +10 -6
  8. package/build/development/server/renderer.js.map +1 -1
  9. package/build/development/server/server.js +2 -2
  10. package/build/development/server/server.js.map +1 -1
  11. package/build/development/shared/components/Button/index.js.map +1 -1
  12. package/build/development/shared/components/Checkbox/index.js.map +1 -1
  13. package/build/development/shared/components/Link.js.map +1 -1
  14. package/build/development/shared/components/Modal/index.js +1 -1
  15. package/build/development/shared/components/Modal/index.js.map +1 -1
  16. package/build/development/shared/components/NavLink.js.map +1 -1
  17. package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
  18. package/build/development/shared/components/WithTooltip/index.js +2 -2
  19. package/build/development/shared/components/WithTooltip/index.js.map +1 -1
  20. package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
  21. package/build/development/shared/components/index.js +3 -3
  22. package/build/development/shared/components/index.js.map +1 -1
  23. package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  24. package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  25. package/build/development/shared/utils/config.js.map +1 -1
  26. package/build/development/shared/utils/index.js +1 -1
  27. package/build/development/shared/utils/index.js.map +1 -1
  28. package/build/development/shared/utils/time.js +1 -1
  29. package/build/development/shared/utils/time.js.map +1 -1
  30. package/build/development/shared/utils/webpack.js.map +1 -1
  31. package/build/production/client/index.js +1 -1
  32. package/build/production/client/index.js.map +1 -1
  33. package/build/production/index.js +1 -1
  34. package/build/production/index.js.map +1 -1
  35. package/build/production/server/index.js +1 -1
  36. package/build/production/server/index.js.map +1 -1
  37. package/build/production/server/renderer.js +4 -4
  38. package/build/production/server/renderer.js.map +1 -1
  39. package/build/production/server/server.js +1 -1
  40. package/build/production/server/server.js.map +1 -1
  41. package/build/production/shared/components/Button/index.js.map +1 -1
  42. package/build/production/shared/components/Checkbox/index.js.map +1 -1
  43. package/build/production/shared/components/Link.js.map +1 -1
  44. package/build/production/shared/components/Modal/index.js +1 -1
  45. package/build/production/shared/components/Modal/index.js.map +1 -1
  46. package/build/production/shared/components/NavLink.js.map +1 -1
  47. package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
  48. package/build/production/shared/components/WithTooltip/index.js +1 -1
  49. package/build/production/shared/components/WithTooltip/index.js.map +1 -1
  50. package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
  51. package/build/production/shared/components/index.js +1 -1
  52. package/build/production/shared/components/index.js.map +1 -1
  53. package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  54. package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  55. package/build/production/shared/utils/config.js.map +1 -1
  56. package/build/production/shared/utils/index.js +1 -1
  57. package/build/production/shared/utils/index.js.map +1 -1
  58. package/build/production/shared/utils/time.js +1 -1
  59. package/build/production/shared/utils/time.js.map +1 -1
  60. package/build/production/shared/utils/webpack.js.map +1 -1
  61. package/build/types-code/index.d.ts +2 -2
  62. package/build/types-code/server/index.d.ts +1 -1
  63. package/build/types-code/server/renderer.d.ts +1 -1
  64. package/build/types-code/server/server.d.ts +1 -1
  65. package/build/types-code/shared/components/Button/index.d.ts +1 -1
  66. package/build/types-code/shared/components/Checkbox/index.d.ts +1 -1
  67. package/build/types-code/shared/components/Link.d.ts +1 -1
  68. package/build/types-code/shared/components/NavLink.d.ts +1 -1
  69. package/build/types-code/shared/components/WithTooltip/Tooltip.d.ts +1 -1
  70. package/build/types-code/shared/components/WithTooltip/index.d.ts +4 -4
  71. package/build/types-code/shared/components/index.d.ts +3 -3
  72. package/build/types-code/shared/components/selectors/CustomDropdown/Options/index.d.ts +2 -2
  73. package/build/types-code/shared/utils/config.d.ts +1 -1
  74. package/build/types-code/shared/utils/index.d.ts +1 -1
  75. package/build/types-code/shared/utils/webpack.d.ts +1 -1
  76. package/build/web/client/index.js +1 -1
  77. package/build/web/client/index.js.map +1 -1
  78. package/build/web/index.js +2 -2
  79. package/build/web/index.js.map +1 -1
  80. package/build/web/server/index.js +1 -1
  81. package/build/web/server/index.js.map +1 -1
  82. package/build/web/server/renderer.js +10 -6
  83. package/build/web/server/renderer.js.map +1 -1
  84. package/build/web/server/server.js +2 -2
  85. package/build/web/server/server.js.map +1 -1
  86. package/build/web/shared/components/Button/index.js.map +1 -1
  87. package/build/web/shared/components/Checkbox/index.js.map +1 -1
  88. package/build/web/shared/components/Link.js.map +1 -1
  89. package/build/web/shared/components/Modal/index.js +1 -1
  90. package/build/web/shared/components/Modal/index.js.map +1 -1
  91. package/build/web/shared/components/NavLink.js.map +1 -1
  92. package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -1
  93. package/build/web/shared/components/WithTooltip/index.js +2 -2
  94. package/build/web/shared/components/WithTooltip/index.js.map +1 -1
  95. package/build/web/shared/components/YouTubeVideo/index.js.map +1 -1
  96. package/build/web/shared/components/index.js +3 -3
  97. package/build/web/shared/components/index.js.map +1 -1
  98. package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
  99. package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  100. package/build/web/shared/utils/config.js.map +1 -1
  101. package/build/web/shared/utils/index.js +1 -1
  102. package/build/web/shared/utils/index.js.map +1 -1
  103. package/build/web/shared/utils/time.js +1 -1
  104. package/build/web/shared/utils/time.js.map +1 -1
  105. package/build/web/shared/utils/webpack.js.map +1 -1
  106. package/config/babel/webpack.d.ts +1 -1
  107. package/config/babel/webpack.js +1 -1
  108. package/config/webpack/app-base.d.ts +1 -1
  109. package/config/webpack/app-base.js +3 -1
  110. package/config/webpack/app-development.d.ts +1 -1
  111. package/package.json +9 -9
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["http","https","cloneDeep","defaults","serverFactory","getDefaultCspSettings","SCRIPT_LOCATIONS","newDefaultLogger","normalizePort","value","port","parseInt","Number","isFinite","launchServer","webpackConfig","options","ops","process","env","PORT","httpsRedirect","logger","defaultLogLevel","defaultLoggerLogLevel","expressServer","httpServer","createServer","cert","key","on","error","syscall","bind","code","exit","undefined","addr","address","info","NODE_ENV","listen"],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register.js';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport { cloneDeep, defaults } from 'lodash-es';\n\n// Polyfill required by ReactJS.\n// TODO: Double-check, if it is still required by React v19?\n// eslint-disable-next-line import/no-unassigned-import\nimport 'raf/polyfill.js';\n\nimport type { Configuration } from 'webpack';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n type ServerT,\n getDefaultCspSettings,\n} from './server';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nexport * from './utils';\n\nexport type {\n BeforeRenderResT,\n BeforeRenderT,\n ConfigT,\n ServerSsrContext,\n} from './renderer';\n\nexport {\n getDefaultCspSettings,\n SCRIPT_LOCATIONS,\n type ServerT,\n};\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @param value Port name or number.\n * @return Port number (Number), name (String).\n */\nfunction normalizePort(value: number | string) {\n const port = typeof value === 'string' ? parseInt(value) : value;\n if (Number.isFinite(port)) return port; /* port number */\n return value; /* named pipe */\n}\n\ntype OptionsT = ServerOptionsT & {\n https?: {\n cert: string;\n key: string;\n };\n\n // TODO: Should we limit it to number | string, and throw if it is different value?\n port?: false | number | string;\n};\n\n/**\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` &rArr; `object` \\\n * which gets the default settings (also used without the hook),\n * and the incoming request object. The hook response will be passed\n * as options to the helmet `contentSecurityPolicy` middleware.\n *\n * Currently, the default settings is the following object in production\n * environment:\n * ```js\n * {\n * directives: {\n * defaultSrc: [\"'self'\"],\n * baseUri: [\"'self'\"],\n * blockAllMixedContent: [],\n * fontSrc: [\"'self'\", 'https:', 'data:'],\n * frameAncestors: [\"'self'\"],\n * frameSrc: [\"'self'\", 'https://*.youtube.com'],\n * imgSrc: [\"'self'\", 'data:'],\n * objectSrc: [\"'none'\"],\n * scriptSrc: [\"'self'\", \"'unsafe-eval'\", `'nonce-UNIQUE_NONCE_VALUE'`],\n * scriptSrcAttr: [\"'none'\"],\n * styleSrc: [\"'self'\", 'https:', \"'unsafe-inline'\"],\n * upgradeInsecureRequests: [] // Removed in dev mode.\n * }\n * }\n * ```\n * It matches the default value used by Helmet with a few updates:\n * - YouTube host is whitelisted in the `frameSrc` directive to ensure\n * the {@link YouTubeVideo} component works.\n * - An unique per-request nonce is added to `scriptSrc` directive to\n * whitelist auxiliary scripts injected by react-utils. The actual nonce\n * value can be fetched by host code via `.nonce` field of `req` argument\n * of `.beforeRender` hook.\n * - `upgradeInsecureRequests` directive is removed in development mode,\n * to simplify local testing with http requests.\n * @param {string} [options.defaultLoggerLogLevel='info'] Log level for\n * the default logger, which is created if no `logger` option provided.\n * @param {boolean} [options.devMode] Pass in `true` to start the server in\n * development mode.\n * @param {string} [options.favicon] Path to the favicon to use by the server.\n * By default no favicon is used.\n * @param {object} [options.https] If provided, HTTPS server will be started,\n * instead of HTTP otherwise. The object should provide SSL certificate and key\n * via two string fields: `cert`, and `key`.\n * @param {string} [options.https.cert] SSL Certificate.\n * @param {string} [options.https.key] SSL key.\n * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable\n * automatic redirection of all incoming HTTP requests to HTTPS.\n *\n * To smoothly use it at `localhost` you need to run the server in HTTPS mode,\n * and also properly create and install a self-signed SSL sertificate on your\n * system. This article is helpful:\n * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)\n * @param {Logger} [options.logger] The logger to use at server side.\n * By default [`winston`](https://www.npmjs.com/package/winston) logger\n * with console transport is used. The logger you provide, or the default\n * `winston` logger otherwise, will be attached to the created ExpressJS server\n * object.\n * @param {function} [options.onExpressJsSetup] An async callback\n * (`(server) => Promise`) to be triggered when most of the server\n * configuration is completed, just before the server-side renderer,\n * and the default error handler are attached. You can use it to mount\n * custom API routes. The server-side logger can be accessed as `server.logger`.\n * @param {number|string} [options.port=3000] The port to start the server on.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &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 * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @return Resolves to an object with created Express and HTTP servers.\n */\nexport async function launchServer(\n webpackConfig: Configuration,\n options: OptionsT = {},\n): Promise<{\n expressServer: ServerT;\n httpServer: http.Server;\n}> {\n /* Options normalization. */\n const ops = cloneDeep(options);\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n defaults(ops, { httpsRedirect: true });\n\n // TODO: Need a separate type for normalized options, which guarantees\n // the logger is set!\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer: http.Server;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer as unknown as () => void);\n } else httpServer = http.createServer(expressServer as unknown as () => void);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as { syscall?: string }).syscall !== 'listen') throw error;\n const bind = typeof ops.port === 'string' ? `Pipe ${ops.port}` : `Port ${ops.port}`;\n\n /* Human-readable message for some specific listen errors. */\n switch ((error as { code?: string }).code) {\n case 'EACCES':\n ops.logger!.error(`${bind} requires elevated privileges`);\n return process.exit(1);\n case 'EADDRINUSE':\n ops.logger!.error(`${bind} is already in use`);\n return process.exit(1);\n case undefined:\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address()!;\n const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;\n ops.logger!.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n"],"mappings":"AAAA;AACA,OAAO,gCAAgC;AAEvC,OAAOA,IAAI,MAAM,WAAW;AAC5B,OAAOC,KAAK,MAAM,YAAY;AAE9B,SAASC,SAAS,EAAEC,QAAQ,QAAQ,WAAW;;AAE/C;AACA;AACA;AACA,OAAO,iBAAiB;AAIxB,OAAOC,aAAa,IAGlBC,qBAAqB;AAGvB,SAASC,gBAAgB,EAAEC,gBAAgB;AAE3C;AASA,SACEF,qBAAqB,EACrBC,gBAAgB;;AAIlB;AACA;AACA;AACA;AACA;AACA;AACA,SAASE,aAAaA,CAACC,KAAsB,EAAE;EAC7C,MAAMC,IAAI,GAAG,OAAOD,KAAK,KAAK,QAAQ,GAAGE,QAAQ,CAACF,KAAK,CAAC,GAAGA,KAAK;EAChE,IAAIG,MAAM,CAACC,QAAQ,CAACH,IAAI,CAAC,EAAE,OAAOA,IAAI,CAAC,CAAC;EACxC,OAAOD,KAAK,CAAC,CAAC;AAChB;AAYA;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;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;A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AAG,QAAQO,GAAG,CAACP,IAAI,EAAE,GAAG,QAAQO,GAAG,CAACP,IAAI,EAAE;;IAEnF;IACA,QAASqB,KAAK,CAAuBG,IAAI;MACvC,KAAK,QAAQ;QACXjB,GAAG,CAACK,MAAM,CAAES,KAAK,CAAC,GAAGE,IAAI,+BAA+B,CAAC;QACzD,OAAOf,OAAO,CAACiB,IAAI,CAAC,CAAC,CAAC;MACxB,KAAK,YAAY;QACflB,GAAG,CAACK,MAAM,CAAES,KAAK,CAAC,GAAGE,IAAI,oBAAoB,CAAC;QAC9C,OAAOf,OAAO,CAACiB,IAAI,CAAC,CAAC,CAAC;MACxB,KAAKC,SAAS;MACd;QACE,MAAML,KAAK;IACf;EACF,CAAC,CAAC;;EAEF;EACAL,UAAU,CAACI,EAAE,CAAC,WAAW,EAAE,MAAM;IAC/B,MAAMO,IAAI,GAAGX,UAAU,CAACY,OAAO,CAAC,CAAE;IAClC,MAAML,IAAI,GAAG,OAAOI,IAAI,KAAK,QAAQ,GAAG,QAAQA,IAAI,EAAE,GAAG,QAAQA,IAAI,CAAC3B,IAAI,EAAE;IAC5EO,GAAG,CAACK,MAAM,CAAEiB,IAAI,CAAC,uBAAuBN,IAAI,OAC1Cf,OAAO,CAACC,GAAG,CAACqB,QAAQ,OAAO,CAAC;EAChC,CAAC,CAAC;EAEFd,UAAU,CAACe,MAAM,CAACxB,GAAG,CAACP,IAAI,CAAC;EAE3B,OAAO;IACLe,aAAa;IACbC;EACF,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["http","https","cloneDeep","defaults","serverFactory","getDefaultCspSettings","SCRIPT_LOCATIONS","newDefaultLogger","normalizePort","value","port","parseInt","Number","isFinite","launchServer","webpackConfig","options","ops","process","env","PORT","httpsRedirect","logger","defaultLogLevel","defaultLoggerLogLevel","expressServer","httpServer","createServer","cert","key","on","error","syscall","bind","code","exit","undefined","addr","address","info","NODE_ENV","listen"],"sources":["../../../src/server/index.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'source-map-support/register.js';\n\nimport http from 'node:http';\nimport https from 'node:https';\n\nimport { cloneDeep, defaults } from 'lodash-es';\n\n// Polyfill required by ReactJS.\n// TODO: Double-check, if it is still required by React v19?\n// eslint-disable-next-line import/no-unassigned-import\nimport 'raf/polyfill.js';\n\nimport type { Configuration } from 'webpack';\n\nimport serverFactory, {\n type OptionsT as ServerOptionsT,\n type ServerT,\n getDefaultCspSettings,\n} from './server';\n\nimport { SCRIPT_LOCATIONS, newDefaultLogger } from './renderer';\n\nexport * from './utils';\n\nexport type {\n BeforeRenderResT,\n BeforeRenderT,\n ConfigT,\n ServerSsrContext,\n} from './renderer';\n\nexport {\n SCRIPT_LOCATIONS,\n type ServerT,\n getDefaultCspSettings,\n};\n\n/**\n * Normalizes a port into a number, string, or false.\n * TODO: Drop this function?\n * @param value Port name or number.\n * @return Port number (Number), name (String).\n */\nfunction normalizePort(value: number | string) {\n const port = typeof value === 'string' ? parseInt(value) : value;\n if (Number.isFinite(port)) return port; /* port number */\n return value; /* named pipe */\n}\n\ntype OptionsT = ServerOptionsT & {\n https?: {\n cert: string;\n key: string;\n };\n\n // TODO: Should we limit it to number | string, and throw if it is different value?\n port?: false | number | string;\n};\n\n/**\n * Creates and launches web-server for ReactJS application. Allows zero\n * or detailed configuration, supports server-side rendering,\n * and development tools, including Hot Module Reloading (HMR).\n *\n * NOTE: Many of options defined below are passed down to the server and\n * renderer factories, and their declared default values are set in those\n * factories, rather than here.\n *\n * @param {object} webpackConfig Webpack configuration used to build\n * the frontend bundle. In production mode the server will read out of it\n * `context`, `publicPath`, and a few other parameters, necessary to locate\n * and serve the app bundle. In development mode the server will use entire\n * provided config to build the app bundle in memory, and further watch and\n * update it via HMR.\n * @param {object} [options] Additional parameters.\n * @param {Component} [options.Application] The root ReactJS component of\n * the app to use for the server-side rendering. When not provided\n * the server-side rendering is disabled.\n * @param {function} [options.beforeExpressJsError] Asynchronous callback\n * (`(server) => Promise<boolean>`) to be executed just before the default error\n * handler is added to ExpressJS server. If the callback is provided and its\n * result resolves to a truthy value, `react-utils` won't attach the default\n * error handler.\n * @param {function} [options.beforeExpressJsSetup] Asynchronous callback\n * (`(server) => Promise) to be executed right after ExpressJS server creation,\n * before any configuration is performed.\n * @param {BeforeRenderHook} [options.beforeRender] The hook to run just before\n * the server-side rendering. For each incoming request, it will be executed\n * just before the HTML markup is generated at the server. It allows to load\n * and provide the data necessary for server-side rendering, and also to inject\n * additional configuration and scripts into the generated HTML code.\n * @param {boolean} [options.noCsp] Set `true` to disable\n * Content-Security-Policy (CSP) headers altogether.\n * @param {function} [options.cspSettingsHook] A hook allowing\n * to customize [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n * settings for [helmet](https://github.com/helmetjs/helmet)'s\n * `contentSecurityPolicy` middleware on per-request basis.\n *\n * If provided it should be a with signature: \\\n * `(defaultSettings: object, req: object)` &rArr; `object` \\\n * which gets the default settings (also used without the hook),\n * and the incoming request object. The hook response will be passed\n * as options to the helmet `contentSecurityPolicy` middleware.\n *\n * Currently, the default settings is the following object in production\n * environment:\n * ```js\n * {\n * directives: {\n * defaultSrc: [\"'self'\"],\n * baseUri: [\"'self'\"],\n * blockAllMixedContent: [],\n * fontSrc: [\"'self'\", 'https:', 'data:'],\n * frameAncestors: [\"'self'\"],\n * frameSrc: [\"'self'\", 'https://*.youtube.com'],\n * imgSrc: [\"'self'\", 'data:'],\n * objectSrc: [\"'none'\"],\n * scriptSrc: [\"'self'\", \"'unsafe-eval'\", `'nonce-UNIQUE_NONCE_VALUE'`],\n * scriptSrcAttr: [\"'none'\"],\n * styleSrc: [\"'self'\", 'https:', \"'unsafe-inline'\"],\n * upgradeInsecureRequests: [] // Removed in dev mode.\n * }\n * }\n * ```\n * It matches the default value used by Helmet with a few updates:\n * - YouTube host is whitelisted in the `frameSrc` directive to ensure\n * the {@link YouTubeVideo} component works.\n * - An unique per-request nonce is added to `scriptSrc` directive to\n * whitelist auxiliary scripts injected by react-utils. The actual nonce\n * value can be fetched by host code via `.nonce` field of `req` argument\n * of `.beforeRender` hook.\n * - `upgradeInsecureRequests` directive is removed in development mode,\n * to simplify local testing with http requests.\n * @param {string} [options.defaultLoggerLogLevel='info'] Log level for\n * the default logger, which is created if no `logger` option provided.\n * @param {boolean} [options.devMode] Pass in `true` to start the server in\n * development mode.\n * @param {string} [options.favicon] Path to the favicon to use by the server.\n * By default no favicon is used.\n * @param {object} [options.https] If provided, HTTPS server will be started,\n * instead of HTTP otherwise. The object should provide SSL certificate and key\n * via two string fields: `cert`, and `key`.\n * @param {string} [options.https.cert] SSL Certificate.\n * @param {string} [options.https.key] SSL key.\n * @param {boolean} [options.httpsRedirect=true] Pass in `true` to enable\n * automatic redirection of all incoming HTTP requests to HTTPS.\n *\n * To smoothly use it at `localhost` you need to run the server in HTTPS mode,\n * and also properly create and install a self-signed SSL sertificate on your\n * system. This article is helpful:\n * [How to get HTTPS working on your local development environment in 5 minutes](https://medium.freecodecamp.org/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec)\n * @param {Logger} [options.logger] The logger to use at server side.\n * By default [`winston`](https://www.npmjs.com/package/winston) logger\n * with console transport is used. The logger you provide, or the default\n * `winston` logger otherwise, will be attached to the created ExpressJS server\n * object.\n * @param {function} [options.onExpressJsSetup] An async callback\n * (`(server) => Promise`) to be triggered when most of the server\n * configuration is completed, just before the server-side renderer,\n * and the default error handler are attached. You can use it to mount\n * custom API routes. The server-side logger can be accessed as `server.logger`.\n * @param {number|string} [options.port=3000] The port to start the server on.\n * @param {number} [options.staticCacheSize=1.e7] The maximum\n * static cache size in bytes. Defaults to ~10 MB.\n * @param {function} [options.staticCacheController] When given, it activates,\n * and controls the static caching of generated HTML markup. When this function\n * is provided, on each incoming request it is triggered with the request\n * passed in as the argument. To attempt to serve the response from the cache\n * it should return the object with the following fields:\n * - `key: string` &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 * @param {number} [options.maxSsrRounds=10] Maximum number of SSR rounds.\n * @param {number} [options.ssrTimeout=1000] SSR timeout in milliseconds,\n * defaults to 1 second.\n * @return Resolves to an object with created Express and HTTP servers.\n */\nexport async function launchServer(\n webpackConfig: Configuration,\n options: OptionsT = {},\n): Promise<{\n expressServer: ServerT;\n httpServer: http.Server;\n}> {\n /* Options normalization. */\n const ops = cloneDeep(options);\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ops.port = normalizePort(ops.port || process.env.PORT || 3000);\n defaults(ops, { httpsRedirect: true });\n\n // TODO: Need a separate type for normalized options, which guarantees\n // the logger is set!\n ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\n });\n\n /* Creates servers, resolves and sets the port. */\n const expressServer = await serverFactory(webpackConfig, ops);\n\n let httpServer: http.Server;\n if (ops.https) {\n httpServer = https.createServer({\n cert: ops.https.cert,\n key: ops.https.key,\n }, expressServer as unknown as () => void);\n } else httpServer = http.createServer(expressServer as unknown as () => void);\n\n /* Sets error handler for HTTP(S) server. */\n httpServer.on('error', (error: Error) => {\n if ((error as { syscall?: string }).syscall !== 'listen') throw error;\n const bind = typeof ops.port === 'string' ? `Pipe ${ops.port}` : `Port ${ops.port}`;\n\n /* Human-readable message for some specific listen errors. */\n switch ((error as { code?: string }).code) {\n case 'EACCES':\n ops.logger!.error(`${bind} requires elevated privileges`);\n return process.exit(1);\n case 'EADDRINUSE':\n ops.logger!.error(`${bind} is already in use`);\n return process.exit(1);\n case undefined:\n default:\n throw error;\n }\n });\n\n /* Listening event handler for HTTP(S) server. */\n httpServer.on('listening', () => {\n const addr = httpServer.address()!;\n const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;\n ops.logger!.info(`Server listening on ${bind} in ${\n process.env.NODE_ENV} mode`);\n });\n\n httpServer.listen(ops.port);\n\n return {\n expressServer,\n httpServer,\n };\n}\n"],"mappings":"AAAA;AACA,OAAO,gCAAgC;AAEvC,OAAOA,IAAI,MAAM,WAAW;AAC5B,OAAOC,KAAK,MAAM,YAAY;AAE9B,SAASC,SAAS,EAAEC,QAAQ,QAAQ,WAAW;;AAE/C;AACA;AACA;AACA,OAAO,iBAAiB;AAIxB,OAAOC,aAAa,IAGlBC,qBAAqB;AAGvB,SAASC,gBAAgB,EAAEC,gBAAgB;AAE3C;AASA,SACED,gBAAgB,EAEhBD,qBAAqB;;AAGvB;AACA;AACA;AACA;AACA;AACA;AACA,SAASG,aAAaA,CAACC,KAAsB,EAAE;EAC7C,MAAMC,IAAI,GAAG,OAAOD,KAAK,KAAK,QAAQ,GAAGE,QAAQ,CAACF,KAAK,CAAC,GAAGA,KAAK;EAChE,IAAIG,MAAM,CAACC,QAAQ,CAACH,IAAI,CAAC,EAAE,OAAOA,IAAI,CAAC,CAAC;EACxC,OAAOD,KAAK,CAAC,CAAC;AAChB;AAYA;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;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;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,OAAO,eAAeK,YAAYA,CAChCC,aAA4B,EAC5BC,OAAiB,GAAG,CAAC,CAAC,EAIrB;EACD;EACA,MAAMC,GAAG,GAAGf,SA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AAK,CAAC,GAAGE,IAAI,oBAAoB,CAAC;QAC9C,OAAOf,OAAO,CAACiB,IAAI,CAAC,CAAC,CAAC;MACxB,KAAKC,SAAS;MACd;QACE,MAAML,KAAK;IACf;EACF,CAAC,CAAC;;EAEF;EACAL,UAAU,CAACI,EAAE,CAAC,WAAW,EAAE,MAAM;IAC/B,MAAMO,IAAI,GAAGX,UAAU,CAACY,OAAO,CAAC,CAAE;IAClC,MAAML,IAAI,GAAG,OAAOI,IAAI,KAAK,QAAQ,GAAG,QAAQA,IAAI,EAAE,GAAG,QAAQA,IAAI,CAAC3B,IAAI,EAAE;IAC5EO,GAAG,CAACK,MAAM,CAAEiB,IAAI,CAAC,uBAAuBN,IAAI,OAC1Cf,OAAO,CAACC,GAAG,CAACqB,QAAQ,OAAO,CAAC;EAChC,CAAC,CAAC;EAEFd,UAAU,CAACe,MAAM,CAACxB,GAAG,CAACP,IAAI,CAAC;EAE3B,OAAO;IACLe,aAAa;IACbC;EACF,CAAC;AACH","ignoreList":[]}
@@ -19,12 +19,12 @@ import path from 'node:path';
19
19
  import { Writable } from 'node:stream';
20
20
  import { brotliCompress, brotliDecompress } from 'node:zlib';
21
21
  import winston from 'winston';
22
- import { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';
23
22
  import { timer } from '@dr.pogodin/js-utils';
23
+ import { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';
24
24
  import { cloneDeep, defaults, get, mapValues } from 'lodash-es';
25
25
  import config from 'config';
26
- import { prerenderToNodeStream } from 'react-dom/static';
27
26
  import { HelmetProvider } from '@dr.pogodin/react-helmet';
27
+ import { prerenderToNodeStream } from 'react-dom/static';
28
28
  import { StaticRouter } from 'react-router';
29
29
  import serializeJs from 'serialize-javascript';
30
30
  import { setBuildInfo } from "../shared/utils/isomorphy/buildInfo";
@@ -175,8 +175,8 @@ export function newDefaultLogger({
175
175
  format: format.combine(format.splat(), format.timestamp(), format.colorize(), format.printf(({
176
176
  level,
177
177
  message,
178
- timestamp,
179
178
  stack,
179
+ timestamp,
180
180
  ...rest
181
181
  }) => {
182
182
  let res = `${level}\t(at ${timestamp}):\t${message}`;
@@ -242,8 +242,8 @@ export default function factory(webpackConfig, options) {
242
242
 
243
243
  // publicPath from webpack.output has a trailing slash at the end.
244
244
  const {
245
- publicPath,
246
- path: outputPath
245
+ path: outputPath,
246
+ publicPath
247
247
  } = webpackConfig.output;
248
248
  const manifestLink = fs.existsSync(`${outputPath}/manifest.json`) ? `<link rel="manifest" href="${publicPath}manifest.json">` : '';
249
249
 
@@ -438,7 +438,11 @@ export default function factory(webpackConfig, options) {
438
438
  // thus for now this handles the default config.
439
439
  ['main', ...ssrContext.chunks].forEach(chunk => {
440
440
  const assets = chunkGroups[chunk];
441
- if (assets) assets.forEach(asset => chunkSet.add(asset));
441
+ if (assets) {
442
+ assets.forEach(asset => {
443
+ chunkSet.add(asset);
444
+ });
445
+ }
442
446
  });
443
447
  let styleChunkString = '';
444
448
  let scriptChunkString = '';
@@ -1 +1 @@
1
- {"version":3,"file":"renderer.js","names":["Buffer","createCipheriv","randomBytes","fs","path","Writable","brotliCompress","brotliDecompress","winston","GlobalStateProvider","SsrContext","timer","cloneDeep","defaults","get","mapValues","config","prerenderToNodeStream","HelmetProvider","StaticRouter","serializeJs","setBuildInfo","Cache","jsx","_jsx","SECRET","sanitizedConfig","SCRIPT_LOCATIONS","ServerSsrContext","chunks","status","constructor","req","chunkGroups","initialState","getBuildInfo","context","url","resolve","JSON","parse","readFileSync","readChunkGroupsJson","buildDir","res","prepareCipher","key","iv","cipher","from","isBrotliAcceptable","acceptable","ops","split","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","code","location","Error","newDefaultLogger","defaultLogLevel","format","transports","createLogger","combine","splat","timestamp","colorize","printf","level","message","stack","rest","Object","keys","length","stringify","Console","factory","webpackConfig","options","beforeRender","Promise","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","publicPath","outputPath","output","manifestLink","existsSync","cache","staticCacheController","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","error","html","h","toString","regex","RegExp","nonce","replace","brr","configToInject","extraScripts","helmet","webpackStats","locals","toJson","all","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","resolveArg","rejectArg","arg","undefined","reject","helmetContext","state","children","onError","then","result","prelude","catch","ssrRound","bailed","dirty","timeout","race","allSettled","pending","logMsg","log","redirectTo","redirect","ready","pipe","destroy","write","chunk","_","payload","CONFIG","ISTATE","ignoreFunction","unsafe","INJ","concat","update","final","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","link","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { type Cipheriv, createCipheriv, randomBytes } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { Writable } from 'node:stream';\nimport { brotliCompress, brotliDecompress } from 'node:zlib';\n\nimport type { Request, RequestHandler } from 'express';\nimport type { ComponentType } from 'react';\nimport type { Configuration, Stats } from 'webpack';\nimport winston from 'winston';\n\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\nimport { timer } from '@dr.pogodin/js-utils';\n\nimport {\n cloneDeep,\n defaults,\n get,\n mapValues,\n} from 'lodash-es';\n\nimport config from 'config';\n\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { type HelmetDataContext, HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { StaticRouter } from 'react-router';\nimport serializeJs from 'serialize-javascript';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport type { ChunkGroupsT, SsrContextT } from 'utils/globalState';\n\nimport Cache from './Cache';\n\n// @ts-expect-error \"Property 'SECRET' does not exist on type 'IConfig'.\"\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst { SECRET, ...sanitizedConfig } = config;\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.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (level: string, message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LeveledLogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface LoggerI {\n debug: LeveledLogMethodI;\n error: LeveledLogMethodI;\n info: LeveledLogMethodI;\n log: LogMethodI;\n warn: LeveledLogMethodI;\n}\n\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 redirectTo?: 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')) as BuildInfoT;\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')) as Record<string, string[]>;\n } catch {\n // TODO: Should we message the error here somehow?\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, Base64-encoded key is expected).\n * @return Returns a tuple of:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key: string): [cipher: Cipheriv, iv: Buffer] {\n const iv = randomBytes(16);\n const cipher = createCipheriv('AES-256-CBC', Buffer.from(key, 'base64'), iv);\n return [cipher, iv];\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param req\n */\nexport function isBrotliAcceptable(req: Request): boolean {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (const op of ops) {\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 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 (const script of scripts) {\n if (typeof script === 'string') {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (script.location in res) 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} = {}): winston.Logger {\n const { format, transports } = winston;\n return winston.createLogger({\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 as string}):\\t${message as string}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack as string}`;\n return res;\n },\n ),\n ),\n level: defaultLogLevel,\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?: unknown;\n};\n\nexport type BeforeRenderT = (\n req: Request,\n config: ConfigT,\n) => 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({ ...options }, {\n beforeRender: async () => 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 ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\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 as string}manifest.json\">` : '';\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface BufferWithNonce extends ArrayBuffer {\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 // TODO: Look at it later.\n // eslint-disable-next-line complexity\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\n // TODO: It should be implemented more careful.\n h = h.replace(regex, (req as unknown as {\n nonce: string;\n }).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 brr = ops.beforeRender!(req, sanitizedConfig as unknown as ConfigT);\n const { configToInject, extraScripts, initialState } = await brr;\n\n const [cipher, iv] = prepareCipher(buildInfo.key);\n\n let helmet: HelmetDataContext['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') as Stats | undefined;\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 );\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: NodeJS.ReadableStream;\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 () => new Promise<NodeJS.ReadableStream>(\n (resolveArg, rejectArg) => {\n ssrContext.chunks = [];\n\n // NOTE: JS does not have problems if resolve() and reject() methods\n // of a Promise are called multiple times, with different arguments;\n // it only respects the first call, and ignores subsequent ones.\n // We, however, really want to assert that here, to safeguard against\n // any future problems due to unexpected internal changes in React,\n // if any.\n let error: unknown;\n\n const resolve = (arg: NodeJS.ReadableStream) => {\n if (error !== undefined) throw Error('Internal error');\n error = null;\n resolveArg(arg);\n };\n\n const reject = (arg: unknown) => {\n if (error !== undefined && error !== arg) {\n throw Error('Internal error');\n }\n error = arg;\n rejectArg(arg as Error);\n };\n\n // TODO: prerenderToNodeStream has (abort) \"signal\" option,\n // and we should wire it up to the SSR timeout below.\n const helmetContext = {} as HelmetDataContext;\n void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider context={helmetContext}>\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then((result) => {\n ({ helmet } = helmetContext);\n resolve(result.prelude);\n }).catch(reject);\n },\n );\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\n stream = await renderPass();\n\n if (!ssrContext.dirty) break;\n\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 }\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 if (ssrContext.redirectTo) {\n res.redirect(ssrContext.status, ssrContext.redirectTo);\n return;\n }\n\n await new Promise((ready) => {\n stream!.pipe(new Writable({\n destroy: ready,\n write: (chunk: { toString: () => string }, _, done) => {\n appHtmlMarkup += chunk.toString();\n done();\n },\n }));\n });\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\n const INJ = Buffer.concat([\n iv,\n cipher.update(payload, 'utf8'),\n cipher.final(),\n ]).toString('base64');\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 as string}${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 as string}${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?.title.toString() ?? ''}\n ${helmet?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmet?.link.toString() ?? ''}${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 if (error) failed(error);\n else {\n const b = buffer as unknown as BufferWithNonce;\n b.nonce = (req as unknown as {\n nonce: string;\n }).nonce;\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":";;;;;;;;;;AAAA;AACA;AACA;;AAEA,SAASA,MAAM,QAAQ,aAAa;AACpC,SAAwBC,cAAc,EAAEC,WAAW,QAAQ,aAAa;AACxE,OAAOC,EAAE,MAAM,SAAS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;UACF,CAAC,CAAC;QACJ,CAAC,CAAC;MACJ;;MAEA;MACA;MACA;MACAvE,GAAG,CAACsE,IAAI,CAACI,IAAI,CAAC;IAChB,CAAC,CAAC,OAAOD,KAAK,EAAE;MACdX,IAAI,CAACW,KAAK,CAAC;IACb;EACF,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"file":"renderer.js","names":["Buffer","createCipheriv","randomBytes","fs","path","Writable","brotliCompress","brotliDecompress","winston","timer","GlobalStateProvider","SsrContext","cloneDeep","defaults","get","mapValues","config","HelmetProvider","prerenderToNodeStream","StaticRouter","serializeJs","setBuildInfo","Cache","jsx","_jsx","SECRET","sanitizedConfig","SCRIPT_LOCATIONS","ServerSsrContext","chunks","status","constructor","req","chunkGroups","initialState","getBuildInfo","context","url","resolve","JSON","parse","readFileSync","readChunkGroupsJson","buildDir","res","prepareCipher","key","iv","cipher","from","isBrotliAcceptable","acceptable","ops","split","op","type","priority","trim","parseFloat","groupExtraScripts","scripts","BODY_OPEN","DEFAULT","HEAD_OPEN","script","code","location","Error","newDefaultLogger","defaultLogLevel","format","transports","createLogger","combine","splat","timestamp","colorize","printf","level","message","stack","rest","Object","keys","length","stringify","Console","factory","webpackConfig","options","beforeRender","Promise","maxSsrRounds","ssrTimeout","staticCacheSize","logger","defaultLoggerLogLevel","buildInfo","outputPath","publicPath","output","manifestLink","existsSync","cache","staticCacheController","CHUNK_GROUPS","next","set","cookie","csrfToken","cacheRef","data","buffer","noCsp","send","done","failed","error","html","h","toString","regex","RegExp","nonce","replace","brr","configToInject","extraScripts","helmet","webpackStats","locals","toJson","all","namedChunkGroups","item","assets","map","name","App","Application","appHtmlMarkup","ssrContext","stream","ssrStart","Date","now","App2","renderPass","resolveArg","rejectArg","arg","undefined","reject","helmetContext","state","children","onError","then","result","prelude","catch","ssrRound","bailed","dirty","timeout","race","allSettled","pending","logMsg","log","redirectTo","redirect","ready","pipe","destroy","write","chunk","_","payload","CONFIG","ISTATE","ignoreFunction","unsafe","INJ","concat","update","final","chunkSet","Set","forEach","asset","add","styleChunkString","scriptChunkString","endsWith","grouppedExtraScripts","faviconLink","favicon","title","meta","link","b"],"sources":["../../../src/server/renderer.tsx"],"sourcesContent":["/**\n * ExpressJS middleware for server-side rendering of a ReactJS app.\n */\n\nimport { Buffer } from 'node:buffer';\nimport { type Cipheriv, createCipheriv, randomBytes } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { Writable } from 'node:stream';\nimport { brotliCompress, brotliDecompress } from 'node:zlib';\n\nimport type { Request, RequestHandler } from 'express';\nimport type { ComponentType } from 'react';\nimport type { Configuration, Stats } from 'webpack';\nimport winston from 'winston';\n\nimport { timer } from '@dr.pogodin/js-utils';\nimport { GlobalStateProvider, SsrContext } from '@dr.pogodin/react-global-state';\n\nimport {\n cloneDeep,\n defaults,\n get,\n mapValues,\n} from 'lodash-es';\n\nimport config from 'config';\n\nimport { type HelmetDataContext, HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { prerenderToNodeStream } from 'react-dom/static';\nimport { StaticRouter } from 'react-router';\nimport serializeJs from 'serialize-javascript';\nimport { type BuildInfoT, setBuildInfo } from 'utils/isomorphy/buildInfo';\n\nimport type { ChunkGroupsT, SsrContextT } from 'utils/globalState';\n\nimport Cache from './Cache';\n\n// @ts-expect-error \"Property 'SECRET' does not exist on type 'IConfig'.\"\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst { SECRET, ...sanitizedConfig } = config;\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.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (level: string, message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface LeveledLogMethodI {\n // eslint-disable-next-line @typescript-eslint/prefer-function-type\n (message: string, ...meta: unknown[]): void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface LoggerI {\n debug: LeveledLogMethodI;\n error: LeveledLogMethodI;\n info: LeveledLogMethodI;\n log: LogMethodI;\n warn: LeveledLogMethodI;\n}\n\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 redirectTo?: 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')) as BuildInfoT;\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')) as Record<string, string[]>;\n } catch {\n // TODO: Should we message the error here somehow?\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, Base64-encoded key is expected).\n * @return Returns a tuple of:\n * 1. cipher - a new Cipher, ready for encryption;\n * 2. iv - initial vector used by the cipher.\n */\nfunction prepareCipher(key: string): [cipher: Cipheriv, iv: Buffer] {\n const iv = randomBytes(16);\n const cipher = createCipheriv('AES-256-CBC', Buffer.from(key, 'base64'), iv);\n return [cipher, iv];\n}\n\n/**\n * Given an incoming HTTP requests, it deduces whether Brotli-encoded responses\n * are acceptable to the caller.\n * @param req\n */\nexport function isBrotliAcceptable(req: Request): boolean {\n const acceptable = req.get('accept-encoding');\n if (acceptable) {\n const ops = acceptable.split(',');\n for (const op of ops) {\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 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<ScriptT | string> = []) {\n const res = {\n [SCRIPT_LOCATIONS.BODY_OPEN]: '',\n [SCRIPT_LOCATIONS.DEFAULT]: '',\n [SCRIPT_LOCATIONS.HEAD_OPEN]: '',\n };\n for (const script of scripts) {\n if (typeof script === 'string') {\n if (script) res[SCRIPT_LOCATIONS.DEFAULT] += script;\n } else if (script.code) {\n if (script.location in res) 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} = {}): winston.Logger {\n const { format, transports } = winston;\n return winston.createLogger({\n format: format.combine(\n format.splat(),\n format.timestamp(),\n format.colorize(),\n format.printf(\n ({\n level,\n message,\n stack,\n timestamp,\n ...rest\n }) => {\n let res = `${level}\\t(at ${timestamp as string}):\\t${message as string}`;\n if (Object.keys(rest).length) {\n res += `\\n${JSON.stringify(rest, null, 2)}`;\n }\n if (stack) res += `\\n${stack as string}`;\n return res;\n },\n ),\n ),\n level: defaultLogLevel,\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?: unknown;\n};\n\nexport type BeforeRenderT = (\n req: Request,\n config: ConfigT,\n) => 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 ssrTimeout?: number;\n staticCacheController?: (req: Request) => CacheRefT | null | undefined;\n staticCacheSize?: number;\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({ ...options }, {\n beforeRender: async () => 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 ops.logger ??= newDefaultLogger({\n defaultLogLevel: ops.defaultLoggerLogLevel,\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 { path: outputPath, publicPath } = webpackConfig.output!;\n\n const manifestLink = fs.existsSync(`${outputPath}/manifest.json`)\n ? `<link rel=\"manifest\" href=\"${publicPath as string}manifest.json\">` : '';\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface BufferWithNonce extends ArrayBuffer {\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 // TODO: Look at it later.\n // eslint-disable-next-line complexity\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\n // TODO: It should be implemented more careful.\n h = h.replace(regex, (req as unknown as {\n nonce: string;\n }).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 brr = ops.beforeRender!(req, sanitizedConfig as unknown as ConfigT);\n const { configToInject, extraScripts, initialState } = await brr;\n\n const [cipher, iv] = prepareCipher(buildInfo.key);\n\n let helmet: HelmetDataContext['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') as Stats | undefined;\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 );\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: NodeJS.ReadableStream;\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 () => new Promise<NodeJS.ReadableStream>(\n (resolveArg, rejectArg) => {\n ssrContext.chunks = [];\n\n // NOTE: JS does not have problems if resolve() and reject() methods\n // of a Promise are called multiple times, with different arguments;\n // it only respects the first call, and ignores subsequent ones.\n // We, however, really want to assert that here, to safeguard against\n // any future problems due to unexpected internal changes in React,\n // if any.\n let error: unknown;\n\n const resolve = (arg: NodeJS.ReadableStream) => {\n if (error !== undefined) throw Error('Internal error');\n error = null;\n resolveArg(arg);\n };\n\n const reject = (arg: unknown) => {\n if (error !== undefined && error !== arg) {\n throw Error('Internal error');\n }\n error = arg;\n rejectArg(arg as Error);\n };\n\n // TODO: prerenderToNodeStream has (abort) \"signal\" option,\n // and we should wire it up to the SSR timeout below.\n const helmetContext = {} as HelmetDataContext;\n void prerenderToNodeStream(\n <GlobalStateProvider\n initialState={ssrContext.state}\n ssrContext={ssrContext}\n >\n <StaticRouter location={req.url}>\n <HelmetProvider context={helmetContext}>\n <App2 />\n </HelmetProvider>\n </StaticRouter>\n </GlobalStateProvider>,\n { onError: reject },\n ).then((result) => {\n ({ helmet } = helmetContext);\n resolve(result.prelude);\n }).catch(reject);\n },\n );\n\n let ssrRound = 0;\n let bailed = false;\n for (; ssrRound < ops.maxSsrRounds!; ++ssrRound) {\n stream = await renderPass();\n\n if (!ssrContext.dirty) break;\n\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 }\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 if (ssrContext.redirectTo) {\n res.redirect(ssrContext.status, ssrContext.redirectTo);\n return;\n }\n\n await new Promise((ready) => {\n stream!.pipe(new Writable({\n destroy: ready,\n write: (chunk: { toString: () => string }, _, done) => {\n appHtmlMarkup += chunk.toString();\n done();\n },\n }));\n });\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\n const INJ = Buffer.concat([\n iv,\n cipher.update(payload, 'utf8'),\n cipher.final(),\n ]).toString('base64');\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) {\n assets.forEach((asset) => {\n chunkSet.add(asset);\n });\n }\n });\n\n let styleChunkString = '';\n let scriptChunkString = '';\n chunkSet.forEach((chunk) => {\n if (chunk.endsWith('.css')) {\n styleChunkString += `<link href=\"${publicPath as string}${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 as string}${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?.title.toString() ?? ''}\n ${helmet?.meta.toString() ?? ''}\n <meta name=\"theme-color\" content=\"#FFFFFF\">\n ${manifestLink}\n ${helmet?.link.toString() ?? ''}${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 if (error) failed(error);\n else {\n const b = buffer as unknown as BufferWithNonce;\n b.nonce = (req as unknown as {\n nonce: string;\n }).nonce;\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":";;;;;;;;;;AAAA;AACA;AACA;;AAEA,SAASA,MAAM,QAAQ,aAAa;AACpC,SAAwBC,cAAc,EAAEC,WAAW,QAAQ,aAAa;AACxE,OAAOC,EAAE,MAAM,SAAS;AACxB,OAAOC,IAAI,MAAM,WAAW;AAC5B,SAASC,QAAQ,QAAQ,aAAa;AACtC,SAASC,cAAc,EAAEC,gBAAgB,QAAQ,WAAW;AAK5D,OAAOC,OAAO,MAAM,SAAS;AAE7B,SAASC,KAAK,QAAQ,sBAAsB;AAC5C,SAASC,mBAAmB,EAAEC,UAAU,QAAQ,gCAAgC;AAEhF,SACEC,SAAS,EACTC,QAAQ,EACRC,GAAG,EACHC,SAAS,QACJ,WAAW;AAElB,OAAOC,MAAM,MAAM,QAAQ;AAE3B,SAAiCC,cAAc,QAAQ,0BAA0B;AACjF,SAASC,qBAAqB,QAAQ,kBAAkB;AACxD,SA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ACA,cAAcY,oBAAoB,CAACxK,gBAAgB,CAACkC,SAAS,CAAC;AAC9D,mCAAmC+E,aAAa;AAChD,cAAcqD,iBAAiB;AAC/B,cAAcE,oBAAoB,CAACxK,gBAAgB,CAACmC,OAAO,CAAC;AAC5D;AACA,gBAAgB;MAEV,MAAMhC,MAAM,GAAG+G,UAAU,CAAC/G,MAAM,IAAI,GAAG;MACvC,IAAIA,MAAM,KAAK,GAAG,EAAEc,GAAG,CAACd,MAAM,CAACA,MAAM,CAAC;MAEtC,IAAIgF,QAAQ,IAAIhF,MAAM,GAAG,GAAG,EAAE;QAC5B;QACA;QACA,MAAM,IAAI6D,OAAO,CAAO,CAACwB,IAAI,EAAEC,MAAM,KAAK;UACxC9G,cAAc,CAACgH,IAAI,EAAE,CAACD,KAAK,EAAEL,MAAM,KAAK;YACtC,IAAIK,KAAK,EAAED,MAAM,CAACC,KAAK,CAAC,CAAC,KACpB;cACH,MAAMoF,CAAC,GAAGzF,MAAoC;cAC9CyF,CAAC,CAAC9E,KAAK,GAAI3F,GAAG,CAEX2F,KAAK;cACRpB,KAAK,CAAEwF,GAAG,CAAC;gBAAE/E,MAAM,EAAEyF,CAAC;gBAAE3K;cAAO,CAAC,EAAEgF,QAAQ,CAAChE,GAAG,EAAEkE,MAAM,CAAC5B,MAAM,CAAC;cAC9D+B,IAAI,CAAC,CAAC;YACR;UACF,CAAC,CAAC;QACJ,CAAC,CAAC;MACJ;;MAEA;MACA;MACA;MACAvE,GAAG,CAACsE,IAAI,CAACI,IAAI,CAAC;IAChB,CAAC,CAAC,OAAOD,KAAK,EAAE;MACdX,IAAI,CAACW,KAAK,CAAC;IACb;EACF,CAAC;AACH","ignoreList":[]}
@@ -10,13 +10,13 @@ import { pathToFileURL } from 'node:url';
10
10
  import { cloneDeep, mapValues, pick } from 'lodash-es';
11
11
  import compression from 'compression';
12
12
  import cookieParser from 'cookie-parser';
13
- import csrf from '@dr.pogodin/csurf';
14
13
  import express from 'express';
15
- import favicon from 'serve-favicon';
16
14
  import helmet from 'helmet';
17
15
  import loggerMiddleware from 'morgan';
18
16
  import requestIp from 'request-ip';
17
+ import favicon from 'serve-favicon';
19
18
  import { v4 as uuid } from 'uuid';
19
+ import csrf from '@dr.pogodin/csurf';
20
20
  import rendererFactory from "./renderer";
21
21
  import { CODES, ERRORS, getErrorForCode, newError } from "./utils/errors";
22
22
 
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":["sep","pathToFileURL","cloneDeep","mapValues","pick","compression","cookieParser","csrf","express","favicon","helmet","loggerMiddleware","requestIp","v4","uuid","rendererFactory","CODES","ERRORS","getErrorForCode","newError","defaultCspSettings","directives","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","factory","webpackConfig","options","rendererOps","renderer","publicPath","output","server","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","cspNonce","cspSettings","cspSettingsHook","send","json","limit","urlencoded","extended","cookieSignatureSecret","mw","cookie","ignoreRequest","csrfIgnoreRequest","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","process","cwd","default","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","NOT_FOUND","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport { cloneDeep, mapValues, pick } from 'lodash-es';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\n\nimport express, {\n type Express,\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\n\nimport favicon from 'serve-favicon';\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport type { Configuration } from 'webpack';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT = Exclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => boolean | Promise<boolean>;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cookieSignatureSecret?: string;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n csrfIgnoreRequest?: (req: Request) => boolean;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser(options.cookieSignatureSecret));\n server.use(requestIp.mw());\n\n server.use(csrf({\n cookie: true,\n ignoreRequest: options.csrfIgnoreRequest,\n }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n const { default: webpack } = await import(/* webpackChunkName: \"server-side-code\" */ 'webpack');\n\n const { default: webpackDevMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-dev-middleware'\n );\n\n const { default: webpackHotMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-hot-middleware'\n );\n\n const compiler = webpack(webpackConfig);\n\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":";;;AAAA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AACI,GAAG,CAAC,CACTyD,KAEC,EACDxD,GAAY,EACZC,GAAa,EACbC,IAAkB,KACf;MACH;MACA;MACA,IAAID,GAAG,CAACwD,WAAW,EAAE;QACnBvD,IAAI,CAACsD,KAAK,CAAC;QACX;MACF;MAEA,MAAME,MAAM,GAAGF,KAAK,CAACE,MAAM,IAAInF,KAAK,CAACoF,qBAAqB;MAC1D,MAAMC,UAAU,GAAGF,MAAM,IAAKnF,KAAK,CAACoF,qBAAgC;;MAEpE;MACArE,OAAO,CAACO,MAAM,CAAEgE,GAAG,CAACD,UAAU,GAAG,OAAO,GAAG,OAAO,EAAEJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC;MAErE,IAAIC,OAAO,GAAGP,KAAK,CAACO,OAAO,IAAItF,eAAe,CAACiF,MAAM,CAAC;MACtD,IAAIE,UAAU,IAAIhB,OAAO,CAACoB,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;QACvDF,OAAO,GAAGvF,MAAM,CAACmF,qBAAqB;MACxC;MAEA1D,GAAG,CAACyD,MAAM,CAACA,MAAM,CAAC,CAACxC,IAAI,CAAC6C,OAAO,CAAC;IAClC,CAAC,CAAC;EACJ;EAEA,OAAOpE,MAAM;AACf","ignoreList":[]}
1
+ {"version":3,"file":"server.js","names":["sep","pathToFileURL","cloneDeep","mapValues","pick","compression","cookieParser","express","helmet","loggerMiddleware","requestIp","favicon","v4","uuid","csrf","rendererFactory","CODES","ERRORS","getErrorForCode","newError","defaultCspSettings","directives","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","factory","webpackConfig","options","rendererOps","renderer","publicPath","output","server","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","cspNonce","cspSettings","cspSettingsHook","send","json","limit","urlencoded","extended","cookieSignatureSecret","mw","cookie","ignoreRequest","csrfIgnoreRequest","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","process","cwd","default","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","NOT_FOUND","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport { cloneDeep, mapValues, pick } from 'lodash-es';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\n\nimport express, {\n type Express,\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\n\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport favicon from 'serve-favicon';\nimport { v4 as uuid } from 'uuid';\n\nimport type { Configuration } from 'webpack';\n\nimport csrf from '@dr.pogodin/csurf';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT = Exclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => Promise<boolean> | boolean;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cookieSignatureSecret?: string;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n csrfIgnoreRequest?: (req: Request) => boolean;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser(options.cookieSignatureSecret));\n server.use(requestIp.mw());\n\n server.use(csrf({\n cookie: true,\n ignoreRequest: options.csrfIgnoreRequest,\n }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n const { default: webpack } = await import(/* webpackChunkName: \"server-side-code\" */ 'webpack');\n\n const { default: webpackDevMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-dev-middleware'\n );\n\n const { default: webpackHotMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-hot-middleware'\n );\n\n const compiler = webpack(webpackConfig);\n\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":";;;AAAA;AACA;AACA;;AAEA,SAASA,GAAG,QAAQ,WAAW;AAC/B,SAASC,aAAa,QAAQ,UAAU;AAExC,SAASC,SAAS,EAAEC,SAAS,EAAEC,IAAI,QAAQ,WAAW;AAEtD,OAAOC,WAAW,MAAM,aAAa;AACrC,OAAOC,YAAY,MAAM,eAAe;AAExC,OAAOC,OAAO,MAKP,SAAS;AAEhB,OAAOC,MAAM,MAA8B,QAAQ;AACnD,OAAOC,gBAAgB,MAAM,QAAQ;AACrC,OAAOC,SAAS,MAAM,YAAY;AAClC,OAAOC,OAAO,MAAM,eAAe;AACnC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAIjC,OAAOC,IAAI,MAAM,mBAAmB;AAEpC,OAAOC,eAAe;AAKtB,SACEC,KAAK,EACLC,MAAM,EACNC,eAAe,EACfC,QAAQ;;AAKV;;AAMA;AACA;AACA;AACA;AACA,MAAMC,kBAAkB,GAAG;EACzBC,UAAU,EAAElB,SAAS,CACnBK,MAAM,CAACc,qBAAqB,CAACC,oBAAoB,CAAC,CAAC;EAEnD;EACA;EACA;EACA;EACCC,KAAK,IAAMA,KAAK,CAA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CAAC;IAClC,CAAC,CAAC;EACJ;EAEA,OAAOpE,MAAM;AACf","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["useTheme","Link","defaultTheme","jsx","_jsx","BaseButton","active","children","disabled","enforceA","keepScrollPosition","onClick","onKeyDown","onKeyDownProp","onKeyUp","onMouseDown","onMouseUp","onPointerDown","onPointerUp","openNewTab","replace","testId","theme","to","className","button","process","env","NODE_ENV","undefined","e","key","role","tabIndex","Button","rest","composed"],"sources":["../../../../../src/shared/components/Button/index.tsx"],"sourcesContent":["// The <Button> component implements a standard button / button-like link.\n\nimport type {\n FunctionComponent,\n KeyboardEventHandler,\n MouseEventHandler,\n PointerEventHandler,\n ReactNode,\n} from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport Link from 'components/Link';\n\nimport defaultTheme from './style.scss';\n\ntype ThemeT = Theme<'active' | 'button' | 'disabled'>;\n\ntype PropsT = {\n active?: boolean;\n children?: ReactNode;\n disabled?: boolean;\n enforceA?: boolean;\n keepScrollPosition?: boolean;\n onClick?: MouseEventHandler & KeyboardEventHandler;\n onKeyDown?: KeyboardEventHandler;\n onKeyUp?: KeyboardEventHandler;\n onMouseDown?: MouseEventHandler;\n onMouseUp?: MouseEventHandler;\n onPointerDown?: PointerEventHandler;\n onPointerUp?: PointerEventHandler;\n openNewTab?: boolean;\n replace?: boolean;\n testId?: string;\n theme: ThemeT;\n\n // TODO: It needs a more precise typing of the object option.\n to?: object | string;\n};\n\nexport const BaseButton: FunctionComponent<PropsT> = ({\n active,\n children,\n disabled,\n enforceA,\n keepScrollPosition,\n onClick,\n onKeyDown: onKeyDownProp,\n onKeyUp,\n onMouseDown,\n onMouseUp,\n onPointerDown,\n onPointerUp,\n openNewTab,\n replace,\n testId,\n theme,\n to,\n}) => {\n let className = theme.button;\n if (active && theme.active) className += ` ${theme.active}`;\n if (disabled) {\n if (theme.disabled) className += ` ${theme.disabled}`;\n return (\n <div\n className={className}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n >\n {children}\n </div>\n );\n }\n\n let onKeyDown = onKeyDownProp;\n if (!onKeyDown && onClick) {\n onKeyDown = (e) => {\n if (e.key === 'Enter') onClick(e);\n };\n }\n\n if (to) {\n return (\n <Link\n className={className}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n enforceA={enforceA}\n\n // TODO: This was exposed as a hotifx... however, I guess we better want\n // to check if the `to` URL contains an anchor (#), and if it does we should\n // automatically opt to keep the position here; and enforce <a> (as\n // react-router link does not seem to respect the hash tag either,\n // at least not without some additional settings).\n keepScrollPosition={keepScrollPosition}\n\n onClick={onClick}\n\n // TODO: For now, the `onKeyDown` handler is not passed to the <Link>,\n // as <Link> component does not call it anyway, presumably due to\n // the inner implementation details. We should look into supporting it:\n // https://github.com/birdofpreyru/react-utils/issues/444\n // onKeyDown={onKeyDown}\n\n onKeyUp={onKeyUp}\n onMouseDown={onMouseDown}\n onMouseUp={onMouseUp}\n onPointerDown={onPointerDown}\n onPointerUp={onPointerUp}\n openNewTab={openNewTab}\n replace={replace}\n to={to}\n >\n {children}\n </Link>\n );\n }\n\n return (\n <div\n className={className}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onClick={onClick}\n onKeyDown={onKeyDown}\n onKeyUp={onKeyUp}\n onMouseDown={onMouseDown}\n onMouseUp={onMouseUp}\n onPointerDown={onPointerDown}\n onPointerUp={onPointerUp}\n role=\"button\"\n tabIndex={0}\n >\n {children}\n </div>\n );\n};\n\nconst Button: FunctionComponent<\n Omit<PropsT, 'theme'> & { theme?: ThemeT }\n> = ({ theme, ...rest }) => {\n const composed = useTheme('Button', defaultTheme, theme);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return <BaseButton {...rest} theme={composed} />;\n};\n\nexport default Button;\n"],"mappings":"AAAA;;AAUA,SAAqBA,QAAQ,QAAQ,0BAA0B;AAE/D,OAAOC,IAAI;AAEX,OAAOC,YAAY;AAAqB,SAAAC,GAA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MAAA;;MAEAG,OAAO,EAAEA,OAAQ;MACjBC,WAAW,EAAEA,WAAY;MACzBC,SAAS,EAAEA,SAAU;MACrBC,aAAa,EAAEA,aAAc;MAC7BC,WAAW,EAAEA,WAAY;MACzBC,UAAU,EAAEA,UAAW;MACvBC,OAAO,EAAEA,OAAQ;MACjBG,EAAE,EAAEA,EAAG;MAAAhB,QAAA,EAENA;IAAQ,CACL,CAAC;EAEX;EAEA,oBACEH,IAAA;IACEoB,SAAS,EAAEA,SAAU;IACrB,eAAaE,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,GAAGC,SAAS,GAAGR,MAAO;IACxEV,OAAO,EAAEA,OAAQ;IACjBC,SAAS,EAAEA,SAAU;IACrBE,OAAO,EAAEA,OAAQ;IACjBC,WAAW,EAAEA,WAAY;IACzBC,SAAS,EAAEA,SAAU;IACrBC,aAAa,EAAEA,aAAc;IAC7BC,WAAW,EAAEA,WAAY;IACzBc,IAAI,EAAC,QAAQ;IACbC,QAAQ,EAAE,CAAE;IAAA1B,QAAA,EAEXA;EAAQ,CACN,CAAC;AAEV,CAAC;AAED,MAAM2B,MAEL,GAAGA,CAAC;EAAEZ,KAAK;EAAE,GAAGa;AAAK,CAAC,KAAK;EAC1B,MAAMC,QAAQ,GAAGpC,QAAQ,CAAC,QAAQ,EAAEE,YAAY,EAAEoB,KAAK,CAAC;;EAExD;EACA,oBAAOlB,IAAA,CAACC,UAAU;IAAA,GAAK8B,IAAI;IAAEb,KAAK,EAAEc;EAAS,CAAE,CAAC;AAClD,CAAC;AAED,eAAeF,MAAM","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["useTheme","Link","defaultTheme","jsx","_jsx","BaseButton","active","children","disabled","enforceA","keepScrollPosition","onClick","onKeyDown","onKeyDownProp","onKeyUp","onMouseDown","onMouseUp","onPointerDown","onPointerUp","openNewTab","replace","testId","theme","to","className","button","process","env","NODE_ENV","undefined","e","key","role","tabIndex","Button","rest","composed"],"sources":["../../../../../src/shared/components/Button/index.tsx"],"sourcesContent":["// The <Button> component implements a standard button / button-like link.\n\nimport type {\n FunctionComponent,\n KeyboardEventHandler,\n MouseEventHandler,\n PointerEventHandler,\n ReactNode,\n} from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport Link from 'components/Link';\n\nimport defaultTheme from './style.scss';\n\ntype ThemeT = Theme<'active' | 'button' | 'disabled'>;\n\ntype PropsT = {\n active?: boolean;\n children?: ReactNode;\n disabled?: boolean;\n enforceA?: boolean;\n keepScrollPosition?: boolean;\n onClick?: KeyboardEventHandler & MouseEventHandler;\n onKeyDown?: KeyboardEventHandler;\n onKeyUp?: KeyboardEventHandler;\n onMouseDown?: MouseEventHandler;\n onMouseUp?: MouseEventHandler;\n onPointerDown?: PointerEventHandler;\n onPointerUp?: PointerEventHandler;\n openNewTab?: boolean;\n replace?: boolean;\n testId?: string;\n theme: ThemeT;\n\n // TODO: It needs a more precise typing of the object option.\n to?: object | string;\n};\n\nexport const BaseButton: FunctionComponent<PropsT> = ({\n active,\n children,\n disabled,\n enforceA,\n keepScrollPosition,\n onClick,\n onKeyDown: onKeyDownProp,\n onKeyUp,\n onMouseDown,\n onMouseUp,\n onPointerDown,\n onPointerUp,\n openNewTab,\n replace,\n testId,\n theme,\n to,\n}) => {\n let className = theme.button;\n if (active && theme.active) className += ` ${theme.active}`;\n if (disabled) {\n if (theme.disabled) className += ` ${theme.disabled}`;\n return (\n <div\n className={className}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n >\n {children}\n </div>\n );\n }\n\n let onKeyDown = onKeyDownProp;\n if (!onKeyDown && onClick) {\n onKeyDown = (e) => {\n if (e.key === 'Enter') onClick(e);\n };\n }\n\n if (to) {\n return (\n <Link\n className={className}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n enforceA={enforceA}\n\n // TODO: This was exposed as a hotifx... however, I guess we better want\n // to check if the `to` URL contains an anchor (#), and if it does we should\n // automatically opt to keep the position here; and enforce <a> (as\n // react-router link does not seem to respect the hash tag either,\n // at least not without some additional settings).\n keepScrollPosition={keepScrollPosition}\n\n onClick={onClick}\n\n // TODO: For now, the `onKeyDown` handler is not passed to the <Link>,\n // as <Link> component does not call it anyway, presumably due to\n // the inner implementation details. We should look into supporting it:\n // https://github.com/birdofpreyru/react-utils/issues/444\n // onKeyDown={onKeyDown}\n\n onKeyUp={onKeyUp}\n onMouseDown={onMouseDown}\n onMouseUp={onMouseUp}\n onPointerDown={onPointerDown}\n onPointerUp={onPointerUp}\n openNewTab={openNewTab}\n replace={replace}\n to={to}\n >\n {children}\n </Link>\n );\n }\n\n return (\n <div\n className={className}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onClick={onClick}\n onKeyDown={onKeyDown}\n onKeyUp={onKeyUp}\n onMouseDown={onMouseDown}\n onMouseUp={onMouseUp}\n onPointerDown={onPointerDown}\n onPointerUp={onPointerUp}\n role=\"button\"\n tabIndex={0}\n >\n {children}\n </div>\n );\n};\n\nconst Button: FunctionComponent<\n Omit<PropsT, 'theme'> & { theme?: ThemeT }\n> = ({ theme, ...rest }) => {\n const composed = useTheme('Button', defaultTheme, theme);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return <BaseButton {...rest} theme={composed} />;\n};\n\nexport default Button;\n"],"mappings":"AAAA;;AAUA,SAAqBA,QAAQ,QAAQ,0BAA0B;AAE/D,OAAOC,IAAI;AAEX,OAAOC,YAAY;AAAqB,SAAAC,GAAA,IAAAC,IAAA;AA0BxC,OAAO,MAAMC,UAAqC,GAAGA,CAAC;EACpDC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,QAAQ;EACRC,kBAAkB;EAClBC,OAAO;EACPC,SAAS,EAAEC,aAAa;EACxBC,OAAO;EACPC,WAAW;EACXC,SAAS;EACTC,aAAa;EACbC,WAAW;EACXC,UAAU;EACVC,OAAO;EACPC,MAAM;EACNC,KAAK;EACLC;AACF,CAAC,KAAK;EACJ,IAAIC,SAAS,GAAGF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AaE,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,GAAGC,SAAS,GAAGR,MAAO;IACxEV,OAAO,EAAEA,OAAQ;IACjBC,SAAS,EAAEA,SAAU;IACrBE,OAAO,EAAEA,OAAQ;IACjBC,WAAW,EAAEA,WAAY;IACzBC,SAAS,EAAEA,SAAU;IACrBC,aAAa,EAAEA,aAAc;IAC7BC,WAAW,EAAEA,WAAY;IACzBc,IAAI,EAAC,QAAQ;IACbC,QAAQ,EAAE,CAAE;IAAA1B,QAAA,EAEXA;EAAQ,CACN,CAAC;AAEV,CAAC;AAED,MAAM2B,MAEL,GAAGA,CAAC;EAAEZ,KAAK;EAAE,GAAGa;AAAK,CAAC,KAAK;EAC1B,MAAMC,QAAQ,GAAGpC,QAAQ,CAAC,QAAQ,EAAEE,YAAY,EAAEoB,KAAK,CAAC;;EAExD;EACA,oBAAOlB,IAAA,CAACC,UAAU;IAAA,GAAK8B,IAAI;IAAEb,KAAK,EAAEc;EAAS,CAAE,CAAC;AAClD,CAAC;AAED,eAAeF,MAAM","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["useTheme","defaultTheme","jsx","_jsx","jsxs","_jsxs","Checkbox","checked","disabled","label","onChange","testId","theme","composed","containerClassName","container","checkboxClassName","checkbox","indeterminate","className","children","undefined","process","env","NODE_ENV","onClick","e","stopPropagation","type"],"sources":["../../../../../src/shared/components/Checkbox/index.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './theme.scss';\n\ntype PropT<ValueT> = {\n checked?: ValueT;\n disabled?: boolean;\n label?: React.ReactNode;\n onChange?: React.ChangeEventHandler<HTMLInputElement>;\n testId?: string;\n theme?: Theme<\n | 'checkbox'\n | 'container'\n | 'disabled'\n | 'indeterminate'\n | 'label'\n >;\n};\n\nconst Checkbox = <ValueT extends boolean | 'indeterminate' = boolean>({\n checked,\n disabled,\n label,\n onChange,\n testId,\n theme,\n}: PropT<ValueT>): ReactNode => {\n const composed = useTheme('Checkbox', defaultTheme, theme);\n\n let containerClassName = composed.container;\n if (disabled) containerClassName += ` ${composed.disabled}`;\n\n let checkboxClassName = composed.checkbox;\n if (checked === 'indeterminate') checkboxClassName += ` ${composed.indeterminate}`;\n\n return (\n <div className={containerClassName}>\n { label === undefined\n ? null : <div className={composed.label}>{label}</div> }\n <input\n checked={checked === undefined ? undefined : checked === true}\n className={checkboxClassName}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n disabled={disabled}\n onChange={onChange}\n onClick={(e) => {\n e.stopPropagation();\n }}\n type=\"checkbox\"\n />\n </div>\n );\n};\n\nexport default Checkbox;\n"],"mappings":"AAEA,SAAqBA,QAAQ,QAAQ,0BAA0B;AAE/D,OAAOC,YAAY;AAAqB,SAAAC,GAAA,IAAAC,IAAA,EAAAC,IAAA,IAAAC,KAAA;AAiBxC,MAAMC,QAAQ,GAAGA,CAAqD;EACpEC,OAAO;EACPC,QAAQ;EACRC,KAAK;EACLC,QAAQ;EACRC,MAAM;EACNC;AACa,CAAC,KAAgB;EAC9B,MAAMC,QAAQ,GAAGb,QAAQ,CAAC,UAAU,EAAEC,YAAY,EAAEW,KAAK,CAAC;EAE1D,IAAIE,kBAAkB,GAAGD,QAAQ,CAACE,SAAS;EAC3C,IAAIP,QAAQ,EAAEM,kBAAkB,IAAI,IAAID,QAAQ,CAACL,QAAQ,EAAE;EAE3D,IAAIQ,iBAAiB,GAAGH,QAAQ,CAACI,QAAQ;EACzC,IAAIV,OAAO,KAAK,eAAe,EAAES,iBAAiB,IAAI,IAAIH,QAAQ,CAACK,aAAa,EAAE;EAElF,oBACEb,KAAA;IAAKc,SAAS,EAAEL,kBAAmB;IAAAM,QAAA,GAC/BX,KAAK,KAAKY,SAAS,GACjB,IAAI,gBAAGlB,IAAA;MAAKgB,SAAS,EAAEN,QAAQ,CAACJ,KAAM;MAAAW,QAAA,EAAEX;IAAK,CAAM,CAAC,eACxDN,IAAA;MACEI,OAAO,EAAEA,OAAO,KAAKc,SAAS,GAAGA,SAAS,GAAGd,OAAO,KAAK,IAAK;MAC9DY,SAAS,EAAEH,iBAAkB;MAC7B,eAAaM,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,GAAGH,SAAS,GAAGV,MAAO;MACxEH,QAAQ,EAAEA,QAAS;MACnBE,QAAQ,EAAEA,QAAS;MACnBe,OAAO,EAAGC,CAAC,IAAK;QACdA,CAAC,CAACC,eAAe,CAAC,CAAC;MACrB,CAAE;MACFC,IAAI,EAAC;IAAU,CAChB,CAAC;EAAA,CACC,CAAC;AAEV,CAAC;AAED,eAAetB,QAAQ","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["useTheme","defaultTheme","jsx","_jsx","jsxs","_jsxs","Checkbox","checked","disabled","label","onChange","testId","theme","composed","containerClassName","container","checkboxClassName","checkbox","indeterminate","className","children","undefined","process","env","NODE_ENV","onClick","e","stopPropagation","type"],"sources":["../../../../../src/shared/components/Checkbox/index.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './theme.scss';\n\ntype PropT<ValueT> = {\n checked?: ValueT;\n disabled?: boolean;\n label?: React.ReactNode;\n onChange?: React.ChangeEventHandler<HTMLInputElement>;\n testId?: string;\n theme?: Theme<\n | 'checkbox'\n | 'container'\n | 'disabled'\n | 'indeterminate'\n | 'label'\n >;\n};\n\nconst Checkbox = <ValueT extends 'indeterminate' | boolean = boolean>({\n checked,\n disabled,\n label,\n onChange,\n testId,\n theme,\n}: PropT<ValueT>): ReactNode => {\n const composed = useTheme('Checkbox', defaultTheme, theme);\n\n let containerClassName = composed.container;\n if (disabled) containerClassName += ` ${composed.disabled}`;\n\n let checkboxClassName = composed.checkbox;\n if (checked === 'indeterminate') checkboxClassName += ` ${composed.indeterminate}`;\n\n return (\n <div className={containerClassName}>\n { label === undefined\n ? null : <div className={composed.label}>{label}</div> }\n <input\n checked={checked === undefined ? undefined : checked === true}\n className={checkboxClassName}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n disabled={disabled}\n onChange={onChange}\n onClick={(e) => {\n e.stopPropagation();\n }}\n type=\"checkbox\"\n />\n </div>\n );\n};\n\nexport default Checkbox;\n"],"mappings":"AAEA,SAAqBA,QAAQ,QAAQ,0BAA0B;AAE/D,OAAOC,YAAY;AAAqB,SAAAC,GAAA,IAAAC,IAAA,EAAAC,IAAA,IAAAC,KAAA;AAiBxC,MAAMC,QAAQ,GAAGA,CAAqD;EACpEC,OAAO;EACPC,QAAQ;EACRC,KAAK;EACLC,QAAQ;EACRC,MAAM;EACNC;AACa,CAAC,KAAgB;EAC9B,MAAMC,QAAQ,GAAGb,QAAQ,CAAC,UAAU,EAAEC,YAAY,EAAEW,KAAK,CAAC;EAE1D,IAAIE,kBAAkB,GAAGD,QAAQ,CAACE,SAAS;EAC3C,IAAIP,QAAQ,EAAEM,kBAAkB,IAAI,IAAID,QAAQ,CAACL,QAAQ,EAAE;EAE3D,IAAIQ,iBAAiB,GAAGH,QAAQ,CAACI,QAAQ;EACzC,IAAIV,OAAO,KAAK,eAAe,EAAES,iBAAiB,IAAI,IAAIH,QAAQ,CAACK,aAAa,EAAE;EAElF,oBACEb,KAAA;IAAKc,SAAS,EAAEL,kBAAmB;IAAAM,QAAA,GAC/BX,KAAK,KAAKY,SAAS,GACjB,IAAI,gBAAGlB,IAAA;MAAKgB,SAAS,EAAEN,QAAQ,CAACJ,KAAM;MAAAW,QAAA,EAAEX;IAAK,CAAM,CAAC,eACxDN,IAAA;MACEI,OAAO,EAAEA,OAAO,KAAKc,SAAS,GAAGA,SAAS,GAAGd,OAAO,KAAK,IAAK;MAC9DY,SAAS,EAAEH,iBAAkB;MAC7B,eAAaM,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,GAAGH,SAAS,GAAGV,MAAO;MACxEH,QAAQ,EAAEA,QAAS;MACnBE,QAAQ,EAAEA,QAAS;MACnBe,OAAO,EAAGC,CAAC,IAAK;QACdA,CAAC,CAACC,eAAe,CAAC,CAAC;MACrB,CAAE;MACFC,IAAI,EAAC;IAAU,CAChB,CAAC;EAAA,CACC,CAAC;AAEV,CAAC;AAED,eAAetB,QAAQ","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"Link.js","names":["Link","RrLink","GenericLink","jsx","_jsx","props","routerLinkType"],"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';\n\nimport GenericLink, { type PropsT as GenericLinkPropsT } from './GenericLink';\n\ntype PropsT = Omit<GenericLinkPropsT, 'routerLinkType'> & LinkProps;\n\nconst Link: React.FunctionComponent<PropsT>\n = (props) => (\n <GenericLink\n // TODO: Avoid the spreading later.\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...props}\n routerLinkType={RrLink}\n />\n );\n\nexport default Link;\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAyBA,IAAI,IAAIC,MAAM,QAAQ,cAAc;AAE7D,OAAOC,WAAW;AAA4D,SAAAC,GAAA,IAAAC,IAAA;AAI9E,MAAMJ,IAAqC,GACtCK,KAAK,iBACND,IAAA,CAACF;AACC;AACA;AAAA;EAAA,GACIG,KAAK;EACTC,cAAc,EAAEL;AAAO,CACxB,CACF;AAEH,eAAeD,IAAI","ignoreList":[]}
1
+ {"version":3,"file":"Link.js","names":["Link","RrLink","GenericLink","jsx","_jsx","props","routerLinkType"],"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';\n\nimport GenericLink, { type PropsT as GenericLinkPropsT } from './GenericLink';\n\ntype PropsT = LinkProps & Omit<GenericLinkPropsT, 'routerLinkType'>;\n\nconst Link: React.FunctionComponent<PropsT>\n = (props) => (\n <GenericLink\n // TODO: Avoid the spreading later.\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...props}\n routerLinkType={RrLink}\n />\n );\n\nexport default Link;\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAyBA,IAAI,IAAIC,MAAM,QAAQ,cAAc;AAE7D,OAAOC,WAAW;AAA4D,SAAAC,GAAA,IAAAC,IAAA;AAI9E,MAAMJ,IAAqC,GACtCK,KAAK,iBACND,IAAA,CAACF;AACC;AACA;AAAA;EAAA,GACIG,KAAK;EACTC,cAAc,EAAEL;AAAO,CACxB,CACF;AAEH,eAAeD,IAAI","ignoreList":[]}
@@ -1,6 +1,6 @@
1
1
  import { useEffect, useMemo, useRef } from 'react';
2
- import { createPortal } from 'react-dom';
3
2
  import { useTheme } from '@dr.pogodin/react-themes';
3
+ import { createPortal } from 'react-dom';
4
4
  import defaultTheme from "./base-theme.scss";
5
5
  import S from "./styles.scss";
6
6
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["useEffect","useMemo","useRef","createPortal","useTheme","defaultTheme","S","jsx","_jsx","jsxs","_jsxs","BaseModal","cancelOnScrolling","children","containerStyle","dontDisableScrolling","onCancel","overlayStyle","style","testId","testIdForOverlay","theme","containerRef","overlayRef","window","addEventListener","removeEventListener","document","body","classList","add","scrollingDisabledByModal","remove","focusLast","onFocus","elems","current","querySelectorAll","i","length","focus","activeElement","tabIndex","className","overlay","process","env","NODE_ENV","undefined","onClick","e","stopPropagation","onKeyDown","key","ref","node","role","container","onWheel","event","Modal","rest","composed"],"sources":["../../../../../src/shared/components/Modal/index.tsx"],"sourcesContent":["import {\n type CSSProperties,\n type FunctionComponent,\n type ReactNode,\n useEffect,\n useMemo,\n useRef,\n} from 'react';\n\nimport { createPortal } from 'react-dom';\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './base-theme.scss';\nimport S from './styles.scss';\n\ntype ThemeT = Theme<'container' | 'overlay'>;\n\ntype PropsT = {\n cancelOnScrolling?: boolean;\n children?: ReactNode;\n dontDisableScrolling?: boolean;\n onCancel?: () => void;\n overlayStyle?: CSSProperties;\n style?: CSSProperties;\n testId?: string;\n testIdForOverlay?: string;\n theme: ThemeT;\n\n /** @deprecated */\n containerStyle?: CSSProperties;\n};\n\n/**\n * The `<Modal>` component implements a simple themeable modal window, wrapped\n * into the default theme. `<BaseModal>` exposes the base non-themed component.\n * **Children:** Component children are rendered as the modal content.\n * @param {object} props Component properties. Beside props documented below,\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties) are supported as well.\n * @param {function} [props.onCancel] The callback to trigger when user\n * clicks outside the modal, or presses Escape. It is expected to hide the\n * modal.\n * @param {ModalTheme} [props.theme] _Ad hoc_ theme.\n */\nconst BaseModal: FunctionComponent<PropsT> = ({\n cancelOnScrolling,\n children,\n containerStyle,\n dontDisableScrolling,\n onCancel,\n overlayStyle,\n style,\n testId,\n testIdForOverlay,\n theme,\n}) => {\n const containerRef = useRef<HTMLDivElement | null>(null);\n const overlayRef = useRef<HTMLDivElement | null>(null);\n\n // Sets up modal cancellation of scrolling, if opted-in.\n useEffect(() => {\n if (cancelOnScrolling && onCancel) {\n window.addEventListener('scroll', onCancel);\n window.addEventListener('wheel', onCancel);\n }\n return () => {\n if (cancelOnScrolling && onCancel) {\n window.removeEventListener('scroll', onCancel);\n window.removeEventListener('wheel', onCancel);\n }\n };\n }, [cancelOnScrolling, onCancel]);\n\n // Disables window scrolling, if it is not opted-out.\n useEffect(() => {\n if (!dontDisableScrolling) {\n document.body.classList.add(S.scrollingDisabledByModal);\n }\n return () => {\n if (!dontDisableScrolling) {\n document.body.classList.remove(S.scrollingDisabledByModal);\n }\n };\n }, [dontDisableScrolling]);\n\n const focusLast = useMemo(() => (\n <div\n onFocus={() => {\n const elems = containerRef.current!.querySelectorAll('*');\n for (let i = elems.length - 1; i >= 0; --i) {\n (elems[i] as HTMLElement).focus();\n if (document.activeElement === elems[i]) return;\n }\n overlayRef.current?.focus();\n }}\n // TODO: Have a look at this later.\n // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex\n tabIndex={0}\n />\n ), []);\n\n return createPortal(\n (\n <div>\n {focusLast}\n <div\n aria-label=\"Cancel\"\n className={theme.overlay}\n data-testid={\n process.env.NODE_ENV === 'production'\n ? undefined : testIdForOverlay\n }\n onClick={(e) => {\n if (onCancel) {\n onCancel();\n e.stopPropagation();\n }\n }}\n onKeyDown={(e) => {\n if (e.key === 'Escape' && onCancel) {\n onCancel();\n e.stopPropagation();\n }\n }}\n ref={(node) => {\n if (node && node !== overlayRef.current) {\n overlayRef.current = node;\n node.focus();\n }\n }}\n role=\"button\"\n style={overlayStyle}\n tabIndex={0}\n />\n {\n // NOTE: These rules are disabled because our intention is to keep\n // the element non-interactive (thus not on the keyboard focus chain),\n // and it has `onClick` handler merely to stop propagation of click\n // events to its parent container. This is needed because, for example\n // when the modal is wrapped into an interactive element we don't want\n // any clicks inside the modal to bubble-up to that parent element\n // (because visually and logically the modal dialog does not belong\n // to its parent container, where it technically belongs from\n // the HTML mark-up perpective).\n }\n <div // eslint-disable-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions\n aria-modal=\"true\"\n className={theme.container}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onClick={(e) => {\n e.stopPropagation();\n }}\n onWheel={(event) => {\n event.stopPropagation();\n }}\n ref={containerRef}\n role=\"dialog\"\n style={style ?? containerStyle}\n >\n {children}\n </div>\n <div\n onFocus={() => {\n overlayRef.current?.focus();\n }}\n // TODO: Have a look at this later.\n // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex\n tabIndex={0}\n />\n {focusLast}\n </div>\n ),\n document.body,\n );\n};\n\n/* Non-themed version of the Modal. */\nexport { BaseModal };\n\nconst Modal: FunctionComponent<\n Omit<PropsT, 'theme'> & { theme?: ThemeT }\n> = ({ theme, ...rest }) => {\n const composed = useTheme('Modal', defaultTheme, theme);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return <BaseModal {...rest} theme={composed} />;\n};\n\nexport default Modal;\n"],"mappings":"AAAA,SAIEA,SAAS,EACTC,OAAO,EACPC,MAAM,QACD,OAAO;AAEd,SAASC,YAAY,QAAQ,WAAW;AACxC,SAAqBC,QAAQ,QAAQ,0BAA0B;AAE/D,OAAOC,YAAY;AACnB,OAAOC,CAAC;AAAsB,SAAAC,GAAA,IAAAC,IAAA,EAAAC,IAAA,IAAAC,KAAA;AAmB9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,SAAoC,GAAGA,CAAC;EAC5CC,iBAAiB;EACjBC,QAAQ;EACRC,cAAc;EACdC,oBAAoB;EACpBC,QAAQ;EACRC,YAAY;EACZC,KAAK;EACLC,MAAM;EACNC,gBAAgB;EAChBC;AACF,CAAC,KAAK;EACJ,MAAMC,YAAY,GAAGpB,MAAM,CAAwB,IAAI,CAAC;EACxD,MAAMqB,UAAU,GAAGrB,MAAM,CAAwB,IAAI,CAAC;;EAEtD;EACAF,SAAS,CAAC,MAAM;IACd,IAAIY,iBAAiB,IAAII,QAAQ,EAAE;MACjCQ,MAAM,CAACC,gBAAgB,CAAC,QAAQ,EAAET,QAAQ,CAAC;MAC3CQ,MAAM,CAACC,gBAAgB,CAAC,OAAO,EAAET,QAAQ,CAAC;IAC5C;IACA,OAAO,MAAM;MACX,IAAIJ,iBAAiB,IAAII,QAAQ,EAAE;QACjCQ,MAAM,CAACE,mBAAmB,CAAC,QAAQ,EAAEV,QAAQ,CAAC;QAC9CQ,MAAM,CAACE,mBAAmB,CAAC,OAAO,EAAEV,QA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AAC;AACH,CAAC;;AAED;AACA,SAASjB,SAAS;AAElB,MAAMiD,KAEL,GAAGA,CAAC;EAAEvC,KAAK;EAAE,GAAGwC;AAAK,CAAC,KAAK;EAC1B,MAAMC,QAAQ,GAAG1D,QAAQ,CAAC,OAAO,EAAEC,YAAY,EAAEgB,KAAK,CAAC;;EAEvD;EACA,oBAAOb,IAAA,CAACG,SAAS;IAAA,GAAKkD,IAAI;IAAExC,KAAK,EAAEyC;EAAS,CAAE,CAAC;AACjD,CAAC;AAED,eAAeF,KAAK","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["useEffect","useMemo","useRef","useTheme","createPortal","defaultTheme","S","jsx","_jsx","jsxs","_jsxs","BaseModal","cancelOnScrolling","children","containerStyle","dontDisableScrolling","onCancel","overlayStyle","style","testId","testIdForOverlay","theme","containerRef","overlayRef","window","addEventListener","removeEventListener","document","body","classList","add","scrollingDisabledByModal","remove","focusLast","onFocus","elems","current","querySelectorAll","i","length","focus","activeElement","tabIndex","className","overlay","process","env","NODE_ENV","undefined","onClick","e","stopPropagation","onKeyDown","key","ref","node","role","container","onWheel","event","Modal","rest","composed"],"sources":["../../../../../src/shared/components/Modal/index.tsx"],"sourcesContent":["import {\n type CSSProperties,\n type FunctionComponent,\n type ReactNode,\n useEffect,\n useMemo,\n useRef,\n} from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\nimport { createPortal } from 'react-dom';\n\nimport defaultTheme from './base-theme.scss';\nimport S from './styles.scss';\n\ntype ThemeT = Theme<'container' | 'overlay'>;\n\ntype PropsT = {\n cancelOnScrolling?: boolean;\n children?: ReactNode;\n dontDisableScrolling?: boolean;\n onCancel?: () => void;\n overlayStyle?: CSSProperties;\n style?: CSSProperties;\n testId?: string;\n testIdForOverlay?: string;\n theme: ThemeT;\n\n /** @deprecated */\n containerStyle?: CSSProperties;\n};\n\n/**\n * The `<Modal>` component implements a simple themeable modal window, wrapped\n * into the default theme. `<BaseModal>` exposes the base non-themed component.\n * **Children:** Component children are rendered as the modal content.\n * @param {object} props Component properties. Beside props documented below,\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties) are supported as well.\n * @param {function} [props.onCancel] The callback to trigger when user\n * clicks outside the modal, or presses Escape. It is expected to hide the\n * modal.\n * @param {ModalTheme} [props.theme] _Ad hoc_ theme.\n */\nconst BaseModal: FunctionComponent<PropsT> = ({\n cancelOnScrolling,\n children,\n containerStyle,\n dontDisableScrolling,\n onCancel,\n overlayStyle,\n style,\n testId,\n testIdForOverlay,\n theme,\n}) => {\n const containerRef = useRef<HTMLDivElement | null>(null);\n const overlayRef = useRef<HTMLDivElement | null>(null);\n\n // Sets up modal cancellation of scrolling, if opted-in.\n useEffect(() => {\n if (cancelOnScrolling && onCancel) {\n window.addEventListener('scroll', onCancel);\n window.addEventListener('wheel', onCancel);\n }\n return () => {\n if (cancelOnScrolling && onCancel) {\n window.removeEventListener('scroll', onCancel);\n window.removeEventListener('wheel', onCancel);\n }\n };\n }, [cancelOnScrolling, onCancel]);\n\n // Disables window scrolling, if it is not opted-out.\n useEffect(() => {\n if (!dontDisableScrolling) {\n document.body.classList.add(S.scrollingDisabledByModal);\n }\n return () => {\n if (!dontDisableScrolling) {\n document.body.classList.remove(S.scrollingDisabledByModal);\n }\n };\n }, [dontDisableScrolling]);\n\n const focusLast = useMemo(() => (\n <div\n onFocus={() => {\n const elems = containerRef.current!.querySelectorAll('*');\n for (let i = elems.length - 1; i >= 0; --i) {\n (elems[i] as HTMLElement).focus();\n if (document.activeElement === elems[i]) return;\n }\n overlayRef.current?.focus();\n }}\n // TODO: Have a look at this later.\n // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex\n tabIndex={0}\n />\n ), []);\n\n return createPortal(\n (\n <div>\n {focusLast}\n <div\n aria-label=\"Cancel\"\n className={theme.overlay}\n data-testid={\n process.env.NODE_ENV === 'production'\n ? undefined : testIdForOverlay\n }\n onClick={(e) => {\n if (onCancel) {\n onCancel();\n e.stopPropagation();\n }\n }}\n onKeyDown={(e) => {\n if (e.key === 'Escape' && onCancel) {\n onCancel();\n e.stopPropagation();\n }\n }}\n ref={(node) => {\n if (node && node !== overlayRef.current) {\n overlayRef.current = node;\n node.focus();\n }\n }}\n role=\"button\"\n style={overlayStyle}\n tabIndex={0}\n />\n {\n // NOTE: These rules are disabled because our intention is to keep\n // the element non-interactive (thus not on the keyboard focus chain),\n // and it has `onClick` handler merely to stop propagation of click\n // events to its parent container. This is needed because, for example\n // when the modal is wrapped into an interactive element we don't want\n // any clicks inside the modal to bubble-up to that parent element\n // (because visually and logically the modal dialog does not belong\n // to its parent container, where it technically belongs from\n // the HTML mark-up perpective).\n }\n <div // eslint-disable-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions\n aria-modal=\"true\"\n className={theme.container}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onClick={(e) => {\n e.stopPropagation();\n }}\n onWheel={(event) => {\n event.stopPropagation();\n }}\n ref={containerRef}\n role=\"dialog\"\n style={style ?? containerStyle}\n >\n {children}\n </div>\n <div\n onFocus={() => {\n overlayRef.current?.focus();\n }}\n // TODO: Have a look at this later.\n // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex\n tabIndex={0}\n />\n {focusLast}\n </div>\n ),\n document.body,\n );\n};\n\n/* Non-themed version of the Modal. */\nexport { BaseModal };\n\nconst Modal: FunctionComponent<\n Omit<PropsT, 'theme'> & { theme?: ThemeT }\n> = ({ theme, ...rest }) => {\n const composed = useTheme('Modal', defaultTheme, theme);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return <BaseModal {...rest} theme={composed} />;\n};\n\nexport default Modal;\n"],"mappings":"AAAA,SAIEA,SAAS,EACTC,OAAO,EACPC,MAAM,QACD,OAAO;AAEd,SAAqBC,QAAQ,QAAQ,0BAA0B;AAC/D,SAASC,YAAY,QAAQ,WAAW;AAExC,OAAOC,YAAY;AACnB,OAAOC,CAAC;AAAsB,SAAAC,G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E;MACFgB,IAAI,EAAC,QAAQ;MACbtC,KAAK,EAAED,YAAa;MACpByB,QAAQ,EAAE;IAAE,CACb,CAAC,eAYFlC,IAAA;MAAK;MACH,cAAW,MAAM;MACjBmC,SAAS,EAAEtB,KAAK,CAACoC,SAAU;MAC3B,eAAaZ,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,GAAGC,SAAS,GAAG7B,MAAO;MACxE8B,OAAO,EAAGC,CAAC,IAAK;QACdA,CAAC,CAACC,eAAe,CAAC,CAAC;MACrB,CAAE;MACFO,OAAO,EAAGC,KAAK,IAAK;QAClBA,KAAK,CAACR,eAAe,CAAC,CAAC;MACzB,CAAE;MACFG,GAAG,EAAEhC,YAAa;MAClBkC,IAAI,EAAC,QAAQ;MACbtC,KAAK,EAAEA,KAAK,IAAIJ,cAAe;MAAAD,QAAA,EAE9BA;IAAQ,CACN,CAAC,eACNL,IAAA;MACE0B,OAAO,EAAEA,CAAA,KAAM;QACbX,UAAU,CAACa,OAAO,EAAEI,KAAK,CAAC,CAAC;MAC7B;MACA;MACA;MAAA;MACAE,QAAQ,EAAE;IAAE,CACb,CAAC,EACDT,SAAS;EAAA,CACP,CAAC,EAERN,QAAQ,CAACC,IACX,CAAC;AACH,CAAC;;AAED;AACA,SAASjB,SAAS;AAElB,MAAMiD,KAEL,GAAGA,CAAC;EAAEvC,KAAK;EAAE,GAAGwC;AAAK,CAAC,KAAK;EAC1B,MAAMC,QAAQ,GAAG3D,QAAQ,CAAC,OAAO,EAAEE,YAAY,EAAEgB,KAAK,CAAC;;EAEvD;EACA,oBAAOb,IAAA,CAACG,SAAS;IAAA,GAAKkD,IAAI;IAAExC,KAAK,EAAEyC;EAAS,CAAE,CAAC;AACjD,CAAC;AAED,eAAeF,KAAK","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"NavLink.js","names":["NavLink","RrNavLink","GenericLink","jsx","_jsx","props","routerLinkType"],"sources":["../../../../src/shared/components/NavLink.tsx"],"sourcesContent":["import { type NavLinkProps, NavLink as RrNavLink } from 'react-router';\n\nimport GenericLink, { type PropsT as GenericLinkPropsT } from './GenericLink';\n\ntype PropsT = Omit<GenericLinkPropsT, 'routerLinkType'> & NavLinkProps;\n\nconst NavLink: React.FunctionComponent<PropsT>\n = (props) => (\n <GenericLink\n // TODO: I guess, we better re-write it to avoid the props spreading,\n // but no need to spend time on it right now.\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...props}\n routerLinkType={RrNavLink}\n />\n );\n\nexport default NavLink;\n"],"mappings":"AAAA,SAA4BA,OAAO,IAAIC,SAAS,QAAQ,cAAc;AAEtE,OAAOC,WAAW;AAA4D,SAAAC,GAAA,IAAAC,IAAA;AAI9E,MAAMJ,OAAwC,GACzCK,KAAK,iBACND,IAAA,CAACF;AACC;AACA;AACA;AAAA;EAAA,GACIG,KAAK;EACTC,cAAc,EAAEL;AAAU,CAC3B,CACF;AAEH,eAAeD,OAAO","ignoreList":[]}
1
+ {"version":3,"file":"NavLink.js","names":["NavLink","RrNavLink","GenericLink","jsx","_jsx","props","routerLinkType"],"sources":["../../../../src/shared/components/NavLink.tsx"],"sourcesContent":["import { type NavLinkProps, NavLink as RrNavLink } from 'react-router';\n\nimport GenericLink, { type PropsT as GenericLinkPropsT } from './GenericLink';\n\ntype PropsT = NavLinkProps & Omit<GenericLinkPropsT, 'routerLinkType'>;\n\nconst NavLink: React.FunctionComponent<PropsT>\n = (props) => (\n <GenericLink\n // TODO: I guess, we better re-write it to avoid the props spreading,\n // but no need to spend time on it right now.\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...props}\n routerLinkType={RrNavLink}\n />\n );\n\nexport default NavLink;\n"],"mappings":"AAAA,SAA4BA,OAAO,IAAIC,SAAS,QAAQ,cAAc;AAEtE,OAAOC,WAAW;AAA4D,SAAAC,GAAA,IAAAC,IAAA;AAI9E,MAAMJ,OAAwC,GACzCK,KAAK,iBACND,IAAA,CAACF;AACC;AACA;AACA;AAAA;EAAA,GACIG,KAAK;EACTC,cAAc,EAAEL;AAAU,CAC3B,CACF;AAEH,eAAeD,OAAO","ignoreList":[]}