@dr.pogodin/react-utils 1.51.0 → 1.51.2

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.
@@ -19,13 +19,29 @@ import "core-js/modules/es.json.parse.js"; /**
19
19
  // we assume development dependencies are available when it is used.
20
20
  /* eslint-disable import/no-extraneous-dependencies */
21
21
  import { fork } from "node:child_process";
22
+ import { access } from "node:fs/promises";
22
23
  import path from "node:path";
23
24
  import JsdomEnv from "jest-environment-jsdom";
24
25
  import { defaults, set } from "lodash-es";
25
26
  import { Volume, createFsFromVolume } from "memfs";
26
27
  import webpack from "webpack";
28
+ import register from "@babel/register/experimental-worker";
27
29
  import { deduceChunkGroups } from "../../../../server/renderer.js";
28
- import { setBuildInfo } from "../../isomorphy/buildInfo.js";
30
+ async function findModule(module) {
31
+ try {
32
+ const res = `${module}.ts`;
33
+ await access(res);
34
+ return res;
35
+ } catch {// NOOP
36
+ }
37
+ try {
38
+ const res = `${module}.js`;
39
+ await access(res);
40
+ return res;
41
+ } catch {// NOOP
42
+ }
43
+ throw Error(`Module "${module}" was not found, neither as TS, nor as JS`);
44
+ }
29
45
  export default class E2eSsrEnv extends JsdomEnv {
30
46
  /**
31
47
  * Loads Webpack config, and exposes it to the environment via global
@@ -76,21 +92,30 @@ export default class E2eSsrEnv extends JsdomEnv {
76
92
  });
77
93
  }
78
94
  async runSsr() {
79
- const cp = fork(`${import.meta.dirname}/ssr.ts`, [], {
80
- // NOTE: This ensures the forked "ssr.ts" module is pre-processed by
81
- // Babel, which is necessary to correctly resolve paths to modules it
82
- // loads, as we rely on Babel aliasing module paths; and we need to have
83
- // a little "register.ts" module (rather than just a command-line argument)
84
- // because we need to specify to Babel that ".ts", ".tsx", etc. files
85
- // need to be processed, in addition to the standard JS modules.
86
- execArgv: ["-r", `${import.meta.dirname}/register.ts`]
95
+ // NOTE: These are TS modules in the source code, and they turn into JS
96
+ // modules in the distributed code, after Babel compilation. As we rely
97
+ // on them for the forked NodeJS process, we need to resolve the correct
98
+ // extentions ourselves (as NodeJS will hit the given paths, without any
99
+ // additional resolutions / transformations).
100
+ const regModulePath = await findModule(`${import.meta.dirname}/register`);
101
+ const ssrModulePath = await findModule(`${import.meta.dirname}/ssr`);
102
+ const cp = fork(ssrModulePath, [], {
103
+ // NOTE: We have to preload this "register" module, to setup Babel
104
+ // transformation for the loaded "ssr.ts" module itself (I believe,
105
+ // it is relevant only when the source code is executed within
106
+ // the library codebase itself, as the distributed code already
107
+ // has "ssr.ts" transpiled).
108
+ execArgv: ["-r", regModulePath]
87
109
  });
88
110
  const optionsString = this.pragmas["ssr-options"];
89
111
  const options = optionsString ? JSON.parse(optionsString) : {};
90
112
  options.buildInfo ??= this.global.buildInfo;
91
113
  if (!this.webpackStats) throw Error("Missing Webpack stats");
92
114
  options.chunkGroups = deduceChunkGroups(this.webpackStats);
93
- return new Promise(resolve => {
115
+ return new Promise((resolve, reject) => {
116
+ cp.on("exit", code => {
117
+ if (code) reject(Error("SSR process crashed"));
118
+ });
94
119
  cp.on("message", message => {
95
120
  this.global.ssrMarkup = message.markup;
96
121
  this.global.ssrOptions = options;
@@ -124,11 +149,50 @@ export default class E2eSsrEnv extends JsdomEnv {
124
149
  this.testFolder = path.dirname(context.testPath);
125
150
  this.withSsr = !pragmas["no-ssr"];
126
151
  this.ssrRequest = request;
127
- this.pragmas = pragmas;
152
+ this.pragmas = pragmas; // The usual "babel-jest" transformation setup does not apply to
153
+ // the environment code and imports from it, this workaround enables it.
154
+ const optionsString = this.pragmas["ssr-options"];
155
+ const options = optionsString ? JSON.parse(optionsString) : {};
156
+ let root;
157
+ switch (options.root) {
158
+ case "TEST":
159
+ root = this.testFolder;
160
+ break;
161
+ default:
162
+ root = process.cwd();
163
+ } // BEWARE: Anything imported prior to this register() call seems to be
164
+ // transpiled again by Babel if loaded after this call. This causes very
165
+ // confusing errors when testing the code dependent on some sort of contexts
166
+ // (because loading a module again effectively creates a new context object,
167
+ // which is not recognized by the code expecting another context instance).
168
+ // That's why below we prefer dynamic imports for some React Utils methods.
169
+ // BEWARE: Although we also do the registration inside SSR testing code,
170
+ // we still need it here to correctly process imported Webpack configurations
171
+ // (which are imported directly from this module).
172
+ register({
173
+ envName: options.babelEnv,
174
+ extensions: [".js", ".jsx", ".ts", ".tsx", ".svg"],
175
+ root
176
+ });
128
177
  }
129
178
  async setup() {
130
179
  await super.setup();
131
- await this.runWebpack();
180
+ await this.runWebpack(); // NOTE: It is possible that the Webpack run above, and the SSR run below
181
+ // load different versions of the same module (CommonJS, and ES), and it may
182
+ // cause very confusing problems (e.g. see:
183
+ // https://github.com/birdofpreyru/react-utils/issues/413).
184
+ // It seems we can't reset the cache of ES modules, and Jest's module reset
185
+ // does not reset modules loaded in this enviroment module, and also only
186
+ // replacing entire cache object by and empty {} seems to help (in contrast
187
+ // to deleting all entries by their keys, as it is done within .teardown()
188
+ // method below). Thus, for now we do this as a hotfix, and we also reset
189
+ // build info to undefined, because ES module version not beeing reset
190
+ // triggers an error on the subsequent test using the environment.
191
+ // TODO: Look for a cleaner solution.
192
+ require.cache = {}; // eslint-disable-next-line import/dynamic-import-chunkname
193
+ const {
194
+ setBuildInfo
195
+ } = await import("../../isomorphy/buildInfo");
132
196
  setBuildInfo(undefined, true);
133
197
  if (this.withSsr) await this.runSsr();
134
198
  this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;
@@ -143,6 +207,7 @@ export default class E2eSsrEnv extends JsdomEnv {
143
207
  Object.keys(require.cache).forEach(key => {
144
208
  delete require.cache[key];
145
209
  });
210
+ register.revert();
146
211
  await super.teardown();
147
212
  }
148
213
  }
@@ -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":";;;0CAAA;AACA;AACA;AACA;AACA;AACA,6CALA,CAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AAEA,SAASA,IAAI,QAAQ,oBAAoB;AACzC,OAAOC,IAAI,MAAM,WAAW;AAE5B,OAAOC,QAAQ,MAAM,wBAAwB;AAC7C,SAASC,QAAQ,EAAEC,GAAG,QAAQ,WAAW;AACzC,SAASC,MAAM,EAAEC,kBAAkB,QAAQ,OAAO;AAClD,OAAOC,OAAO,MAA0C,SAAS;AAOjE,SAASC,iBAAiB;AAAA,SAEjBC,YAAY;AAIrB,eAAe,MAAMC,SAAS,SAASR,QAAS;EAa9C;AACF;AACA;AACA;EACE,MAAcS,iBAAiBA,CAAA,EAAG;IAChC,MAAMC,aAAa,GAAG,IAAI,CAACC,OAAO,CAAC,wBAAwB,CAAW;IAEtE,MAAMC,OAAO,GAAIF,aAAa,GAAGG,IAAI,CAACC,KAAK,CAACJ,aAAa,CAAC,GAAG,CAAC,CACvC;IAEvBT,QAAQ,CAACW,OAAO,EAAE;MAChBG,OAAO,EAAE,IAAI,CAACC,UAAU;MACxBC,EAAE,EAAE,IAAI,CAACC,MAAM,CAACC;IAClB,CAAC,CAAC;IAEF,MAAMC,WAAW,GAAG,IAAI,CAACT,OAAO,CAAC,wBAAwB,CAAW;IAEpE,IAAIU,OAAO,GAAG,MAAM,MAAM,CAAC,2CACzBtB,IAAI,CAACuB,OAAO,CAAC,IAAI,CAACC,OA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C;IACjC,IAAI,CAACqD,UAAU,GAAGK,OAAO;IACzB,IAAI,CAAC1D,OAAO,GAAGA,OAAO;EACxB;EAEA,MAAMgE,KAAKA,CAAA,EAAkB;IAC3B,MAAM,KAAK,CAACA,KAAK,CAAC,CAAC;IACnB,MAAM,IAAI,CAAC9C,UAAU,CAAC,CAAC;IAEvBtB,YAAY,CAACqE,SAAS,EAAE,IAAI,CAAC;IAE7B,IAAI,IAAI,CAACF,OAAO,EAAE,MAAM,IAAI,CAAC7B,MAAM,CAAC,CAAC;IACrC,IAAI,CAAC3B,MAAM,CAAC2D,6BAA6B,GAAG,IAAI;EAClD;EAEA,MAAMC,QAAQA,CAAA,EAAkB;IAC9B,OAAO,IAAI,CAAC5D,MAAM,CAAC2D,6BAA6B,CAEhD;IACA;IACA;IACA;IACA;IACA;IACAE,MAAM,CAACC,IAAI,CAACC,OAAO,CAACC,KAAK,CAAC,CAACC,OAAO,CAAEC,GAAG,IAAK;MAC1C,OAAOH,OAAO,CAACC,KAAK,CAACE,GAAG,CAAC;IAC3B,CAAC,CAAC;IAEF,MAAM,KAAK,CAACN,QAAQ,CAAC,CAAC;EACxB;AACF","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":";;;0CAAA;AACA;AACA;AACA;AACA;AACA,6CALA,CAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA;AACA;AACA;AAEA,SAASA,IAAI,QAAQ,oBAAoB;AACzC,SAASC,MAAM,QAAQ,kBAAkB;AACzC,OAAOC,IAAI,MAAM,WAAW;AAE5B,OAAOC,QAAQ,MAAM,wBAAwB;AAC7C,SAASC,QAAQ,EAAEC,GAAG,QAAQ,WAAW;AACzC,SAASC,MAAM,EAAEC,kBAAkB,QAAQ,OAAO;AAClD,OAAOC,OAAO,MAA0C,SAAS;AAEjE,OAAOC,QAAQ,MAAM,qCAAqC;AAO1D,SAASC,iBAAiB;AAI1B,eAAeC,UAAUA,CAACC,MAAc,EAAmB;EACzD,IAAI;IACF,MAAMC,GAAG,GAAG,GAAGD,MAAM,KAAK;IAC1B,MAAMX,MAAM,CAACY,GAAG,CAAC;IACjB,OAAOA,GAAG;EACZ,CAAE,OAAM,CACN;EAAA;EAGF,IAAI;IACF,MAAMA,GAAG,GAAG,GAAGD,MAAM,KAAK;IAC1B,MAAMX,MAAM,CAACY,GAAG,CAAC;IACjB,OAAOA,GAAG;EACZ,CAAE,OAAM,CACN;EAAA;EAGF,MAAMC,KAAK,CAAC,WAAWF,MAAM,2CAA2C,CAAC;AAC3E;AAEA,eAAe,MAAMG,SAAS,SAASZ,QAAS;EAa9C;AACF;AACA;AACA;EACE,MAAca,iBAAiBA,CAAA,EAAG;IAChC,MAAMC,aAAa,GAAG,IAAI,CAACC,OAAO,CAAC,wBAAwB,CAAW;IAEtE,MAAMC,OAAO,GAAIF,aAAa,GAAGG,IAAI,CAACC,KAAK,CAACJ,aAAa,CAAC,GAAG,CAAC,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ACF,CAAC,CAAC;EACJ;EAEA,MAAMiB,KAAKA,CAAA,EAAkB;IAC3B,MAAM,KAAK,CAACA,KAAK,CAAC,CAAC;IACnB,MAAM,IAAI,CAACpD,UAAU,CAAC,CAAC,CAEvB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACAqD,OAAO,CAACC,KAAK,GAAG,CAAC,CAAC,CAElB;IACA,MAAM;MAAEC;IAAa,CAAC,GAAG,MAAM,MAAM,4BAA4B,CAAC;IAClEA,YAAY,CAACC,SAAS,EAAE,IAAI,CAAC;IAE7B,IAAI,IAAI,CAACR,OAAO,EAAE,MAAM,IAAI,CAACjC,MAAM,CAAC,CAAC;IACrC,IAAI,CAAC1B,MAAM,CAACoE,6BAA6B,GAAG,IAAI;EAClD;EAEA,MAAMC,QAAQA,CAAA,EAAkB;IAC9B,OAAO,IAAI,CAACrE,MAAM,CAACoE,6BAA6B,CAEhD;IACA;IACA;IACA;IACA;IACA;IACAE,MAAM,CAACC,IAAI,CAACP,OAAO,CAACC,KAAK,CAAC,CAACO,OAAO,CAAEC,GAAG,IAAK;MAC1C,OAAOT,OAAO,CAACC,KAAK,CAACQ,GAAG,CAAC;IAC3B,CAAC,CAAC;IACFzF,QAAQ,CAAC0F,MAAM,CAAC,CAAC;IAEjB,MAAM,KAAK,CAACL,QAAQ,CAAC,CAAC;EACxB;AACF","ignoreList":[]}
@@ -1,5 +1,9 @@
1
- /* eslint-disable import/dynamic-import-chunkname, import/no-extraneous-dependencies */import { resolve } from "node:path";
2
- import register from "@babel/register";
1
+ /* eslint-disable import/dynamic-import-chunkname, import/no-extraneous-dependencies */import { readFileSync } from "node:fs";
2
+ import { registerHooks } from "node:module";
3
+ import { basename, dirname, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { transformSync } from "@babel/core";
6
+ import ssrFactory from "../../../../server/renderer.js";
3
7
  function noop() {// NOOP
4
8
  }
5
9
  async function run({
@@ -9,23 +13,45 @@ async function run({
9
13
  testFolder,
10
14
  webpackConfig
11
15
  }) {
12
- register({
13
- envName: options.babelEnv,
14
- extensions: [".js", ".jsx", ".ts", ".tsx", ".svg"],
15
- root
16
+ // NOTE: It looks like @babel/register does not work for us here, because
17
+ // it only supports transpiling of modules loaded with require(), so here
18
+ // is, presumably, a temporary workaround relying on the new NodeJS module
19
+ // API, and Babel's core, to transpile all modules loaded further into
20
+ // CommonJS. I guess, later we'll be able to get rid of this, as Babel
21
+ // register supports runtime transformation of modules loaded with import().
22
+ registerHooks({
23
+ load(url, context, nextLoad) {
24
+ if (url.startsWith("file://") && !url.includes("/node_modules/") && !url.includes("/config/babel/") && url.match(/\.(js|jsx|ts|tsx|svg)$/)) {
25
+ const path = fileURLToPath(url);
26
+ let code = readFileSync(path, "utf8");
27
+ code = transformSync(code, {
28
+ cwd: dirname(path),
29
+ envName: options.babelEnv,
30
+ filename: basename(path),
31
+ root
32
+ })?.code ?? "";
33
+ return {
34
+ format: "commonjs",
35
+ shortCircuit: true,
36
+ source: code
37
+ };
38
+ }
39
+ return nextLoad(url, context);
40
+ }
16
41
  });
17
42
  if (options.entry) {
18
43
  const p = resolve(testFolder, options.entry);
19
- const module = await import(p);
44
+ const babelModule = await import(p); // TODO: This is basically a hotfix hack, which works both for the library
45
+ // itself, and for dependent projects... (those tested so far). It sure has
46
+ // to be reworked later.
47
+ /* eslint-disable no-underscore-dangle */
48
+ const module = "__esModule" in babelModule && typeof babelModule.__esModule === "boolean" && babelModule.__esModule && "default" in babelModule ? babelModule.default : babelModule; /* eslint-enable no-underscore-dangle */
20
49
  const exportName = options.entryExportName || "default";
21
50
  if (exportName in module) {
22
51
  // eslint-disable-next-line no-param-reassign
23
- options.Application = module[exportName];
24
- }
52
+ options.Application = module[exportName]; // eslint-disable-next-line no-param-reassign
53
+ } else options.Application = module;
25
54
  }
26
- const {
27
- default: ssrFactory
28
- } = await import("../../../../server/renderer");
29
55
  const renderer = ssrFactory(webpackConfig, options);
30
56
  let status = 200; // OK
31
57
  // eslint-disable-next-line no-param-reassign
@@ -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,SAASA,OAAO,QAAQ,WAAW;AAMnC,OAAOC,QAAQ,MAAM,iBAAiB;AAiBtC,SAASC,IAAIA,CAAA,EAAG,CACd;AAAA;AAGF,eAAeC,GAAGA,CAAC;EACjBC,OAAO;EACPC,IAAI;EACJC,UAAU;EACVC,UAAU;EACVC;AACO,CAAC,EAAE;EACVP,QAAQ,CAAC;IACPQ,OAAO,EAAEL,OAAO,CAACM,QAAkB;IACnCC,UAAU,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC;IAClDN;EACF,CAAC,CAAC;EAEF,IAAID,OAAO,CAACQ,KAAK,EAAE;IACjB,MAAMC,CAAC,GAAGb,OAAO,CAACO,UAAU,EAAEH,OAAO,CAACQ,KAAe,CAAC;IACtD,MAAME,MAAM,GAAG,MAAM,MAAM,CAACD,CAAC,CAAkB;IAE/C,MAAME,UAAU,GAAIX,OAAO,CAACY,eAAe,IAAe,SAAS;IACnE,IAAID,UAAU,IAAID,MAAM,EAAE;MACxB;MACAV,OAAO,CAACa,WAAW,GACjBH,MAAM,CACNC,UAAU,CAAc;IAC5B;EACF;EAEA,MAAM;IAAEG,OAAO,EAAEC;EAAW,CAAC,GAAG,MAAM,MAAM,8BAAkB,CAAC;EAE/D,MAAMC,QAAQ,GAAGD,UAAU,CAACX,aAAa,EAAEJ,OAAO,CAAC;EACnD,IAAIiB,MAAM,GAAG,GAAG,CAAE;EAElB;EACCf,UAAU,CAAagB,SAAS,GAAG,MAAM,EAAE;EAE5C,MAAMC,MAAM,GAAG,MAAM,IAAIC,OAAO,CAAS,CAACC,IAAI,EAAEC,IAAI,KAAK;IACvD,KAAKN,QAAQ,CACXd,UAAU;IAEV;IACA;IACA;IACC;MACCqB,MAAM,EAAEzB,IAAI;MACZ0B,IAAI,EAAEH,IAAI;MACVI,GAAG,EAAE3B,IAAI;MACTmB,MAAM,EAAGS,KAAa,IAAK;QACzBT,MAAM,GAAGS,KAAK;MAChB;IACF,CAAC,EAEAC,KAAK,IAAK;MACT;MACA;MACA,IAAIA,KAAK,EAAEL,IAAI,CAACK,KAAc,CAAC,CAAC,KAC3BN,IAAI,CAAC,EAAE,CAAC;IACf,CACF,CAAC;EACH,CAAC,CAAC;EAEFO,OAAO,CAACJ,IAAI,GAAG;IAAEL,MAAM;IAAEF;EAAO,CAAmB,CAAC;AACtD;AAEAW,OAAO,CAACC,EAAE,CAAC,SAAS,EAAGC,OAAgB,IAAK;EAC1C,KAAK/B,GAAG,CAAC+B,OAAO,CAAC;AACnB,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);\n}\n\nprocess.on('message', (message: LaunchT) => {\n void run(message);\n});\n"],"mappings":"AAAA,uFAEA,SAASA,YAAY,QAAQ,SAAS;AACtC,SAASC,aAAa,QAAQ,aAAa;AAC3C,SAASC,QAAQ,EAAEC,OAAO,EAAEC,OAAO,QAAQ,WAAW;AACtD,SAASC,aAAa,QAAQ,UAAU;AAMxC,SAASC,aAAa,QAAQ,aAAa;AAE3C,OAAOC,UAAU;AAiBjB,SAASC,IAAIA,CAAA,EAAG,CACd;AAAA;AAGF,eAAeC,GAAGA,CAAC;EACjBC,OAAO;EACPC,IAAI;EACJC,UAAU;EACVC,UAAU;EACVC;AACO,CAAC,EAAE;EACV;EACA;EACA;EACA;EACA;EACA;EACAb,aAAa,CAAC;IACZc,IAAIA,CAACC,GAAG,EAAEC,OAAO,EAAEC,QAAQ,EAAE;MAC3B,IACEF,GAAG,CAACG,UAAU,CAAC,SAAS,CAAC,IACtB,CAACH,GAAG,CAACI,QAAQ,CAAC,gBAAgB,CAAC,IAC/B,CAACJ,GAAG,CAACI,QAAQ,CAAC,gBAAgB,CAAC,IAC/BJ,GAAG,CAACK,KAAK,CAAC,wBAAwB,CAAC,EACtC;QACA,MAAMC,IAAI,GAAGjB,aAAa,CAACW,GAAG,CAAC;QAC/B,IAAIO,IAAI,GAAGvB,YAAY,CAACsB,IAAI,EAAE,MAAM,CAAC;QACrCC,IAAI,GAAGjB,aAAa,CAACiB,IAAI,EAAE;UACzBC,GAAG,EAAErB,OAAO,CAACmB,IAAI,CAAC;UACl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ACZwC,IAAI,EAAEH,IAAI;MACVI,GAAG,EAAEzC,IAAI;MACTiC,MAAM,EAAGS,KAAa,IAAK;QACzBT,MAAM,GAAGS,KAAK;MAChB;IACF,CAAC,EAEAC,KAAK,IAAK;MACT;MACA;MACA,IAAIA,KAAK,EAAEL,IAAI,CAACK,KAAc,CAAC,CAAC,KAC3BN,IAAI,CAAC,EAAE,CAAC;IACf,CACF,CAAC;EACH,CAAC,CAAC;EAEFO,OAAO,CAACJ,IAAI,GAAG;IAAEL,MAAM;IAAEF;EAAO,CAAmB,CAAC;AACtD;AAEAW,OAAO,CAACC,EAAE,CAAC,SAAS,EAAGC,OAAgB,IAAK;EAC1C,KAAK7C,GAAG,CAAC6C,OAAO,CAAC;AACnB,CAAC,CAAC","ignoreList":[]}
@@ -14,7 +14,9 @@ import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.iterat
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.js";import{setBuildInfo}from"../../isomorphy/buildInfo.js";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.js";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":"4LAAA;AACA;AACA;AACA;AACA;AACA,GAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;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E,IAAI,CAAC,CAE7B,GAAI,IAAI,CAACF,OAAO,CAAE,KAAM,KAAI,CAAC7B,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC3B,MAAM,CAAC2D,6BAA6B,CAAG,IAAI,CAClD,CAEA,KAAM,CAAAC,QAAQA,CAAA,CAAkB,CAC9B,MAAO,KAAI,CAAC5D,MAAM,CAAC2D,6BAA6B,CAEhD;AACA;AACA;AACA;AACA;AACA;AACAE,MAAM,CAACC,IAAI,CAACC,OAAO,CAACC,KAAK,CAAC,CAACC,OAAO,CAAEC,GAAG,EAAK,CAC1C,MAAO,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":"4LAAA;AACA;AACA;AACA;AACA;AACA,GAEA;AACA;AACA;AAC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AM,CAAC,CAClDhB,IACF,CAAC,CAAC,CACJ,CAEA,KAAM,CAAAiB,KAAKA,CAAA,CAAkB,CAC3B,KAAM,MAAK,CAACA,KAAK,CAAC,CAAC,CACnB,KAAM,KAAI,CAACpD,UAAU,CAAC,CAAC,CAEvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAqD,OAAO,CAACC,KAAK,CAAG,CAAC,CAAC,CAElB;AACA,KAAM,CAAEC,YAAa,CAAC,CAAG,KAAM,OAAM,4BAA4B,CAAC,CAClEA,YAAY,CAACC,SAAS,CAAE,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.js";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,CACJC,UAAU,CACVC,UAAU,CACVC,aACO,CAAC,CAAE,CACVP,QAAQ,CAAC,CACPQ,OAAO,CAAEL,OAAO,CAACM,QAAkB,CACnCC,UAAU,CAAE,CAAC,KAAK,CAAE,MAAM,CAAE,KAAK,CAAE,MAAM,CAAE,MAAM,CAAC,CAClDN,IACF,CAAC,CAAC,CAEF,GAAID,OAAO,CAACQ,KAAK,CAAE,CACjB,KAAM,CAAAC,CAAC,CAAGb,OAAO,CAACO,UAAU,CAAEH,OAAO,CAACQ,KAAe,CAAC,CACtD,KAAM,CAAAE,MAAM,CAAG,KAAM,OAAM,CAACD,CAAC,CAAkB,CAE/C,KAAM,CAAAE,UAAU,CAAIX,OAAO,CAACY,eAAe,EAAe,SAAS,CACnE,GAAID,UAAU,GAAI,CAAAD,MAAM,CAAE,CACxB;AACAV,OAAO,CAACa,WAAW,CACjBH,MAAM,CACNC,UAAU,CAAc,CAC5B,CACF,CAEA,KAAM,CAAEG,OAAO,CAAEC,UAAW,CAAC,CAAG,KAAM,OAAM,8BAAkB,CAAC,CAE/D,KAAM,CAAAC,QAAQ,CAAGD,UAAU,CAACX,aAAa,CAAEJ,OAAO,CAAC,CACnD,GAAI,CAAAiB,MAAM,CAAG,GAAG,CAAE;AAElB;AACCf,UAAU,CAAagB,SAAS,CAAG,IAAM,EAAE,CAE5C,KAAM,CAAAC,MAAM,CAAG,KAAM,IAAI,CAAAC,OAAO,CAAS,CAACC,IAAI,CAAEC,IAAI,GAAK,CACvD,IAAK,CAAAN,QAAQ,CACXd,UAAU,CAEV;AACA;AACA;AACC,CACCqB,MAAM,CAAEzB,IAAI,CACZ0B,IAAI,CAAEH,IAAI,CACVI,GAAG,CAAE3B,IAAI,CACTmB,MAAM,CAAGS,KAAa,EAAK,CACzBT,MAAM,CAAGS,KAAK,CAChB,CACF,CAAC,CAEAC,KAAK,EAAK,CACT;AACA;AACA,GAAIA,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,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);\n}\n\nprocess.on('message', (message: LaunchT) => {\n void run(message);\n});\n"],"mappings":"AAAA,uFAEA,OAASA,YAAY,KAAQ,SAAS,CACtC,OAASC,aAAa,KAAQ,aAAa,CAC3C,OAASC,QAAQ,CAAEC,OAAO,CAAEC,OAAO,KAAQ,WAAW,CACtD,OAASC,aAAa,KAAQ,UAAU,CAMxC,OAASC,aAAa,KAAQ,aAAa,CAE3C,MAAO,CAAAC,UAAU,sCAiBjB,QAAS,CAAAC,IAAIA,CAAA,CAAG,CACd;AAAA,CAGF,cAAe,CAAAC,GAAGA,CAAC,CACjBC,OAAO,CACPC,IAAI,CACJC,UAAU,CACVC,UAAU,CACVC,aACO,CAAC,CAAE,CACV;AACA;AACA;AACA;AACA;AACA;AACAb,aAAa,CAAC,CACZc,IAAIA,CAACC,GAAG,CAAEC,OAAO,CAAEC,QAAQ,CAAE,CAC3B,GACEF,GAAG,CAACG,UAAU,CAAC,SAAS,CAAC,EACtB,CAACH,GAAG,CAACI,QAAQ,CAAC,gBAAgB,CAAC,EAC/B,CAACJ,GAAG,CAACI,QAAQ,CAAC,gBAAgB,CAAC,EAC/BJ,GAAG,CAACK,KAAK,CAAC,wBAAwB,CAAC,CACtC,CACA,KAAM,CAAAC,IAAI,CAAGjB,aAAa,CAACW,GAAG,CAAC,CAC/B,GAAI,CAAAO,IAAI,CAAGvB,YAAY,CAACsB,IAAI,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B,SAAS,CAAG,IAAM,EAAE,CAE5C,KAAM,CAAAC,MAAM,CAAG,KAAM,IAAI,CAAAC,OAAO,CAAS,CAACC,IAAI,CAAEC,IAAI,GAAK,CACvD,IAAK,CAAAN,QAAQ,CACX5B,UAAU,CAEV;AACA;AACA;AACC,CACCmC,MAAM,CAAEvC,IAAI,CACZwC,IAAI,CAAEH,IAAI,CACVI,GAAG,CAAEzC,IAAI,CACTiC,MAAM,CAAGS,KAAa,EAAK,CACzBT,MAAM,CAAGS,KAAK,CAChB,CACF,CAAC,CAEAC,KAAK,EAAK,CACT;AACA;AACA,GAAIA,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":[]}
@@ -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;AACA,KACE,KAAc,CAAAS,iBAAiBA,CAAA,CAAG,CAChC,KAAM,CAAAC,aAAa,CAAG,IAAI,CAACC,OAAO,CAAC,wBAAwB,CAAW,CAEtE,KAAM,CAAAC,OAAO,CAAIF,aAAa,CAAGG,IAAI,CAACC,KAAK,CAACJ,aAAa,CAAC,CAAG,CAAC,CACvC,CAEvBT,QAAQ,CAACW,OAAO,CAAE,CAChBG,OAAO,CAAE,IAAI,CAACC,UAAU,CACxBC,EAAE,CAAE,IAAI,CAACC,MAAM,CAACC,eAClB,CAAC,CAAC,CAEF,KAAM,CAAAC,WAAW,CAAG,IAAI,CAACT,OAAO,CAAC,wBAAwB,CAAW,CAEpE,GAAI,CAAAU,OAAO,CAAG,KAAM,OAAM,CAAC,2CACzBtB,IAAI,CAACuB,OAAO,CAAC,IAAI,CAACC,OAAO,CAAEH,WAAW,CACxC,CAEE,CAEFC,OAAO,CAAG,SAAS,EAAI,CAAAA,OAAO,CAAGA,OAAO,CAACG,OAAO,CAAGH,OAAO,CAE1D,IAAI,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AAGK,OAAO,CACzB,IAAI,CAAC1D,OAAO,CAAGA,OAAO,CACxB,CAEA,KAAM,CAAAgE,KAAKA,CAAA,CAAkB,CAC3B,KAAM,MAAK,CAACA,KAAK,CAAC,CAAC,CACnB,KAAM,KAAI,CAAC9C,UAAU,CAAC,CAAC,CAEvBtB,YAAY,CAACqE,SAAS,CAAE,IAAI,CAAC,CAE7B,GAAI,IAAI,CAACF,OAAO,CAAE,KAAM,KAAI,CAAC7B,MAAM,CAAC,CAAC,CACrC,IAAI,CAAC3B,MAAM,CAAC2D,6BAA6B,CAAG,IAAI,CAClD,CAEA,KAAM,CAAAC,QAAQA,CAAA,CAAkB,CAC9B,MAAO,KAAI,CAAC5D,MAAM,CAAC2D,6BAA6B,CAEhD;AACA;AACA;AACA;AACA;AACA;AACAE,MAAM,CAACC,IAAI,CAACC,OAAO,CAACC,KAAK,CAAC,CAACC,OAAO,CAAEC,GAAG,EAAK,CAC1C,MAAO,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,OAASC,iBAAiB,mCAI1B,cAAe,CAAAC,UAAUA,CAACC,MAAc,CAAmB,CACzD,GAAI,CACF,KAAM,CAAAC,GAAG,CAAG,GAAGD,MAAM,KAAK,CAC1B,KAAM,CAAAX,MAAM,CAACY,GAAG,CAAC,CACjB,MAAO,CAAAA,GAAG,CACZ,CAAE,KAAM,CACN;AAAA,CAGF,GAAI,CACF,KAAM,CAAAA,GAAG,CAAG,GAAGD,MAAM,KAAK,CAC1B,KAAM,CAAAX,MAAM,CAACY,GAAG,CAAC,CACjB,MAAO,CAAAA,GAAG,CACZ,CAAE,KAAM,CACN;AAAA,CAGF,KAAM,CAAAC,KAAK,CAAC,WAAWF,MAAM,2CAA2C,CAAC,CAC3E,CAEA,cAAe,MAAM,CAAAG,SAAS,QAAS,CAAAZ,QAAS,CAa9C;AACF;AACA;AACA,KACE,KAAc,CAAAa,iBAAiBA,CAAA,CAAG,CAChC,KAAM,CAAAC,aAAa,CAAG,IAAI,CAACC,OAAO,CAAC,wBAAwB,CAAW,CAEtE,K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OAAO,CAACC,GAAG,CAAC,CAAC,CAC/B,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAhE,QAAQ,CAAC,CACP4E,OAAO,CAAElE,OAAO,CAACmE,QAAkB,CACnCC,UAAU,CAAE,CAAC,KAAK,CAAE,MAAM,CAAE,KAAK,CAAE,MAAM,CAAE,MAAM,CAAC,CAClDhB,IACF,CAAC,CAAC,CACJ,CAEA,KAAM,CAAAiB,KAAKA,CAAA,CAAkB,CAC3B,KAAM,MAAK,CAACA,KAAK,CAAC,CAAC,CACnB,KAAM,KAAI,CAACpD,UAAU,CAAC,CAAC,CAEvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAqD,OAAO,CAACC,KAAK,CAAG,CAAC,CAAC,CAElB;AACA,KAAM,CAAEC,YAAa,CAAC,CAAG,KAAM,OAAM,4BAA4B,CAAC,CAClEA,YAAY,CAACC,SAAS,CAAE,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,CACJC,UAAU,CACVC,UAAU,CACVC,aACO,CAAC,CAAE,CACVP,QAAQ,CAAC,CACPQ,OAAO,CAAEL,OAAO,CAACM,QAAkB,CACnCC,UAAU,CAAE,CAAC,KAAK,CAAE,MAAM,CAAE,KAAK,CAAE,MAAM,CAAE,MAAM,CAAC,CAClDN,IACF,CAAC,CAAC,CAEF,GAAID,OAAO,CAACQ,KAAK,CAAE,CACjB,KAAM,CAAAC,CAAC,CAAGb,OAAO,CAACO,UAAU,CAAEH,OAAO,CAACQ,KAAe,CAAC,CACtD,KAAM,CAAAE,MAAM,CAAG,KAAM,OAAM,CAACD,CAAC,CAAkB,CAE/C,KAAM,CAAAE,UAAU,CAAIX,OAAO,CAACY,eAAe,EAAe,SAAS,CACnE,GAAID,UAAU,GAAI,CAAAD,MAAM,CAAE,CACxB;AACAV,OAAO,CAACa,WAAW,CACjBH,MAAM,CACNC,UAAU,CAAc,CAC5B,CACF,CAEA,KAAM,CAAEG,OAAO,CAAEC,UAAW,CAAC,CAAG,KAAM,OAAM,8BAAkB,CAAC,CAE/D,KAAM,CAAAC,QAAQ,CAAGD,UAAU,CAACX,aAAa,CAAEJ,OAAO,CAAC,CACnD,GAAI,CAAAiB,MAAM,CAAG,GAAG,CAAE;AAElB;AACCf,UAAU,CAAagB,SAAS,CAAG,IAAM,EAAE,CAE5C,KAAM,CAAAC,MAAM,CAAG,KAAM,IAAI,CAAAC,OAAO,CAAS,CAACC,IAAI,CAAEC,IAAI,GAAK,CACvD,IAAK,CAAAN,QAAQ,CACXd,UAAU,CAEV;AACA;AACA;AACC,CACCqB,MAAM,CAAEzB,IAAI,CACZ0B,IAAI,CAAEH,IAAI,CACVI,GAAG,CAAE3B,IAAI,CACTmB,MAAM,CAAGS,KAAa,EAAK,CACzBT,MAAM,CAAGS,KAAK,CAChB,CACF,CAAC,CAEAC,KAAK,EAAK,CACT;AACA;AACA,GAAIA,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,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);\n}\n\nprocess.on('message', (message: LaunchT) => {\n void run(message);\n});\n"],"mappings":"AAAA,uFAEA,OAASA,YAAY,KAAQ,SAAS,CACtC,OAASC,aAAa,KAAQ,aAAa,CAC3C,OAASC,QAAQ,CAAEC,OAAO,CAAEC,OAAO,KAAQ,WAAW,CACtD,OAASC,aAAa,KAAQ,UAAU,CAMxC,OAASC,aAAa,KAAQ,aAAa,CAE3C,MAAO,CAAAC,UAAU,mCAiBjB,QAAS,CAAAC,IAAIA,CAAA,CAAG,CACd;AAAA,CAGF,cAAe,CAAAC,GAAGA,CAAC,CACjBC,OAAO,CACPC,IAAI,CACJC,UAAU,CACVC,UAAU,CACVC,aACO,CAAC,CAAE,CACV;AACA;AACA;AACA;AACA;AACA;AACAb,aAAa,CAAC,CACZc,IAAIA,CAACC,GAAG,CAAEC,OAAO,CAAEC,QAAQ,CAAE,CAC3B,GACEF,GAAG,CAACG,UAAU,CAAC,SAAS,CAAC,EACtB,CAACH,GAAG,CAACI,QAAQ,CAAC,gBAAgB,CAAC,EA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,CAC1B;AACF,CAAC,IAAM,CAAA3B,OAAO,CAAC6B,WAAW,CAAGL,MAAM,CACrC,CAEA,KAAM,CAAAM,QAAQ,CAAGjC,UAAU,CAACO,aAAa,CAAEJ,OAAO,CAAC,CACnD,GAAI,CAAA+B,MAAM,CAAG,GAAG,CAAE;AAElB;AACC7B,UAAU,CAAa8B,SAAS,CAAG,IAAM,EAAE,CAE5C,KAAM,CAAAC,MAAM,CAAG,KAAM,IAAI,CAAAC,OAAO,CAAS,CAACC,IAAI,CAAEC,IAAI,GAAK,CACvD,IAAK,CAAAN,QAAQ,CACX5B,UAAU,CAEV;AACA;AACA;AACC,CACCmC,MAAM,CAAEvC,IAAI,CACZwC,IAAI,CAAEH,IAAI,CACVI,GAAG,CAAEzC,IAAI,CACTiC,MAAM,CAAGS,KAAa,EAAK,CACzBT,MAAM,CAAGS,KAAK,CAChB,CACF,CAAC,CAEAC,KAAK,EAAK,CACT;AACA;AACA,GAAIA,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":[]}
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.51.0",
2
+ "version": "1.51.2",
3
3
  "bin": {
4
4
  "react-utils-build": "bin/build.js",
5
5
  "react-utils-setup": "bin/setup.js"
@@ -35,7 +35,7 @@
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",
@@ -82,7 +82,7 @@
82
82
  "@types/supertest": "^7.2.0",
83
83
  "@types/webpack": "^5.28.5",
84
84
  "@types/webpack-hot-middleware": "^2.25.12",
85
- "autoprefixer": "^10.4.27",
85
+ "autoprefixer": "^10.5.0",
86
86
  "babel-jest": "^30.3.0",
87
87
  "babel-loader": "^10.1.1",
88
88
  "babel-plugin-add-import-extension": "^1.6.0",
@@ -107,14 +107,14 @@
107
107
  "sass-loader": "^16.0.7",
108
108
  "sitemap": "^9.0.1",
109
109
  "source-map-loader": "^5.0.0",
110
- "stylelint": "^17.6.0",
110
+ "stylelint": "^17.7.0",
111
111
  "stylelint-config-standard-scss": "^17.0.0",
112
112
  "supertest": "^7.2.2",
113
113
  "tsc-alias": "1.8.16",
114
114
  "tstyche": "^7.0.0",
115
115
  "typed-scss-modules": "^8.1.1",
116
116
  "typescript": "^5.9.3",
117
- "webpack": "^5.106.0",
117
+ "webpack": "^5.106.1",
118
118
  "webpack-dev-middleware": "^8.0.3",
119
119
  "webpack-hot-middleware": "^2.26.1",
120
120
  "webpack-merge": "^6.0.1",