PHP WebShell

Текущая директория: /opt/BitGoJS/node_modules/nx/src/nx-init/angular

Просмотр файла: index.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addNxToAngularCliRepo = void 0;
const tslib_1 = require("tslib");
const enquirer_1 = require("enquirer");
const fs_1 = require("fs");
const path_1 = require("path");
const angular_json_1 = require("../../adapter/angular-json");
const fileutils_1 = require("../../utils/fileutils");
const object_sort_1 = require("../../utils/object-sort");
const output_1 = require("../../utils/output");
const path_2 = require("../../utils/path");
const utils_1 = require("../utils");
const legacy_angular_versions_1 = require("./legacy-angular-versions");
const yargsParser = require("yargs-parser");
const defaultCacheableOperations = [
    'build',
    'server',
    'test',
    'lint',
];
const parsedArgs = yargsParser(process.argv, {
    boolean: ['yes'],
    string: ['cacheable'],
    alias: {
        yes: ['y'],
    },
});
let repoRoot;
let workspaceTargets;
function addNxToAngularCliRepo() {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        repoRoot = process.cwd();
        output_1.output.log({ title: '🧐 Checking versions compatibility' });
        const legacyMigrationFn = yield (0, legacy_angular_versions_1.getLegacyMigrationFunctionIfApplicable)(repoRoot, parsedArgs.yes !== true);
        if (legacyMigrationFn) {
            output_1.output.log({ title: '💽 Running migration for a legacy Angular version' });
            yield legacyMigrationFn();
            process.exit(0);
        }
        output_1.output.success({
            title: '✅ The Angular version is compatible with the latest version of Nx!',
        });
        output_1.output.log({ title: '🐳 Nx initialization' });
        const cacheableOperations = yield collectCacheableOperations();
        const useNxCloud = parsedArgs.yes !== true ? yield (0, utils_1.askAboutNxCloud)() : false;
        output_1.output.log({ title: '📦 Installing dependencies' });
        installDependencies(useNxCloud);
        output_1.output.log({ title: '📝 Setting up workspace' });
        yield setupWorkspace(cacheableOperations);
        if (useNxCloud) {
            output_1.output.log({ title: '🛠️ Setting up Nx Cloud' });
            (0, utils_1.initCloud)(repoRoot, 'nx-init-angular');
        }
        output_1.output.success({
            title: '🎉 Nx is now enabled in your workspace!',
            bodyLines: [
                `Execute 'npx nx build' twice to see the computation caching in action.`,
                'Learn more about the changes done to your workspace at https://nx.dev/recipes/adopting-nx/migration-angular.',
            ],
        });
    });
}
exports.addNxToAngularCliRepo = addNxToAngularCliRepo;
function collectCacheableOperations() {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        let cacheableOperations;
        workspaceTargets = getWorkspaceTargets();
        const defaultCacheableTargetsInWorkspace = defaultCacheableOperations.filter((t) => workspaceTargets.includes(t));
        if (parsedArgs.yes !== true) {
            output_1.output.log({
                title: `🧑‍🔧 Please answer the following questions about the targets found in your angular.json in order to generate task runner configuration`,
            });
            cacheableOperations = (yield (0, enquirer_1.prompt)([
                {
                    type: 'multiselect',
                    name: 'cacheableOperations',
                    initial: defaultCacheableTargetsInWorkspace,
                    message: 'Which of the following targets are cacheable? (Produce the same output given the same input, e.g. build, test and lint usually are, serve and start are not)',
                    // enquirer mutates the array below, create a new one to avoid it
                    choices: [...workspaceTargets],
                },
            ])).cacheableOperations;
        }
        else {
            cacheableOperations = parsedArgs.cacheable
                ? parsedArgs.cacheable.split(',')
                : defaultCacheableTargetsInWorkspace;
        }
        return cacheableOperations;
    });
}
function installDependencies(useNxCloud) {
    (0, utils_1.addDepsToPackageJson)(repoRoot, useNxCloud);
    addPluginDependencies();
    (0, utils_1.runInstall)(repoRoot);
}
function addPluginDependencies() {
    var _a, _b, _c, _d, _e, _f, _g;
    const packageJsonPath = (0, path_1.join)(repoRoot, 'package.json');
    const packageJson = (0, fileutils_1.readJsonFile)(packageJsonPath);
    const nxVersion = require('../../../package.json').version;
    (_a = packageJson.devDependencies) !== null && _a !== void 0 ? _a : (packageJson.devDependencies = {});
    packageJson.devDependencies['@nrwl/angular'] = nxVersion;
    packageJson.devDependencies['@nrwl/workspace'] = nxVersion;
    const peerDepsToInstall = [
        '@angular-devkit/core',
        '@angular-devkit/schematics',
        '@schematics/angular',
    ];
    const angularCliVersion = (_e = (_d = (_b = packageJson.devDependencies['@angular/cli']) !== null && _b !== void 0 ? _b : (_c = packageJson.dependencies) === null || _c === void 0 ? void 0 : _c['@angular/cli']) !== null && _d !== void 0 ? _d : packageJson.devDependencies['@angular-devkit/build-angular']) !== null && _e !== void 0 ? _e : (_f = packageJson.dependencies) === null || _f === void 0 ? void 0 : _f['@angular-devkit/build-angular'];
    for (const dep of peerDepsToInstall) {
        if (!packageJson.devDependencies[dep] && !((_g = packageJson.dependencies) === null || _g === void 0 ? void 0 : _g[dep])) {
            packageJson.devDependencies[dep] = angularCliVersion;
        }
    }
    packageJson.devDependencies = (0, object_sort_1.sortObjectByKeys)(packageJson.devDependencies);
    (0, fileutils_1.writeJsonFile)(packageJsonPath, packageJson);
}
function setupWorkspace(cacheableOperations) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const angularJsonPath = (0, path_1.join)(repoRoot, 'angular.json');
        const angularJson = (0, fileutils_1.readJsonFile)(angularJsonPath);
        const workspaceCapabilities = getWorkspaceCapabilities(angularJson.projects);
        createNxJson(angularJson, cacheableOperations, workspaceCapabilities);
        (0, utils_1.addVsCodeRecommendedExtensions)(repoRoot, [
            'nrwl.angular-console',
            'angular.ng-template',
            workspaceCapabilities.eslintProjectConfigFile
                ? 'dbaeumer.vscode-eslint'
                : undefined,
        ].filter(Boolean));
        replaceNgWithNxInPackageJsonScripts();
        // convert workspace config format to standalone project configs
        // update its targets outputs and delete angular.json
        const projects = (0, angular_json_1.toNewFormat)(angularJson).projects;
        for (const [projectName, project] of Object.entries(projects)) {
            updateProjectOutputs(project);
            (0, fileutils_1.writeJsonFile)((0, path_1.join)(project.root, 'project.json'), Object.assign(Object.assign({ $schema: (0, path_2.normalizePath)((0, path_1.relative)((0, path_1.join)(repoRoot, project.root), (0, path_1.join)(repoRoot, 'node_modules/nx/schemas/project-schema.json'))), name: projectName }, project), { root: undefined }));
        }
        (0, fs_1.unlinkSync)(angularJsonPath);
    });
}
function createNxJson(angularJson, cacheableOperations, { eslintProjectConfigFile, test, karmaProjectConfigFile, }) {
    (0, utils_1.createNxJsonFile)(repoRoot, [], cacheableOperations, {});
    const nxJson = (0, fileutils_1.readJsonFile)((0, path_1.join)(repoRoot, 'nx.json'));
    nxJson.namedInputs = {
        sharedGlobals: [],
        default: ['{projectRoot}/**/*', 'sharedGlobals'],
        production: [
            'default',
            ...(test
                ? [
                    '!{projectRoot}/tsconfig.spec.json',
                    '!{projectRoot}/**/*.spec.[jt]s',
                    karmaProjectConfigFile ? '!{projectRoot}/karma.conf.js' : undefined,
                ].filter(Boolean)
                : []),
            eslintProjectConfigFile ? '!{projectRoot}/.eslintrc.json' : undefined,
        ].filter(Boolean),
    };
    nxJson.targetDefaults = {};
    if (workspaceTargets.includes('build')) {
        nxJson.targetDefaults.build = {
            dependsOn: ['^build'],
            inputs: ['production', '^production'],
        };
    }
    if (workspaceTargets.includes('server')) {
        nxJson.targetDefaults.server = { inputs: ['production', '^production'] };
    }
    if (workspaceTargets.includes('test')) {
        const inputs = ['default', '^production'];
        if ((0, fileutils_1.fileExists)((0, path_1.join)(repoRoot, 'karma.conf.js'))) {
            inputs.push('{workspaceRoot}/karma.conf.js');
        }
        nxJson.targetDefaults.test = { inputs };
    }
    if (workspaceTargets.includes('lint')) {
        const inputs = ['default'];
        if ((0, fileutils_1.fileExists)((0, path_1.join)(repoRoot, '.eslintrc.json'))) {
            inputs.push('{workspaceRoot}/.eslintrc.json');
        }
        nxJson.targetDefaults.lint = { inputs };
    }
    if (workspaceTargets.includes('e2e')) {
        nxJson.targetDefaults.e2e = { inputs: ['default', '^production'] };
    }
    // Angular 14 workspaces support defaultProject, keep it until we drop support
    nxJson.defaultProject = angularJson.defaultProject;
    (0, fileutils_1.writeJsonFile)((0, path_1.join)(repoRoot, 'nx.json'), nxJson);
}
function updateProjectOutputs(project) {
    var _a;
    Object.values((_a = project.targets) !== null && _a !== void 0 ? _a : {}).forEach((target) => {
        if ([
            '@angular-devkit/build-angular:browser',
            '@angular-builders/custom-webpack:browser',
            'ngx-build-plus:browser',
            '@angular-devkit/build-angular:server',
            '@angular-builders/custom-webpack:server',
            'ngx-build-plus:server',
        ].includes(target.executor)) {
            target.outputs = ['{options.outputPath}'];
        }
        else if (target.executor === '@angular-eslint/builder:lint') {
            target.outputs = ['{options.outputFile}'];
        }
        else if (target.executor === '@angular-devkit/build-angular:ng-packagr') {
            try {
                const ngPackageJsonPath = (0, path_1.join)(repoRoot, target.options.project);
                const ngPackageJson = (0, fileutils_1.readJsonFile)(ngPackageJsonPath);
                const outputPath = (0, path_1.relative)(repoRoot, (0, path_1.resolve)((0, path_1.dirname)(ngPackageJsonPath), ngPackageJson.dest));
                target.outputs = [`{workspaceRoot}/${(0, path_2.normalizePath)(outputPath)}`];
            }
            catch (_a) { }
        }
    });
}
function getWorkspaceTargets() {
    var _a;
    const { projects } = (0, fileutils_1.readJsonFile)((0, path_1.join)(repoRoot, 'angular.json'));
    const targets = new Set();
    for (const project of Object.values(projects !== null && projects !== void 0 ? projects : {})) {
        for (const target of Object.keys((_a = project.architect) !== null && _a !== void 0 ? _a : {})) {
            targets.add(target);
        }
    }
    return Array.from(targets);
}
function getWorkspaceCapabilities(projects) {
    const capabilities = {
        eslintProjectConfigFile: false,
        test: false,
        karmaProjectConfigFile: false,
    };
    for (const project of Object.values(projects)) {
        if (!capabilities.eslintProjectConfigFile &&
            projectHasEslintConfig(project)) {
            capabilities.eslintProjectConfigFile = true;
        }
        if (!capabilities.test && projectUsesKarmaBuilder(project)) {
            capabilities.test = true;
        }
        if (!capabilities.karmaProjectConfigFile &&
            projectHasKarmaConfig(project)) {
            capabilities.karmaProjectConfigFile = true;
        }
        if (capabilities.eslintProjectConfigFile &&
            capabilities.test &&
            capabilities.karmaProjectConfigFile) {
            return capabilities;
        }
    }
    return capabilities;
}
function projectUsesKarmaBuilder(project) {
    var _a;
    return Object.values((_a = project.architect) !== null && _a !== void 0 ? _a : {}).some((target) => target.builder === '@angular-devkit/build-angular:karma');
}
function projectHasKarmaConfig(project) {
    return (0, fileutils_1.fileExists)((0, path_1.join)(project.root, 'karma.conf.js'));
}
function projectHasEslintConfig(project) {
    return (0, fileutils_1.fileExists)((0, path_1.join)(project.root, '.eslintrc.json'));
}
function replaceNgWithNxInPackageJsonScripts() {
    var _a;
    const packageJsonPath = (0, path_1.join)(repoRoot, 'package.json');
    const packageJson = (0, fileutils_1.readJsonFile)(packageJsonPath);
    (_a = packageJson.scripts) !== null && _a !== void 0 ? _a : (packageJson.scripts = {});
    Object.keys(packageJson.scripts).forEach((script) => {
        packageJson.scripts[script] = packageJson.scripts[script]
            .replace(/^nx$/, 'nx')
            .replace(/^ng /, 'nx ')
            .replace(/ ng /g, ' nx ');
    });
    (0, fileutils_1.writeJsonFile)(packageJsonPath, packageJson);
}
//# sourceMappingURL=index.js.map

Выполнить команду


Для локальной разработки. Не используйте в интернете!