esa-cli 1.0.2-beta.0 → 1.0.3-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -73,7 +73,7 @@ export function handleCommit(argv) {
73
73
  }));
74
74
  }
75
75
  logger.startSubStep('Generating code version');
76
- const res = yield generateCodeVersion(projectName, description, argv === null || argv === void 0 ? void 0 : argv.entry, argv === null || argv === void 0 ? void 0 : argv.assets, argv === null || argv === void 0 ? void 0 : argv.minify, undefined, (argv.bundle === false));
76
+ const res = yield generateCodeVersion(projectName, description, argv === null || argv === void 0 ? void 0 : argv.entry, argv === null || argv === void 0 ? void 0 : argv.assets, argv === null || argv === void 0 ? void 0 : argv.minify, undefined, argv.bundle === false);
77
77
  const { isSuccess } = res || {};
78
78
  if (!isSuccess) {
79
79
  logger.endSubStep('Generate version failed');
@@ -318,7 +318,7 @@ export function deployCodeVersion(name, codeVersion, environment) {
318
318
  });
319
319
  }
320
320
  /**
321
- * 部署指定的多个版本及其百分比
321
+ * Deploy specified multiple versions and their percentages
322
322
  */
323
323
  export function deployCodeVersions(name, versions, env) {
324
324
  return __awaiter(this, void 0, void 0, function* () {
@@ -444,7 +444,7 @@ export function displayDeploySuccess(projectName_1) {
444
444
  });
445
445
  }
446
446
  /**
447
- * 解析 --versions 参数并执行按百分比分发部署;成功后打印展示和百分比分配
447
+ * Parse --versions parameter and execute distributed deployment by percentage; print display and percentage allocation after successful deployment
448
448
  */
449
449
  export function deployWithVersionPercentages(nameArg, versionsArg, env, projectPath) {
450
450
  return __awaiter(this, void 0, void 0, function* () {
@@ -1,10 +1,8 @@
1
- import worker from '$userPath';
2
1
  import Cache from './mock/cache.js';
3
2
  import mockKV from './mock/kv.js';
3
+ import worker from '$userPath';
4
4
 
5
- var mock_cache = new Cache($userPort);
6
- globalThis.mockCache = mock_cache;
5
+ Cache.port = $userPort;
7
6
  mockKV.port = $userPort;
8
- globalThis.mockKV = mockKV;
9
7
 
10
8
  export default worker;
@@ -1,7 +1,7 @@
1
1
  class MockCache {
2
- constructor(port) {
3
- this.port = port;
4
- }
2
+ static port = 0;
3
+
4
+ constructor() {}
5
5
 
6
6
  async put(reqOrUrl, response) {
7
7
  if (arguments.length < 2) {
@@ -30,7 +30,7 @@ class MockCache {
30
30
 
31
31
  const key = this.normalizeKey(reqOrUrl);
32
32
  const fetchRes = await fetch(
33
- `http://localhost:${this.port}/mock_cache/put`,
33
+ `http://localhost:${MockCache.port}/mock_cache/put`,
34
34
  {
35
35
  method: 'POST',
36
36
  headers: { 'Content-Type': 'application/json' },
@@ -58,7 +58,7 @@ class MockCache {
58
58
  async get(reqOrUrl) {
59
59
  const key = this.normalizeKey(reqOrUrl);
60
60
  const fetchRes = await fetch(
61
- `http://localhost:${this.port}/mock_cache/get`,
61
+ `http://localhost:${MockCache.port}/mock_cache/get`,
62
62
  {
63
63
  method: 'POST',
64
64
  headers: { 'Content-Type': 'application/json' },
@@ -85,7 +85,7 @@ class MockCache {
85
85
  async delete(reqOrUrl) {
86
86
  const key = this.normalizeKey(reqOrUrl);
87
87
  const fetchRes = await fetch(
88
- `http://localhost:${this.port}/mock_cache/delete`,
88
+ `http://localhost:${MockCache.port}/mock_cache/delete`,
89
89
  {
90
90
  method: 'POST',
91
91
  headers: { 'Content-Type': 'application/json' },
@@ -113,4 +113,7 @@ class MockCache {
113
113
  }
114
114
  }
115
115
 
116
+ var mock_cache = new MockCache();
117
+ globalThis.mockCache = mock_cache;
118
+
116
119
  export default MockCache;
@@ -163,4 +163,6 @@ class EdgeKV {
163
163
  }
164
164
  }
165
165
 
166
+ globalThis.mockKV = EdgeKV;
167
+
166
168
  export default EdgeKV;
@@ -10,14 +10,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  import { isCancel, select as clackSelect, text as clackText } from '@clack/prompts';
11
11
  import chalk from 'chalk';
12
12
  import t from '../../i18n/index.js';
13
- import { ApiService } from '../../libs/apiService.js';
14
13
  import logger from '../../libs/logger.js';
15
- import { getApiConfig, getCliConfig, updateCliConfigFile, generateDefaultConfig } from '../../utils/fileUtils/index.js';
14
+ import { getCliConfig, updateCliConfigFile, generateDefaultConfig } from '../../utils/fileUtils/index.js';
15
+ import { validateCredentials } from '../../utils/validateCredentials.js';
16
16
  const login = {
17
17
  command: 'login',
18
18
  describe: `🔑 ${t('login_describe').d('Login to the server')}`,
19
19
  builder: (yargs) => {
20
- var _a, _b, _c;
20
+ var _a, _b;
21
21
  return yargs
22
22
  .option('access-key-id', {
23
23
  alias: 'ak',
@@ -28,11 +28,6 @@ const login = {
28
28
  alias: 'sk',
29
29
  describe: (_b = t('login_option_access_key_secret')) === null || _b === void 0 ? void 0 : _b.d('AccessKey Secret'),
30
30
  type: 'string'
31
- })
32
- .option('endpoint', {
33
- alias: 'e',
34
- describe: (_c = t('login_option_endpoint')) === null || _c === void 0 ? void 0 : _c.d('Endpoint'),
35
- type: 'string'
36
31
  });
37
32
  },
38
33
  handler: (argv) => __awaiter(void 0, void 0, void 0, function* () {
@@ -43,18 +38,34 @@ export default login;
43
38
  export function handleLogin(argv) {
44
39
  return __awaiter(this, void 0, void 0, function* () {
45
40
  generateDefaultConfig();
41
+ if (process.env.ESA_ACCESS_KEY_ID && process.env.ESA_ACCESS_KEY_SECRET) {
42
+ const result = yield validateCredentials(process.env.ESA_ACCESS_KEY_ID, process.env.ESA_ACCESS_KEY_SECRET);
43
+ if (result.valid) {
44
+ logger.log(t('login_get_credentials_from_environment_variables').d('Get credentials from environment variables'));
45
+ logger.success(t('login_success').d('Login success!'));
46
+ }
47
+ else {
48
+ logger.error(result.message || 'Login failed');
49
+ }
50
+ return;
51
+ }
46
52
  const accessKeyId = argv === null || argv === void 0 ? void 0 : argv['access-key-id'];
47
53
  const accessKeySecret = argv === null || argv === void 0 ? void 0 : argv['access-key-secret'];
48
- const endpoint = (argv === null || argv === void 0 ? void 0 : argv['endpoint']) || process.env.ESA_ENDPOINT;
49
54
  if (accessKeyId && accessKeySecret) {
50
- yield handleLoginWithAKSK(accessKeyId, accessKeySecret, endpoint);
51
- return;
52
- }
53
- if (process.env.ESA_ACCESS_KEY_ID && process.env.ESA_ACCESS_KEY_SECRET) {
54
- logger.log(`🔑 ${t('login_get_from_env').d(`Get AccessKey ID and AccessKey Secret from environment variables.`)}`);
55
- yield handleLoginWithAKSK(process.env.ESA_ACCESS_KEY_ID, process.env.ESA_ACCESS_KEY_SECRET, endpoint);
55
+ const result = yield validateCredentials(accessKeyId, accessKeySecret);
56
+ if (result.valid) {
57
+ logger.success(t('login_success').d('Login success!'));
58
+ updateCliConfigFile(Object.assign({ auth: {
59
+ accessKeyId,
60
+ accessKeySecret
61
+ } }, (result.endpoint ? { endpoint: result.endpoint } : {})));
62
+ }
63
+ else {
64
+ logger.error(result.message || 'Login failed');
65
+ }
56
66
  return;
57
67
  }
68
+ // interactive login
58
69
  const cliConfig = getCliConfig();
59
70
  if (!cliConfig)
60
71
  return;
@@ -62,9 +73,8 @@ export function handleLogin(argv) {
62
73
  cliConfig.auth &&
63
74
  cliConfig.auth.accessKeyId &&
64
75
  cliConfig.auth.accessKeySecret) {
65
- const service = yield ApiService.getInstance();
66
- const loginStatus = yield service.checkLogin();
67
- if (loginStatus.success) {
76
+ const loginStatus = yield validateCredentials(cliConfig.auth.accessKeyId, cliConfig.auth.accessKeySecret);
77
+ if (loginStatus.valid) {
68
78
  logger.warn(t('login_already').d('You are already logged in.'));
69
79
  const selected = (yield clackSelect({
70
80
  message: t('login_existing_credentials_message').d('Existing credentials found. What do you want to do?'),
@@ -79,48 +89,15 @@ export function handleLogin(argv) {
79
89
  if (isCancel(selected) || selected === 'exit') {
80
90
  return;
81
91
  }
82
- yield getUserInputAuthInfo(endpoint);
83
92
  }
84
93
  else {
85
94
  logger.error(t('pre_login_failed').d('The previously entered Access Key ID (AK) and Secret Access Key (SK) are incorrect. Please enter them again.'));
86
- logger.log(`${t('login_logging').d('Logging in')}...`);
87
- yield getUserInputAuthInfo(endpoint);
88
- }
89
- }
90
- else {
91
- logger.log(`${t('login_logging').d('Logging in')}...`);
92
- yield getUserInputAuthInfo(endpoint);
93
- }
94
- });
95
- }
96
- function handleLoginWithAKSK(accessKeyId, accessKeySecret, endpoint) {
97
- return __awaiter(this, void 0, void 0, function* () {
98
- let apiConfig = getApiConfig();
99
- apiConfig.auth = {
100
- accessKeyId,
101
- accessKeySecret
102
- };
103
- if (endpoint) {
104
- apiConfig.endpoint = endpoint;
105
- }
106
- try {
107
- yield updateCliConfigFile(Object.assign({ auth: apiConfig.auth }, (endpoint ? { endpoint } : {})));
108
- const service = yield ApiService.getInstance();
109
- service.updateConfig(apiConfig);
110
- const loginStatus = yield service.checkLogin();
111
- if (loginStatus.success) {
112
- logger.success(t('login_success').d('Login success!'));
113
95
  }
114
- else {
115
- logger.error(loginStatus.message || 'Login failed');
116
- }
117
- }
118
- catch (error) {
119
- logger.error(t('login_failed').d('An error occurred while trying to log in.'));
120
96
  }
97
+ yield interactiveLogin();
121
98
  });
122
99
  }
123
- export function getUserInputAuthInfo(endpoint) {
100
+ export function interactiveLogin() {
124
101
  return __awaiter(this, void 0, void 0, function* () {
125
102
  const styledUrl = chalk.underline.blue('https://ram.console.aliyun.com/manage/ak');
126
103
  logger.log(`🔑 ${chalk.underline(t('login_get_ak_sk').d(`Please go to the following link to get your account's AccessKey ID and AccessKey Secret`))}`);
@@ -129,28 +106,16 @@ export function getUserInputAuthInfo(endpoint) {
129
106
  const accessKeySecret = (yield clackText({
130
107
  message: 'AccessKey Secret:'
131
108
  }));
132
- let apiConfig = getApiConfig();
133
- apiConfig.auth = {
134
- accessKeyId,
135
- accessKeySecret
136
- };
137
- if (endpoint) {
138
- apiConfig.endpoint = endpoint;
139
- }
140
- try {
141
- yield updateCliConfigFile(Object.assign({ auth: apiConfig.auth }, (endpoint ? { endpoint } : {})));
142
- const service = yield ApiService.getInstance();
143
- service.updateConfig(apiConfig);
144
- const loginStatus = yield service.checkLogin();
145
- if (loginStatus.success) {
146
- logger.success(t('login_success').d('Login success!'));
147
- }
148
- else {
149
- logger.error(loginStatus.message || 'Login failed');
150
- }
109
+ const loginStatus = yield validateCredentials(accessKeyId, accessKeySecret);
110
+ if (loginStatus.valid) {
111
+ yield updateCliConfigFile(Object.assign({ auth: {
112
+ accessKeyId,
113
+ accessKeySecret
114
+ } }, (loginStatus.endpoint ? { endpoint: loginStatus.endpoint } : {})));
115
+ logger.success(t('login_success').d('Login success!'));
151
116
  }
152
- catch (error) {
153
- logger.error(t('login_failed').d('An error occurred while trying to log in.'));
117
+ else {
118
+ logger.error(loginStatus.message || 'Login failed');
154
119
  }
155
120
  });
156
121
  }
@@ -17,6 +17,7 @@ import { isInstalledGit } from '../libs/git/index.js';
17
17
  import logger from '../libs/logger.js';
18
18
  import { getRoot } from '../utils/fileUtils/base.js';
19
19
  import { getCliConfig, projectConfigPath } from '../utils/fileUtils/index.js';
20
+ import { validateCredentials } from '../utils/validateCredentials.js';
20
21
  import { getRoutineDetails } from './common/utils.js';
21
22
  export const checkDirectory = (isCheckGit = false) => {
22
23
  const root = getRoot();
@@ -78,55 +79,26 @@ export function validDomain(domain) {
78
79
  export function checkIsLoginSuccess() {
79
80
  return __awaiter(this, void 0, void 0, function* () {
80
81
  var _a, _b;
81
- let accessKeyId = process.env.ESA_ACCESS_KEY_ID;
82
- let accessKeySecret = process.env.ESA_ACCESS_KEY_SECRET;
83
- let endpoint = process.env.ESA_ENDPOINT;
84
82
  const cliConfig = getCliConfig();
85
- if (!accessKeyId || !accessKeySecret) {
86
- accessKeyId = (_a = cliConfig === null || cliConfig === void 0 ? void 0 : cliConfig.auth) === null || _a === void 0 ? void 0 : _a.accessKeyId;
87
- accessKeySecret = (_b = cliConfig === null || cliConfig === void 0 ? void 0 : cliConfig.auth) === null || _b === void 0 ? void 0 : _b.accessKeySecret;
88
- }
89
- if (!endpoint) {
90
- endpoint = cliConfig === null || cliConfig === void 0 ? void 0 : cliConfig.endpoint;
91
- }
92
- const namedCommand = chalk.green('esa-cli login');
93
- if (!accessKeyId || !accessKeySecret) {
94
- logger.log(`❌ ${t('utils_login_error').d('Maybe you are not logged in yet.')}`);
95
- logger.log(`🔔 ${t('utils_login_error_config', { namedCommand }).d(`Please run command to login: ${namedCommand}`)}`);
96
- return false;
97
- }
98
- return yield validateLoginCredentials(accessKeyId, accessKeySecret, endpoint, namedCommand);
99
- });
100
- }
101
- /**
102
- * 验证登录凭据的公共函数
103
- * @param accessKeyId AccessKey ID
104
- * @param accessKeySecret AccessKey Secret
105
- * @param namedCommand 命令名称(用于错误提示)
106
- * @param showError 是否显示错误信息
107
- * @returns 登录是否成功
108
- */
109
- export function validateLoginCredentials(accessKeyId_1, accessKeySecret_1, endpoint_1, namedCommand_1) {
110
- return __awaiter(this, arguments, void 0, function* (accessKeyId, accessKeySecret, endpoint, namedCommand, showError = true) {
111
- const server = yield ApiService.getInstance();
112
- server.updateConfig({
113
- auth: {
114
- accessKeyId,
115
- accessKeySecret
116
- },
117
- endpoint: endpoint
118
- });
119
- const res = yield server.checkLogin();
120
- if (res.success) {
121
- return true;
122
- }
123
- if (showError) {
124
- logger.log(res.message || '');
125
- logger.log(`❌ ${t('utils_login_error').d('Maybe you are not logged in yet.')}`);
126
- if (namedCommand) {
127
- logger.log(`🔔 ${t('utils_login_error_config', { namedCommand }).d(`Please run command to login: ${namedCommand}`)}`);
83
+ let accessKeyId = process.env.ESA_ACCESS_KEY_ID || ((_a = cliConfig === null || cliConfig === void 0 ? void 0 : cliConfig.auth) === null || _a === void 0 ? void 0 : _a.accessKeyId);
84
+ let accessKeySecret = process.env.ESA_ACCESS_KEY_SECRET || ((_b = cliConfig === null || cliConfig === void 0 ? void 0 : cliConfig.auth) === null || _b === void 0 ? void 0 : _b.accessKeySecret);
85
+ if (accessKeyId && accessKeySecret) {
86
+ const result = yield validateCredentials(accessKeyId, accessKeySecret);
87
+ const server = yield ApiService.getInstance();
88
+ if (result.valid) {
89
+ server.updateConfig({
90
+ auth: {
91
+ accessKeyId,
92
+ accessKeySecret
93
+ },
94
+ endpoint: result.endpoint
95
+ });
96
+ return true;
128
97
  }
129
98
  }
99
+ const namedCommand = chalk.green('esa-cli login');
100
+ logger.log(`❌ ${t('utils_login_error').d('Maybe you are not logged in yet.')}`);
101
+ logger.log(`🔔 ${t('utils_login_error_config', { namedCommand }).d(`Please run command to login: ${namedCommand}`)}`);
130
102
  return false;
131
103
  });
132
104
  }
@@ -160,7 +132,7 @@ export const getAllSites = () => __awaiter(void 0, void 0, void 0, function* ()
160
132
  return res.map((site) => {
161
133
  return {
162
134
  label: site.SiteName,
163
- value: site.SiteId
135
+ value: site.SiteId.toString()
164
136
  };
165
137
  });
166
138
  });
@@ -1318,5 +1318,9 @@
1318
1318
  "login_option_endpoint": {
1319
1319
  "en": "Endpoint",
1320
1320
  "zh_CN": "Endpoint"
1321
+ },
1322
+ "login_get_credentials_from_environment_variables": {
1323
+ "en": "Get credentials from environment variables",
1324
+ "zh_CN": ""
1321
1325
  }
1322
1326
  }
@@ -0,0 +1,126 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import * as $OpenApi from '@alicloud/openapi-client';
11
+ // Domestic site endpoint
12
+ const DOMESTIC_ENDPOINT = 'esa.cn-hangzhou.aliyuncs.com';
13
+ // International site endpoint
14
+ const INTERNATIONAL_ENDPOINT = 'esa.ap-southeast-1.aliyuncs.com';
15
+ /**
16
+ * Validate credentials for a single endpoint
17
+ */
18
+ function validateEndpoint(accessKeyId, accessKeySecret, endpoint) {
19
+ return __awaiter(this, void 0, void 0, function* () {
20
+ try {
21
+ const apiConfig = new $OpenApi.Config({
22
+ accessKeyId,
23
+ accessKeySecret,
24
+ endpoint
25
+ });
26
+ const client = new $OpenApi.default.default(apiConfig);
27
+ const params = {
28
+ action: 'GetErService',
29
+ version: '2024-09-10',
30
+ protocol: 'https',
31
+ method: 'GET',
32
+ authType: 'AK',
33
+ bodyType: 'json',
34
+ reqBodyType: 'json',
35
+ style: 'RPC',
36
+ pathname: '/',
37
+ toMap: function () {
38
+ return this;
39
+ }
40
+ };
41
+ const request = new $OpenApi.OpenApiRequest({
42
+ query: {}
43
+ });
44
+ const runtime = {
45
+ toMap: function () {
46
+ return this;
47
+ }
48
+ };
49
+ const response = yield client.callApi(params, request, runtime);
50
+ if (response.statusCode === 200) {
51
+ if (response.body.Status === 'Running') {
52
+ return { valid: true };
53
+ }
54
+ else {
55
+ return {
56
+ valid: false,
57
+ message: 'Functions and Pages is not active'
58
+ };
59
+ }
60
+ }
61
+ else if (response.statusCode === 403) {
62
+ return {
63
+ valid: false,
64
+ message: 'Permission denied: Access key or secret is incorrect'
65
+ };
66
+ }
67
+ else {
68
+ return {
69
+ valid: false,
70
+ message: `Error: ${response.statusCode}`
71
+ };
72
+ }
73
+ }
74
+ catch (error) {
75
+ return {
76
+ valid: false,
77
+ message: error instanceof Error ? error.message : 'Unknown error'
78
+ };
79
+ }
80
+ });
81
+ }
82
+ /**
83
+ * Validate if AK/SK/endpoint are valid
84
+ *
85
+ * @param accessKeyId - AccessKey ID
86
+ * @param accessKeySecret - AccessKey Secret
87
+ * @returns Validation result, including whether valid, site type and endpoint
88
+ */
89
+ export function validateCredentials(accessKeyId, accessKeySecret) {
90
+ return __awaiter(this, void 0, void 0, function* () {
91
+ if (process.env.CUSTOM_ENDPOINT) {
92
+ const result = yield validateEndpoint(accessKeyId, accessKeySecret, process.env.CUSTOM_ENDPOINT);
93
+ if (result.valid) {
94
+ return { valid: true, endpoint: process.env.CUSTOM_ENDPOINT };
95
+ }
96
+ else {
97
+ return { valid: false, message: result.message };
98
+ }
99
+ }
100
+ // First validate domestic site
101
+ const domesticResult = yield validateEndpoint(accessKeyId, accessKeySecret, DOMESTIC_ENDPOINT);
102
+ if (domesticResult.valid) {
103
+ return {
104
+ valid: true,
105
+ siteType: 'domestic',
106
+ endpoint: DOMESTIC_ENDPOINT
107
+ };
108
+ }
109
+ // If domestic site validation fails, validate international site
110
+ const internationalResult = yield validateEndpoint(accessKeyId, accessKeySecret, INTERNATIONAL_ENDPOINT);
111
+ if (internationalResult.valid) {
112
+ return {
113
+ valid: true,
114
+ siteType: 'international',
115
+ endpoint: INTERNATIONAL_ENDPOINT
116
+ };
117
+ }
118
+ // Both failed, return failure result
119
+ return {
120
+ valid: false,
121
+ message: domesticResult.message ||
122
+ internationalResult.message ||
123
+ 'Invalid credentials'
124
+ };
125
+ });
126
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "esa-cli",
3
- "version": "1.0.2-beta.0",
3
+ "version": "1.0.3-beta.1",
4
4
  "description": "A CLI for operating Alibaba Cloud ESA Functions and Pages.",
5
5
  "main": "bin/enter.cjs",
6
6
  "type": "module",