@cloudbase/manager-node 4.2.4 → 4.2.5

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.
Files changed (85) hide show
  1. package/lib/access/index.js +141 -0
  2. package/lib/access/types.js +2 -0
  3. package/lib/billing/index.js +36 -0
  4. package/lib/cam/index.js +77 -0
  5. package/lib/cloudBaseRun/index.js +36 -0
  6. package/lib/cloudBaseRun/types.js +2 -0
  7. package/lib/common/index.js +39 -0
  8. package/lib/constant.js +55 -0
  9. package/lib/context.js +14 -0
  10. package/lib/database/index.js +244 -0
  11. package/lib/debug.js +34 -0
  12. package/lib/env/index.js +289 -0
  13. package/lib/environment.js +124 -0
  14. package/lib/environmentManager.js +44 -0
  15. package/lib/error.js +16 -0
  16. package/lib/function/index.js +1019 -0
  17. package/lib/function/packer.js +129 -0
  18. package/lib/function/types.js +2 -0
  19. package/lib/hosting/index.js +461 -0
  20. package/lib/index.js +83 -0
  21. package/lib/interfaces/base.interface.js +2 -0
  22. package/lib/interfaces/billing.interface.js +2 -0
  23. package/lib/interfaces/cam.interface.js +2 -0
  24. package/lib/interfaces/flexdb.interface.js +2 -0
  25. package/lib/interfaces/function.interface.js +2 -0
  26. package/lib/interfaces/index.js +19 -0
  27. package/lib/interfaces/storage.interface.js +2 -0
  28. package/lib/interfaces/tcb.interface.js +2 -0
  29. package/lib/storage/index.js +1051 -0
  30. package/lib/third/index.js +18 -0
  31. package/lib/user/index.js +136 -0
  32. package/lib/user/types.js +2 -0
  33. package/lib/utils/auth.js +97 -0
  34. package/lib/utils/cloud-api-request.js +212 -0
  35. package/lib/utils/cloudbase-request.js +69 -0
  36. package/lib/utils/envLazy.js +18 -0
  37. package/lib/utils/fs.js +64 -0
  38. package/lib/utils/http-request.js +44 -0
  39. package/lib/utils/index.js +103 -0
  40. package/lib/utils/parallel.js +69 -0
  41. package/lib/utils/runenv.js +8 -0
  42. package/lib/utils/uuid.js +18 -0
  43. package/package.json +1 -1
  44. package/types/access/index.d.ts +38 -0
  45. package/types/access/types.d.ts +42 -0
  46. package/types/billing/index.d.ts +21 -0
  47. package/types/cam/index.d.ts +63 -0
  48. package/types/cloudBaseRun/index.d.ts +12 -0
  49. package/types/cloudBaseRun/types.d.ts +21 -0
  50. package/types/common/index.d.ts +18 -0
  51. package/types/constant.d.ts +44 -0
  52. package/types/context.d.ts +17 -0
  53. package/types/database/index.d.ts +66 -0
  54. package/types/debug.d.ts +1 -0
  55. package/types/env/index.d.ts +127 -0
  56. package/types/environment.d.ts +51 -0
  57. package/types/environmentManager.d.ts +13 -0
  58. package/types/error.d.ts +18 -0
  59. package/types/function/index.d.ts +379 -0
  60. package/types/function/packer.d.ts +37 -0
  61. package/types/function/types.d.ts +154 -0
  62. package/types/hosting/index.d.ts +253 -0
  63. package/types/index.d.ts +52 -0
  64. package/types/interfaces/base.interface.d.ts +7 -0
  65. package/types/interfaces/billing.interface.d.ts +18 -0
  66. package/types/interfaces/cam.interface.d.ts +24 -0
  67. package/types/interfaces/flexdb.interface.d.ts +67 -0
  68. package/types/interfaces/function.interface.d.ts +65 -0
  69. package/types/interfaces/index.d.ts +7 -0
  70. package/types/interfaces/storage.interface.d.ts +26 -0
  71. package/types/interfaces/tcb.interface.d.ts +305 -0
  72. package/types/storage/index.d.ts +324 -0
  73. package/types/third/index.d.ts +11 -0
  74. package/types/user/index.d.ts +52 -0
  75. package/types/user/types.d.ts +20 -0
  76. package/types/utils/auth.d.ts +8 -0
  77. package/types/utils/cloud-api-request.d.ts +21 -0
  78. package/types/utils/cloudbase-request.d.ts +14 -0
  79. package/types/utils/envLazy.d.ts +1 -0
  80. package/types/utils/fs.d.ts +7 -0
  81. package/types/utils/http-request.d.ts +2 -0
  82. package/types/utils/index.d.ts +20 -0
  83. package/types/utils/parallel.d.ts +17 -0
  84. package/types/utils/runenv.d.ts +1 -0
  85. package/types/utils/uuid.d.ts +2 -0
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ThirdService = void 0;
4
+ const utils_1 = require("../utils");
5
+ class ThirdService {
6
+ constructor(environment) {
7
+ this.cloudService = new utils_1.CloudService(environment.cloudBaseContext, 'tcb', '2018-06-08');
8
+ }
9
+ // 解除第三方小程序绑定
10
+ async deleteThirdPartAttach(options) {
11
+ const { ThirdPartAppid, TypeFlag } = options;
12
+ return this.cloudService.request('DeleteThirdPartAttach', {
13
+ ThirdPartAppid,
14
+ TypeFlag
15
+ });
16
+ }
17
+ }
18
+ exports.ThirdService = ThirdService;
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.UserService = void 0;
10
+ const utils_1 = require("../utils");
11
+ class UserService {
12
+ constructor(environment) {
13
+ this.environment = environment;
14
+ this.tcbService = new utils_1.CloudService(environment.cloudBaseContext, 'tcb', '2018-06-08');
15
+ }
16
+ // 获取云开发用户列表
17
+ async getEndUserList(options) {
18
+ const { limit, offset } = options;
19
+ const { EnvId } = this.environment.lazyEnvironmentConfig;
20
+ return this.tcbService.request('DescribeEndUsers', {
21
+ EnvId,
22
+ Limit: limit,
23
+ Offset: offset
24
+ });
25
+ }
26
+ // // 停用云开发用户
27
+ // @preLazy()
28
+ // public async disableEndUser(options: {
29
+ // uuid: string
30
+ // }) {
31
+ // const { uuid } = options
32
+ // const { EnvId } = this.environment.lazyEnvironmentConfig
33
+ // return this.tcbService.request<{
34
+ // RequestId: string
35
+ // }>('ModifyEndUser', {
36
+ // EnvId,
37
+ // UUId: uuid,
38
+ // Status: 'DISABLE'
39
+ // })
40
+ // }
41
+ // 设置云开发用户状态(停用或启用)
42
+ async setEndUserStatus(options) {
43
+ const { uuid, status } = options;
44
+ const { EnvId } = this.environment.lazyEnvironmentConfig;
45
+ return this.tcbService.request('ModifyEndUser', {
46
+ EnvId,
47
+ UUId: uuid,
48
+ Status: status
49
+ });
50
+ }
51
+ // 批量删除云开发用户
52
+ async deleteEndUsers(options) {
53
+ const { userList } = options;
54
+ const { EnvId } = this.environment.lazyEnvironmentConfig;
55
+ return this.tcbService.request('DeleteEndUser', {
56
+ EnvId,
57
+ UserList: userList
58
+ });
59
+ }
60
+ // 创建用户名密码
61
+ async createEndUser(options) {
62
+ const { username, password } = options;
63
+ const { EnvId } = this.environment.lazyEnvironmentConfig;
64
+ return this.tcbService.request('CreateEndUserAccount', {
65
+ EnvId,
66
+ Username: username,
67
+ Password: password,
68
+ });
69
+ }
70
+ // 更改用户账户
71
+ async modifyEndUser(options) {
72
+ const { uuid, username, password } = options;
73
+ const { EnvId } = this.environment.lazyEnvironmentConfig;
74
+ const reqData = {
75
+ EnvId,
76
+ Uuid: uuid
77
+ };
78
+ if (this.isValidStr(username)) {
79
+ reqData.Username = username;
80
+ }
81
+ if (this.isValidStr(password)) {
82
+ reqData.Password = password;
83
+ }
84
+ return this.tcbService.request('ModifyEndUserAccount', reqData);
85
+ }
86
+ // 更改用户信息
87
+ async updateEndUser(options) {
88
+ const { uuid, nickName, gender, avatarUrl, country, province, city } = options;
89
+ const { EnvId } = this.environment.lazyEnvironmentConfig;
90
+ return this.tcbService.request('ModifyEndUserInfo', {
91
+ UUId: uuid,
92
+ EnvId,
93
+ Data: [{
94
+ Key: 'Name',
95
+ Value: nickName
96
+ }, {
97
+ Key: 'Gender',
98
+ Value: gender
99
+ }, {
100
+ Key: 'AvatarUrl',
101
+ Value: avatarUrl
102
+ }, {
103
+ Key: 'Country',
104
+ Value: country
105
+ }, {
106
+ Key: 'Province',
107
+ Value: province
108
+ }, {
109
+ Key: 'City',
110
+ Value: city
111
+ }]
112
+ });
113
+ }
114
+ isValidStr(obj) {
115
+ return typeof obj === 'string' && obj.trim().length > 0;
116
+ }
117
+ }
118
+ __decorate([
119
+ utils_1.preLazy()
120
+ ], UserService.prototype, "getEndUserList", null);
121
+ __decorate([
122
+ utils_1.preLazy()
123
+ ], UserService.prototype, "setEndUserStatus", null);
124
+ __decorate([
125
+ utils_1.preLazy()
126
+ ], UserService.prototype, "deleteEndUsers", null);
127
+ __decorate([
128
+ utils_1.preLazy()
129
+ ], UserService.prototype, "createEndUser", null);
130
+ __decorate([
131
+ utils_1.preLazy()
132
+ ], UserService.prototype, "modifyEndUser", null);
133
+ __decorate([
134
+ utils_1.preLazy()
135
+ ], UserService.prototype, "updateEndUser", null);
136
+ exports.UserService = UserService;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getAuth = void 0;
7
+ const crypto_1 = __importDefault(require("crypto"));
8
+ function camSafeUrlEncode(str) {
9
+ return encodeURIComponent(str)
10
+ .replace(/!/g, '%21')
11
+ .replace(/'/g, '%27')
12
+ .replace(/\(/g, '%28')
13
+ .replace(/\)/g, '%29')
14
+ .replace(/\*/g, '%2A');
15
+ }
16
+ function getAuth(options) {
17
+ const SecretId = options.secretId;
18
+ const SecretKey = options.secretKey;
19
+ const method = options.method.toLowerCase() || 'get';
20
+ const queryParams = options.params || {};
21
+ const headers = options.headers || {};
22
+ let pathname = options.pathname || '/';
23
+ pathname.indexOf('/') !== 0 && (pathname = '/' + pathname);
24
+ if (!SecretId) {
25
+ throw Error('missing param SecretId');
26
+ }
27
+ if (!SecretKey) {
28
+ throw Error('missing param SecretKey');
29
+ }
30
+ const getObjectKeys = function (obj) {
31
+ return Object.keys(obj)
32
+ .filter(key => typeof obj[key] !== 'undefined')
33
+ .sort();
34
+ };
35
+ const objectToString = function (obj) {
36
+ const list = [];
37
+ const keyList = getObjectKeys(obj);
38
+ keyList.forEach(key => {
39
+ let value = obj[key] === null || typeof obj[key] === 'undefined' ? '' : obj[key];
40
+ if (typeof value !== 'string') {
41
+ value = JSON.stringify(value);
42
+ }
43
+ list.push(`${camSafeUrlEncode(key.toLowerCase())}=${camSafeUrlEncode(value)}`);
44
+ });
45
+ return list.join('&');
46
+ };
47
+ // 签名有效起止时间
48
+ const now = Math.floor(Date.now() / 1000) - 1;
49
+ // 签名过期时间为当前 + 900s
50
+ const exp = now + 900;
51
+ // 要用到的 Authorization 参数列表
52
+ const qSignAlgorithm = 'sha1';
53
+ const qAk = SecretId;
54
+ const qKeyTime = now + ';' + exp;
55
+ const qHeaderList = getObjectKeys(headers)
56
+ .join(';')
57
+ .toLowerCase();
58
+ const qUrlParamList = getObjectKeys(queryParams)
59
+ .join(';')
60
+ .toLowerCase();
61
+ // 签名算法说明文档:https://www.qcloud.com/document/product/436/7778
62
+ // 步骤一:计算 SignKey
63
+ const signKey = crypto_1.default
64
+ .createHmac('sha1', SecretKey)
65
+ .update(qKeyTime)
66
+ .digest('hex');
67
+ // 步骤二:构成 FormatString
68
+ const formatString = [
69
+ method,
70
+ pathname,
71
+ objectToString(queryParams),
72
+ objectToString(headers),
73
+ ''
74
+ ].join('\n');
75
+ // 步骤三:计算 StringToSign
76
+ const sha1Algo = crypto_1.default.createHash('sha1');
77
+ sha1Algo.update(Buffer.from(formatString));
78
+ const res = sha1Algo.digest('hex');
79
+ const stringToSign = ['sha1', qKeyTime, res, ''].join('\n');
80
+ // 步骤四:计算 Signature
81
+ const qSignature = crypto_1.default
82
+ .createHmac('sha1', signKey)
83
+ .update(stringToSign)
84
+ .digest('hex');
85
+ // 步骤五:构造 Authorization
86
+ const authorization = [
87
+ 'q-sign-algorithm=' + qSignAlgorithm,
88
+ 'q-ak=' + qAk,
89
+ 'q-sign-time=' + qKeyTime,
90
+ 'q-key-time=' + qKeyTime,
91
+ 'q-header-list=' + qHeaderList,
92
+ 'q-url-param-list=' + qUrlParamList,
93
+ 'q-signature=' + qSignature
94
+ ].join('&');
95
+ return authorization;
96
+ }
97
+ exports.getAuth = getAuth;
@@ -0,0 +1,212 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CloudService = void 0;
7
+ const crypto_1 = __importDefault(require("crypto"));
8
+ const url_1 = require("url");
9
+ const query_string_1 = __importDefault(require("query-string"));
10
+ const error_1 = require("../error");
11
+ const http_request_1 = require("./http-request");
12
+ const constant_1 = require("../constant");
13
+ const utils_1 = require("../utils");
14
+ function isObject(x) {
15
+ return typeof x === 'object' && !Array.isArray(x) && x !== null;
16
+ }
17
+ // 移除对象中的空值
18
+ function deepRemoveVoid(obj) {
19
+ if (Array.isArray(obj)) {
20
+ return obj.map(deepRemoveVoid);
21
+ }
22
+ else if (isObject(obj)) {
23
+ let result = {};
24
+ for (let key in obj) {
25
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
26
+ const value = obj[key];
27
+ if (typeof value !== 'undefined' && value !== null) {
28
+ result[key] = deepRemoveVoid(value);
29
+ }
30
+ }
31
+ }
32
+ return result;
33
+ }
34
+ else {
35
+ return obj;
36
+ }
37
+ }
38
+ function sha256(message, secret, encoding) {
39
+ const hmac = crypto_1.default.createHmac('sha256', secret);
40
+ return hmac.update(message).digest(encoding);
41
+ }
42
+ function getHash(message) {
43
+ const hash = crypto_1.default.createHash('sha256');
44
+ return hash.update(message).digest('hex');
45
+ }
46
+ function getDate(timestamp) {
47
+ const date = new Date(timestamp * 1000);
48
+ const year = date.getUTCFullYear();
49
+ const month = ('0' + (date.getUTCMonth() + 1)).slice(-2);
50
+ // UTC 日期,非本地时间
51
+ const day = ('0' + date.getUTCDate()).slice(-2);
52
+ return `${year}-${month}-${day}`;
53
+ }
54
+ class CloudService {
55
+ /* eslint-disable-next-line */
56
+ constructor(context, service, version, baseParams) {
57
+ this.service = service;
58
+ this.version = version;
59
+ this.timeout = 60000;
60
+ this.baseParams = baseParams || {};
61
+ this.cloudBaseContext = context;
62
+ }
63
+ get baseUrl() {
64
+ const tcb = process.env.TCB_BASE_URL || 'https://tcb.tencentcloudapi.com';
65
+ const urlMap = {
66
+ tcb,
67
+ scf: 'https://scf.tencentcloudapi.com',
68
+ vpc: 'https://vpc.tencentcloudapi.com',
69
+ flexdb: 'https://flexdb.tencentcloudapi.com',
70
+ cam: 'https://cam.tencentcloudapi.com',
71
+ cdn: 'https://cdn.tencentcloudapi.com'
72
+ };
73
+ // 云梯账号走内网域名
74
+ const intranetUrlMap = Object.keys(urlMap).map((service) => ({
75
+ [service]: `https://${service}.internal.tencentcloudapi.com`,
76
+ })).reduce((acc, cur) => (Object.assign(Object.assign({}, acc), cur)), {});
77
+ if (constant_1.USE_INTERNAL_ENDPOINT) {
78
+ return intranetUrlMap[this.service];
79
+ }
80
+ if (urlMap[this.service]) {
81
+ return urlMap[this.service];
82
+ }
83
+ else {
84
+ return `https://${this.service}.tencentcloudapi.com`;
85
+ }
86
+ }
87
+ async request(action, data = {}, method = 'POST') {
88
+ this.action = action;
89
+ this.data = deepRemoveVoid(Object.assign(Object.assign({}, data), this.baseParams));
90
+ this.method = method;
91
+ this.url = this.baseUrl;
92
+ let { secretId, secretKey, token } = this.cloudBaseContext;
93
+ // 当在云函数环境下执行时,可init时不传入密钥,取环境变量中密钥使用
94
+ // request执行时一般处于main函数内部,取环境变量逻辑写这里更可靠
95
+ if (!secretId || !secretKey) {
96
+ // 未主动传入密钥,从环境变量中读取
97
+ const envSecretId = utils_1.getEnvVar(constant_1.ENV_NAME.ENV_SECRETID);
98
+ const envSecretKey = utils_1.getEnvVar(constant_1.ENV_NAME.ENV_SECRETKEY);
99
+ const envToken = utils_1.getEnvVar(constant_1.ENV_NAME.ENV_SESSIONTOKEN);
100
+ if (!envSecretId || !envSecretKey) {
101
+ if (utils_1.getRuntime() === constant_1.RUN_ENV.SCF) {
102
+ throw new Error('missing authoration key, redeploy the function');
103
+ }
104
+ else {
105
+ throw new Error('missing secretId or secretKey of tencent cloud');
106
+ }
107
+ }
108
+ else {
109
+ secretId = envSecretId;
110
+ secretKey = envSecretKey;
111
+ token = envToken;
112
+ }
113
+ }
114
+ this.secretId = secretId;
115
+ this.secretKey = secretKey;
116
+ this.token = token;
117
+ try {
118
+ const data = await this.requestWithSign();
119
+ if (data.Response.Error) {
120
+ const tcError = new error_1.CloudBaseError(data.Response.Error.Message, {
121
+ action,
122
+ requestId: data.Response.RequestId,
123
+ code: data.Response.Error.Code,
124
+ original: data.Response.Error
125
+ });
126
+ throw tcError;
127
+ }
128
+ else {
129
+ return data.Response;
130
+ }
131
+ }
132
+ catch (e) {
133
+ if (e.name === 'CloudBaseError') {
134
+ throw e;
135
+ }
136
+ else {
137
+ throw new error_1.CloudBaseError(e.message, {
138
+ action,
139
+ code: e.code
140
+ });
141
+ }
142
+ }
143
+ }
144
+ async requestWithSign() {
145
+ // data 中可能带有 readStream,由于需要计算整个 body 的 hash,
146
+ // 所以这里把 readStream 转为 Buffer
147
+ // await convertReadStreamToBuffer(data)
148
+ const timestamp = Math.floor(new Date().getTime() / 1000);
149
+ const { proxy } = this.cloudBaseContext;
150
+ const { method, timeout, data = {} } = this;
151
+ if (method === 'GET') {
152
+ this.url += '?' + query_string_1.default.stringify(data);
153
+ }
154
+ if (method === 'POST') {
155
+ this.payload = data;
156
+ }
157
+ const config = {
158
+ method,
159
+ timeout,
160
+ headers: {
161
+ Host: new url_1.URL(this.url).host,
162
+ 'X-TC-Action': this.action,
163
+ // region 优先级 mock本地注入 > init 指定 > 云函数环境变量
164
+ 'X-TC-Region': process.env.TCB_REGION ||
165
+ this.cloudBaseContext.region ||
166
+ process.env.TENCENTCLOUD_REGION ||
167
+ 'ap-shanghai',
168
+ 'X-TC-Timestamp': timestamp,
169
+ 'X-TC-Version': this.version
170
+ }
171
+ };
172
+ if (this.token) {
173
+ config.headers['X-TC-Token'] = this.token;
174
+ }
175
+ if (method === 'GET') {
176
+ config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
177
+ }
178
+ if (method === 'POST') {
179
+ config.body = JSON.stringify(data);
180
+ config.headers['Content-Type'] = 'application/json';
181
+ }
182
+ const sign = this.getRequestSign(timestamp);
183
+ config.headers['Authorization'] = sign;
184
+ return http_request_1.fetch(this.url, config, proxy);
185
+ }
186
+ getRequestSign(timestamp) {
187
+ const { method = 'POST', url, service, secretId, secretKey } = this;
188
+ const urlObj = new url_1.URL(url);
189
+ // 通用头部
190
+ let headers = '';
191
+ const signedHeaders = 'content-type;host';
192
+ if (method === 'GET') {
193
+ headers = 'content-type:application/x-www-form-urlencoded\n';
194
+ }
195
+ else if (method === 'POST') {
196
+ headers = 'content-type:application/json\n';
197
+ }
198
+ headers += `host:${urlObj.hostname}\n`;
199
+ const path = urlObj.pathname;
200
+ const querystring = urlObj.search.slice(1);
201
+ const payloadHash = this.payload ? getHash(JSON.stringify(this.payload)) : getHash('');
202
+ const canonicalRequest = `${method}\n${path}\n${querystring}\n${headers}\n${signedHeaders}\n${payloadHash}`;
203
+ const date = getDate(timestamp);
204
+ const StringToSign = `TC3-HMAC-SHA256\n${timestamp}\n${date}/${service}/tc3_request\n${getHash(canonicalRequest)}`;
205
+ const kDate = sha256(date, `TC3${secretKey}`);
206
+ const kService = sha256(service, kDate);
207
+ const kSigning = sha256('tc3_request', kService);
208
+ const signature = sha256(StringToSign, kSigning, 'hex');
209
+ return `TC3-HMAC-SHA256 Credential=${secretId}/${date}/${service}/tc3_request, SignedHeaders=${signedHeaders}, Signature=${signature}`;
210
+ }
211
+ }
212
+ exports.CloudService = CloudService;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cloudBaseRequest = void 0;
4
+ const auth_1 = require("./auth");
5
+ const http_request_1 = require("./http-request");
6
+ const SUPPORT_REGIONS = ['ap-shanghai', 'ap-guangzhou'];
7
+ async function cloudBaseRequest(options) {
8
+ // const url = 'https://tcb-admin.tencentcloudapi.com/admin'
9
+ const { config, params = {}, method = 'POST', headers = {} } = options;
10
+ const { region, envId } = config;
11
+ const isInScf = process.env.TENCENTCLOUD_RUNENV === 'SCF'; // 是否scf环境内
12
+ const protocol = isInScf ? 'http' : 'https';
13
+ const isInContainer = !!process.env.KUBERNETES_SERVICE_HOST; // 是否容器环境
14
+ // region 优先级 本地mock 注入 > init region > 云函数环境变量region
15
+ const finalRegion = process.env.TCB_REGION || region || process.env.TENCENTCLOUD_REGION || '';
16
+ let internetRegionEndpoint = '';
17
+ let internalRegionEndpoint = '';
18
+ if (finalRegion) {
19
+ if (SUPPORT_REGIONS.includes(finalRegion)) {
20
+ internetRegionEndpoint = `${finalRegion}.tcb-api.tencentcloudapi.com`;
21
+ internalRegionEndpoint = `internal.${finalRegion}.tcb-api.tencentcloudapi.com`;
22
+ }
23
+ else {
24
+ console.warn('当前仅支持上海,广州地域,其他地域默认解析到固定域名(上海地域)');
25
+ internetRegionEndpoint = `tcb-api.tencentcloudapi.com`;
26
+ internalRegionEndpoint = `internal.tcb-api.tencentcloudapi.com`;
27
+ }
28
+ }
29
+ else {
30
+ internetRegionEndpoint = `tcb-api.tencentcloudapi.com`;
31
+ internalRegionEndpoint = `internal.tcb-api.tencentcloudapi.com`;
32
+ }
33
+ // 有地域信息则访问地域级别域名,无地域信息则访问默认域名,默认域名固定解析到上海地域保持兼容
34
+ // const internetRegionEndpoint = finalRegion
35
+ // ? `${finalRegion}.tcb-api.tencentcloudapi.com`
36
+ // : `tcb-api.tencentcloudapi.com`
37
+ // const internalRegionEndpoint = finalRegion
38
+ // ? `internal.${finalRegion}.tcb-api.tencentcloudapi.com`
39
+ // : `internal.tcb-api.tencentcloudapi.com`
40
+ // 同地域走内网,跨地域走公网
41
+ const isSameRegionVisit = region ? region === process.env.TENCENTCLOUD_REGION : true;
42
+ // const endpoint = isInScf || isInContainer ? internalRegionEndpoint : internetRegionEndpoint
43
+ const endpoint = isSameRegionVisit && (isInScf || isInContainer)
44
+ ? internalRegionEndpoint
45
+ : internetRegionEndpoint;
46
+ // const envpoint = envId ? `${envId}.${endpoint}` : endpoint
47
+ const envpoint = endpoint;
48
+ const url = `${protocol}://${envpoint}/admin`;
49
+ const requestData = Object.assign(Object.assign({}, params), { envName: config.envId, timestamp: Date.now() });
50
+ const requestHeaders = Object.assign(Object.assign({}, headers), { 'content-type': 'application/json', 'user-agent': `cloudbase-manager-node/0.1.0`, 'x-tcb-source': 'cloudbase-manager-node, not-scf' });
51
+ const { secretId, secretKey, token, proxy } = config;
52
+ const authData = {
53
+ secretId,
54
+ secretKey,
55
+ method: method,
56
+ pathname: '/admin',
57
+ params: requestData,
58
+ headers: requestHeaders
59
+ };
60
+ const authorization = auth_1.getAuth(authData);
61
+ const requestBody = Object.assign(Object.assign({}, requestData), { sessionToken: token, authorization });
62
+ const res = await http_request_1.fetch(url, {
63
+ method,
64
+ body: JSON.stringify(requestBody),
65
+ headers: requestHeaders
66
+ }, process.env.TCB_ADMIN_PROXY || proxy);
67
+ return res;
68
+ }
69
+ exports.cloudBaseRequest = cloudBaseRequest;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.preLazy = void 0;
4
+ function preLazy() {
5
+ return function (target, propertyKey, descriptor) {
6
+ let oldFunc = descriptor.value;
7
+ descriptor.value = async function () {
8
+ // 检查当前环境对象上是否已加载好环境信息
9
+ const currentEnvironment = this.environment;
10
+ if (!currentEnvironment.inited) {
11
+ await currentEnvironment.lazyInit();
12
+ }
13
+ let result = await oldFunc.apply(this, arguments);
14
+ return result;
15
+ };
16
+ };
17
+ }
18
+ exports.preLazy = preLazy;
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.delSync = exports.formateFileSize = exports.isDirectory = exports.checkReadable = exports.checkFullAccess = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const error_1 = require("../error");
9
+ const del_1 = __importDefault(require("del"));
10
+ // 检查路径是否可以访问(读、写)
11
+ function checkFullAccess(dest, throwError = false) {
12
+ try {
13
+ // 可见、可写
14
+ fs_1.default.accessSync(dest, fs_1.default.constants.F_OK);
15
+ fs_1.default.accessSync(dest, fs_1.default.constants.W_OK);
16
+ fs_1.default.accessSync(dest, fs_1.default.constants.R_OK);
17
+ return true;
18
+ }
19
+ catch (e) {
20
+ if (throwError) {
21
+ throw new error_1.CloudBaseError(`路径不存在或无读写权限:${dest}`);
22
+ }
23
+ else {
24
+ return false;
25
+ }
26
+ }
27
+ }
28
+ exports.checkFullAccess = checkFullAccess;
29
+ // 检查路径是否可以写
30
+ function checkReadable(dest, throwError = false) {
31
+ try {
32
+ // 可见、可读
33
+ fs_1.default.accessSync(dest, fs_1.default.constants.F_OK);
34
+ fs_1.default.accessSync(dest, fs_1.default.constants.R_OK);
35
+ return true;
36
+ }
37
+ catch (e) {
38
+ if (throwError) {
39
+ throw new error_1.CloudBaseError(`路径不存在或无读权限:${dest}`);
40
+ }
41
+ else {
42
+ return false;
43
+ }
44
+ }
45
+ }
46
+ exports.checkReadable = checkReadable;
47
+ function isDirectory(dest) {
48
+ checkFullAccess(dest, true);
49
+ return fs_1.default.statSync(dest).isDirectory();
50
+ }
51
+ exports.isDirectory = isDirectory;
52
+ function formateFileSize(size, unit) {
53
+ const unitMap = {
54
+ KB: 1024,
55
+ MB: Math.pow(1024, 2),
56
+ GB: Math.pow(1024, 3)
57
+ };
58
+ return Number(size / unitMap[unit]).toFixed(2);
59
+ }
60
+ exports.formateFileSize = formateFileSize;
61
+ function delSync(patterns) {
62
+ del_1.default.sync(patterns, { force: true });
63
+ }
64
+ exports.delSync = delSync;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.fetchStream = exports.fetch = void 0;
7
+ const url_1 = require("url");
8
+ const node_fetch_1 = __importDefault(require("node-fetch"));
9
+ const https_proxy_agent_1 = require("https-proxy-agent");
10
+ const error_1 = require("../error");
11
+ // 使用 fetch + 代理
12
+ async function fetch(url, config = {}, proxy) {
13
+ if (proxy || process.env.http_proxy) {
14
+ config.agent = new https_proxy_agent_1.HttpsProxyAgent(proxy || process.env.http_proxy);
15
+ }
16
+ // 解决中文编码问题
17
+ const escapeUrl = new url_1.URL(url).toString();
18
+ let json;
19
+ let text;
20
+ try {
21
+ const res = await node_fetch_1.default(escapeUrl, config);
22
+ text = await res.text();
23
+ json = JSON.parse(text);
24
+ }
25
+ catch (e) {
26
+ // 某些情况下回返回 HTML 文本异常
27
+ // JSON 解析错误,抛出原响应文本
28
+ if (e.name === 'SyntaxError') {
29
+ throw new error_1.CloudBaseError(text);
30
+ }
31
+ throw new error_1.CloudBaseError(e);
32
+ }
33
+ return json;
34
+ }
35
+ exports.fetch = fetch;
36
+ async function fetchStream(url, config = {}, proxy) {
37
+ if (proxy || process.env.http_proxy) {
38
+ config.agent = new https_proxy_agent_1.HttpsProxyAgent(proxy || process.env.http_proxy);
39
+ }
40
+ // 解决中文编码问题
41
+ const escapeUrl = new url_1.URL(url).toString();
42
+ return node_fetch_1.default(escapeUrl, config);
43
+ }
44
+ exports.fetchStream = fetchStream;