@dr.pogodin/react-utils 1.51.1 → 1.51.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,7 +14,9 @@ import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.ite
14
14
  // TODO: We need to add correct typing for environment options.
15
15
  // As this environment is a part of the Jest testing utils,
16
16
  // we assume development dependencies are available when it is used.
17
- /* eslint-disable import/no-extraneous-dependencies */import{fork}from"node:child_process";import path from"node:path";import JsdomEnv from"jest-environment-jsdom";import{defaults,set}from"lodash-es";import{Volume,createFsFromVolume}from"memfs";import webpack from"webpack";import{deduceChunkGroups}from"../../../../server/renderer";import{setBuildInfo}from"../../isomorphy/buildInfo";export default class E2eSsrEnv extends JsdomEnv{/**
17
+ /* eslint-disable import/no-extraneous-dependencies */import{fork}from"node:child_process";import{access}from"node:fs/promises";import path from"node:path";import JsdomEnv from"jest-environment-jsdom";import{defaults,set}from"lodash-es";import{Volume,createFsFromVolume}from"memfs";import webpack from"webpack";import register from"@babel/register/experimental-worker";import{deduceChunkGroups}from"../../../../server/renderer";async function findModule(module){try{const res=`${module}.ts`;await access(res);return res;}catch{// NOOP
18
+ }try{const res=`${module}.js`;await access(res);return res;}catch{// NOOP
19
+ }throw Error(`Module "${module}" was not found, neither as TS, nor as JS`);}export default class E2eSsrEnv extends JsdomEnv{/**
18
20
  * Loads Webpack config, and exposes it to the environment via global
19
21
  * webpackConfig object.
20
22
  */async loadWebpackConfig(){const optionsString=this.pragmas["webpack-config-options"];const options=optionsString?JSON.parse(optionsString):{};defaults(options,{context:this.testFolder,fs:this.global.webpackOutputFs});const factoryPath=this.pragmas["webpack-config-factory"];let factory=await import(/* webpackChunkName: "not-a-valid-chunk" */path.resolve(this.rootDir,factoryPath));factory="default"in factory?factory.default:factory;this.global.webpackConfig=factory(options);const fs=this.global.webpackOutputFs;let buildInfo=`${options.context}/.build-info`;if(fs.existsSync(buildInfo)){buildInfo=fs.readFileSync(buildInfo,"utf8");this.global.buildInfo=JSON.parse(buildInfo);}}/**
@@ -27,19 +29,47 @@ compiler.outputFileSystem=this.global.webpackOutputFs;return new Promise((done,f
27
29
  console.error(stats.toJson().errors);fail(Error("Webpack compilation failed"));}this.global.webpackStats=stats?.toJson();// Keeps reference to the raw Webpack stats object, which should be
28
30
  // explicitly passed to the server-side renderer alongside the request,
29
31
  // so that it can to pick up asset paths for different named chunks.
30
- this.webpackStats=stats;done();});});}async runSsr(){const cp=fork(`${import.meta.dirname}/ssr.ts`,[],{// NOTE: This ensures the forked "ssr.ts" module is pre-processed by
31
- // Babel, which is necessary to correctly resolve paths to modules it
32
- // loads, as we rely on Babel aliasing module paths; and we need to have
33
- // a little "register.ts" module (rather than just a command-line argument)
34
- // because we need to specify to Babel that ".ts", ".tsx", etc. files
35
- // need to be processed, in addition to the standard JS modules.
36
- execArgv:["-r",`${import.meta.dirname}/register.ts`]});const optionsString=this.pragmas["ssr-options"];const options=optionsString?JSON.parse(optionsString):{};options.buildInfo??=this.global.buildInfo;if(!this.webpackStats)throw Error("Missing Webpack stats");options.chunkGroups=deduceChunkGroups(this.webpackStats);return new Promise(resolve=>{cp.on("message",message=>{this.global.ssrMarkup=message.markup;this.global.ssrOptions=options;this.global.ssrStatus=message.status;cp.kill();resolve();});if(!this.global.webpackConfig)throw Error("Missing Webpack config");cp.send({options,root:options.root==="TEST"?this.testFolder:process.cwd(),ssrRequest:this.ssrRequest,testFolder:this.testFolder,webpackConfig:this.global.webpackConfig});});}constructor(config,context){const pragmas=context.docblockPragmas;const requestString=pragmas["ssr-request"];const request=requestString?JSON.parse(requestString):{};request.url??="/";// This ensures the initial JsDom URL matches the value we use for SSR.
32
+ this.webpackStats=stats;done();});});}async runSsr(){// NOTE: These are TS modules in the source code, and they turn into JS
33
+ // modules in the distributed code, after Babel compilation. As we rely
34
+ // on them for the forked NodeJS process, we need to resolve the correct
35
+ // extentions ourselves (as NodeJS will hit the given paths, without any
36
+ // additional resolutions / transformations).
37
+ const regModulePath=await findModule(`${import.meta.dirname}/register`);const ssrModulePath=await findModule(`${import.meta.dirname}/ssr`);const cp=fork(ssrModulePath,[],{// NOTE: We have to preload this "register" module, to setup Babel
38
+ // transformation for the loaded "ssr.ts" module itself (I believe,
39
+ // it is relevant only when the source code is executed within
40
+ // the library codebase itself, as the distributed code already
41
+ // has "ssr.ts" transpiled).
42
+ execArgv:["-r",regModulePath]});const optionsString=this.pragmas["ssr-options"];const options=optionsString?JSON.parse(optionsString):{};options.buildInfo??=this.global.buildInfo;if(!this.webpackStats)throw Error("Missing Webpack stats");options.chunkGroups=deduceChunkGroups(this.webpackStats);return new Promise((resolve,reject)=>{cp.on("exit",code=>{if(code)reject(Error("SSR process crashed"));});cp.on("message",message=>{this.global.ssrMarkup=message.markup;this.global.ssrOptions=options;this.global.ssrStatus=message.status;cp.kill();resolve();});if(!this.global.webpackConfig)throw Error("Missing Webpack config");cp.send({options,root:options.root==="TEST"?this.testFolder:process.cwd(),ssrRequest:this.ssrRequest,testFolder:this.testFolder,webpackConfig:this.global.webpackConfig});});}constructor(config,context){const pragmas=context.docblockPragmas;const requestString=pragmas["ssr-request"];const request=requestString?JSON.parse(requestString):{};request.url??="/";// This ensures the initial JsDom URL matches the value we use for SSR.
37
43
  set(config.projectConfig,"testEnvironmentOptions.url",`http://localhost${request.url}`);super(config,context);this.global.dom=this.dom;this.global.webpackOutputFs=createFsFromVolume(new Volume);// Extracts necessary settings from config and context.
38
- const{projectConfig}=config;this.rootDir=projectConfig.rootDir;this.testFolder=path.dirname(context.testPath);this.withSsr=!pragmas["no-ssr"];this.ssrRequest=request;this.pragmas=pragmas;}async setup(){await super.setup();await this.runWebpack();setBuildInfo(undefined,true);if(this.withSsr)await this.runSsr();this.global.REACT_UTILS_FORCE_CLIENT_SIDE=true;}async teardown(){delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;// Resets module cache and @babel/register. Effectively this ensures that
44
+ const{projectConfig}=config;this.rootDir=projectConfig.rootDir;this.testFolder=path.dirname(context.testPath);this.withSsr=!pragmas["no-ssr"];this.ssrRequest=request;this.pragmas=pragmas;// The usual "babel-jest" transformation setup does not apply to
45
+ // the environment code and imports from it, this workaround enables it.
46
+ const optionsString=this.pragmas["ssr-options"];const options=optionsString?JSON.parse(optionsString):{};let root;switch(options.root){case"TEST":root=this.testFolder;break;default:root=process.cwd();}// BEWARE: Anything imported prior to this register() call seems to be
47
+ // transpiled again by Babel if loaded after this call. This causes very
48
+ // confusing errors when testing the code dependent on some sort of contexts
49
+ // (because loading a module again effectively creates a new context object,
50
+ // which is not recognized by the code expecting another context instance).
51
+ // That's why below we prefer dynamic imports for some React Utils methods.
52
+ // BEWARE: Although we also do the registration inside SSR testing code,
53
+ // we still need it here to correctly process imported Webpack configurations
54
+ // (which are imported directly from this module).
55
+ register({envName:options.babelEnv,extensions:[".js",".jsx",".ts",".tsx",".svg"],root});}async setup(){await super.setup();await this.runWebpack();// NOTE: It is possible that the Webpack run above, and the SSR run below
56
+ // load different versions of the same module (CommonJS, and ES), and it may
57
+ // cause very confusing problems (e.g. see:
58
+ // https://github.com/birdofpreyru/react-utils/issues/413).
59
+ // It seems we can't reset the cache of ES modules, and Jest's module reset
60
+ // does not reset modules loaded in this enviroment module, and also only
61
+ // replacing entire cache object by and empty {} seems to help (in contrast
62
+ // to deleting all entries by their keys, as it is done within .teardown()
63
+ // method below). Thus, for now we do this as a hotfix, and we also reset
64
+ // build info to undefined, because ES module version not beeing reset
65
+ // triggers an error on the subsequent test using the environment.
66
+ // TODO: Look for a cleaner solution.
67
+ require.cache={};// eslint-disable-next-line import/dynamic-import-chunkname
68
+ const{setBuildInfo}=await import("../../isomorphy/buildInfo");setBuildInfo(undefined,true);if(this.withSsr)await this.runSsr();this.global.REACT_UTILS_FORCE_CLIENT_SIDE=true;}async teardown(){delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;// Resets module cache and @babel/register. Effectively this ensures that
39
69
  // the next time an instance of this environment is set up, all modules are
40
70
  // transformed by Babel from scratch, thus taking into account the latest
41
71
  // Babel config (which may change between different environment instances,
42
72
  // which does not seem to be taken into account by Babel / Node caches
43
73
  // automatically).
44
- Object.keys(require.cache).forEach(key=>{delete require.cache[key];});await super.teardown();}}
74
+ Object.keys(require.cache).forEach(key=>{delete require.cache[key];});register.revert();await super.teardown();}}
45
75
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["fork","path","JsdomEnv","defaults","set","Volume","createFsFromVolume","webpack","deduceChunkGroups","setBuildInfo","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","Error","compiler","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","cp","import","meta","dirname","execArgv","chunkGroups","on","message","ssrMarkup","markup","ssrOptions","ssrStatus","status","kill","send","root","process","cwd","ssrRequest","constructor","config","docblockPragmas","requestString","request","url","projectConfig","dom","testPath","withSsr","setup","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","require","cache","forEach","key"],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/index.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport { fork } from 'node:child_process';\nimport path from 'node:path';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { defaults, set } from 'lodash-es';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration, type Stats } from 'webpack';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport { deduceChunkGroups } from 'server/renderer';\n\nimport { setBuildInfo } from '../../isomorphy/buildInfo';\n\nimport type { LaunchT, ResultT } from './ssr';\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: Stats;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private async loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n\n let factory = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n path.resolve(this.rootDir, factoryPath)\n ) as (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n await this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr(): Promise<void> {\n const cp = fork(`${import.meta.dirname}/ssr.ts`, [], {\n // NOTE: This ensures the forked \"ssr.ts\" module is pre-processed by\n // Babel, which is necessary to correctly resolve paths to modules it\n // loads, as we rely on Babel aliasing module paths; and we need to have\n // a little \"register.ts\" module (rather than just a command-line argument)\n // because we need to specify to Babel that \".ts\", \".tsx\", etc. files\n // need to be processed, in addition to the standard JS modules.\n execArgv: ['-r', `${import.meta.dirname}/register.ts`],\n });\n\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n options.buildInfo ??= this.global.buildInfo;\n\n if (!this.webpackStats) throw Error('Missing Webpack stats');\n\n options.chunkGroups = deduceChunkGroups(this.webpackStats);\n\n return new Promise((resolve) => {\n cp.on('message', (message: ResultT) => {\n this.global.ssrMarkup = message.markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = message.status;\n cp.kill();\n resolve();\n });\n\n if (!this.global.webpackConfig) throw Error('Missing Webpack config');\n\n cp.send({\n options,\n root: options.root === 'TEST' ? this.testFolder : process.cwd(),\n ssrRequest: this.ssrRequest,\n testFolder: this.testFolder,\n webpackConfig: this.global.webpackConfig,\n } satisfies LaunchT);\n });\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n\n await super.teardown();\n }\n}\n"],"mappings":"4IAAA;AACA;AACA;AACA;AACA;AACA,GAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA,sDAEA,OAASA,IAAI,KAAQ,oBAAoB,CACzC,MAAO,CAAAC,IAAI,KAAM,WAAW,CAE5B,MAAO,CAAAC,QAAQ,KAAM,wBAAwB,CAC7C,OAASC,QAAQ,CAAEC,GAAG,KAAQ,WAAW,CACzC,OAASC,MAAM,CAAEC,kBAAkB,KAAQ,OAAO,CAClD,MAAO,CAAAC,OAAO,KAA0C,SAAS,CAOjE,OAASC,iBAAiB,mCAE1B,OAASC,YAAY,iCAIrB,cAAe,MAAM,CAAAC,SAAS,QAAS,CAAAR,QAAS,CAa9C;AACF;AACA;AAC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CAAAH,OAAO,CAACC,KAAK,CAACE,GAAG,CAAC,CAC3B,CAAC,CAAC,CAEF,KAAM,MAAK,CAACN,QAAQ,CAAC,CAAC,CACxB,CACF","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["fork","access","path","JsdomEnv","defaults","set","Volume","createFsFromVolume","webpack","register","deduceChunkGroups","findModule","module","res","Error","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","compiler","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","regModulePath","import","meta","dirname","ssrModulePath","cp","execArgv","chunkGroups","reject","on","code","message","ssrMarkup","markup","ssrOptions","ssrStatus","status","kill","send","root","process","cwd","ssrRequest","constructor","config","docblockPragmas","requestString","request","url","projectConfig","dom","testPath","withSsr","envName","babelEnv","extensions","setup","require","cache","setBuildInfo","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","forEach","key","revert"],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/index.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport { fork } from 'node:child_process';\nimport { access } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { defaults, set } from 'lodash-es';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration, type Stats } from 'webpack';\n\nimport register from '@babel/register/experimental-worker';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport { deduceChunkGroups } from 'server/renderer';\n\nimport type { LaunchT, ResultT } from './ssr';\n\nasync function findModule(module: string): Promise<string> {\n try {\n const res = `${module}.ts`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n try {\n const res = `${module}.js`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n throw Error(`Module \"${module}\" was not found, neither as TS, nor as JS`);\n}\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: Stats;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private async loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n\n let factory = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n path.resolve(this.rootDir, factoryPath)\n ) as (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n await this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr(): Promise<void> {\n // NOTE: These are TS modules in the source code, and they turn into JS\n // modules in the distributed code, after Babel compilation. As we rely\n // on them for the forked NodeJS process, we need to resolve the correct\n // extentions ourselves (as NodeJS will hit the given paths, without any\n // additional resolutions / transformations).\n const regModulePath = await findModule(`${import.meta.dirname}/register`);\n const ssrModulePath = await findModule(`${import.meta.dirname}/ssr`);\n\n const cp = fork(ssrModulePath, [], {\n // NOTE: We have to preload this \"register\" module, to setup Babel\n // transformation for the loaded \"ssr.ts\" module itself (I believe,\n // it is relevant only when the source code is executed within\n // the library codebase itself, as the distributed code already\n // has \"ssr.ts\" transpiled).\n execArgv: ['-r', regModulePath],\n });\n\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n options.buildInfo ??= this.global.buildInfo;\n\n if (!this.webpackStats) throw Error('Missing Webpack stats');\n\n options.chunkGroups = deduceChunkGroups(this.webpackStats);\n\n return new Promise((resolve, reject) => {\n cp.on('exit', (code) => {\n if (code) reject(Error('SSR process crashed'));\n });\n\n cp.on('message', (message: ResultT) => {\n this.global.ssrMarkup = message.markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = message.status;\n cp.kill();\n resolve();\n });\n\n if (!this.global.webpackConfig) throw Error('Missing Webpack config');\n\n cp.send({\n options,\n root: options.root === 'TEST' ? this.testFolder : process.cwd(),\n ssrRequest: this.ssrRequest,\n testFolder: this.testFolder,\n webpackConfig: this.global.webpackConfig,\n } satisfies LaunchT);\n });\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n let root;\n switch (options.root) {\n case 'TEST':\n root = this.testFolder;\n break;\n default: root = process.cwd();\n }\n\n // BEWARE: Anything imported prior to this register() call seems to be\n // transpiled again by Babel if loaded after this call. This causes very\n // confusing errors when testing the code dependent on some sort of contexts\n // (because loading a module again effectively creates a new context object,\n // which is not recognized by the code expecting another context instance).\n // That's why below we prefer dynamic imports for some React Utils methods.\n // BEWARE: Although we also do the registration inside SSR testing code,\n // we still need it here to correctly process imported Webpack configurations\n // (which are imported directly from this module).\n register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // NOTE: It is possible that the Webpack run above, and the SSR run below\n // load different versions of the same module (CommonJS, and ES), and it may\n // cause very confusing problems (e.g. see:\n // https://github.com/birdofpreyru/react-utils/issues/413).\n // It seems we can't reset the cache of ES modules, and Jest's module reset\n // does not reset modules loaded in this enviroment module, and also only\n // replacing entire cache object by and empty {} seems to help (in contrast\n // to deleting all entries by their keys, as it is done within .teardown()\n // method below). Thus, for now we do this as a hotfix, and we also reset\n // build info to undefined, because ES module version not beeing reset\n // triggers an error on the subsequent test using the environment.\n // TODO: Look for a cleaner solution.\n require.cache = {};\n\n // eslint-disable-next-line import/dynamic-import-chunkname\n const { setBuildInfo } = await import('../../isomorphy/buildInfo');\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n\n await super.teardown();\n }\n}\n"],"mappings":"4IAAA;AACA;AACA;AACA;AACA;AACA,GAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA,sDAEA,OAASA,IAAI,KAAQ,oBAAoB,CACzC,OAASC,MAAM,KAAQ,kBAAkB,CACzC,MAAO,CAAAC,IAAI,KAAM,WAAW,CAE5B,MAAO,CAAAC,QAAQ,KAAM,wBAAwB,CAC7C,OAASC,QAAQ,CAAEC,GAAG,KAAQ,WAAW,CACzC,OAASC,MAAM,CAAEC,kBAAkB,KAAQ,OAAO,CAClD,MAAO,CAAAC,OAAO,KAA0C,SAAS,CAEjE,MAAO,CAAAC,QAAQ,KAAM,qCAAqC,CAO1D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IAAI,CAAC,CAE7B,GAAI,IAAI,CAACR,OAAO,CAAE,KAAM,KAAI,CAACjC,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC1B,MAAM,CAACoE,6BAA6B,CAAG,IAAI,CAClD,CAEA,KAAM,CAAAC,QAAQA,CAAA,CAAkB,CAC9B,MAAO,KAAI,CAACrE,MAAM,CAACoE,6BAA6B,CAEhD;AACA;AACA;AACA;AACA;AACA;AACAE,MAAM,CAACC,IAAI,CAACP,OAAO,CAACC,KAAK,CAAC,CAACO,OAAO,CAAEC,GAAG,EAAK,CAC1C,MAAO,CAAAT,OAAO,CAACC,KAAK,CAACQ,GAAG,CAAC,CAC3B,CAAC,CAAC,CACFzF,QAAQ,CAAC0F,MAAM,CAAC,CAAC,CAEjB,KAAM,MAAK,CAACL,QAAQ,CAAC,CAAC,CACxB,CACF","ignoreList":[]}
@@ -1,6 +1,16 @@
1
- /* eslint-disable import/dynamic-import-chunkname, import/no-extraneous-dependencies */import{resolve}from"node:path";import register from"@babel/register";function noop(){// NOOP
2
- }async function run({options,root,ssrRequest,testFolder,webpackConfig}){register({envName:options.babelEnv,extensions:[".js",".jsx",".ts",".tsx",".svg"],root});if(options.entry){const p=resolve(testFolder,options.entry);const module=await import(p);const exportName=options.entryExportName||"default";if(exportName in module){// eslint-disable-next-line no-param-reassign
3
- options.Application=module[exportName];}}const{default:ssrFactory}=await import("../../../../server/renderer");const renderer=ssrFactory(webpackConfig,options);let status=200;// OK
1
+ /* eslint-disable import/dynamic-import-chunkname, import/no-extraneous-dependencies */import{readFileSync}from"node:fs";import{registerHooks}from"node:module";import{basename,dirname,resolve}from"node:path";import{fileURLToPath}from"node:url";import{transformSync}from"@babel/core";import ssrFactory from"../../../../server/renderer";function noop(){// NOOP
2
+ }async function run({options,root,ssrRequest,testFolder,webpackConfig}){// NOTE: It looks like @babel/register does not work for us here, because
3
+ // it only supports transpiling of modules loaded with require(), so here
4
+ // is, presumably, a temporary workaround relying on the new NodeJS module
5
+ // API, and Babel's core, to transpile all modules loaded further into
6
+ // CommonJS. I guess, later we'll be able to get rid of this, as Babel
7
+ // register supports runtime transformation of modules loaded with import().
8
+ registerHooks({load(url,context,nextLoad){if(url.startsWith("file://")&&!url.includes("/node_modules/")&&!url.includes("/config/babel/")&&url.match(/\.(js|jsx|ts|tsx|svg)$/)){const path=fileURLToPath(url);let code=readFileSync(path,"utf8");code=transformSync(code,{cwd:dirname(path),envName:options.babelEnv,filename:basename(path),root})?.code??"";return{format:"commonjs",shortCircuit:true,source:code};}return nextLoad(url,context);}});if(options.entry){const p=resolve(testFolder,options.entry);const babelModule=await import(p);// TODO: This is basically a hotfix hack, which works both for the library
9
+ // itself, and for dependent projects... (those tested so far). It sure has
10
+ // to be reworked later.
11
+ /* eslint-disable no-underscore-dangle */const module="__esModule"in babelModule&&typeof babelModule.__esModule==="boolean"&&babelModule.__esModule&&"default"in babelModule?babelModule.default:babelModule;/* eslint-enable no-underscore-dangle */const exportName=options.entryExportName||"default";if(exportName in module){// eslint-disable-next-line no-param-reassign
12
+ options.Application=module[exportName];// eslint-disable-next-line no-param-reassign
13
+ }else options.Application=module;}const renderer=ssrFactory(webpackConfig,options);let status=200;// OK
4
14
  // eslint-disable-next-line no-param-reassign
5
15
  ssrRequest.csrfToken=()=>"";const markup=await new Promise((done,fail)=>{void renderer(ssrRequest,// TODO: This will do for now, with the current implementation of
6
16
  // the renderer, but it will require a rework once the renderer is
@@ -1 +1 @@
1
- {"version":3,"file":"ssr.js","names":["resolve","register","noop","run","options","root","ssrRequest","testFolder","webpackConfig","envName","babelEnv","extensions","entry","p","module","exportName","entryExportName","Application","default","ssrFactory","renderer","status","csrfToken","markup","Promise","done","fail","cookie","send","set","value","error","process","on","message"],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/ssr.ts"],"sourcesContent":["/* eslint-disable import/dynamic-import-chunkname, import/no-extraneous-dependencies */\n\nimport { resolve } from 'node:path';\n\nimport type { Request, Response } from 'express';\nimport type { ReactNode } from 'react';\nimport type { Configuration } from 'webpack';\n\nimport register from '@babel/register';\n\nexport type LaunchT = {\n // TODO: Should it be typed as the renderer's options type?\n options: Record<string, unknown>;\n\n root: string;\n ssrRequest: object;\n testFolder: string;\n webpackConfig: Configuration;\n};\n\nexport type ResultT = {\n markup: string;\n status: number;\n};\n\nfunction noop() {\n // NOOP\n}\n\nasync function run({\n options,\n root,\n ssrRequest,\n testFolder,\n webpackConfig,\n}: LaunchT) {\n register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n\n if (options.entry) {\n const p = resolve(testFolder, options.entry as string);\n const module = await import(p) as NodeJS.Module;\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n // eslint-disable-next-line no-param-reassign\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n }\n }\n\n const { default: ssrFactory } = await import('server/renderer');\n\n const renderer = ssrFactory(webpackConfig, options);\n let status = 200; // OK\n\n // eslint-disable-next-line no-param-reassign\n (ssrRequest as Request).csrfToken = () => '';\n\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n process.send?.({ markup, status } satisfies ResultT);\n}\n\nprocess.on('message', (message: LaunchT) => {\n void run(message);\n});\n"],"mappings":"AAAA,uFAEA,OAASA,OAAO,KAAQ,WAAW,CAMnC,MAAO,CAAAC,QAAQ,KAAM,iBAAiB,CAiBtC,QAAS,CAAAC,IAAIA,CAAA,CAAG,CACd;AAAA,CAGF,cAAe,CAAAC,GAAGA,CAAC,CACjBC,OAAO,CACPC,IAAI,CACJ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AI,CAAC,EAAE,CAAC,CACf,CACF,CAAC,CACH,CAAC,CAAC,CAEFO,OAAO,CAACJ,IAAI,GAAG,CAAEL,MAAM,CAAEF,MAAO,CAAmB,CAAC,CACtD,CAEAW,OAAO,CAACC,EAAE,CAAC,SAAS,CAAGC,OAAgB,EAAK,CAC1C,IAAK,CAAA/B,GAAG,CAAC+B,OAAO,CAAC,CACnB,CAAC,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"ssr.js","names":["readFileSync","registerHooks","basename","dirname","resolve","fileURLToPath","transformSync","ssrFactory","noop","run","options","root","ssrRequest","testFolder","webpackConfig","load","url","context","nextLoad","startsWith","includes","match","path","code","cwd","envName","babelEnv","filename","format","shortCircuit","source","entry","p","babelModule","module","__esModule","default","exportName","entryExportName","Application","renderer","status","csrfToken","markup","Promise","done","fail","cookie","send","set","value","error","process","on","message"],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/ssr.ts"],"sourcesContent":["/* eslint-disable import/dynamic-import-chunkname, import/no-extraneous-dependencies */\n\nimport { readFileSync } from 'node:fs';\nimport { registerHooks } from 'node:module';\nimport { basename, dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { Request, Response } from 'express';\nimport type { ReactNode } from 'react';\nimport type { Configuration } from 'webpack';\n\nimport { transformSync } from '@babel/core';\n\nimport ssrFactory from 'server/renderer';\n\nexport type LaunchT = {\n // TODO: Should it be typed as the renderer's options type?\n options: Record<string, unknown>;\n\n root: string;\n ssrRequest: object;\n testFolder: string;\n webpackConfig: Configuration;\n};\n\nexport type ResultT = {\n markup: string;\n status: number;\n};\n\nfunction noop() {\n // NOOP\n}\n\nasync function run({\n options,\n root,\n ssrRequest,\n testFolder,\n webpackConfig,\n}: LaunchT) {\n // NOTE: It looks like @babel/register does not work for us here, because\n // it only supports transpiling of modules loaded with require(), so here\n // is, presumably, a temporary workaround relying on the new NodeJS module\n // API, and Babel's core, to transpile all modules loaded further into\n // CommonJS. I guess, later we'll be able to get rid of this, as Babel\n // register supports runtime transformation of modules loaded with import().\n registerHooks({\n load(url, context, nextLoad) {\n if (\n url.startsWith('file://')\n && !url.includes('/node_modules/')\n && !url.includes('/config/babel/')\n && url.match(/\\.(js|jsx|ts|tsx|svg)$/)\n ) {\n const path = fileURLToPath(url);\n let code = readFileSync(path, 'utf8');\n code = transformSync(code, {\n cwd: dirname(path),\n envName: options.babelEnv as string,\n filename: basename(path),\n root,\n })?.code ?? '';\n return {\n format: 'commonjs',\n shortCircuit: true,\n source: code,\n };\n }\n\n return nextLoad(url, context);\n },\n });\n\n if (options.entry) {\n const p = resolve(testFolder, options.entry as string);\n const babelModule = await import(p) as NodeJS.Module;\n\n // TODO: This is basically a hotfix hack, which works both for the library\n // itself, and for dependent projects... (those tested so far). It sure has\n // to be reworked later.\n /* eslint-disable no-underscore-dangle */\n const module = (\n '__esModule' in babelModule\n && typeof babelModule.__esModule === 'boolean'\n && babelModule.__esModule\n && 'default' in babelModule\n ? babelModule.default : babelModule\n ) as NodeJS.Module;\n /* eslint-enable no-underscore-dangle */\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n // eslint-disable-next-line no-param-reassign\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n // eslint-disable-next-line no-param-reassign\n } else options.Application = module;\n }\n\n const renderer = ssrFactory(webpackConfig, options);\n let status = 200; // OK\n\n // eslint-disable-next-line no-param-reassign\n (ssrRequest as Request).csrfToken = () => '';\n\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n process.send?.({ markup, status } satisfies ResultT);\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AIA,KAAK,CAAEL,IAAI,CAACK,KAAc,CAAC,CAAC,IAC3B,CAAAN,IAAI,CAAC,EAAE,CAAC,CACf,CACF,CAAC,CACH,CAAC,CAAC,CAEFO,OAAO,CAACJ,IAAI,GAAG,CAAEL,MAAM,CAAEF,MAAO,CAAmB,CAAC,CACtD,CAEAW,OAAO,CAACC,EAAE,CAAC,SAAS,CAAGC,OAAgB,EAAK,CAC1C,IAAK,CAAA7C,GAAG,CAAC6C,OAAO,CAAC,CACnB,CAAC,CAAC","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["mockdate","act","createRoot","render","default","getGlobal","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","undefined","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockAxios","handlers","axios","jest","requireActual","defaults","adapter","config","handler","res","data","headers","status","statusText","console","warn","JSON","stringify","e","mockTimer","time","set","Date","now","advanceTimersByTimeAsync","mount","scene","root","element","document","createElement","body","appendChild","destroy","unmount","remove","snapshot","expect","toMatchSnapshot","options","promise","await","Error","Promise","resolve","then","nodes","asFragment","childNodes","length"],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global jest, document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): string {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: React.ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve) => {\n void promise.then(() => {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n const nodes = res!.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res!);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"6CAAA,2BACA,sDASA,MAAO,CAAAA,QAAQ,KAAM,UAAU,CAC/B,OAA4CC,GAAG,KAAQ,OAAO,CAC9D,OAAoBC,UAAU,KAAQ,kBAAkB,CAExD,OAA4BC,MAAM,KAAQ,wBAAwB,CAElE;AACA;AACA;AACA,GACA,OAASF,GAAG,EAEZ,OAASG,OAAO,GAAI,CAAAC,SAAS,gBAE7BC,MAAM,CAACC,wBAAwB,CAAG,IAAI,CAEtC,KAAM,CAAAC,uBAAuB,CAAGC,OAAO,CAACC,QAAQ,CAEhD;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,cAAcA,CAAA,CAAS,CACrCC,MAAM,CAACC,cAAc,CAACJ,OAAO,CAAE,UAAU,CAAE,CAAEK,KAAK,CAAEC,SAAU,CAAC,CAAC,CAClE,CAEA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,gBAAgBA,CAAA,CAAS,CACvCJ,MAAM,CAACC,cAAc,CAACJ,OAAO,CAAE,UAAU,CAAE,CACzCK,KAAK,CAAEN,uBAAuB,CAC9BS,QAAQ,CAAE,KACZ,CAAC,CAAC,CACJ,CAEA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,WAAWA,CAACC,IAAI,CAAG,CAAC,CAAU,CAC5C,KAAM,CAAAC,CAAC,CAAGD,IAAI,CAACE,QAAQ,CAAC,EAAE,CAAC,CAACC,QAAQ,CAAC,EAAE,CAAE,GAAG,CAAC,CAC7C,MAAO,GAAGF,CAAC,CAACG,KAAK,CAAC,CAAC,CA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,OAA2B,CAC3BW,OAA+B,CACO,CACtC,GAAI,CAAA9B,GAA6B,CAEjC;AACA;AACA;AACA;AACA;AACA;AACA,KAAM,CAAA+B,OAAO,CAAG/D,GAAG,CAAC,IAAM,CACxBgC,GAAG,CAAG9B,MAAM,CAACiD,OAAO,CAAC,CACrB,MAAO,CAAAW,OAAO,EAAEE,KAAK,CACvB,CAAC,CAAC,CAEF,GAAIhC,GAAG,GAAKlB,SAAS,CAAE,KAAM,CAAAmD,KAAK,CAAC,eAAe,CAAC,CACnD,GAAIH,OAAO,EAAEE,KAAK,CAAE,CAClB;AACA;AACA;AACA;AACA,MAAO,IAAI,CAAAE,OAAO,CAAEC,OAAO,EAAK,CAC9B,IAAK,CAAAJ,OAAO,CAACK,IAAI,CAAC,IAAM,CACtB;AACA;AACA,KAAM,CAAAC,KAAK,CAAGrC,GAAG,CAAEsC,UAAU,CAAC,CAAC,CAACC,UAAU,CAC1CX,MAAM,CAACS,KAAK,CAACG,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGH,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC,CAClEM,OAAO,CAACnC,GAAI,CAAC,CACf,CAAC,CAAC,CACJ,CAAC,CAAC,CACJ,CAEA,KAAM,CAAAqC,KAAK,CAAGrC,GAAG,CAACsC,UAAU,CAAC,CAAC,CAACC,UAAU,CACzCX,MAAM,CAACS,KAAK,CAACG,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGH,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC,CAClE,MAAO,CAAA7B,GAAG,CACZ","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["mockdate","act","createRoot","render","default","getGlobal","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","undefined","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockAxios","handlers","axios","jest","requireActual","defaults","adapter","config","handler","res","data","headers","status","statusText","console","warn","JSON","stringify","e","mockTimer","time","set","Date","now","advanceTimersByTimeAsync","mount","scene","root","element","document","createElement","body","appendChild","destroy","unmount","remove","snapshot","expect","toMatchSnapshot","options","promise","await","Error","Promise","resolve","then","nodes","asFragment","childNodes","length"],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global jest, document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): `${string}-${string}-${string}-${string}-${string}` {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: React.ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve) => {\n void promise.then(() => {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n const nodes = res!.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res!);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"6CAAA,2BACA,sDASA,MAAO,CAAAA,QAAQ,KAAM,UAAU,CAC/B,OAA4CC,GAAG,KAAQ,OAAO,CAC9D,OAAoBC,UAAU,KAAQ,kBAAkB,CAExD,OAA4BC,MAAM,KAAQ,wBAAwB,CAElE;AACA;AACA;AACA,GACA,OAASF,GAAG,EAEZ,OAASG,OAAO,GAAI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AM,CAAAC,KAAK,CAAGrC,GAAG,CAAEsC,UAAU,CAAC,CAAC,CAACC,UAAU,CAC1CX,MAAM,CAACS,KAAK,CAACG,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGH,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC,CAClEM,OAAO,CAACnC,GAAI,CAAC,CACf,CAAC,CAAC,CACJ,CAAC,CAAC,CACJ,CAEA,KAAM,CAAAqC,KAAK,CAAGrC,GAAG,CAACsC,UAAU,CAAC,CAAC,CAACC,UAAU,CACzCX,MAAM,CAACS,KAAK,CAACG,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGH,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC,CAClE,MAAO,CAAA7B,GAAG,CACZ","ignoreList":[]}
@@ -9,7 +9,6 @@ const modulesToTransform = [
9
9
  '@dr.pogodin/react-global-state',
10
10
  '@dr.pogodin/react-utils',
11
11
  'lodash-es',
12
- 'uuid',
13
12
  ];
14
13
 
15
14
  module.exports = {
@@ -5,6 +5,8 @@ import { subtle } from 'node:crypto';
5
5
  // eslint-disable-next-line import/no-unassigned-import
6
6
  import 'raf/polyfill';
7
7
 
8
+ import { getMockUuid } from 'utils/jest';
9
+
8
10
  // TODO: This is a temporary polyfill necessary for react-router,
9
11
  // as JSDom does not provide TextEncoder, see:
10
12
  // https://github.com/remix-run/react-router/issues/12363
@@ -19,3 +21,6 @@ if (typeof window !== 'undefined') {
19
21
  window.crypto.subtle = subtle;
20
22
  window.isSecureContext = true;
21
23
  }
24
+
25
+ let state = 0;
26
+ globalThis.crypto.randomUUID = () => getMockUuid(++state);
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.51.1",
2
+ "version": "1.51.3",
3
3
  "bin": {
4
4
  "react-utils-build": "bin/build.js",
5
5
  "react-utils-setup": "bin/setup.js"
@@ -13,7 +13,7 @@
13
13
  "@dr.pogodin/babel-plugin-react-css-modules": "^6.13.9",
14
14
  "@dr.pogodin/csurf": "^1.16.9",
15
15
  "@dr.pogodin/js-utils": "^0.1.6",
16
- "@dr.pogodin/react-global-state": "^0.22.0",
16
+ "@dr.pogodin/react-global-state": "^0.23.0",
17
17
  "@dr.pogodin/react-helmet": "^3.1.1",
18
18
  "@dr.pogodin/react-themes": "^1.10.3",
19
19
  "@jest/environment": "^30.3.0",
@@ -35,13 +35,12 @@
35
35
  "raf": "^3.4.1",
36
36
  "react": "^19.2.5",
37
37
  "react-dom": "^19.2.5",
38
- "react-router": "^7.14.0",
38
+ "react-router": "^7.14.1",
39
39
  "request-ip": "^3.3.0",
40
40
  "rimraf": "^6.1.3",
41
41
  "serialize-javascript": "^7.0.5",
42
42
  "serve-favicon": "^2.5.1",
43
43
  "source-map-support": "^0.5.21",
44
- "uuid": "^13.0.0",
45
44
  "winston": "^3.19.0"
46
45
  },
47
46
  "description": "Collection of generic ReactJS components and utils",
@@ -82,7 +81,7 @@
82
81
  "@types/supertest": "^7.2.0",
83
82
  "@types/webpack": "^5.28.5",
84
83
  "@types/webpack-hot-middleware": "^2.25.12",
85
- "autoprefixer": "^10.4.27",
84
+ "autoprefixer": "^10.5.0",
86
85
  "babel-jest": "^30.3.0",
87
86
  "babel-loader": "^10.1.1",
88
87
  "babel-plugin-add-import-extension": "^1.6.0",
@@ -93,11 +92,11 @@
93
92
  "identity-obj-proxy": "^3.0.0",
94
93
  "jest": "^30.3.0",
95
94
  "jest-environment-jsdom": "^30.3.0",
96
- "memfs": "^4.57.1",
95
+ "memfs": "^4.57.2",
97
96
  "mini-css-extract-plugin": "^2.10.2",
98
97
  "mockdate": "^3.0.5",
99
98
  "nodelist-foreach-polyfill": "^1.2.0",
100
- "postcss": "^8.5.9",
99
+ "postcss": "^8.5.10",
101
100
  "postcss-loader": "^8.2.1",
102
101
  "postcss-scss": "^4.0.9",
103
102
  "pretty": "^2.0.0",
@@ -107,14 +106,14 @@
107
106
  "sass-loader": "^16.0.7",
108
107
  "sitemap": "^9.0.1",
109
108
  "source-map-loader": "^5.0.0",
110
- "stylelint": "^17.7.0",
109
+ "stylelint": "^17.8.0",
111
110
  "stylelint-config-standard-scss": "^17.0.0",
112
111
  "supertest": "^7.2.2",
113
112
  "tsc-alias": "1.8.16",
114
113
  "tstyche": "^7.0.0",
115
114
  "typed-scss-modules": "^8.1.1",
116
115
  "typescript": "^5.9.3",
117
- "webpack": "^5.106.1",
116
+ "webpack": "^5.106.2",
118
117
  "webpack-dev-middleware": "^8.0.3",
119
118
  "webpack-hot-middleware": "^2.26.1",
120
119
  "webpack-merge": "^6.0.1",