@rushstack/lockfile-explorer
Version:
Rush Lockfile Explorer: The UI for solving version conflicts quickly in a large monorepo
270 lines • 13.1 kB
JavaScript
;
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExplorerCommandLineParser = void 0;
const node_process_1 = __importDefault(require("node:process"));
const path = __importStar(require("node:path"));
const express_1 = __importDefault(require("express"));
const js_yaml_1 = __importDefault(require("js-yaml"));
const cors_1 = __importDefault(require("cors"));
const node_core_library_1 = require("@rushstack/node-core-library");
const terminal_1 = require("@rushstack/terminal");
const ts_command_line_1 = require("@rushstack/ts-command-line");
const lfx_shared_1 = require("../../../build/lfx-shared");
const lockfilePath = __importStar(require("../../graph/lockfilePath"));
const init_1 = require("../../utils/init");
const PnpmfileRunner_1 = require("../../graph/PnpmfileRunner");
const lfxGraphLoader = __importStar(require("../../graph/lfxGraphLoader"));
const constants_1 = require("../../utils/constants");
const PackageUpdateChecker_1 = require("../../utils/PackageUpdateChecker");
const EXPLORER_TOOL_FILENAME = 'lockfile-explorer';
function printUpdateNotification(result, terminal) {
if (result === null || result === void 0 ? void 0 : result.isOutdated) {
terminal.writeLine(terminal_1.Colorize.yellow(`\nUpdate available: ${constants_1.LFX_VERSION} → ${result.latestVersion}\n` +
`Run: npm install -g ${constants_1.LFX_PACKAGE_NAME}\n`));
}
}
class ExplorerCommandLineParser extends ts_command_line_1.CommandLineParser {
constructor(terminal) {
super({
toolFilename: EXPLORER_TOOL_FILENAME,
toolDescription: 'Lockfile Explorer is a desktop app for investigating and solving version conflicts in a PNPM workspace.'
});
this._debugParameter = this.defineFlagParameter({
parameterLongName: '--debug',
parameterShortName: '-d',
description: 'Show the full call stack if an error occurs while executing the tool'
});
this._subspaceParameter = this.defineStringParameter({
parameterLongName: '--subspace',
argumentName: 'SUBSPACE_NAME',
description: 'Specifies an individual Rush subspace to check.',
defaultValue: 'default'
});
this.globalTerminal = terminal;
}
get isDebug() {
return this._debugParameter.value;
}
async onExecuteAsync() {
const terminal = this.globalTerminal;
terminal.writeLine(terminal_1.Colorize.bold(`\nRush Lockfile Explorer ${constants_1.LFX_VERSION}`) +
terminal_1.Colorize.cyan(' - https://lfx.rushstack.io/\n'));
// Start the update check now so it runs concurrently with server setup.
// The result is awaited and displayed inside app.listen once the server is ready.
const updateChecker = new PackageUpdateChecker_1.PackageUpdateChecker({
packageName: constants_1.LFX_PACKAGE_NAME,
currentVersion: constants_1.LFX_VERSION,
// In debug mode, bypass the cache so the notice appears immediately.
forceCheck: this.isDebug
});
const updateCheckPromise = updateChecker.tryGetUpdateAsync();
const PORT = 8091;
// Must not have a trailing slash
const SERVICE_URL = `http://localhost:${PORT}`;
const appState = (0, init_1.init)({
appVersion: constants_1.LFX_VERSION,
debugMode: this.isDebug,
subspaceName: this._subspaceParameter.value
});
const lfxWorkspace = appState.lfxWorkspace;
// Important: This must happen after init() reads the current working directory
node_process_1.default.chdir(appState.lockfileExplorerProjectRoot);
const distFolderPath = `${appState.lockfileExplorerProjectRoot}/dist`;
const app = (0, express_1.default)();
app.use(express_1.default.json());
app.use((0, cors_1.default)());
// Variable used to check if the front-end client is still connected
let awaitingFirstConnect = true;
let isClientConnected = false;
let disconnected = false;
setInterval(() => {
if (!isClientConnected && !awaitingFirstConnect && !disconnected) {
terminal.writeLine(terminal_1.Colorize.red('The client has disconnected!'));
terminal.writeLine(`Please open a browser window at http://localhost:${PORT}/app`);
disconnected = true;
}
else if (!awaitingFirstConnect) {
isClientConnected = false;
}
}, 4000);
// This takes precedence over the `/app` static route, which also has an `initappcontext.js` file.
app.get('/initappcontext.js', (req, res) => {
const appContext = {
serviceUrl: SERVICE_URL,
appVersion: appState.appVersion,
debugMode: this.isDebug
};
const sourceCode = [
`console.log('Loaded initappcontext.js');`,
`appContext = ${JSON.stringify(appContext)}`
].join('\n');
res.type('application/javascript').send(sourceCode);
});
app.use('/', express_1.default.static(distFolderPath));
app.use('/favicon.ico', express_1.default.static(distFolderPath, { index: 'favicon.ico' }));
app.get('/api/health', (req, res) => {
awaitingFirstConnect = false;
isClientConnected = true;
if (disconnected) {
disconnected = false;
terminal.writeLine(terminal_1.Colorize.green('The client has reconnected!'));
}
res.status(200).send();
});
app.get('/api/graph', async (req, res) => {
const pnpmLockfileText = await node_core_library_1.FileSystem.readFileAsync(appState.pnpmLockfileLocation);
const lockfile = js_yaml_1.default.load(pnpmLockfileText);
const graph = lfxGraphLoader.generateLockfileGraph(lockfile, lfxWorkspace);
const jsonGraph = lfx_shared_1.lfxGraphSerializer.serializeToJson(graph);
res.type('application/json').send(jsonGraph);
});
app.post('/api/package-json', async (req, res) => {
const { projectPath } = req.body;
const fileLocation = `${appState.projectRoot}/${projectPath}/package.json`;
let packageJsonText;
try {
packageJsonText = await node_core_library_1.FileSystem.readFileAsync(fileLocation);
}
catch (e) {
if (node_core_library_1.FileSystem.isNotExistError(e)) {
return res.status(404).send({
message: `Could not load package.json file for this package. Have you installed all the dependencies for this workspace?`,
error: `No package.json in location: ${projectPath}`
});
}
else {
throw e;
}
}
res.send(packageJsonText);
});
app.get('/api/pnpmfile', async (req, res) => {
var _a, _b;
const pnpmfilePath = lockfilePath.join(lfxWorkspace.workspaceRootFullPath, (_b = (_a = lfxWorkspace.rushConfig) === null || _a === void 0 ? void 0 : _a.rushPnpmfilePath) !== null && _b !== void 0 ? _b : lfxWorkspace.pnpmfilePath);
let pnpmfile;
try {
pnpmfile = await node_core_library_1.FileSystem.readFileAsync(pnpmfilePath);
}
catch (e) {
if (node_core_library_1.FileSystem.isNotExistError(e)) {
return res.status(404).send({
message: `Could not load .pnpmfile.cjs file in this repo: "${pnpmfilePath}"`,
error: `No .pnpmifile.cjs found.`
});
}
else {
throw e;
}
}
res.send(pnpmfile);
});
app.post('/api/package-spec', async (req, res) => {
const { projectPath } = req.body;
const fileLocation = `${appState.projectRoot}/${projectPath}/package.json`;
let packageJson;
try {
packageJson = await node_core_library_1.JsonFile.loadAsync(fileLocation);
}
catch (e) {
if (node_core_library_1.FileSystem.isNotExistError(e)) {
return res.status(404).send({
message: `Could not load package.json file in location: ${projectPath}`
});
}
else {
throw e;
}
}
let parsedPackage = packageJson;
const pnpmfilePath = path.join(lfxWorkspace.workspaceRootFullPath, lfxWorkspace.pnpmfilePath);
if (await node_core_library_1.FileSystem.existsAsync(pnpmfilePath)) {
const pnpmFileRunner = new PnpmfileRunner_1.PnpmfileRunner(pnpmfilePath);
try {
parsedPackage = await pnpmFileRunner.transformPackageAsync(packageJson, fileLocation);
}
finally {
await pnpmFileRunner.disposeAsync();
}
}
res.send(parsedPackage);
});
app.listen(PORT, async () => {
terminal.writeLine(`App launched on ${SERVICE_URL}`);
printUpdateNotification(await updateCheckPromise, terminal);
if (!appState.debugMode) {
try {
// Launch the default web browser using the platform-native open command.
let browserCmd;
let browserArgs;
switch (node_process_1.default.platform) {
case 'win32': {
// "start" is a cmd.exe built-in, not a standalone executable.
// The empty string is the required [title] argument; without it,
// cmd interprets the URL as the title and ignores it.
browserCmd = 'cmd';
browserArgs = ['/c', 'start', '', SERVICE_URL];
break;
}
case 'darwin': {
browserCmd = 'open';
browserArgs = [SERVICE_URL];
break;
}
default: {
// Linux and other Unix-like systems
browserCmd = 'xdg-open';
browserArgs = [SERVICE_URL];
break;
}
}
const browserProcess = node_core_library_1.Executable.spawn(browserCmd, browserArgs, { stdio: 'ignore' });
// Detach from our Node.js process so the browser stays open after we exit
browserProcess.unref();
}
catch (e) {
terminal.writeError('Error launching browser: ' + e.toString());
}
}
});
}
}
exports.ExplorerCommandLineParser = ExplorerCommandLineParser;
//# sourceMappingURL=ExplorerCommandLineParser.js.map