Project Init

This commit is contained in:
Muluhabt
2026-05-29 15:23:46 +03:00
commit 2fbc557aac
67387 changed files with 6063341 additions and 0 deletions

8
node_modules/nx/dist/bin/init-local.d.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
import { WorkspaceTypeAndRoot } from '../src/utils/find-workspace-root';
/**
* Nx is being run inside a workspace.
*
* @param workspace Relevant local workspace properties
*/
export declare function initLocal(workspace: WorkspaceTypeAndRoot): Promise<void>;
export declare function rewriteTargetsAndProjects(args: string[]): string[];

197
node_modules/nx/dist/bin/init-local.js generated vendored Normal file
View File

@@ -0,0 +1,197 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initLocal = initLocal;
exports.rewriteTargetsAndProjects = rewriteTargetsAndProjects;
const perf_hooks_1 = require("perf_hooks");
const nx_commands_1 = require("../src/command-line/nx-commands");
const strip_indents_1 = require("../src/utils/strip-indents");
const client_1 = require("../src/daemon/client/client");
const enquirer_1 = require("enquirer");
const output_1 = require("../src/utils/output");
const analytics_1 = require("../src/analytics");
/**
* Nx is being run inside a workspace.
*
* @param workspace Relevant local workspace properties
*/
async function initLocal(workspace) {
process.env.NX_CLI_SET = 'true';
try {
// In case Nx Cloud forcibly exits while the TUI is running, ensure the terminal is restored etc.
process.on('exit', (...args) => {
if (typeof globalThis.tuiOnProcessExit === 'function') {
globalThis.tuiOnProcessExit(...args);
}
});
perf_hooks_1.performance.mark('init-local');
if (workspace.type !== 'nx' && shouldDelegateToAngularCLI()) {
console.warn((0, strip_indents_1.stripIndents) `Using Nx to run Angular CLI commands is deprecated and will be removed in a future version.
To run Angular CLI commands, use \`ng\`.`);
handleAngularCLIFallbacks(workspace);
return;
}
// Ensure NxConsole is installed if the user has it configured.
try {
await ensureNxConsoleInstalledViaDaemon();
}
catch { }
const command = process.argv[2];
if (command === 'run' || command === 'g' || command === 'generate') {
nx_commands_1.commandsObject.parse(process.argv.slice(2));
}
else if (isKnownCommand(command)) {
const newArgs = rewriteTargetsAndProjects(process.argv);
const help = newArgs.indexOf('--help');
const split = newArgs.indexOf('--');
if (help > -1 && (split === -1 || split > help)) {
nx_commands_1.commandsObject.showHelp();
process.exit(0);
}
else {
nx_commands_1.commandsObject.parse(newArgs);
}
}
else {
nx_commands_1.commandsObject.parse(process.argv.slice(2));
}
}
catch (e) {
console.error(e.message);
(0, analytics_1.flushAnalytics)();
process.exit(1);
}
}
function rewriteTargetsAndProjects(args) {
const newArgs = [args[2]];
let i = 3;
while (i < args.length) {
if (args[i] === '--') {
return [...newArgs, ...args.slice(i)];
}
else if (args[i] === '-p' ||
args[i] === '--projects' ||
args[i] === '--exclude' ||
args[i] === '--files' ||
args[i] === '-t' ||
args[i] === '--target' ||
args[i] === '--targets') {
newArgs.push(args[i]);
i++;
const items = [];
while (i < args.length && !args[i].startsWith('-')) {
items.push(args[i]);
i++;
}
newArgs.push(items.join(','));
}
else {
newArgs.push(args[i]);
++i;
}
}
return newArgs;
}
function isKnownCommand(command) {
const commands = [
...Object.keys(nx_commands_1.commandsObject
.getInternalMethods()
.getCommandInstance()
.getCommandHandlers()),
'g',
'dep-graph',
'affected:dep-graph',
'format',
'workspace-schematic',
'connect-to-nx-cloud',
'clear-cache',
'help',
];
return !command || command.startsWith('-') || commands.indexOf(command) > -1;
}
function shouldDelegateToAngularCLI() {
const command = process.argv[2];
const commands = [
'analytics',
'cache',
'completion',
'config',
'doc',
'update',
];
return commands.indexOf(command) > -1;
}
async function ensureNxConsoleInstalledViaDaemon() {
// Only proceed if daemon is available
if (!client_1.daemonClient.enabled() || !(await client_1.daemonClient.isServerAvailable())) {
return;
}
// Get status from daemon
const status = await client_1.daemonClient.getNxConsoleStatus();
// If we should prompt the user
if (status.shouldPrompt && process.stdout.isTTY) {
output_1.output.log({
title: "Install Nx's official editor extension to:",
bodyLines: [
'- Enable your AI assistant to do more by understanding your workspace',
'- Add IntelliSense for Nx configuration files',
'- Explore your workspace visually',
],
});
try {
const { shouldInstallNxConsole } = await (0, enquirer_1.prompt)({
type: 'confirm',
name: 'shouldInstallNxConsole',
message: 'Install Nx Console? (you can uninstall anytime)',
initial: true,
});
// Set preference and install if user said yes
const result = await client_1.daemonClient.setNxConsolePreferenceAndInstall(shouldInstallNxConsole);
if (result.installed) {
output_1.output.log({ title: 'Successfully installed Nx Console!' });
}
}
catch (error) {
// User cancelled or error occurred, save preference as false
await client_1.daemonClient.setNxConsolePreferenceAndInstall(false);
}
}
}
function handleAngularCLIFallbacks(workspace) {
if (process.argv[2] === 'update' && process.env.FORCE_NG_UPDATE != 'true') {
console.log(`Nx provides a much improved version of "ng update". It runs the same migrations, but allows you to:`);
console.log(`- rerun the same migration multiple times`);
console.log(`- reorder migrations, skip migrations`);
console.log(`- fix migrations that "almost work"`);
console.log(`- commit a partially migrated state`);
console.log(`- change versions of packages to match organizational requirements`);
console.log(`And, in general, it is lot more reliable for non-trivial workspaces. Read more at: https://nx.dev/getting-started/nx-and-angular#ng-update-and-nx-migrate`);
console.log(`Run "nx migrate latest" to update to the latest version of Nx.`);
console.log(`Running "ng update" can still be useful in some dev workflows, so we aren't planning to remove it.`);
console.log(`If you need to use it, run "FORCE_NG_UPDATE=true ng update".`);
}
else if (process.argv[2] === 'completion') {
if (!process.argv[3]) {
console.log(`"ng completion" is not natively supported by Nx.
Instead, you could try an Nx Editor Plugin for a visual tool to run Nx commands. If you're using VSCode, you can use the Nx Console plugin, or if you're using WebStorm, you could use one of the available community plugins.
For more information, see https://nx.dev/getting-started/editor-setup`);
}
}
else if (process.argv[2] === 'cache') {
console.log(`"ng cache" is not natively supported by Nx.
To clear the cache, you can delete the ".angular/cache" directory (or the directory configured by "cli.cache.path" in the "nx.json" file).
To update the cache configuration, you can directly update the relevant options in your "nx.json" file (https://angular.dev/reference/configs/workspace-config#cache-options).`);
}
else {
try {
// nx-ignore-next-line
const cli = require.resolve('@angular/cli/lib/init.js', {
paths: [workspace.dir],
});
require(cli);
}
catch (e) {
console.error(`Could not find '@angular/cli/lib/init.js' module in this workspace.`, e);
process.exit(1);
}
}
}

3
node_modules/nx/dist/bin/nx-cloud.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
import type { CloudTaskRunnerOptions } from '../src/nx-cloud/nx-cloud-tasks-runner-shell';
export declare function invokeCommandWithNxCloudClient(options: CloudTaskRunnerOptions): Promise<any>;

47
node_modules/nx/dist/bin/nx-cloud.js generated vendored Executable file
View File

@@ -0,0 +1,47 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.invokeCommandWithNxCloudClient = invokeCommandWithNxCloudClient;
const get_cloud_options_1 = require("../src/nx-cloud/utilities/get-cloud-options");
const update_manager_1 = require("../src/nx-cloud/update-manager");
const output_1 = require("../src/utils/output");
const client_1 = require("../src/nx-cloud/utilities/client");
const command = process.argv[2];
const options = (0, get_cloud_options_1.getCloudOptions)();
Promise.resolve().then(async () => invokeCommandWithNxCloudClient(options));
async function invokeCommandWithNxCloudClient(options) {
try {
const client = await (0, client_1.getCloudClient)(options);
client.invoke(command);
}
catch (e) {
if (e instanceof client_1.UnknownCommandError) {
output_1.output.error({
title: `Unknown Command "${e.command}"`,
});
output_1.output.log({
title: 'Available Commands:',
bodyLines: e.availableCommands.map((c) => `- ${c}`),
});
process.exit(1);
}
const body = ['Cannot run commands from the `nx-cloud` CLI.'];
if (e instanceof update_manager_1.NxCloudEnterpriseOutdatedError) {
try {
// TODO: Remove this when all enterprise customers have updated.
// Try requiring the bin from the `nx-cloud` package.
return require('nx-cloud/bin/nx-cloud');
}
catch { }
body.push('If you are an Nx Enterprise customer, please reach out to your assigned Developer Productivity Engineer.', 'If you are NOT an Nx Enterprise customer but are seeing this message, please reach out to cloud-support@nrwl.io.');
}
if (e instanceof update_manager_1.NxCloudClientUnavailableError) {
body.unshift('You may be offline. Please try again when you are back online.');
}
output_1.output.error({
title: e.message,
bodyLines: body,
});
process.exit(1);
}
}

3
node_modules/nx/dist/bin/nx.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
import '../src/utils/enable-compile-cache';
import '../src/utils/perf-logging';

306
node_modules/nx/dist/bin/nx.js generated vendored Executable file
View File

@@ -0,0 +1,306 @@
#!/usr/bin/env node
"use strict";
// TODO: Remove this workaround once picocolors handles FORCE_COLOR=0 correctly
// See: https://github.com/alexeyraspopov/picocolors/issues/100
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
if (process.env.FORCE_COLOR === '0') {
process.env.NO_COLOR = '1';
delete process.env.FORCE_COLOR;
}
// Must be the first import — see enable-compile-cache.ts.
require("../src/utils/enable-compile-cache");
const find_workspace_root_1 = require("../src/utils/find-workspace-root");
const pc = tslib_1.__importStar(require("picocolors"));
const output_1 = require("../src/utils/output");
const installation_directory_1 = require("../src/utils/installation-directory");
const semver_1 = require("semver");
const strip_indents_1 = require("../src/utils/strip-indents");
const child_process_1 = require("child_process");
const module_1 = require("module");
const path_1 = require("path");
const fs_1 = require("fs");
const perf_hooks_1 = require("perf_hooks");
// Register the performance observer as early as possible so any
// `performance.mark` / `measure` anywhere downstream is captured. The module
// is side-effect only and its heavy deps (analytics, daemon logger) are
// lazy-loaded inside the observer callback, so the import itself is cheap.
require("../src/utils/perf-logging");
const isTsExt = (0, path_1.extname)(__filename).endsWith('.ts');
const pathToPkgJson = isTsExt ? '../package.json' : '../../package.json';
async function main() {
if (process.argv[2] !== 'report' &&
process.argv[2] !== '--version' &&
process.argv[2] !== '--help' &&
process.argv[2] !== 'reset') {
const { assertSupportedPlatform } = await import('../src/native/assert-supported-platform.js');
assertSupportedPlatform();
}
const workspace = (0, find_workspace_root_1.findWorkspaceRoot)(process.cwd());
// --version doesn't need any env / daemon / analytics state — skip dotenv
// loading (and the heavy modules it would pull in).
if (workspace && process.argv[2] !== '--version') {
const { workspaceDataDirectoryForWorkspace } = await import('../src/utils/cache-directory.js');
process.report.reportOnFatalError = true;
process.report.directory = workspaceDataDirectoryForWorkspace(workspace.dir);
const { loadRootEnvFiles } = await import('../src/utils/dotenv.js');
perf_hooks_1.performance.mark('loading dotenv files:start');
loadRootEnvFiles(workspace.dir);
perf_hooks_1.performance.mark('loading dotenv files:end');
perf_hooks_1.performance.measure('loading dotenv files', 'loading dotenv files:start', 'loading dotenv files:end');
}
// new is a special case because there is no local workspace to load
if (process.argv[2] === 'new' ||
process.argv[2] === '_migrate' ||
process.argv[2] === 'init' ||
process.argv[2] === 'configure-ai-agents' ||
process.argv[2] === 'mcp' ||
(process.argv[2] === 'graph' && !workspace)) {
process.env.NX_DAEMON = 'false';
(await import('nx/src/command-line/nx-commands')).commandsObject.argv;
}
else {
// polyfill rxjs observable to avoid issues with multiple version of Observable installed in node_modules
// https://twitter.com/BenLesh/status/1192478226385428483?s=20
if (!Symbol.observable)
Symbol.observable = Symbol('observable polyfill');
// Make sure that a local copy of Nx exists in workspace
let localNx;
try {
localNx = workspace && resolveNx(workspace);
}
catch {
localNx = null;
}
const isLocalInstall = localNx === resolveNx(null) || localNx === __filename;
const { LOCAL_NX_VERSION, GLOBAL_NX_VERSION } = determineNxVersions(localNx, workspace, isLocalInstall);
if (process.argv[2] === '--version') {
handleNxVersionCommand(LOCAL_NX_VERSION, GLOBAL_NX_VERSION);
}
if (!workspace && !isNxCloudCommand(process.argv[2])) {
handleNoWorkspace(GLOBAL_NX_VERSION);
}
if (!localNx && !isNxCloudCommand(process.argv[2])) {
handleMissingLocalInstallation(workspace ? workspace.dir : null);
}
// this file is already in the local workspace
if (isNxCloudCommand(process.argv[2])) {
const { daemonClient } = await import('../src/daemon/client/client.js');
if (!daemonClient.enabled() && workspace !== null) {
const { setupWorkspaceContext } = await import('../src/utils/workspace-context.js');
setupWorkspaceContext(workspace.dir);
}
await initAnalytics();
// nx-cloud commands can run without local Nx installation
process.env.NX_DAEMON = 'false';
(await import('nx/src/command-line/nx-commands')).commandsObject.argv;
}
else if (isLocalInstall) {
const { daemonClient } = await import('../src/daemon/client/client.js');
if (!daemonClient.enabled() && workspace !== null) {
const { setupWorkspaceContext } = await import('../src/utils/workspace-context.js');
setupWorkspaceContext(workspace.dir);
}
await initAnalytics();
const { initLocal } = await import('./init-local.js');
await initLocal(workspace);
}
else if (localNx) {
// Nx is being run from globally installed CLI - hand off to the local
// Don't start analytics, connect to the DB, or set up the workspace
// context here — the local Nx will handle it when it runs its own bin/nx.ts
warnIfUsingOutdatedGlobalInstall(GLOBAL_NX_VERSION, LOCAL_NX_VERSION);
if (localNx.includes('.nx')) {
const nxWrapperPath = localNx.replace(/\.nx.*/, '.nx/') + 'nxw.js';
require(nxWrapperPath);
}
else {
require(localNx);
}
}
}
}
function handleNoWorkspace(globalNxVersion) {
output_1.output.log({
title: `The current directory isn't part of an Nx workspace.`,
bodyLines: [
`To create a workspace run:`,
pc.bold(pc.white(`npx create-nx-workspace@latest <workspace name>`)),
'',
`To add Nx to an existing workspace with a workspace-specific nx.json, run:`,
pc.bold(pc.white(`npx nx@latest init`)),
],
});
output_1.output.note({
title: `For more information please visit https://nx.dev/`,
});
warnIfUsingOutdatedGlobalInstall(globalNxVersion);
process.exit(1);
}
function handleNxVersionCommand(LOCAL_NX_VERSION, GLOBAL_NX_VERSION) {
console.log((0, strip_indents_1.stripIndents) `Nx Version:
- Local: ${LOCAL_NX_VERSION ? 'v' + LOCAL_NX_VERSION : 'Not found'}
- Global: ${GLOBAL_NX_VERSION ? 'v' + GLOBAL_NX_VERSION : 'Not found'}`);
process.exit(0);
}
function determineNxVersions(localNx, workspace, isLocalInstall) {
const LOCAL_NX_VERSION = localNx
? getLocalNxVersion(workspace)
: null;
const GLOBAL_NX_VERSION = isLocalInstall
? null
: require(pathToPkgJson).version;
globalThis.GLOBAL_NX_VERSION ??= GLOBAL_NX_VERSION;
return { LOCAL_NX_VERSION, GLOBAL_NX_VERSION };
}
function resolveNx(workspace) {
// root relative to location of the nx bin
const globalsRoot = (0, path_1.join)(__dirname, '../../../../');
const root = workspace ? workspace.dir : globalsRoot;
// Use createRequire to resolve from outside the nx package,
// avoiding self-referencing caused by the exports field
// prefer Nx installed in .nx/installation
try {
const installPath = (0, installation_directory_1.getNxInstallationPath)(root);
if ((0, fs_1.existsSync)(installPath)) {
const installRequire = (0, module_1.createRequire)((0, path_1.join)(installPath, 'package.json'));
return installRequire.resolve('nx/bin/nx.js');
}
}
catch { }
// check for root install
const rootRequire = (0, module_1.createRequire)((0, path_1.join)(root, 'package.json'));
return rootRequire.resolve('nx/bin/nx.js');
}
function isNxCloudCommand(command) {
const nxCloudCommands = [
'start-ci-run',
'start-agent',
'stop-all-agents',
'complete-ci-run',
'login',
'logout',
'connect',
'view-logs',
'fix-ci',
'record',
'download-cloud-client',
];
return nxCloudCommands.includes(command);
}
let analyticsStarted = false;
async function initAnalytics() {
const { ensureAnalyticsPreferenceSet } = await import('../src/utils/analytics-prompt.js');
const { startAnalytics } = await import('../src/analytics/index.js');
try {
await ensureAnalyticsPreferenceSet();
}
catch { }
await startAnalytics();
analyticsStarted = true;
}
function handleMissingLocalInstallation(detectedWorkspaceRoot) {
output_1.output.error({
title: detectedWorkspaceRoot
? `Could not find Nx modules at "${detectedWorkspaceRoot}".`
: `Could not find Nx modules in this workspace.`,
bodyLines: [`Have you run ${pc.bold(pc.white(`npm/yarn install`))}?`],
});
process.exit(1);
}
/**
* Assumes currently running Nx is global install.
* Warns if out of date by 1 major version or more.
*/
function warnIfUsingOutdatedGlobalInstall(globalNxVersion, localNxVersion) {
// Never display this warning if Nx is already running via Nx
if (process.env.NX_CLI_SET) {
return;
}
const isOutdatedGlobalInstall = checkOutdatedGlobalInstallation(globalNxVersion, localNxVersion);
// Using a global Nx Install
if (isOutdatedGlobalInstall) {
const bodyLines = localNxVersion
? [
`Your repository uses a higher version of Nx (${localNxVersion}) than your global CLI version (${globalNxVersion})`,
]
: [];
bodyLines.push('For more information, see https://nx.dev/more-concepts/global-nx');
output_1.output.warn({
title: `It's time to update Nx 🎉`,
bodyLines,
});
}
}
function checkOutdatedGlobalInstallation(globalNxVersion, localNxVersion) {
// We aren't running a global install, so we can't know if its outdated.
if (!globalNxVersion) {
return false;
}
if (localNxVersion) {
// If the global Nx install is at least a major version behind the local install, warn.
return (0, semver_1.major)(globalNxVersion) < (0, semver_1.major)(localNxVersion);
}
// No local installation was detected. This can happen if the user is running a global install
// that contains an older version of Nx, which is unable to detect the local installation. The most
// recent case where this would have happened would be when we stopped generating workspace.json by default,
// as older global installations used it to determine the workspace root. This only be hit in rare cases,
// but can provide valuable insights for troubleshooting.
const latestVersionOfNx = getLatestVersionOfNx();
if (latestVersionOfNx && (0, semver_1.major)(globalNxVersion) < (0, semver_1.major)(latestVersionOfNx)) {
return true;
}
}
function getLocalNxVersion(workspace) {
try {
const searchPaths = (0, installation_directory_1.getNxRequirePaths)(workspace.dir);
for (const searchPath of searchPaths) {
if (!(0, fs_1.existsSync)(searchPath)) {
continue;
}
try {
const externalRequire = (0, module_1.createRequire)((0, path_1.join)(searchPath, 'package.json'));
const pkgJsonPath = externalRequire.resolve('nx/package.json');
return require(pkgJsonPath).version;
}
catch { }
}
}
catch { }
return null;
}
function _getLatestVersionOfNx() {
try {
return (0, child_process_1.execSync)('npm view nx@latest version', {
windowsHide: true,
})
.toString()
.trim();
}
catch {
try {
return (0, child_process_1.execSync)('pnpm view nx@latest version', {
windowsHide: true,
})
.toString()
.trim();
}
catch {
return null;
}
}
}
const getLatestVersionOfNx = ((fn) => {
let cache = null;
return () => cache || (cache = fn());
})(_getLatestVersionOfNx);
main().catch(async (error) => {
console.error(error);
if (analyticsStarted) {
// analyticsStarted implies '../src/analytics' is already in the module
// cache, so this resolves from cache without any disk work.
const { flushAnalytics } = await import('../src/analytics/index.js');
flushAnalytics();
}
process.exit(1);
});

1
node_modules/nx/dist/bin/post-install.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export {};

52
node_modules/nx/dist/bin/post-install.js generated vendored Normal file
View File

@@ -0,0 +1,52 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const workspace_root_1 = require("../src/utils/workspace-root");
const fileutils_1 = require("../src/utils/fileutils");
const path_1 = require("path");
const assert_supported_platform_1 = require("../src/native/assert-supported-platform");
const update_manager_1 = require("../src/nx-cloud/update-manager");
const get_cloud_options_1 = require("../src/nx-cloud/utilities/get-cloud-options");
const nx_cloud_utils_1 = require("../src/utils/nx-cloud-utils");
const nx_json_1 = require("../src/config/nx-json");
const logger_1 = require("../src/utils/logger");
// The post install is not critical, to avoid any chance that it may hang
// we will kill this process after 30 seconds.
const postinstallTimeout = setTimeout(() => {
logger_1.logger.verbose('Nx post-install timed out.');
process.exit(0);
}, 30_000);
(async () => {
const start = new Date();
try {
if (isMainNxPackage() && (0, fileutils_1.fileExists)((0, path_1.join)(workspace_root_1.workspaceRoot, 'nx.json'))) {
(0, assert_supported_platform_1.assertSupportedPlatform)();
if ((0, nx_cloud_utils_1.isNxCloudUsed)((0, nx_json_1.readNxJson)())) {
await (0, update_manager_1.verifyOrUpdateNxCloudClient)((0, get_cloud_options_1.getCloudOptions)());
}
}
}
catch (e) {
logger_1.logger.verbose(e);
}
finally {
const end = new Date();
logger_1.logger.verbose(`Nx postinstall steps took ${end.getTime() - start.getTime()}ms`);
clearTimeout(postinstallTimeout);
process.exit(0);
}
})();
function isMainNxPackage() {
const mainNxPath = require.resolve('nx', {
paths: [workspace_root_1.workspaceRoot],
});
const thisNxPath = require.resolve('nx');
return mainNxPath === thisNxPath;
}
process.on('uncaughtException', (e) => {
logger_1.logger.verbose(e);
process.exit(0);
});
process.on('unhandledRejection', (e) => {
logger_1.logger.verbose(e);
process.exit(0);
});

1
node_modules/nx/dist/bin/run-executor.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export {};

66
node_modules/nx/dist/bin/run-executor.js generated vendored Normal file
View File

@@ -0,0 +1,66 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = require("fs");
const run_1 = require("../src/command-line/run/run");
if (process.env.NX_TERMINAL_OUTPUT_PATH) {
setUpOutputWatching(process.env.NX_TERMINAL_CAPTURE_STDERR === 'true', process.env.NX_STREAM_OUTPUT === 'true');
}
if (!process.env.NX_WORKSPACE_ROOT) {
console.error('Invalid Nx command invocation');
process.exit(1);
}
process.env.NX_CLI_SET = 'true';
/**
* We need to collect all stdout and stderr and store it, so the caching mechanism
* could store it.
*
* Writing stdout and stderr into different streams is too risky when using TTY.
*
* So we are simply monkey-patching the Javascript object. In this case the actual output will always be correct.
* And the cached output should be correct unless the CLI bypasses process.stdout or console.log and uses some
* C-binary to write to stdout.
*/
function setUpOutputWatching(captureStderr, streamOutput) {
const stdoutWrite = process.stdout._write;
const stderrWrite = process.stderr._write;
// The terminal output file gets out and err
const outputPath = process.env.NX_TERMINAL_OUTPUT_PATH;
const stdoutAndStderrLogFileHandle = (0, fs_1.openSync)(outputPath, 'w');
const onlyStdout = [];
process.stdout._write = (chunk, encoding, callback) => {
onlyStdout.push(chunk);
(0, fs_1.appendFileSync)(stdoutAndStderrLogFileHandle, chunk);
if (streamOutput) {
stdoutWrite.apply(process.stdout, [chunk, encoding, callback]);
}
else {
callback();
}
};
process.stderr._write = (chunk, encoding, callback) => {
(0, fs_1.appendFileSync)(stdoutAndStderrLogFileHandle, chunk);
if (streamOutput) {
stderrWrite.apply(process.stderr, [chunk, encoding, callback]);
}
else {
callback();
}
};
process.on('exit', (code) => {
// when the process exits successfully, and we are not asked to capture stderr
// override the file with only stdout
if (code === 0 && !captureStderr) {
(0, fs_1.writeFileSync)(outputPath, onlyStdout.join(''));
}
});
}
process.on('message', async (message) => {
try {
const statusCode = await (0, run_1.run)(process.cwd(), process.env.NX_WORKSPACE_ROOT, message.targetDescription, message.overrides, message.isVerbose, message.taskGraph);
process.exit(statusCode);
}
catch (e) {
console.error(e);
process.exit(1);
}
});