@nx/jest 22.7.0-beta.11 → 22.7.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nx/jest",
3
- "version": "22.7.0-beta.11",
3
+ "version": "22.7.0-beta.13",
4
4
  "private": false,
5
5
  "description": "The Nx Plugin for Jest contains executors and generators allowing your workspace to use the powerful Jest testing capabilities.",
6
6
  "repository": {
@@ -38,8 +38,8 @@
38
38
  "dependencies": {
39
39
  "@jest/reporters": "^30.0.2",
40
40
  "@jest/test-result": "^30.0.2",
41
- "@nx/devkit": "22.7.0-beta.11",
42
- "@nx/js": "22.7.0-beta.11",
41
+ "@nx/devkit": "22.7.0-beta.13",
42
+ "@nx/js": "22.7.0-beta.13",
43
43
  "@phenomnomnominal/tsquery": "~6.1.4",
44
44
  "identity-obj-proxy": "3.0.0",
45
45
  "jest-config": "^30.0.2",
@@ -53,7 +53,7 @@
53
53
  "yargs-parser": "21.1.1"
54
54
  },
55
55
  "devDependencies": {
56
- "nx": "22.7.0-beta.11"
56
+ "nx": "22.7.0-beta.13"
57
57
  },
58
58
  "publishConfig": {
59
59
  "access": "public"
@@ -18,6 +18,10 @@ function getCompilerSetup(rootDir) {
18
18
  const readResult = ts.readConfigFile(tsConfigPath, ts.sys.readFile);
19
19
  const config = ts.parseJsonConfigFileContent(readResult.config, ts.sys, (0, path_1.dirname)(tsConfigPath));
20
20
  const compilerOptions = config.options;
21
+ if (!compilerOptions.baseUrl) {
22
+ const { resolvePathsBaseUrl, } = require('@nx/js/src/utils/typescript/ts-config');
23
+ compilerOptions.baseUrl = resolvePathsBaseUrl(tsConfigPath);
24
+ }
21
25
  const host = ts.createCompilerHost(compilerOptions, true);
22
26
  return { compilerOptions, host };
23
27
  }
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../../../../packages/jest/src/plugins/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,aAAa,EAUd,MAAM,YAAY,CAAC;AA4BpB,MAAM,WAAW,iBAAiB;IAChC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B;;;;;;;;OAQG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAmBD,eAAO,MAAM,WAAW,EAAE,aAAa,CAAC,iBAAiB,CAsFxD,CAAC;AAEF,eAAO,MAAM,aAAa,kCAAc,CAAC"}
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../../../../packages/jest/src/plugins/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,aAAa,EAUd,MAAM,YAAY,CAAC;AAiCpB,MAAM,WAAW,iBAAiB;IAChC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B;;;;;;;;OAQG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAwBD,eAAO,MAAM,WAAW,EAAE,aAAa,CAAC,iBAAiB,CA8IxD,CAAC;AAEF,eAAO,MAAM,aAAa,kCAAc,CAAC"}
@@ -15,6 +15,8 @@ const globs_1 = require("nx/src/utils/globs");
15
15
  const installation_directory_1 = require("nx/src/utils/installation-directory");
16
16
  const plugins_1 = require("nx/src/utils/plugins");
17
17
  const workspace_context_1 = require("nx/src/utils/workspace-context");
18
+ const js_1 = require("@nx/js");
19
+ const internal_1 = require("@nx/js/src/internal");
18
20
  const versions_1 = require("../utils/versions");
19
21
  const REPORTER_BUILTINS = new Set(['default', 'github-actions', 'summary']);
20
22
  function readTargetsCache(cachePath) {
@@ -34,9 +36,15 @@ exports.createNodes = [
34
36
  const targetsCache = readTargetsCache(cachePath);
35
37
  // Cache jest preset(s) to avoid penalties of module load times. Most of jest configs will use the same preset.
36
38
  const presetCache = {};
39
+ // Cache tsconfig reads + isolatedModules resolution. Many projects share
40
+ // the same base tsconfig in their extends chain — read each file once.
41
+ const tsconfigJsonCache = new Map();
42
+ const tsconfigExistsCache = new Map();
43
+ const isolatedModulesCache = new Map();
37
44
  const isInPackageManagerWorkspaces = buildPackageJsonWorkspacesMatcher(context.workspaceRoot);
38
45
  options = normalizeOptions(options);
39
- const pmc = (0, devkit_1.getPackageManagerCommand)((0, devkit_1.detectPackageManager)(context.workspaceRoot));
46
+ const packageManager = (0, devkit_1.detectPackageManager)(context.workspaceRoot);
47
+ const pmc = (0, devkit_1.getPackageManagerCommand)(packageManager);
40
48
  const { roots: projectRoots, configFiles: validConfigFiles } = configFiles.reduce((acc, configFile) => {
41
49
  const potentialRoot = (0, node_path_1.dirname)(configFile);
42
50
  if (checkIfConfigFileShouldBeProject(configFile, potentialRoot, isInPackageManagerWorkspaces, context)) {
@@ -48,12 +56,47 @@ exports.createNodes = [
48
56
  roots: [],
49
57
  configFiles: [],
50
58
  });
51
- const hashes = await (0, calculate_hash_for_create_nodes_1.calculateHashesForCreateNodes)(projectRoots, options, context);
59
+ const lockFilePattern = (0, js_1.getLockFileName)(packageManager);
60
+ // Load configs in parallel. `loadConfigFile` calls `registerTsProject`,
61
+ // whose transpiler dedup is refcounted: serial register/unregister cycles
62
+ // drop refCount to 0 between iterations and recreate a fresh ts-node
63
+ // service each time (ts-node has no cleanup — see
64
+ // packages/nx/src/plugins/js/utils/register.js), stacking N services in
65
+ // `require.extensions` and OOM'ing under NX_PREFER_TS_NODE. Parallel
66
+ // loads keep all registrations alive concurrently so the dedup holds and
67
+ // a single transpiler instance is shared.
68
+ let requireCacheCleared = false;
69
+ const loadedConfigs = await Promise.all(validConfigFiles.map(async (configFilePath, i) => {
70
+ const projectRoot = projectRoots[i];
71
+ const absConfigFilePath = (0, node_path_1.resolve)(context.workspaceRoot, configFilePath);
72
+ if (!requireCacheCleared && require.cache[absConfigFilePath]) {
73
+ (0, config_utils_1.clearRequireCache)();
74
+ requireCacheCleared = true;
75
+ }
76
+ const rawConfig = await (0, config_utils_1.loadConfigFile)(absConfigFilePath, [
77
+ 'tsconfig.spec.json',
78
+ 'tsconfig.test.json',
79
+ 'tsconfig.jest.json',
80
+ 'tsconfig.json',
81
+ ]);
82
+ const { externalFiles, needsDtsInputs } = await collectExternalFileReferences(rawConfig, absConfigFilePath, projectRoot, context.workspaceRoot, {
83
+ presetCache,
84
+ tsconfigJsonCache,
85
+ tsconfigExistsCache,
86
+ isolatedModulesCache,
87
+ });
88
+ return { rawConfig, externalFiles, needsDtsInputs };
89
+ }));
90
+ const hashes = await (0, calculate_hash_for_create_nodes_1.calculateHashesForCreateNodes)(projectRoots, options, context, loadedConfigs.map(({ externalFiles }) => [
91
+ lockFilePattern,
92
+ ...externalFiles,
93
+ ]));
52
94
  try {
53
95
  return await (0, devkit_1.createNodesFromFiles)(async (configFilePath, options, context, idx) => {
54
96
  const projectRoot = projectRoots[idx];
55
97
  const hash = hashes[idx];
56
- targetsCache[hash] ??= await buildJestTargets(configFilePath, projectRoot, options, context, presetCache, pmc);
98
+ const { rawConfig, needsDtsInputs } = loadedConfigs[idx];
99
+ targetsCache[hash] ??= await buildJestTargets(rawConfig, needsDtsInputs, configFilePath, projectRoot, options, context, presetCache, pmc);
57
100
  const { targets, metadata } = targetsCache[hash];
58
101
  return {
59
102
  projects: {
@@ -103,18 +146,8 @@ function checkIfConfigFileShouldBeProject(configFilePath, projectRoot, isInPacka
103
146
  }
104
147
  return true;
105
148
  }
106
- async function buildJestTargets(configFilePath, projectRoot, options, context, presetCache, pmc) {
149
+ async function buildJestTargets(rawConfig, needsDtsInputs, configFilePath, projectRoot, options, context, presetCache, pmc) {
107
150
  const absConfigFilePath = (0, node_path_1.resolve)(context.workspaceRoot, configFilePath);
108
- if (require.cache[absConfigFilePath])
109
- (0, config_utils_1.clearRequireCache)();
110
- const rawConfig = await (0, config_utils_1.loadConfigFile)(absConfigFilePath,
111
- // lookup for the same files we look for in the resolver and fall back to tsconfig.json
112
- [
113
- 'tsconfig.spec.json',
114
- 'tsconfig.test.json',
115
- 'tsconfig.jest.json',
116
- 'tsconfig.json',
117
- ]);
118
151
  const targets = {};
119
152
  const namedInputs = (0, get_named_inputs_1.getNamedInputs)(projectRoot, context);
120
153
  const tsNodeCompilerOptions = JSON.stringify({
@@ -154,7 +187,7 @@ async function buildJestTargets(configFilePath, projectRoot, options, context, p
154
187
  ? (0, node_path_1.resolve)((0, node_path_1.dirname)(absConfigFilePath), rawConfig.rootDir)
155
188
  : (0, node_path_1.resolve)(context.workspaceRoot, projectRoot);
156
189
  const cache = (target.cache = true);
157
- const inputs = (target.inputs = await getInputs(namedInputs, rawConfig, rootDir, projectRoot, context.workspaceRoot, presetCache, useJestResolver));
190
+ const inputs = (target.inputs = await getInputs(namedInputs, rawConfig, rootDir, projectRoot, context.workspaceRoot, presetCache, needsDtsInputs, useJestResolver));
158
191
  let metadata;
159
192
  const groupName = options?.ciGroupName ?? (0, plugins_1.deriveGroupNameFromTarget)(options?.ciTargetName);
160
193
  if (disableJestRuntime) {
@@ -265,7 +298,7 @@ async function buildJestTargets(configFilePath, projectRoot, options, context, p
265
298
  });
266
299
  const jest = require(resolveJestPath(projectRoot, context.workspaceRoot));
267
300
  const source = new jest.SearchSource(jestContext);
268
- const jestVersion = (0, versions_1.getInstalledJestMajorVersion)();
301
+ const jestVersion = getJestMajorVersion();
269
302
  const specs = jestVersion >= 30
270
303
  ? await source.getTestPaths(config.globalConfig, config.projectConfig)
271
304
  : // @ts-expect-error Jest v29 doesn't have the projectConfig parameter
@@ -347,7 +380,7 @@ async function buildJestTargets(configFilePath, projectRoot, options, context, p
347
380
  }
348
381
  return { targets, metadata };
349
382
  }
350
- async function getInputs(namedInputs, rawConfig, rootDir, projectRoot, workspaceRoot, presetCache, useJestResolver) {
383
+ async function getInputs(namedInputs, rawConfig, rootDir, projectRoot, workspaceRoot, presetCache, needsDtsInputs, useJestResolver) {
351
384
  const inputs = [
352
385
  ...('production' in namedInputs
353
386
  ? ['default', '^production']
@@ -388,6 +421,16 @@ async function getInputs(namedInputs, rawConfig, rootDir, projectRoot, workspace
388
421
  }
389
422
  }
390
423
  inputs.push({ externalDependencies });
424
+ // When ts-jest runs without isolatedModules, it creates a TypeScript
425
+ // Language Service that reads .d.ts files from dependency projects.
426
+ // Declare these as dependentTasksOutputFiles so changes to dependency
427
+ // type declarations correctly invalidate the test cache.
428
+ if (needsDtsInputs) {
429
+ inputs.push({
430
+ dependentTasksOutputFiles: '**/*.d.ts',
431
+ transitive: true,
432
+ });
433
+ }
391
434
  return inputs;
392
435
  }
393
436
  function resolvePresetInputWithoutJestResolver(presetValue, rootDir, projectRoot, workspaceRoot) {
@@ -568,6 +611,96 @@ async function getTestPaths(projectRoot, rawConfig, rootDir, context, presetCach
568
611
  }
569
612
  return { specs: paths, testMatch };
570
613
  }
614
+ /**
615
+ * Collects workspace-relative paths to files whose CONTENT the plugin reads
616
+ * when computing inferred targets and that live OUTSIDE the project root.
617
+ *
618
+ * Only two kinds of files qualify:
619
+ * - The jest preset (loaded to read its `transform`, etc.)
620
+ * - Tsconfig files in the extends chain referenced by ts-jest (read to
621
+ * determine `isolatedModules`); only walked when ts-jest is not already
622
+ * known to be in isolated mode.
623
+ *
624
+ * Other config references (setup files, custom resolvers, transformers,
625
+ * etc.) are NOT collected — the plugin only resolves their paths and emits
626
+ * them as task inputs; their content is not read by the plugin, so changes
627
+ * to them don't influence inference.
628
+ */
629
+ async function collectExternalFileReferences(rawConfig, absConfigFilePath, projectRoot, workspaceRoot, caches) {
630
+ const { presetCache, tsconfigJsonCache, tsconfigExistsCache, isolatedModulesCache, } = caches;
631
+ const absWorkspaceRoot = (0, node_path_1.resolve)(workspaceRoot);
632
+ const rootDir = rawConfig.rootDir
633
+ ? (0, node_path_1.resolve)((0, node_path_1.dirname)(absConfigFilePath), rawConfig.rootDir)
634
+ : (0, node_path_1.resolve)(absWorkspaceRoot, projectRoot);
635
+ const absoluteProjectRoot = (0, node_path_1.resolve)(absWorkspaceRoot, projectRoot);
636
+ const externalFiles = new Set();
637
+ const addIfExternal = (absolutePath) => {
638
+ if (!absolutePath)
639
+ return;
640
+ const rel = (0, devkit_1.normalizePath)((0, node_path_1.relative)(absWorkspaceRoot, absolutePath));
641
+ if (rel.startsWith('..') || (0, node_path_1.isAbsolute)(rel))
642
+ return; // outside workspace
643
+ if (rel.includes('node_modules/'))
644
+ return; // covered by lockfile
645
+ const relToProject = (0, devkit_1.normalizePath)((0, node_path_1.relative)(absoluteProjectRoot, absolutePath));
646
+ if (!relToProject.startsWith('..') && !(0, node_path_1.isAbsolute)(relToProject))
647
+ return; // inside project root
648
+ externalFiles.add(rel);
649
+ };
650
+ // Preset path (content is loaded by the plugin to merge with rawConfig)
651
+ if (typeof rawConfig.preset === 'string') {
652
+ const replaced = replaceRootDirInPath(rootDir, rawConfig.preset);
653
+ if (replaced.startsWith('.') || (0, node_path_1.isAbsolute)(replaced)) {
654
+ addIfExternal((0, node_path_1.resolve)(rootDir, replaced));
655
+ }
656
+ }
657
+ // ts-jest tsconfig extends chain — only walked when ts-jest is in
658
+ // non-isolated mode (otherwise the chain doesn't influence the output).
659
+ // Loading the preset is required to merge its transform with the raw
660
+ // config, since presets are the common source of ts-jest configuration.
661
+ const presetConfig = await loadPresetConfig(rawConfig, rootDir, presetCache);
662
+ const transform = {
663
+ ...(presetConfig?.transform ?? {}),
664
+ ...(rawConfig.transform ?? {}),
665
+ };
666
+ let needsDtsInputs = false;
667
+ for (const value of Object.values(transform)) {
668
+ let transformPath;
669
+ let transformOptions;
670
+ if (Array.isArray(value)) {
671
+ transformPath = value[0];
672
+ transformOptions = value[1];
673
+ }
674
+ else if (typeof value === 'string') {
675
+ transformPath = value;
676
+ }
677
+ else {
678
+ continue;
679
+ }
680
+ if (!isTsJestTransformer(transformPath))
681
+ continue;
682
+ if (transformOptions?.isolatedModules === true) {
683
+ const tsJestMajor = getTsJestMajorVersion();
684
+ if (tsJestMajor !== null && tsJestMajor < 30)
685
+ continue;
686
+ }
687
+ const tsconfigAbsPath = transformOptions?.tsconfig
688
+ ? (0, node_path_1.resolve)(rootDir, replaceRootDirInPath(rootDir, transformOptions.tsconfig))
689
+ : findNearestTsconfig(rootDir, absWorkspaceRoot, tsconfigExistsCache);
690
+ if (!tsconfigAbsPath) {
691
+ // No tsconfig found — ts-jest defaults to non-isolated mode
692
+ needsDtsInputs = true;
693
+ continue;
694
+ }
695
+ const { value: isolatedValue, visitedFiles } = resolveIsolatedModules(tsconfigAbsPath, tsconfigJsonCache, isolatedModulesCache);
696
+ for (const visitedFile of visitedFiles) {
697
+ addIfExternal(visitedFile);
698
+ }
699
+ if (isolatedValue !== true)
700
+ needsDtsInputs = true;
701
+ }
702
+ return { externalFiles: [...externalFiles], needsDtsInputs };
703
+ }
571
704
  async function loadPresetConfig(rawConfig, rootDir, presetCache) {
572
705
  if (!rawConfig.preset)
573
706
  return null;
@@ -708,6 +841,93 @@ async function getConfigFileInputs(rawConfig, rootDir, presetCache, resolveFileP
708
841
  externalDeps: [...externalDeps],
709
842
  };
710
843
  }
844
+ /**
845
+ * Walks up from `startDir` looking for `tsconfig.json`, stopping at
846
+ * `stopDir` (inclusive). Mirrors `ts.findConfigFile` but capped at the
847
+ * workspace root to avoid escaping the monorepo.
848
+ */
849
+ function findNearestTsconfig(startDir, stopDir, existsCache) {
850
+ let dir = startDir;
851
+ while (true) {
852
+ const candidate = (0, node_path_1.join)(dir, 'tsconfig.json');
853
+ let exists = existsCache.get(candidate);
854
+ if (exists === undefined) {
855
+ exists = (0, node_fs_1.existsSync)(candidate);
856
+ existsCache.set(candidate, exists);
857
+ }
858
+ if (exists)
859
+ return candidate;
860
+ if (dir === stopDir)
861
+ return null;
862
+ const parent = (0, node_path_1.dirname)(dir);
863
+ if (parent === dir)
864
+ return null;
865
+ dir = parent;
866
+ }
867
+ }
868
+ function isTsJestTransformer(value) {
869
+ if (value === 'ts-jest' || value.startsWith('ts-jest/')) {
870
+ return true;
871
+ }
872
+ // Handle resolved paths (e.g. from require.resolve('ts-jest') in configs)
873
+ const normalized = (0, devkit_1.normalizePath)(value);
874
+ return (normalized.includes('/node_modules/ts-jest/') ||
875
+ normalized.endsWith('/node_modules/ts-jest'));
876
+ }
877
+ /**
878
+ * Returns the effective `compilerOptions.isolatedModules` for a tsconfig,
879
+ * walking the `extends` chain via `walkTsconfigExtendsChain`. Tri-state:
880
+ * `value` is `undefined` when the option is not set anywhere in the chain.
881
+ */
882
+ function resolveIsolatedModules(tsconfigPath, jsonCache, resultCache) {
883
+ const cached = resultCache.get(tsconfigPath);
884
+ if (cached)
885
+ return cached;
886
+ let value;
887
+ const visitedFiles = new Set();
888
+ (0, internal_1.walkTsconfigExtendsChain)(tsconfigPath, (absPath, rawJson) => {
889
+ visitedFiles.add(absPath);
890
+ const opts = rawJson?.compilerOptions;
891
+ if (opts?.isolatedModules !== undefined) {
892
+ value = opts.isolatedModules === true;
893
+ return 'stop';
894
+ }
895
+ // verbatimModuleSyntax: true implies isolatedModules: true (TS 5.0+,
896
+ // the minimum TS version Nx supports)
897
+ if (opts?.verbatimModuleSyntax === true) {
898
+ value = true;
899
+ return 'stop';
900
+ }
901
+ return 'continue';
902
+ }, { jsonCache });
903
+ const result = { value, visitedFiles };
904
+ resultCache.set(tsconfigPath, result);
905
+ return result;
906
+ }
907
+ // Module-level memoization: package versions don't change during a process
908
+ // lifetime, so it's safe to cache across createNodes invocations.
909
+ let cachedJestMajorVersion;
910
+ function getJestMajorVersion() {
911
+ if (cachedJestMajorVersion === undefined) {
912
+ cachedJestMajorVersion = (0, versions_1.getInstalledJestMajorVersion)();
913
+ }
914
+ return cachedJestMajorVersion;
915
+ }
916
+ let cachedTsJestMajorVersion;
917
+ function getTsJestMajorVersion() {
918
+ if (cachedTsJestMajorVersion !== undefined) {
919
+ return cachedTsJestMajorVersion;
920
+ }
921
+ try {
922
+ const { major } = require('semver');
923
+ const version = require('ts-jest/package.json').version;
924
+ cachedTsJestMajorVersion = major(version);
925
+ }
926
+ catch {
927
+ cachedTsJestMajorVersion = null;
928
+ }
929
+ return cachedTsJestMajorVersion;
930
+ }
711
931
  async function getJestOption(rawConfig, rootDir, optionName, presetCache) {
712
932
  if (rawConfig[optionName])
713
933
  return rawConfig[optionName];