feat(core): extract js related code from affected and hasher (#16244)

This commit is contained in:
Miroslav Jonaš 2023-04-18 16:42:05 +02:00 committed by GitHub
parent 0d7dbbc525
commit 2dd59c3b57
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
77 changed files with 397 additions and 329 deletions

View File

@ -101,8 +101,6 @@ It only uses language primitives and immutable objects
- [applySharedFunction](../../devkit/documents/nrwl_devkit#applysharedfunction) - [applySharedFunction](../../devkit/documents/nrwl_devkit#applysharedfunction)
- [convertNxExecutor](../../devkit/documents/nrwl_devkit#convertnxexecutor) - [convertNxExecutor](../../devkit/documents/nrwl_devkit#convertnxexecutor)
- [convertNxGenerator](../../devkit/documents/nrwl_devkit#convertnxgenerator) - [convertNxGenerator](../../devkit/documents/nrwl_devkit#convertnxgenerator)
- [createLockFile](../../devkit/documents/nrwl_devkit#createlockfile)
- [createPackageJson](../../devkit/documents/nrwl_devkit#createpackagejson)
- [createProjectGraphAsync](../../devkit/documents/nrwl_devkit#createprojectgraphasync) - [createProjectGraphAsync](../../devkit/documents/nrwl_devkit#createprojectgraphasync)
- [defaultTasksRunner](../../devkit/documents/nrwl_devkit#defaulttasksrunner) - [defaultTasksRunner](../../devkit/documents/nrwl_devkit#defaulttasksrunner)
- [detectPackageManager](../../devkit/documents/nrwl_devkit#detectpackagemanager) - [detectPackageManager](../../devkit/documents/nrwl_devkit#detectpackagemanager)
@ -1054,53 +1052,6 @@ Convert an Nx Generator into an Angular Devkit Schematic.
--- ---
### createLockFile
**createLockFile**(`packageJson`, `packageManager?`): `string`
**`Deprecated`**
Import this from @nrwl/js instead
#### Parameters
| Name | Type |
| :--------------- | :-------------------------------------------------------------------- |
| `packageJson` | `PackageJson` |
| `packageManager` | [`PackageManager`](../../devkit/documents/nrwl_devkit#packagemanager) |
#### Returns
`string`
---
### createPackageJson
**createPackageJson**(`projectName`, `graph`, `options?`): `PackageJson`
**`Deprecated`**
Import this from @nrwl/js instead
#### Parameters
| Name | Type |
| :---------------------------- | :---------------------------------------------------------------- |
| `projectName` | `string` |
| `graph` | [`ProjectGraph`](../../devkit/documents/nrwl_devkit#projectgraph) |
| `options` | `Object` |
| `options.helperDependencies?` | `string`[] |
| `options.isProduction?` | `boolean` |
| `options.root?` | `string` |
| `options.target?` | `string` |
#### Returns
`PackageJson`
---
### createProjectGraphAsync ### createProjectGraphAsync
**createProjectGraphAsync**(`opts?`): `Promise`<[`ProjectGraph`](../../devkit/documents/nrwl_devkit#projectgraph)\> **createProjectGraphAsync**(`opts?`): `Promise`<[`ProjectGraph`](../../devkit/documents/nrwl_devkit#projectgraph)\>

View File

@ -101,8 +101,6 @@ It only uses language primitives and immutable objects
- [applySharedFunction](../../devkit/documents/nrwl_devkit#applysharedfunction) - [applySharedFunction](../../devkit/documents/nrwl_devkit#applysharedfunction)
- [convertNxExecutor](../../devkit/documents/nrwl_devkit#convertnxexecutor) - [convertNxExecutor](../../devkit/documents/nrwl_devkit#convertnxexecutor)
- [convertNxGenerator](../../devkit/documents/nrwl_devkit#convertnxgenerator) - [convertNxGenerator](../../devkit/documents/nrwl_devkit#convertnxgenerator)
- [createLockFile](../../devkit/documents/nrwl_devkit#createlockfile)
- [createPackageJson](../../devkit/documents/nrwl_devkit#createpackagejson)
- [createProjectGraphAsync](../../devkit/documents/nrwl_devkit#createprojectgraphasync) - [createProjectGraphAsync](../../devkit/documents/nrwl_devkit#createprojectgraphasync)
- [defaultTasksRunner](../../devkit/documents/nrwl_devkit#defaulttasksrunner) - [defaultTasksRunner](../../devkit/documents/nrwl_devkit#defaulttasksrunner)
- [detectPackageManager](../../devkit/documents/nrwl_devkit#detectpackagemanager) - [detectPackageManager](../../devkit/documents/nrwl_devkit#detectpackagemanager)
@ -1054,53 +1052,6 @@ Convert an Nx Generator into an Angular Devkit Schematic.
--- ---
### createLockFile
**createLockFile**(`packageJson`, `packageManager?`): `string`
**`Deprecated`**
Import this from @nrwl/js instead
#### Parameters
| Name | Type |
| :--------------- | :-------------------------------------------------------------------- |
| `packageJson` | `PackageJson` |
| `packageManager` | [`PackageManager`](../../devkit/documents/nrwl_devkit#packagemanager) |
#### Returns
`string`
---
### createPackageJson
**createPackageJson**(`projectName`, `graph`, `options?`): `PackageJson`
**`Deprecated`**
Import this from @nrwl/js instead
#### Parameters
| Name | Type |
| :---------------------------- | :---------------------------------------------------------------- |
| `projectName` | `string` |
| `graph` | [`ProjectGraph`](../../devkit/documents/nrwl_devkit#projectgraph) |
| `options` | `Object` |
| `options.helperDependencies?` | `string`[] |
| `options.isProduction?` | `boolean` |
| `options.root?` | `string` |
| `options.target?` | `string` |
#### Returns
`PackageJson`
---
### createProjectGraphAsync ### createProjectGraphAsync
**createProjectGraphAsync**(`opts?`): `Promise`<[`ProjectGraph`](../../devkit/documents/nrwl_devkit#projectgraph)\> **createProjectGraphAsync**(`opts?`): `Promise`<[`ProjectGraph`](../../devkit/documents/nrwl_devkit#projectgraph)\>

View File

@ -135,7 +135,7 @@ In order to use Jest's global setup/teardown functions that reference nx librari
Nx provides a helper function that you can import within your setup/teardown file. Nx provides a helper function that you can import within your setup/teardown file.
```typescript {% fileName="global-setup.ts" %} ```typescript {% fileName="global-setup.ts" %}
import { registerTsProject } from 'nx/src/utils/register'; import { registerTsProject } from '@nrwl/js/src/internal';
const cleanupRegisteredPaths = registerTsProject('.', 'tsconfig.base.json'); const cleanupRegisteredPaths = registerTsProject('.', 'tsconfig.base.json');
import { yourFancyFunction } from '@some-org/my-util-library'; import { yourFancyFunction } from '@some-org/my-util-library';

View File

@ -135,7 +135,7 @@ In order to use Jest's global setup/teardown functions that reference nx librari
Nx provides a helper function that you can import within your setup/teardown file. Nx provides a helper function that you can import within your setup/teardown file.
```typescript {% fileName="global-setup.ts" %} ```typescript {% fileName="global-setup.ts" %}
import { registerTsProject } from 'nx/src/utils/register'; import { registerTsProject } from '@nrwl/js/src/internal';
const cleanupRegisteredPaths = registerTsProject('.', 'tsconfig.base.json'); const cleanupRegisteredPaths = registerTsProject('.', 'tsconfig.base.json');
import { yourFancyFunction } from '@some-org/my-util-library'; import { yourFancyFunction } from '@some-org/my-util-library';

View File

@ -48,7 +48,7 @@ describe('Jest', () => {
updateFile( updateFile(
`libs/${mylib}/setup.ts`, `libs/${mylib}/setup.ts`,
stripIndents` stripIndents`
const { registerTsProject } = require('nx/src/utils/register'); const { registerTsProject } = require('@nx/js/src/internal');
const cleanup = registerTsProject('.', 'tsconfig.base.json'); const cleanup = registerTsProject('.', 'tsconfig.base.json');
import {setup} from '@global-fun/globals'; import {setup} from '@global-fun/globals';
@ -61,7 +61,7 @@ describe('Jest', () => {
updateFile( updateFile(
`libs/${mylib}/teardown.ts`, `libs/${mylib}/teardown.ts`,
stripIndents` stripIndents`
import { registerTsProject } from 'nx/src/utils/register'; const { registerTsProject } = require('@nx/js/src/internal');
const cleanup = registerTsProject('.', 'tsconfig.base.json'); const cleanup = registerTsProject('.', 'tsconfig.base.json');
import {teardown} from '@global-fun/globals'; import {teardown} from '@global-fun/globals';
@ -73,15 +73,14 @@ describe('Jest', () => {
updateFile( updateFile(
`libs/${mylib}/jest.config.ts`, `libs/${mylib}/jest.config.ts`,
stripIndents` stripIndents`
module.exports = { export default {
testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'], displayName: "${mylib}",
preset: "../../jest.preset.js",
transform: { transform: {
'^.+\\.(ts|js|html)$': 'ts-jest' "^.+\\.[tj]s$": ["ts-jest", { tsconfig: "<rootDir>/tsconfig.spec.json" }],
}, },
resolver: '@nrwl/jest/plugins/resolver', moduleFileExtensions: ["ts", "js", "html"],
moduleFileExtensions: ['ts', 'js', 'html'], coverageDirectory: "../../coverage/libs/${mylib}",
coverageReporters: ['html'],
passWithNoTests: true,
globals: { testGlobal: ${testGlobal} }, globals: { testGlobal: ${testGlobal} },
globalSetup: '<rootDir>/setup.ts', globalSetup: '<rootDir>/setup.ts',
globalTeardown: '<rootDir>/teardown.ts' globalTeardown: '<rootDir>/teardown.ts'

View File

@ -14,7 +14,6 @@ import {
packageManagerLockFile, packageManagerLockFile,
promisifiedTreeKill, promisifiedTreeKill,
readFile, readFile,
readJson,
runCLI, runCLI,
runCLIAsync, runCLIAsync,
runCommand, runCommand,
@ -26,7 +25,7 @@ import {
} from '@nrwl/e2e/utils'; } from '@nrwl/e2e/utils';
import { exec, execSync } from 'child_process'; import { exec, execSync } from 'child_process';
import * as http from 'http'; import * as http from 'http';
import { getLockFileName } from 'nx/src/plugins/js/lock-file/lock-file'; import { getLockFileName } from '@nx/js';
import { satisfies } from 'semver'; import { satisfies } from 'semver';
function getData(port, path = '/api'): Promise<any> { function getData(port, path = '/api'): Promise<any> {

View File

@ -17,7 +17,7 @@ import type { Schema } from './schema';
import { createTmpTsConfigForBuildableLibs } from '../utilities/buildable-libs'; import { createTmpTsConfigForBuildableLibs } from '../utilities/buildable-libs';
import { from } from 'rxjs'; import { from } from 'rxjs';
import { switchMap } from 'rxjs/operators'; import { switchMap } from 'rxjs/operators';
import { getRootTsConfigPath } from 'nx/src/utils/typescript'; import { getRootTsConfigPath } from '@nx/js';
type BuildTargetOptions = { type BuildTargetOptions = {
tsConfig: string; tsConfig: string;

View File

@ -1,6 +1,6 @@
import type { Tree } from '@nx/devkit'; import type { Tree } from '@nx/devkit';
import { ensureTypescript } from '@nx/js/src/utils/typescript/ensure-typescript'; import { ensureTypescript } from '@nx/js/src/utils/typescript/ensure-typescript';
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from '@nx/js';
import type { PropertyAssignment } from 'typescript'; import type { PropertyAssignment } from 'typescript';
import { import {

View File

@ -5,7 +5,7 @@ import {
stripIndents, stripIndents,
visitNotIgnoredFiles, visitNotIgnoredFiles,
} from '@nx/devkit'; } from '@nx/devkit';
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from '@nx/js';
import { extname } from 'path'; import { extname } from 'path';
import type { import type {
ClassDeclaration, ClassDeclaration,

View File

@ -1,6 +1,5 @@
import type { Tree } from '@nx/devkit'; import type { Tree } from '@nx/devkit';
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes, getSourceNodes } from '@nx/js';
import { getSourceNodes } from '@nx/js';
import type { PropertyDeclaration } from 'typescript'; import type { PropertyDeclaration } from 'typescript';
import { getTsSourceFile } from '../../../utils/nx-devkit/ast-utils'; import { getTsSourceFile } from '../../../utils/nx-devkit/ast-utils';
import { ensureTypescript } from '@nx/js/src/utils/typescript/ensure-typescript'; import { ensureTypescript } from '@nx/js/src/utils/typescript/ensure-typescript';

View File

@ -1,5 +1,5 @@
import type * as ts from 'typescript'; import type * as ts from 'typescript';
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from '@nx/js';
import { import {
getImport, getImport,
getSourceNodes, getSourceNodes,

View File

@ -1,6 +1,5 @@
import type { Tree } from 'nx/src/generators/tree'; import type { Tree } from 'nx/src/generators/tree';
// eslint-disable-next-line @typescript-eslint/no-restricted-imports import { typescriptVersion } from '../utils/versions';
import { typescriptVersion } from 'nx/src/utils/versions';
import { ensurePackage } from '../utils/package-json'; import { ensurePackage } from '../utils/package-json';
/** /**

View File

@ -12,7 +12,7 @@ import {
collectWorkspaceLibrarySecondaryEntryPoints, collectWorkspaceLibrarySecondaryEntryPoints,
} from './secondary-entry-points'; } from './secondary-entry-points';
// eslint-disable-next-line @typescript-eslint/no-restricted-imports // eslint-disable-next-line @typescript-eslint/no-restricted-imports
import { getRootTsConfigPath } from 'nx/src/utils/typescript'; import { getRootTsConfigPath } from 'nx/src/plugins/js/utils/typescript';
import type { ProjectGraph } from 'nx/src/config/project-graph'; import type { ProjectGraph } from 'nx/src/config/project-graph';
import { requireNx } from '../../../nx'; import { requireNx } from '../../../nx';

View File

@ -1,7 +1,7 @@
import { existsSync } from 'fs'; import { existsSync } from 'fs';
import { ParsedCommandLine } from 'typescript'; import { ParsedCommandLine } from 'typescript';
// eslint-disable-next-line @typescript-eslint/no-restricted-imports // eslint-disable-next-line @typescript-eslint/no-restricted-imports
import { getRootTsConfigPath } from 'nx/src/utils/typescript'; import { getRootTsConfigPath } from 'nx/src/plugins/js/utils/typescript';
import { dirname } from 'path'; import { dirname } from 'path';
let tsConfig: ParsedCommandLine; let tsConfig: ParsedCommandLine;

View File

@ -0,0 +1 @@
export const typescriptVersion = '~4.9.5';

View File

@ -33,11 +33,12 @@
} }
}, },
"dependencies": { "dependencies": {
"@nx/devkit": "file:../devkit",
"@nx/js": "file:../js",
"@typescript-eslint/utils": "^5.58.0", "@typescript-eslint/utils": "^5.58.0",
"chalk": "^4.1.0", "chalk": "^4.1.0",
"confusing-browser-globals": "^1.0.9", "confusing-browser-globals": "^1.0.9",
"semver": "7.3.4", "semver": "7.3.4"
"@nx/devkit": "file:../devkit"
}, },
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"

View File

@ -1,6 +1,6 @@
import type { TSESLint } from '@typescript-eslint/utils'; import type { TSESLint } from '@typescript-eslint/utils';
import { existsSync } from 'fs'; import { existsSync } from 'fs';
import { registerTsProject } from 'nx/src/utils/register'; import { registerTsProject } from '@nx/js/src/internal';
import { WORKSPACE_PLUGIN_DIR, WORKSPACE_RULE_NAMESPACE } from './constants'; import { WORKSPACE_PLUGIN_DIR, WORKSPACE_RULE_NAMESPACE } from './constants';
type ESLintRules = Record<string, TSESLint.RuleModule<string, unknown[]>>; type ESLintRules = Record<string, TSESLint.RuleModule<string, unknown[]>>;

View File

@ -33,7 +33,7 @@ import {
isComboDepConstraint, isComboDepConstraint,
} from '../utils/runtime-lint-utils'; } from '../utils/runtime-lint-utils';
import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils'; import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils';
import { TargetProjectLocator } from 'nx/src/plugins/js/project-graph/build-dependencies/target-project-locator'; import { TargetProjectLocator } from '@nx/js/src/internal';
import { basename, dirname, relative } from 'path'; import { basename, dirname, relative } from 'path';
import { import {
getBarrelEntryPointByImportScope, getBarrelEntryPointByImportScope,

View File

@ -8,7 +8,7 @@ import {
} from '@nx/devkit'; } from '@nx/devkit';
import { findProject, getSourceFilePath } from '../utils/runtime-lint-utils'; import { findProject, getSourceFilePath } from '../utils/runtime-lint-utils';
import { existsSync } from 'fs'; import { existsSync } from 'fs';
import { registerTsProject } from 'nx/src/utils/register'; import { registerTsProject } from '@nx/js/src/internal';
import * as path from 'path'; import * as path from 'path';
import { createESLintRule } from '../utils/create-eslint-rule'; import { createESLintRule } from '../utils/create-eslint-rule';

View File

@ -3,7 +3,7 @@ import {
ProjectGraphProjectNode, ProjectGraphProjectNode,
readJsonFile, readJsonFile,
} from '@nx/devkit'; } from '@nx/devkit';
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from 'nx/src/plugins/js/utils/typescript';
import { existsSync, readFileSync } from 'fs'; import { existsSync, readFileSync } from 'fs';
import { dirname } from 'path'; import { dirname } from 'path';
import ts = require('typescript'); import ts = require('typescript');

View File

@ -13,15 +13,15 @@ import {
} from '@nx/devkit'; } from '@nx/devkit';
import { getPath, pathExists } from './graph-utils'; import { getPath, pathExists } from './graph-utils';
import { readFileIfExisting } from 'nx/src/utils/fileutils'; import { readFileIfExisting } from 'nx/src/utils/fileutils';
import { TargetProjectLocator } from 'nx/src/plugins/js/project-graph/build-dependencies/target-project-locator';
import { import {
findProjectForPath, findProjectForPath,
ProjectRootMappings, ProjectRootMappings,
} from 'nx/src/project-graph/utils/find-project-for-path'; } from 'nx/src/project-graph/utils/find-project-for-path';
import { getRootTsConfigFileName } from '@nx/js';
import { import {
getRootTsConfigFileName,
resolveModuleByImport, resolveModuleByImport,
} from 'nx/src/utils/typescript'; TargetProjectLocator,
} from '@nx/js/src/internal';
export type Deps = { [projectName: string]: ProjectGraphDependency[] }; export type Deps = { [projectName: string]: ProjectGraphDependency[] };
type SingleSourceTagConstraint = { type SingleSourceTagConstraint = {

View File

@ -1,4 +1,4 @@
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from '@nx/js';
import * as ts from 'typescript'; import * as ts from 'typescript';
import { ChangeType, StringChange } from '@nx/devkit'; import { ChangeType, StringChange } from '@nx/devkit';

View File

@ -11,5 +11,13 @@ export * from './utils/assets';
export * from './utils/package-json/update-package-json'; export * from './utils/package-json/update-package-json';
export { libraryGenerator } from './generators/library/library'; export { libraryGenerator } from './generators/library/library';
export { initGenerator } from './generators/init/init'; export { initGenerator } from './generators/init/init';
export { createLockFile } from 'nx/src/plugins/js/lock-file/lock-file';
export {
createLockFile,
getLockFileName,
} from 'nx/src/plugins/js/lock-file/lock-file';
export { createPackageJson } from 'nx/src/plugins/js/package-json/create-package-json'; export { createPackageJson } from 'nx/src/plugins/js/package-json/create-package-json';
export {
findNodes,
getRootTsConfigPath,
} from 'nx/src/plugins/js/utils/typescript';

View File

@ -0,0 +1,6 @@
export { resolveModuleByImport } from 'nx/src/plugins/js/utils/typescript';
export {
registerTsProject,
registerTsConfigPaths,
} from 'nx/src/plugins/js/utils/register';
export { TargetProjectLocator } from 'nx/src/plugins/js/project-graph/build-dependencies/target-project-locator';

View File

@ -1,5 +1,10 @@
import { addDependenciesToPackageJson, Tree } from '@nx/devkit'; import { addDependenciesToPackageJson, Tree } from '@nx/devkit';
import { swcCliVersion, swcCoreVersion, swcHelpersVersion } from '../versions'; import {
swcCliVersion,
swcCoreVersion,
swcHelpersVersion,
swcNodeVersion,
} from '../versions';
export function addSwcDependencies(tree: Tree) { export function addSwcDependencies(tree: Tree) {
return addDependenciesToPackageJson( return addDependenciesToPackageJson(
@ -13,3 +18,11 @@ export function addSwcDependencies(tree: Tree) {
} }
); );
} }
export function addSwcRegisterDependencies(tree: Tree) {
return addDependenciesToPackageJson(
tree,
{},
{ '@swc-node/register': swcNodeVersion, '@swc/core': swcCoreVersion }
);
}

View File

@ -0,0 +1,12 @@
import { addDependenciesToPackageJson, Tree } from '@nx/devkit';
import { tsLibVersion } from '../versions';
export function addTsLibDependencies(tree: Tree) {
addDependenciesToPackageJson(
tree,
{
tslib: tsLibVersion,
},
{}
);
}

View File

@ -2,7 +2,7 @@ import type { Tree } from '@nx/devkit';
import type * as ts from 'typescript'; import type * as ts from 'typescript';
// TODO(colum): replace when https://github.com/nrwl/nx/pull/15497 is merged // TODO(colum): replace when https://github.com/nrwl/nx/pull/15497 is merged
import { getSourceNodes } from '@nx/workspace/src/utilities/typescript'; import { getSourceNodes } from '@nx/workspace/src/utilities/typescript';
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from 'nx/src/plugins/js/utils/typescript';
import { ensureTypescript } from './ensure-typescript'; import { ensureTypescript } from './ensure-typescript';
let tsModule: typeof import('typescript'); let tsModule: typeof import('typescript');

View File

@ -42,9 +42,13 @@ export function getRelativePathToRootTsConfig(
return offsetFromRoot(targetPath) + getRootTsConfigPathInTree(tree); return offsetFromRoot(targetPath) + getRootTsConfigPathInTree(tree);
} }
export function getRootTsConfigFileName(tree: Tree): string | null { export function getRootTsConfigFileName(tree?: Tree): string | null {
for (const tsConfigName of ['tsconfig.base.json', 'tsconfig.json']) { for (const tsConfigName of ['tsconfig.base.json', 'tsconfig.json']) {
if (tree.exists(tsConfigName)) { const pathExists = tree
? tree.exists(tsConfigName)
: existsSync(join(workspaceRoot, tsConfigName));
if (pathExists) {
return tsConfigName; return tsConfigName;
} }
} }

View File

@ -1,10 +1,11 @@
export { swcCoreVersion } from 'nx/src/utils/versions';
export const nxVersion = require('../../package.json').version; export const nxVersion = require('../../package.json').version;
export const esbuildVersion = '^0.17.5'; export const esbuildVersion = '^0.17.5';
export const prettierVersion = '^2.6.2'; export const prettierVersion = '^2.6.2';
export const swcCliVersion = '~0.1.55'; export const swcCliVersion = '~0.1.55';
export const swcCoreVersion = '^1.2.173';
export const swcNodeVersion = '^1.4.2';
export const swcHelpersVersion = '~0.4.11'; export const swcHelpersVersion = '~0.4.11';
export const tsLibVersion = '^2.3.0';
export const typesNodeVersion = '18.7.1'; export const typesNodeVersion = '18.7.1';
export const typescriptVersion = '~4.9.5'; export const typescriptVersion = '~4.9.5';

View File

@ -1,5 +1,4 @@
import { import {
addDependenciesToPackageJson,
addProjectConfiguration, addProjectConfiguration,
convertNxGenerator, convertNxGenerator,
ensurePackage, ensurePackage,
@ -14,10 +13,10 @@ import {
updateNxJson, updateNxJson,
} from '@nx/devkit'; } from '@nx/devkit';
import { getRelativePathToRootTsConfig } from '@nx/js'; import { getRelativePathToRootTsConfig } from '@nx/js';
import { addSwcRegisterDependencies } from '@nx/js/src/utils/swc/add-swc-dependencies';
import { join } from 'path'; import { join } from 'path';
import { workspaceLintPluginDir } from '../../utils/workspace-lint-rules';
import { swcCoreVersion, swcNodeVersion } from 'nx/src/utils/versions';
import { nxVersion } from '../../utils/versions'; import { nxVersion } from '../../utils/versions';
import { workspaceLintPluginDir } from '../../utils/workspace-lint-rules';
export const WORKSPACE_RULES_PROJECT_NAME = 'eslint-rules'; export const WORKSPACE_RULES_PROJECT_NAME = 'eslint-rules';
@ -105,11 +104,7 @@ export async function lintWorkspaceRulesProjectGenerator(
); );
// Add swc dependencies // Add swc dependencies
addDependenciesToPackageJson( addSwcRegisterDependencies(tree);
tree,
{},
{ '@swc-node/register': swcNodeVersion, '@swc/core': swcCoreVersion }
);
// Add extra config to the jest.config.ts file to allow ESLint 8 exports mapping to work with jest // Add extra config to the jest.config.ts file to allow ESLint 8 exports mapping to work with jest
addPropertyToJestConfig( addPropertyToJestConfig(

View File

@ -1,15 +1,11 @@
import { addDependenciesToPackageJson, formatFiles, Tree } from '@nx/devkit'; import { formatFiles, Tree } from '@nx/devkit';
import { swcCoreVersion, swcNodeVersion } from 'nx/src/utils/versions'; import { addSwcRegisterDependencies } from '@nx/js/src/utils/swc/add-swc-dependencies';
import { WORKSPACE_PLUGIN_DIR } from '../../generators/workspace-rules-project/workspace-rules-project'; import { WORKSPACE_PLUGIN_DIR } from '../../generators/workspace-rules-project/workspace-rules-project';
export default async function addSwcNodeIfNeeded(tree: Tree) { export default async function addSwcNodeIfNeeded(tree: Tree) {
try { try {
if (tree.exists(WORKSPACE_PLUGIN_DIR)) { if (tree.exists(WORKSPACE_PLUGIN_DIR)) {
addDependenciesToPackageJson( addSwcRegisterDependencies(tree);
tree,
{},
{ '@swc-node/register': swcNodeVersion, '@swc/core': swcCoreVersion }
);
await formatFiles(tree); await formatFiles(tree);
return; return;
} }

View File

@ -1,7 +1,6 @@
export const nxVersion = require('../../package.json').version; export const nxVersion = require('../../package.json').version;
export const tslintToEslintConfigVersion = '^2.13.0';
export const typescriptESLintVersion = '^5.58.0';
export const eslintVersion = '~8.15.0'; export const eslintVersion = '~8.15.0';
export const eslintConfigPrettierVersion = '8.1.0'; export const eslintConfigPrettierVersion = '8.1.0';
export const tslintToEslintConfigVersion = '^2.13.0';
export const typescriptESLintVersion = '^5.58.0';

View File

@ -5,7 +5,7 @@ import {
workspaceRoot, workspaceRoot,
writeJsonFile, writeJsonFile,
} from '@nx/devkit'; } from '@nx/devkit';
import { createLockFile, createPackageJson } from '@nx/js'; import { createLockFile, createPackageJson, getLockFileName } from '@nx/js';
import build from 'next/dist/build'; import build from 'next/dist/build';
import { join, resolve } from 'path'; import { join, resolve } from 'path';
import { copySync, existsSync, mkdir, writeFileSync } from 'fs-extra'; import { copySync, existsSync, mkdir, writeFileSync } from 'fs-extra';
@ -18,8 +18,6 @@ import { createNextConfigFile } from './lib/create-next-config-file';
import { checkPublicDirectory } from './lib/check-project'; import { checkPublicDirectory } from './lib/check-project';
import { NextBuildBuilderOptions } from '../../utils/types'; import { NextBuildBuilderOptions } from '../../utils/types';
import { getLockFileName } from 'nx/src/plugins/js/lock-file/lock-file';
export default async function buildExecutor( export default async function buildExecutor(
options: NextBuildBuilderOptions, options: NextBuildBuilderOptions,
context: ExecutorContext context: ExecutorContext

View File

@ -12,18 +12,19 @@ import {
import { libraryGenerator as jsLibraryGenerator } from '@nx/js'; import { libraryGenerator as jsLibraryGenerator } from '@nx/js';
import { addSwcDependencies } from '@nx/js/src/utils/swc/add-swc-dependencies'; import { addSwcDependencies } from '@nx/js/src/utils/swc/add-swc-dependencies';
import { Linter } from '@nx/linter'; import { Linter } from '@nx/linter';
import { swcNodeVersion } from 'nx/src/utils/versions';
import * as path from 'path'; import * as path from 'path';
import { nxVersion, tsLibVersion } from '../../utils/versions';
import { e2eProjectGenerator } from '../e2e-project/e2e'; import { e2eProjectGenerator } from '../e2e-project/e2e';
import { executorGenerator } from '../executor/executor'; import { executorGenerator } from '../executor/executor';
import { generatorGenerator } from '../generator/generator'; import { generatorGenerator } from '../generator/generator';
import pluginLintCheckGenerator from '../lint-checks/generator'; import pluginLintCheckGenerator from '../lint-checks/generator';
import { NormalizedSchema, normalizeOptions } from './utils/normalize-schema'; import { NormalizedSchema, normalizeOptions } from './utils/normalize-schema';
import { addTsLibDependencies } from '@nx/js/src/utils/typescript/add-tslib-dependencies';
import { addSwcRegisterDependencies } from '@nx/js/src/utils/swc/add-swc-dependencies';
import type { Schema } from './schema'; import type { Schema } from './schema';
const nxVersion = require('../../../package.json').version;
async function addFiles(host: Tree, options: NormalizedSchema) { async function addFiles(host: Tree, options: NormalizedSchema) {
host.delete(normalizePath(`${options.projectRoot}/src/lib`)); host.delete(normalizePath(`${options.projectRoot}/src/lib`));
@ -102,19 +103,19 @@ export async function pluginGenerator(host: Tree, schema: Schema) {
host, host,
{ {
'@nx/devkit': nxVersion, '@nx/devkit': nxVersion,
tslib: tsLibVersion,
}, },
{ {
'@nx/jest': nxVersion, '@nx/jest': nxVersion,
'@nx/js': nxVersion, '@nx/js': nxVersion,
'@nx/nx-plugin': nxVersion, '@nx/nx-plugin': nxVersion,
'@swc-node/register': swcNodeVersion,
} }
); );
addTsLibDependencies(host);
// Ensures Swc Deps are installed to handle running // Ensures Swc Deps are installed to handle running
// local plugin generators and executors // local plugin generators and executors
addSwcDependencies(host); addSwcDependencies(host);
addSwcRegisterDependencies(host);
await addFiles(host, options); await addFiles(host, options);
updatePluginConfig(host, options); updatePluginConfig(host, options);

View File

@ -1,17 +1,8 @@
import { import { formatFiles, installPackagesTask, Tree } from '@nx/devkit';
addDependenciesToPackageJson, import { addSwcRegisterDependencies } from '@nx/js/src/utils/swc/add-swc-dependencies';
formatFiles,
installPackagesTask,
Tree,
} from '@nx/devkit';
import { swcCoreVersion, swcNodeVersion } from 'nx/src/utils/versions';
export default async function addSwcNodeIfNeeded(tree: Tree) { export default async function addSwcNodeIfNeeded(tree: Tree) {
addDependenciesToPackageJson( addSwcRegisterDependencies(tree);
tree,
{},
{ '@swc-node/register': swcNodeVersion, '@swc/core': swcCoreVersion }
);
await formatFiles(tree); await formatFiles(tree);
return installPackagesTask(tree); return installPackagesTask(tree);
} }

View File

@ -1,3 +1 @@
export const nxVersion = require('../../package.json').version;
export const jsoncEslintParserVersion = '^2.1.0'; export const jsoncEslintParserVersion = '^2.1.0';
export const tsLibVersion = '^2.3.0';

View File

@ -15,7 +15,7 @@ import { sortObjectByKeys } from '../utils/object-sort';
import { import {
getRootTsConfigFileName, getRootTsConfigFileName,
getRootTsConfigPath, getRootTsConfigPath,
} from '../utils/typescript'; } from '../plugins/js/utils/typescript';
import { createProjectGraphAsync } from '../project-graph/project-graph'; import { createProjectGraphAsync } from '../project-graph/project-graph';
import { filterAffected } from '../project-graph/affected/affected-project-graph'; import { filterAffected } from '../project-graph/affected/affected-project-graph';
import { readNxJson } from '../config/configuration'; import { readNxJson } from '../config/configuration';

View File

@ -225,18 +225,3 @@ export { Hash, Hasher } from './hasher/hasher';
* @category Utils * @category Utils
*/ */
export { cacheDir } from './utils/cache-directory'; export { cacheDir } from './utils/cache-directory';
import { createLockFile as _createLockFile } from './plugins/js/lock-file/lock-file';
import { createPackageJson as _createPackageJson } from './plugins/js/package-json/create-package-json';
/**
* @category Package Manager
*/
/**
* @deprecated Import this from @nrwl/js instead
*/
export const createLockFile = _createLockFile;
/**
* @deprecated Import this from @nrwl/js instead
*/
export const createPackageJson = _createPackageJson;

View File

@ -1,17 +1,20 @@
// This must come before the Hasher import // This must come before the Hasher import
import { DependencyType } from '../config/project-graph'; import { DependencyType } from '../config/project-graph';
jest.doMock('../utils/workspace-root', () => { jest.mock('../utils/workspace-root', () => {
return { return {
workspaceRoot: '/root', workspaceRoot: '/root',
}; };
}); });
jest.mock('fs', () => require('memfs').fs); jest.mock('fs', () => require('memfs').fs);
jest.mock('../utils/typescript'); jest.mock('../plugins/js/utils/typescript', () => ({
getRootTsConfigFileName: jest
.fn()
.mockImplementation(() => '/root/tsconfig.base.json'),
}));
import { vol } from 'memfs'; import { vol } from 'memfs';
import tsUtils = require('../utils/typescript');
import { import {
expandNamedInput, expandNamedInput,
filterUsingGlobPatterns, filterUsingGlobPatterns,
@ -59,7 +62,6 @@ describe('Hasher', () => {
}, },
'/root' '/root'
); );
tsUtils.getRootTsConfigFileName = () => '/root/tsconfig.base.json';
}); });
afterEach(() => { afterEach(() => {

View File

@ -1,6 +1,5 @@
import { exec } from 'child_process'; import { exec } from 'child_process';
import * as minimatch from 'minimatch'; import * as minimatch from 'minimatch';
import { getRootTsConfigFileName } from '../utils/typescript';
import { defaultHashing, HashingImpl } from './hashing-impl'; import { defaultHashing, HashingImpl } from './hashing-impl';
import { import {
FileData, FileData,
@ -10,9 +9,8 @@ import {
} from '../config/project-graph'; } from '../config/project-graph';
import { NxJsonConfiguration } from '../config/nx-json'; import { NxJsonConfiguration } from '../config/nx-json';
import { Task } from '../config/task-graph'; import { Task } from '../config/task-graph';
import { readJsonFile } from '../utils/fileutils';
import { InputDefinition } from '../config/workspace-json-project-json'; import { InputDefinition } from '../config/workspace-json-project-json';
import { getImportPath } from '../utils/path'; import { hashTsConfig } from '../plugins/js/hasher/hasher';
type ExpandedSelfInput = type ExpandedSelfInput =
| { fileset: string } | { fileset: string }
@ -42,14 +40,6 @@ export interface Hash {
}; };
} }
interface CompilerOptions {
paths: Record<string, string[]>;
}
interface TsconfigJsonConfiguration {
compilerOptions: CompilerOptions;
}
/** /**
* The default hasher used by executors. * The default hasher used by executors.
*/ */
@ -94,7 +84,6 @@ export class Hasher {
legacyRuntimeInputs, legacyRuntimeInputs,
legacyFilesetInputs, legacyFilesetInputs,
this.projectGraph, this.projectGraph,
this.readTsConfig(),
this.hashing, this.hashing,
{ selectivelyHashTsConfig: this.options.selectivelyHashTsConfig ?? false } { selectivelyHashTsConfig: this.options.selectivelyHashTsConfig ?? false }
); );
@ -171,18 +160,6 @@ export class Hasher {
hashFile(path: string): string { hashFile(path: string): string {
return this.hashing.hashFile(path); return this.hashing.hashFile(path);
} }
private readTsConfig() {
try {
const res = readJsonFile(getRootTsConfigFileName());
res.compilerOptions.paths ??= {};
return res;
} catch {
return {
compilerOptions: { paths: {} },
};
}
}
} }
const DEFAULT_INPUTS: ReadonlyArray<InputDefinition> = [ const DEFAULT_INPUTS: ReadonlyArray<InputDefinition> = [
@ -209,7 +186,6 @@ class TaskHasher {
private readonly legacyRuntimeInputs: { runtime: string }[], private readonly legacyRuntimeInputs: { runtime: string }[],
private readonly legacyFilesetInputs: { fileset: string }[], private readonly legacyFilesetInputs: { fileset: string }[],
private readonly projectGraph: ProjectGraph, private readonly projectGraph: ProjectGraph,
private readonly tsConfigJson: TsconfigJsonConfiguration,
private readonly hashing: HashingImpl, private readonly hashing: HashingImpl,
private readonly options: { selectivelyHashTsConfig: boolean } private readonly options: { selectivelyHashTsConfig: boolean }
) {} ) {}
@ -490,13 +466,11 @@ class TaskHasher {
const fileNames = filteredFiles.map((f) => f.file); const fileNames = filteredFiles.map((f) => f.file);
const values = filteredFiles.map((f) => f.hash); const values = filteredFiles.map((f) => f.hash);
let tsConfig: string;
tsConfig = this.hashTsConfig(p);
const value = this.hashing.hashArray([ const value = this.hashing.hashArray([
...fileNames, ...fileNames,
...values, ...values,
JSON.stringify({ ...p.data, files: undefined }), JSON.stringify({ ...p.data, files: undefined }),
tsConfig, hashTsConfig(p, this.nxJson, this.options),
]); ]);
res({ res({
value, value,
@ -536,30 +510,6 @@ class TaskHasher {
value, value,
}; };
} }
private hashTsConfig(p: ProjectGraphProjectNode) {
if (this.options.selectivelyHashTsConfig) {
return this.removeOtherProjectsPathRecords(p);
} else {
return JSON.stringify(this.tsConfigJson);
}
}
private removeOtherProjectsPathRecords(p: ProjectGraphProjectNode) {
const { paths, ...compilerOptions } = this.tsConfigJson.compilerOptions;
const rootPath = p.data.root.split('/');
rootPath.shift();
const pathAlias = getImportPath(this.nxJson?.npmScope, rootPath.join('/'));
return JSON.stringify({
compilerOptions: {
...compilerOptions,
paths: {
[pathAlias]: paths[pathAlias] ?? [],
},
},
});
}
} }
export function getNamedInputs( export function getNamedInputs(

View File

@ -0,0 +1,62 @@
import { getImportPath } from '../../../utils/path';
import { ProjectGraphProjectNode } from '../../../config/project-graph';
import { readJsonFile } from '../../../utils/fileutils';
import { getRootTsConfigFileName } from '../utils/typescript';
import { NxJsonConfiguration } from '../../../config/nx-json';
interface CompilerOptions {
paths: Record<string, string[]>;
}
interface TsconfigJsonConfiguration {
compilerOptions: CompilerOptions;
}
function readTsConfigJson(): TsconfigJsonConfiguration {
try {
const res = readJsonFile(getRootTsConfigFileName());
res.compilerOptions.paths ??= {};
return res;
} catch {
return {
compilerOptions: { paths: {} },
};
}
}
let tsConfigJson: TsconfigJsonConfiguration;
export function hashTsConfig(
p: ProjectGraphProjectNode,
nxJson: NxJsonConfiguration,
{ selectivelyHashTsConfig }: { selectivelyHashTsConfig: boolean }
) {
if (!tsConfigJson) {
tsConfigJson = readTsConfigJson();
}
if (selectivelyHashTsConfig) {
return removeOtherProjectsPathRecords(p, tsConfigJson, nxJson);
} else {
return JSON.stringify(tsConfigJson);
}
}
function removeOtherProjectsPathRecords(
p: ProjectGraphProjectNode,
tsConfigJson: TsconfigJsonConfiguration,
nxJson: NxJsonConfiguration
) {
const { paths, ...compilerOptions } = tsConfigJson.compilerOptions;
const rootPath = p.data.root.split('/');
rootPath.shift();
const pathAlias = getImportPath(nxJson?.npmScope, rootPath.join('/'));
return JSON.stringify({
compilerOptions: {
...compilerOptions,
paths: {
[pathAlias]: paths[pathAlias] ?? [],
},
},
});
}

View File

@ -16,7 +16,7 @@ import { projectGraphCacheDirectory } from '../../utils/cache-directory';
import { readFileSync, writeFileSync } from 'fs'; import { readFileSync, writeFileSync } from 'fs';
import { workspaceRoot } from '../../utils/workspace-root'; import { workspaceRoot } from '../../utils/workspace-root';
import { ensureDirSync } from 'fs-extra'; import { ensureDirSync } from 'fs-extra';
import { removeNpmNodes } from 'nx/src/plugins/js/lock-file/remove-npm-nodes'; import { removeNpmNodes } from './lock-file/remove-npm-nodes';
export const processProjectGraph: ProjectGraphProcessor = async ( export const processProjectGraph: ProjectGraphProcessor = async (
graph, graph,

View File

@ -0,0 +1,75 @@
import { ProjectGraph } from '../../../../config/project-graph';
import { WholeFileChange } from '../../../../project-graph/file-utils';
import { getTouchedProjectsFromLockFile } from './lock-file-changes';
describe('getTouchedProjectsFromLockFile', () => {
let graph: ProjectGraph;
let allNodes = [];
beforeEach(() => {
graph = {
nodes: {
proj1: {
name: 'proj1',
type: 'app',
data: {
root: 'libs/proj1',
files: [],
},
},
proj2: {
name: 'proj2',
type: 'lib',
data: {
root: 'packages/proj2',
files: [],
},
},
app1: {
name: 'app1',
type: 'app',
data: {
root: 'apps/app1',
files: [],
},
},
},
dependencies: {},
};
allNodes = Object.keys(graph.nodes);
});
['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'pnpm-lock.yml'].forEach(
(lockFile) => {
describe(`"${lockFile}"`, () => {
it(`should not return changes when "${lockFile}" is not touched`, () => {
const result = getTouchedProjectsFromLockFile(
[
{
file: 'source.ts',
hash: 'some-hash',
getChanges: () => [new WholeFileChange()],
},
],
graph.nodes
);
expect(result).toEqual([]);
});
it(`should return all nodes when "${lockFile}" is touched`, () => {
const result = getTouchedProjectsFromLockFile(
[
{
file: lockFile,
hash: 'some-hash',
getChanges: () => [new WholeFileChange()],
},
],
graph.nodes
);
expect(result).toEqual(allNodes);
});
});
}
);
});

View File

@ -0,0 +1,19 @@
import { TouchedProjectLocator } from '../../../../project-graph/affected/affected-project-graph-models';
import { WholeFileChange } from '../../../../project-graph/file-utils';
import { JsonChange } from '../../../../utils/json-diff';
export const getTouchedProjectsFromLockFile: TouchedProjectLocator<
WholeFileChange | JsonChange
> = (fileChanges, projectGraphNodes): string[] => {
const lockFiles = [
'package-lock.json',
'yarn.lock',
'pnpm-lock.yaml',
'pnpm-lock.yml',
];
if (fileChanges.some((f) => lockFiles.includes(f.file))) {
return Object.values(projectGraphNodes).map((p) => p.name);
}
return [];
};

View File

@ -1,8 +1,8 @@
import { NxJsonConfiguration } from '../../../config/nx-json'; import { NxJsonConfiguration } from '../../../../config/nx-json';
import { ProjectGraph } from '../../../config/project-graph'; import { ProjectGraph } from '../../../../config/project-graph';
import { JsonDiffType } from '../../../utils/json-diff'; import { JsonDiffType } from '../../../../utils/json-diff';
import { logger } from '../../../utils/logger'; import { logger } from '../../../../utils/logger';
import { WholeFileChange } from '../../file-utils'; import { WholeFileChange } from '../../../../project-graph/file-utils';
import { getTouchedNpmPackages } from './npm-packages'; import { getTouchedNpmPackages } from './npm-packages';
describe('getTouchedNpmPackages', () => { describe('getTouchedNpmPackages', () => {

View File

@ -1,15 +1,18 @@
import { isWholeFileChange, WholeFileChange } from '../../file-utils'; import {
isWholeFileChange,
WholeFileChange,
} from '../../../../project-graph/file-utils';
import { import {
JsonDiffType, JsonDiffType,
isJsonChange, isJsonChange,
JsonChange, JsonChange,
} from '../../../utils/json-diff'; } from '../../../../utils/json-diff';
import { logger } from '../../../utils/logger'; import { logger } from '../../../../utils/logger';
import { TouchedProjectLocator } from '../affected-project-graph-models'; import { TouchedProjectLocator } from '../../../../project-graph/affected/affected-project-graph-models';
import { import {
ProjectGraphExternalNode, ProjectGraphExternalNode,
ProjectGraphProjectNode, ProjectGraphProjectNode,
} from '../../../config/project-graph'; } from '../../../../config/project-graph';
export const getTouchedNpmPackages: TouchedProjectLocator< export const getTouchedNpmPackages: TouchedProjectLocator<
WholeFileChange | JsonChange WholeFileChange | JsonChange

View File

@ -0,0 +1,26 @@
import { TouchedProjectLocator } from '../../../../project-graph/affected/affected-project-graph-models';
import { getTouchedProjectsFromLockFile } from './lock-file-changes';
import { getTouchedNpmPackages } from './npm-packages';
import { getTouchedProjectsFromTsConfig } from './tsconfig-json-changes';
export const getTouchedProjects: TouchedProjectLocator = (
touchedFiles,
nodes,
nxJson,
packageJson,
graph
): string[] => {
const touchedProjects = new Set<string>();
[
getTouchedProjectsFromLockFile,
getTouchedNpmPackages,
getTouchedProjectsFromTsConfig,
].forEach((fn) => {
(fn(touchedFiles, nodes, nxJson, packageJson, graph) as string[]).forEach(
(p) => touchedProjects.add(p)
);
});
return Array.from(touchedProjects);
};

View File

@ -1,8 +1,8 @@
import { WholeFileChange } from '../../file-utils'; import { WholeFileChange } from '../../../../project-graph/file-utils';
import { jsonDiff } from '../../../utils/json-diff'; import { jsonDiff } from '../../../../utils/json-diff';
import { getTouchedProjectsFromTsConfig } from './tsconfig-json-changes'; import { getTouchedProjectsFromTsConfig } from './tsconfig-json-changes';
import * as tsUtils from '../../../utils/typescript'; import * as tsUtils from '../../utils/typescript';
import { DependencyType, ProjectGraph } from '../../../config/project-graph'; import { DependencyType, ProjectGraph } from '../../../../config/project-graph';
describe('getTouchedProjectsFromTsConfig', () => { describe('getTouchedProjectsFromTsConfig', () => {
let graph: ProjectGraph; let graph: ProjectGraph;

View File

@ -1,12 +1,12 @@
import { WholeFileChange } from '../../file-utils'; import { WholeFileChange } from '../../../../project-graph/file-utils';
import { import {
JsonDiffType, JsonDiffType,
isJsonChange, isJsonChange,
JsonChange, JsonChange,
} from '../../../utils/json-diff'; } from '../../../../utils/json-diff';
import { getRootTsConfigFileName } from '../../../utils/typescript'; import { getRootTsConfigFileName } from '../../utils/typescript';
import { TouchedProjectLocator } from '../affected-project-graph-models'; import { TouchedProjectLocator } from '../../../../project-graph/affected/affected-project-graph-models';
import { ProjectGraphProjectNode } from '../../../config/project-graph'; import { ProjectGraphProjectNode } from '../../../../config/project-graph';
export const getTouchedProjectsFromTsConfig: TouchedProjectLocator< export const getTouchedProjectsFromTsConfig: TouchedProjectLocator<
WholeFileChange | JsonChange WholeFileChange | JsonChange

View File

@ -1,7 +1,7 @@
import { import {
getRootTsConfigFileName, getRootTsConfigFileName,
resolveModuleByImport, resolveModuleByImport,
} from '../../../../utils/typescript'; } from '../../utils/typescript';
import { isRelativePath, readJsonFile } from '../../../../utils/fileutils'; import { isRelativePath, readJsonFile } from '../../../../utils/fileutils';
import { dirname, join, posix } from 'path'; import { dirname, join, posix } from 'path';
import { workspaceRoot } from '../../../../utils/workspace-root'; import { workspaceRoot } from '../../../../utils/workspace-root';

View File

@ -1,6 +1,6 @@
import { dirname, join } from 'path'; import { dirname, join } from 'path';
import type { CompilerOptions, ModuleResolutionKind } from 'typescript'; import type { CompilerOptions } from 'typescript';
import { logger, NX_PREFIX, stripIndent } from './logger'; import { logger, NX_PREFIX, stripIndent } from '../../../utils/logger';
const swcNodeInstalled = packageIsInstalled('@swc-node/register'); const swcNodeInstalled = packageIsInstalled('@swc-node/register');
const tsNodeInstalled = packageIsInstalled('ts-node/register'); const tsNodeInstalled = packageIsInstalled('ts-node/register');

View File

@ -1,4 +1,4 @@
import { workspaceRoot } from './workspace-root'; import { workspaceRoot } from '../../../utils/workspace-root';
import { existsSync } from 'fs'; import { existsSync } from 'fs';
import { dirname, join } from 'path'; import { dirname, join } from 'path';
import type * as ts from 'typescript'; import type * as ts from 'typescript';

View File

@ -0,0 +1 @@
export const typescriptVersion = '~4.9.5';

View File

@ -4,7 +4,6 @@ import {
ProjectGraph, ProjectGraph,
ProjectGraphProjectNode, ProjectGraphProjectNode,
} from '../../config/project-graph'; } from '../../config/project-graph';
import { ProjectConfiguration } from '../../config/workspace-json-project-json';
export interface AffectedProjectGraphContext { export interface AffectedProjectGraphContext {
projectGraphNodes: Record<string, ProjectGraphProjectNode>; projectGraphNodes: Record<string, ProjectGraphProjectNode>;

View File

@ -3,12 +3,11 @@ import {
getImplicitlyTouchedProjects, getImplicitlyTouchedProjects,
getTouchedProjects, getTouchedProjects,
} from './locators/workspace-projects'; } from './locators/workspace-projects';
import { getTouchedNpmPackages } from './locators/npm-packages'; import { getTouchedProjects as getJSTouchedProjects } from '../../plugins/js/project-graph/affected/touched-projects';
import { import {
AffectedProjectGraphContext, AffectedProjectGraphContext,
TouchedProjectLocator, TouchedProjectLocator,
} from './affected-project-graph-models'; } from './affected-project-graph-models';
import { getTouchedProjectsFromTsConfig } from './locators/tsconfig-json-changes';
import { NxJsonConfiguration } from '../../config/nx-json'; import { NxJsonConfiguration } from '../../config/nx-json';
import { ProjectGraph } from '../../config/project-graph'; import { ProjectGraph } from '../../config/project-graph';
import { reverse } from '../operators'; import { reverse } from '../operators';
@ -25,9 +24,8 @@ export async function filterAffected(
const touchedProjectLocators: TouchedProjectLocator[] = [ const touchedProjectLocators: TouchedProjectLocator[] = [
getTouchedProjects, getTouchedProjects,
getImplicitlyTouchedProjects, getImplicitlyTouchedProjects,
getTouchedNpmPackages,
getTouchedProjectsFromTsConfig,
getTouchedProjectsFromProjectGlobChanges, getTouchedProjectsFromProjectGlobChanges,
getJSTouchedProjects,
]; ];
const touchedProjects = []; const touchedProjects = [];

View File

@ -27,14 +27,7 @@ export const getImplicitlyTouchedProjects: TouchedProjectLocator = (
nxJson nxJson
): string[] => { ): string[] => {
const implicits = {}; const implicits = {};
const globalFiles = [ const globalFiles = [...extractGlobalFilesFromInputs(nxJson), 'nx.json'];
...extractGlobalFilesFromInputs(nxJson),
'nx.json',
'package-lock.json',
'yarn.lock',
'pnpm-lock.yaml',
'pnpm-lock.yml',
];
globalFiles.forEach((file) => { globalFiles.forEach((file) => {
implicits[file] = '*' as any; implicits[file] = '*' as any;
}); });

View File

@ -16,7 +16,7 @@ import { buildWorkspaceProjectNodes } from './build-nodes';
import { loadNxPlugins } from '../utils/nx-plugin'; import { loadNxPlugins } from '../utils/nx-plugin';
import { defaultFileHasher } from '../hasher/file-hasher'; import { defaultFileHasher } from '../hasher/file-hasher';
import { createProjectFileMap } from './file-map-utils'; import { createProjectFileMap } from './file-map-utils';
import { getRootTsConfigPath } from '../utils/typescript'; import { getRootTsConfigPath } from '../plugins/js/utils/typescript';
import { import {
ProjectFileMap, ProjectFileMap,
ProjectGraph, ProjectGraph,

View File

@ -10,7 +10,10 @@ import {
PackageJson, PackageJson,
readModulePackageJsonWithoutFallbacks, readModulePackageJsonWithoutFallbacks,
} from './package-json'; } from './package-json';
import { registerTranspiler, registerTsConfigPaths } from './register'; import {
registerTranspiler,
registerTsConfigPaths,
} from '../plugins/js/utils/register';
import { import {
ProjectConfiguration, ProjectConfiguration,
ProjectsConfigurations, ProjectsConfigurations,
@ -24,7 +27,7 @@ import {
import { normalizePath } from './path'; import { normalizePath } from './path';
import { join } from 'path'; import { join } from 'path';
import { getNxRequirePaths } from './installation-directory'; import { getNxRequirePaths } from './installation-directory';
import { readTsConfig } from './typescript'; import { readTsConfig } from '../plugins/js/utils/typescript';
import type * as ts from 'typescript'; import type * as ts from 'typescript';

View File

@ -1,5 +1,5 @@
import { JsxEmit, ModuleKind, ScriptTarget } from 'typescript'; import { JsxEmit, ModuleKind, ScriptTarget } from 'typescript';
import { getTsNodeCompilerOptions } from './register'; import { getTsNodeCompilerOptions } from '../plugins/js/utils/register';
describe('getTsNodeCompilerOptions', () => { describe('getTsNodeCompilerOptions', () => {
it('should replace enum value with enum key for module', () => { it('should replace enum value with enum key for module', () => {

View File

@ -1,10 +1 @@
export const nxVersion = require('../../package.json').version; export const nxVersion = require('../../package.json').version;
export const angularCliVersion = '~15.2.0';
export const typescriptVersion = '~4.9.5';
export const prettierVersion = '^2.6.2';
export const typescriptESLintVersion = '^5.58.0';
export const eslintVersion = '~8.15.0';
export const eslintConfigPrettierVersion = '8.1.0';
export const swcNodeVersion = '^1.4.2';
export const swcCoreVersion = '^1.2.173';

View File

@ -1,4 +1,4 @@
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from '@nx/js';
import type * as ts from 'typescript'; import type * as ts from 'typescript';
import { ChangeType, StringChange } from '@nx/devkit'; import { ChangeType, StringChange } from '@nx/devkit';
import { ensureTypescript } from '@nx/js/src/utils/typescript/ensure-typescript'; import { ensureTypescript } from '@nx/js/src/utils/typescript/ensure-typescript';

View File

@ -7,7 +7,7 @@ import {
} from '@nx/devkit'; } from '@nx/devkit';
import ts = require('typescript'); import ts = require('typescript');
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from '@nx/js';
export async function migrateToWebPack5(tree: Tree) { export async function migrateToWebPack5(tree: Tree) {
allReactProjectsWithStorybookConfiguration(tree).forEach((project) => { allReactProjectsWithStorybookConfiguration(tree).forEach((project) => {

View File

@ -7,7 +7,7 @@ import {
Tree, Tree,
formatFiles, formatFiles,
} from '@nx/devkit'; } from '@nx/devkit';
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from '@nx/js';
import * as ts from 'typescript'; import * as ts from 'typescript';
export async function update(tree: Tree) { export async function update(tree: Tree) {

View File

@ -1,6 +1,7 @@
import type * as ts from 'typescript'; import type * as ts from 'typescript';
import { ChangeType, StringChange } from '@nx/devkit'; import { ChangeType, StringChange } from '@nx/devkit';
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from '@nx/js';
import { import {
findClosestOpening, findClosestOpening,
findElements, findElements,

View File

@ -1,5 +1,5 @@
import type * as ts from 'typescript'; import type * as ts from 'typescript';
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from '@nx/js';
import { ChangeType, logger, StringChange, StringInsertion } from '@nx/devkit'; import { ChangeType, logger, StringChange, StringInsertion } from '@nx/devkit';
import { ensureTypescript } from '@nx/js/src/utils/typescript/ensure-typescript'; import { ensureTypescript } from '@nx/js/src/utils/typescript/ensure-typescript';

View File

@ -1,5 +1,5 @@
import { joinPathFragments, logger } from '@nx/devkit'; import { joinPathFragments, logger } from '@nx/devkit';
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from '@nx/js';
import 'dotenv/config'; import 'dotenv/config';
import { existsSync, readFileSync } from 'fs'; import { existsSync, readFileSync } from 'fs';
import { join } from 'path'; import { join } from 'path';

View File

@ -6,7 +6,7 @@ import {
import { joinPathFragments, writeJson } from '@nx/devkit'; import { joinPathFragments, writeJson } from '@nx/devkit';
import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing'; import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing';
import { storybookVersion } from '@nx/storybook'; import { storybookVersion } from '@nx/storybook';
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from '@nx/js';
import * as ts from 'typescript'; import * as ts from 'typescript';
import { SyntaxKind } from 'typescript'; import { SyntaxKind } from 'typescript';
import { nxVersion } from '../../../utils/versions'; import { nxVersion } from '../../../utils/versions';

View File

@ -9,7 +9,7 @@ import {
visitNotIgnoredFiles, visitNotIgnoredFiles,
} from '@nx/devkit'; } from '@nx/devkit';
import { fileExists } from '@nx/workspace/src/utilities/fileutils'; import { fileExists } from '@nx/workspace/src/utilities/fileutils';
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from '@nx/js';
import { join, normalize } from 'path'; import { join, normalize } from 'path';
import { SyntaxKind } from 'typescript'; import { SyntaxKind } from 'typescript';
import { getTsSourceFile } from '../../../utils/utilities'; import { getTsSourceFile } from '../../../utils/utilities';

View File

@ -2,7 +2,7 @@ import { readJson, readJsonFile, TargetConfiguration, Tree } from '@nx/devkit';
import { CompilerOptions } from 'typescript'; import { CompilerOptions } from 'typescript';
import { storybookVersion } from './versions'; import { storybookVersion } from './versions';
import { statSync } from 'fs'; import { statSync } from 'fs';
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from '@nx/js';
import ts = require('typescript'); import ts = require('typescript');
import { gte, lt, major } from 'semver'; import { gte, lt, major } from 'semver';
import { join } from 'path'; import { join } from 'path';

View File

@ -11,7 +11,7 @@ import { existsSync } from 'fs';
import { resolve } from 'path'; import { resolve } from 'path';
import { createAsyncIterable } from '@nx/devkit/src/utils/async-iterable'; import { createAsyncIterable } from '@nx/devkit/src/utils/async-iterable';
import { registerTsConfigPaths } from 'nx/src/utils/register'; import { registerTsConfigPaths } from '@nx/js/src/internal';
export async function* viteBuildExecutor( export async function* viteBuildExecutor(
options: ViteBuildExecutorOptions, options: ViteBuildExecutorOptions,

View File

@ -11,7 +11,7 @@ import {
import { ViteDevServerExecutorOptions } from './schema'; import { ViteDevServerExecutorOptions } from './schema';
import { ViteBuildExecutorOptions } from '../build/schema'; import { ViteBuildExecutorOptions } from '../build/schema';
import { registerTsConfigPaths } from 'nx/src/utils/register'; import { registerTsConfigPaths } from '@nx/js/src/internal';
import { resolve } from 'path'; import { resolve } from 'path';
export async function* viteDevServerExecutor( export async function* viteDevServerExecutor(

View File

@ -7,7 +7,7 @@ import {
} from '@nx/devkit'; } from '@nx/devkit';
import { forEachExecutorOptions } from '@nx/devkit/src/generators/executor-options-utils'; import { forEachExecutorOptions } from '@nx/devkit/src/generators/executor-options-utils';
import { tsquery } from '@phenomnomnominal/tsquery'; import { tsquery } from '@phenomnomnominal/tsquery';
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from '@nx/js';
import { normalizeViteConfigFilePathWithTree } from '../../utils/generator-utils'; import { normalizeViteConfigFilePathWithTree } from '../../utils/generator-utils';
import ts = require('typescript'); import ts = require('typescript');

View File

@ -1,5 +1,5 @@
import { applyChangesToString, ChangeType, Tree } from '@nx/devkit'; import { applyChangesToString, ChangeType, Tree } from '@nx/devkit';
import { findNodes } from 'nx/src/utils/typescript'; import { findNodes } from '@nx/js';
import { TargetFlags } from './generator-utils'; import { TargetFlags } from './generator-utils';
import type { Node, ReturnStatement } from 'typescript'; import type { Node, ReturnStatement } from 'typescript';

View File

@ -3,10 +3,10 @@ import { createLockFile, createPackageJson } from '@nx/js';
import { ExecutorContext, type ProjectGraph, serializeJson } from '@nx/devkit'; import { ExecutorContext, type ProjectGraph, serializeJson } from '@nx/devkit';
import { import {
getHelperDependenciesFromProjectGraph, getHelperDependenciesFromProjectGraph,
getLockFileName,
HelperDependency, HelperDependency,
readTsConfig, readTsConfig,
} from '@nx/js'; } from '@nx/js';
import { getLockFileName } from 'nx/src/plugins/js/lock-file/lock-file';
const pluginName = 'GeneratePackageJsonPlugin'; const pluginName = 'GeneratePackageJsonPlugin';

View File

@ -13,8 +13,10 @@ import {
getImportPath, getImportPath,
} from '@nx/devkit'; } from '@nx/devkit';
import type * as ts from 'typescript'; import type * as ts from 'typescript';
import { getRootTsConfigPathInTree } from '../../../utilities/ts-config'; import {
import { findNodes } from 'nx/src/utils/typescript'; getRootTsConfigPathInTree,
findNodes,
} from '../../../utilities/ts-config';
import { NormalizedSchema } from '../schema'; import { NormalizedSchema } from '../schema';
import { normalizeSlashes } from './utils'; import { normalizeSlashes } from './utils';
import { relative } from 'path'; import { relative } from 'path';

View File

@ -1,6 +1,7 @@
import { offsetFromRoot, Tree, workspaceRoot } from '@nx/devkit'; import { offsetFromRoot, Tree, workspaceRoot } from '@nx/devkit';
import { existsSync } from 'fs'; import { existsSync } from 'fs';
import { dirname, join } from 'path'; import { dirname, join } from 'path';
import type { Node, SyntaxKind } from 'typescript';
import { ensureTypescript } from './typescript'; import { ensureTypescript } from './typescript';
let tsModule: typeof import('typescript'); let tsModule: typeof import('typescript');
@ -47,3 +48,38 @@ export function getRootTsConfigFileName(): string | null {
return null; return null;
} }
export function findNodes(
node: Node,
kind: SyntaxKind | SyntaxKind[],
max = Infinity
): Node[] {
if (!node || max == 0) {
return [];
}
const arr: Node[] = [];
const hasMatch = Array.isArray(kind)
? kind.includes(node.kind)
: node.kind === kind;
if (hasMatch) {
arr.push(node);
max--;
}
if (max > 0) {
for (const child of node.getChildren()) {
findNodes(child, kind, max).forEach((node) => {
if (max > 0) {
arr.push(node);
}
max--;
});
if (max <= 0) {
break;
}
}
}
return arr;
}

View File

@ -93,9 +93,9 @@
"@nx/nx-plugin": ["packages/nx-plugin"], "@nx/nx-plugin": ["packages/nx-plugin"],
"@nx/nx-plugin/*": ["packages/nx-plugin/*"], "@nx/nx-plugin/*": ["packages/nx-plugin/*"],
"@nx/react": ["packages/react"], "@nx/react": ["packages/react"],
"@nx/react/*": ["packages/react/*"],
"@nx/react-native": ["packages/react-native"], "@nx/react-native": ["packages/react-native"],
"@nx/react-native/*": ["packages/react-native/*"], "@nx/react-native/*": ["packages/react-native/*"],
"@nx/react/*": ["packages/react/*"],
"@nx/rollup": ["packages/rollup"], "@nx/rollup": ["packages/rollup"],
"@nx/rollup/*": ["packages/rollup/*"], "@nx/rollup/*": ["packages/rollup/*"],
"@nx/storybook": ["packages/storybook"], "@nx/storybook": ["packages/storybook"],