esa-cli
Version:
A CLI for operating Alibaba Cloud ESA EdgeRoutine (Edge Functions).
197 lines (196 loc) • 7.61 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import fs from 'fs';
import os from 'os';
import path from 'path';
import toml from '@iarna/toml';
import { promises as fsPromises } from 'fs';
import { getDirName, getRoot } from './base.js';
import logger from '../../libs/logger.js';
import t from '../../i18n/index.js';
const projectConfigFile = 'esa.toml';
const __dirname = getDirName(import.meta.url);
const root = getRoot();
export const projectConfigPath = path.join(root, projectConfigFile);
export const cliConfigPath = path.join(os.homedir(), '.esa/config/default.toml');
export const hiddenConfigDir = path.join(os.homedir(), '.esa/config');
export const generateHiddenConfigDir = () => {
if (!fs.existsSync(hiddenConfigDir)) {
fs.mkdirSync(hiddenConfigDir, { recursive: true });
}
};
export const generateToml = (path) => {
if (!fs.existsSync(path)) {
fs.writeFileSync(path, '', 'utf-8');
// 添加默认的endpoint
const defaultConfig = {
endpoint: 'esa.cn-hangzhou.aliyuncs.com'
};
updateCliConfigFile(defaultConfig);
}
};
export const generateDefaultConfig = () => {
generateHiddenConfigDir();
generateToml(cliConfigPath);
};
export function updateProjectConfigFile(configUpdate_1) {
return __awaiter(this, arguments, void 0, function* (configUpdate, filePath = root) {
const configPath = path.join(filePath, projectConfigFile);
try {
let configFileContent = yield fsPromises.readFile(configPath, 'utf8');
let config = toml.parse(configFileContent);
config = Object.assign(Object.assign({}, config), configUpdate);
const updatedConfigString = toml.stringify(config);
yield fsPromises.writeFile(configPath, updatedConfigString);
}
catch (error) {
logger.error(`Error updating TOML file: ${error}`);
logger.pathEacces(__dirname);
}
});
}
export function updateCliConfigFile(configUpdate) {
return __awaiter(this, void 0, void 0, function* () {
try {
let configFileContent = yield fsPromises.readFile(cliConfigPath, 'utf8');
let config = toml.parse(configFileContent);
config = Object.assign(Object.assign({}, config), configUpdate);
const updatedConfigString = toml.stringify(config);
yield fsPromises.writeFile(cliConfigPath, updatedConfigString);
}
catch (error) {
logger.error(`Error updating TOML file: ${error}`);
logger.pathEacces(__dirname);
throw new Error('Login error');
}
});
}
export function readConfigFile(configPath) {
if (fs.existsSync(configPath)) {
const configFileContent = fs.readFileSync(configPath, 'utf-8');
try {
const config = toml.parse(configFileContent);
return config;
}
catch (error) {
logger.error(`Error parsing TOML file: ${error}`);
return null;
}
}
return null;
}
export function getCliConfig() {
const res = readConfigFile(cliConfigPath);
if (!res) {
return null;
}
return res;
}
export function getProjectConfig(filePath = root) {
const res = readConfigFile(path.join(filePath, projectConfigFile));
if (!res) {
return null;
}
return res;
}
export function readEdgeRoutineFile(projectPath = root) {
const projectConfig = getProjectConfig(projectPath);
if (!projectConfig) {
return null;
}
const pubFilePath = `.dev/pub.js`;
const edgeRoutinePath = path.join(projectPath, pubFilePath);
if (fs.existsSync(edgeRoutinePath)) {
const edgeRoutineFile = fs.readFileSync(edgeRoutinePath, 'utf-8');
return edgeRoutineFile;
}
return null;
}
export function getConfigurations() {
try {
const [cliConfig, projectConfig] = [getCliConfig(), getProjectConfig()];
return [cliConfig, projectConfig];
}
catch (error) {
return [null, null];
}
}
export function generateConfigFile(projectName, initConfigs) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const newFilePath = path.join(process.cwd(), 'esa.toml');
const currentDirName = path.basename(process.cwd());
const entry = ((_a = initConfigs === null || initConfigs === void 0 ? void 0 : initConfigs.dev) === null || _a === void 0 ? void 0 : _a.entry) || 'src/index.js';
const port = (initConfigs === null || initConfigs === void 0 ? void 0 : initConfigs.port) || 18080;
const name = projectName || currentDirName;
if (fs.existsSync(newFilePath)) {
logger.error(t('generate_config_error').d('esa.toml already exists'));
return;
}
else {
const genConfig = `name = "${name}"
entry = "${entry}"
[dev]
port = ${port}
`;
yield fsPromises.writeFile(newFilePath, genConfig, 'utf-8');
logger.success(t('generate_config_success').d('Generated esa.toml'));
}
});
}
export function getConfigValue(globalValue, configValue, defaultValue) {
if (globalValue !== undefined) {
return globalValue;
}
if (configValue !== undefined) {
return configValue;
}
return defaultValue;
}
export function getDevConf(name, type, defaultValue) {
const projectConfig = getProjectConfig();
const configPath = `${type ? type + '.' : ''}${name}`;
const userConf = configPath.split('.').reduce((current, key) => {
return current && key in current ? current[key] : undefined;
}, projectConfig);
// @ts-ignore
const globalConf = global[name];
return getConfigValue(globalConf, userConf, defaultValue);
}
export function getDevOpenBrowserUrl() {
const port = getDevConf('port', 'dev', 18080);
return `http://localhost:${port}`;
}
export const getApiConfig = () => {
var _a, _b;
const [cliConfig, projectConfig] = getConfigurations();
let defaultConfig = {
auth: {
accessKeyId: '',
accessKeySecret: ''
},
endpoint: `esa.cn-hangzhou.aliyuncs.com`
};
const combinedConfig = Object.assign(Object.assign(Object.assign({}, defaultConfig), cliConfig), projectConfig);
const config = {
auth: {
accessKeyId: (_a = combinedConfig.auth) === null || _a === void 0 ? void 0 : _a.accessKeyId,
accessKeySecret: (_b = combinedConfig.auth) === null || _b === void 0 ? void 0 : _b.accessKeySecret
},
endpoint: combinedConfig.endpoint
};
return config;
};
export const templateHubPath = path.join(getDirName(import.meta.url), '../../../node_modules/esa-template/src');
export const getTemplatesConfig = () => {
const manifestPath = path.join(templateHubPath, 'manifest.json');
const config = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
return config;
};