@serpent/common-cli
Version:
通用的 cli 相关的函数
220 lines (216 loc) • 12.4 kB
JavaScript
import { _ as __awaiter, a as __generator, b as __spreadArray } from './tslib.es6-636c4f06.mjs';
import path from 'path';
import Module from 'module';
import { fileURLToPath } from 'url';
import { c as cmd, o as opt } from './cmd-f38c24cc.mjs';
import './isCommandExists-0f8fbb8f.mjs';
import { run } from './run.mjs';
import { b as findupPackage } from './context-96dcd180.mjs';
import './Dir-b98fddc7.mjs';
import { g as tryGetProjectBinFile } from './project-0299066e.mjs';
import { r as readJsonFile } from './readJsonFile-255f65c0.mjs';
import 'fs';
import { c as createPackage } from './createPackage-cfe91bd7.mjs';
import './satisfies-144b0f35.mjs';
import './format-e8a6577a.mjs';
import './info-fd7bb244.mjs';
import './logger.mjs';
import './warn-1994a28d.mjs';
import 'http';
import 'https';
import { createDebug } from './debug.mjs';
import './supportColor-2e661db8.mjs';
import 'os';
import './_commonjsHelpers-7d1333e8.mjs';
import './table-75b962e9.mjs';
import './index-c12dbf5e.mjs';
import './helper-1331d234.mjs';
import './exists-d3d14d46.mjs';
import 'crypto';
import 'child_process';
import 'node:buffer';
import 'node:path';
import 'node:child_process';
import 'node:process';
import 'node:url';
import 'node:os';
import './index-3b2c9171.mjs';
import 'assert';
import 'events';
import 'buffer';
import 'stream';
import 'util';
import 'tty';
function proxy(COMMAND_KEY, COMMAND_VERSION, options) {
var _this = this;
var pkgName = options.pkgName, _a = options.configOpts, configOpts = _a === void 0 ? [] : _a, configPath = options.configPath, _b = options.nodeArgs, nodeArgs = _b === void 0 ? [] : _b, silent = options.silent, bootstrap = options.bootstrap;
var binName = options.binName || pkgName;
var debug = createDebug("".concat(COMMAND_KEY.replace(/-/g, ':'), ":").concat(binName));
return cmd({
usage: "".concat(COMMAND_KEY, " ").concat(binName, " [options]"),
version: false,
help: false,
options: {
forceVendor: opt('boolean', '是否强制重新创建 durka/vendors 下的项目'),
},
}, function (ctx) { return __awaiter(_this, void 0, void 0, function () {
var forceVendor, cliRootDir, resolve, pkg, binFile, exec, workRootDir, workVendorsDir_1, configArgs, cacheFile, cache, _a, entry, _b, args, newCache;
var _this = this;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
forceVendor = ctx.options.forceVendor;
debug('command options %o', ctx.options);
cliRootDir = ctx.findupPackageRoot(fileURLToPath(options.metaUrl));
resolve = Module.createRequire(options.metaUrl).resolve;
debug('cli root dir: %s', cliRootDir);
pkg = resolvePkg(pkgName, resolve);
binFile = ctx.tryGetProjectBinFile(pkg.rootDir, binName);
if (!binFile)
throw new Error("\u65E0\u6CD5\u627E\u5230 ".concat(pkgName, " \u9879\u76EE\u7684 bin \u6587\u4EF6"));
debug('target command bin file %s', binFile);
exec = function (file, args) {
if (args === void 0) { args = []; }
return __awaiter(_this, void 0, void 0, function () {
var child, e_1, exited;
var _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_c.trys.push([0, 2, , 3]);
child = run(__spreadArray(__spreadArray(__spreadArray(__spreadArray(['node'], nodeArgs, true), [file], false), args, true), ctx.args, true), { silent: silent });
(_a = options.onChildForked) === null || _a === void 0 ? void 0 : _a.call(options, child);
return [4 /*yield*/, child];
case 1:
_c.sent();
return [3 /*break*/, 3];
case 2:
e_1 = _c.sent();
exited = (_b = options.onChildError) === null || _b === void 0 ? void 0 : _b.call(options, e_1);
if (!exited) {
console.log(e_1.message);
process.exit(e_1.exitCode || 1);
}
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
});
};
if (!(ctx.args.includes('-h') || ctx.args.includes('--help'))) return [3 /*break*/, 2];
ctx.help(); // 输出当前代理的帮助信息
return [4 /*yield*/, exec(binFile)]; // 输出代理的命令的帮助信息
case 1:
_c.sent(); // 输出代理的命令的帮助信息
return [3 /*break*/, 6];
case 2:
workRootDir = ctx.findupPackageRoot();
workVendorsDir_1 = path.join(workRootDir, 'durka', 'vendors');
debug('work root dir: %s', workRootDir);
configArgs = [];
if (configPath && configOpts.length && configOpts.every(function (c) { return !ctx.args.includes(c); })) {
configArgs.push(configOpts[0], configPath);
}
debug('config args: %o, opts: %o, path: %s', configArgs, configOpts, configPath);
cacheFile = path.join(workVendorsDir_1, pkgName, '.cache');
if (!(!forceVendor && ctx.existsFile(cacheFile))) return [3 /*break*/, 4];
cache = ctx.tryReadJsonFile(cacheFile);
debug('proxy command cache %o', cache);
if (!(cache && cache.version === COMMAND_VERSION && cache.path === cacheFile && cache.entry)) return [3 /*break*/, 4];
debug('run proxy command on cache');
return [4 /*yield*/, exec(cache.entry, __spreadArray(__spreadArray([], configArgs, true), cache.args, true))];
case 3: return [2 /*return*/, _c.sent()];
case 4:
_a = bootstrap({
pkg: pkg,
binFile: binFile,
workRootDir: workRootDir,
workVendorsDir: workVendorsDir_1,
cliRootDir: cliRootDir,
resolve: resolve,
resolvePkg: function (pkgName) { return resolvePkg(pkgName, resolve); },
proxyPackage: function (pkgName, cb, opts) { return proxyPackage(resolve, workVendorsDir_1, pkgName, cb, opts); },
createPackage: function (pkgName, cb, pkgDetail) {
if (pkgDetail === void 0) { pkgDetail = {}; }
return createPackage(workVendorsDir_1, pkgName, pkgDetail, cb);
},
}), entry = _a.entry, _b = _a.args, args = _b === void 0 ? [] : _b;
debug('created proxy command', { entry: entry, args: args });
newCache = { version: COMMAND_VERSION, path: cacheFile, entry: entry, args: args };
ctx.writeJsonFile(cacheFile, newCache);
debug('write proxy command cache %o', newCache);
debug('run proxy command on fresh');
return [4 /*yield*/, exec(entry, __spreadArray(__spreadArray([], configArgs, true), args, true))];
case 5:
_c.sent();
_c.label = 6;
case 6: return [2 /*return*/];
}
});
}); });
}
function getTypesFileFromPkg(pkg) {
var _a;
if (pkg.types)
return pkg.types;
var exp = (_a = pkg.exports) === null || _a === void 0 ? void 0 : _a['.'];
return exp && exp.types ? exp.types : '';
}
function resolvePkg(pkgName, resolve) {
// 不要直接 resolve('xxx/package.json'),esm 中没声明 export package.json 就 resolve 不了
var mainFile = resolve(pkgName);
var jsonPath = findupPackage(mainFile);
var rootDir = path.dirname(jsonPath);
return {
name: pkgName,
rootDir: rootDir,
jsonPath: jsonPath,
mainFile: mainFile,
get typesFile() {
return path.resolve(rootDir, getTypesFileFromPkg(readJsonFile(jsonPath)));
},
get jsonDetail() {
return readJsonFile(jsonPath);
},
};
}
function proxyPackage(resolve, vendorsDir, pkgName, _cb, _opts) {
var pkg = resolvePkg(pkgName, resolve);
var jsonDetail = pkg.jsonDetail, rootDir = pkg.rootDir;
var cb = _cb;
var options = _opts;
if (typeof _cb === 'object') {
options = _cb;
cb = null;
}
if (!options)
options = {};
var exportDefault = options.exportDefault;
return createPackage(vendorsDir, pkgName, {}, function (dist) {
var _a, _b;
if (jsonDetail.type)
dist.jsonDetail.type = jsonDetail.type;
if (jsonDetail.version)
dist.jsonDetail.version = jsonDetail.version;
if (jsonDetail.bin && !options.noBin) {
var binFile = options.binFile || tryGetProjectBinFile(rootDir, options.binName);
if (!binFile)
throw new Error("\u5728\u76EE\u5F55 ".concat(rootDir, " \u4E2D\u65E0\u6CD5\u627E\u5230\u9879\u76EE ").concat(pkg.name, " \u7684 bin \u6587\u4EF6"));
if (jsonDetail.type === 'module' || binFile.endsWith('.mjs'))
dist.setBinMJS({ source: binFile });
else
dist.setBinCJS({ source: binFile });
}
if (jsonDetail.main && !options.noMain && !options.noMainCJS)
dist.setMainCJS({ source: rootDir, exportDefault: exportDefault });
if ((jsonDetail.module || ((_b = (_a = jsonDetail.exports) === null || _a === void 0 ? void 0 : _a['.']) === null || _b === void 0 ? void 0 : _b['import'])) && !options.noMain && !options.noMainMJS)
dist.setMainMJS({ source: rootDir, exportDefault: exportDefault });
if (jsonDetail.types && !options.noTypes)
dist.setTypes({ source: rootDir, exportDefault: exportDefault });
if (typeof cb === 'function')
cb(dist);
});
}
/** 重写查找指定CJS 与 ESM模块的方法 */
var redirectResolve = function (modules, path) { return "const Module = require('module')\nconst path = require('path')\nconst { fileURLToPath } = require('url')\n\nconst proxies = [".concat(modules.map(function (m) { return "'".concat(m, "'"); }).join(', '), "]\nconst resolvePath = '").concat(path, "'\nconst match = (id) => typeof id === 'string' && (proxies.includes(id) || proxies.some(p => id.startsWith(p + '/')))\n\nconst originalRequire = Module.prototype.require\nModule.prototype.require = function(id) {\n if (match(id)) {\n const local = require.resolve(id, { paths: Array.from(new Set([resolvePath, process.cwd()])) }) // \u4F18\u5148\u4F7F\u7528\u6307\u5B9A\u7684\u8DEF\u5F84\u4E0A\u6A21\u5757\n return originalRequire.apply(this, [local])\n }\n return originalRequire.apply(this, arguments)\n}\n\nconst originalCreateRequire = Module.createRequire || Module.createRequireFromPath\nModule.createRequire = function(importerFileUrl) {\n const newRequire = originalCreateRequire.apply(this, arguments)\n const originalResolve = newRequire.resolve\n\n const importerFile = fileURLToPath(importerFileUrl)\n newRequire.resolve = function(id) {\n if (match(id)) {\n const result = require.resolve(id, { paths: Array.from(new Set([resolvePath, path.dirname(importerFile)])) })\n return result\n }\n return originalResolve.apply(this, arguments)\n }\n return newRequire\n}\n"); };
export { proxy, redirectResolve };