@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,129 @@
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.FunctionPacker = exports.CodeType = exports.API_MAX_SIZE = exports.BIG_FILE_SIZE = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const del_1 = __importDefault(require("del"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const make_dir_1 = __importDefault(require("make-dir"));
11
+ const util_1 = __importDefault(require("util"));
12
+ const utils_1 = require("../utils");
13
+ const error_1 = require("../error");
14
+ // 10 MB
15
+ exports.BIG_FILE_SIZE = 10485760;
16
+ exports.API_MAX_SIZE = 52428800;
17
+ var CodeType;
18
+ (function (CodeType) {
19
+ CodeType[CodeType["File"] = 0] = "File";
20
+ CodeType[CodeType["JavaFile"] = 1] = "JavaFile";
21
+ })(CodeType = exports.CodeType || (exports.CodeType = {}));
22
+ const TEMPDIR_NAME = '.cloudbase_temp';
23
+ /**
24
+ * 将函数代码转换成 Base64 编码
25
+ * 普通文件:Node,PHP
26
+ * Java 文件:Jar,ZIP
27
+ */
28
+ class FunctionPacker {
29
+ constructor(options) {
30
+ const { root, name, codeType, ignore, incrementalPath, functionPath } = options;
31
+ this.name = name;
32
+ this.ignore = ignore;
33
+ this.codeType = codeType;
34
+ this.incrementalPath = incrementalPath;
35
+ this.funcPath = functionPath ? functionPath : path_1.default.resolve(root, name);
36
+ // 每个函数采用不同的文件夹
37
+ this.tmpPath = root
38
+ ? path_1.default.join(root, `${TEMPDIR_NAME}_${name}`)
39
+ : path_1.default.join(process.cwd(), `${TEMPDIR_NAME}_${name}`);
40
+ }
41
+ async compressFiles() {
42
+ utils_1.checkFullAccess(this.funcPath, true);
43
+ // 清除原打包文件
44
+ this.clean();
45
+ // 确保目标路径存在
46
+ await make_dir_1.default(this.tmpPath);
47
+ // 生成 name.zip 文件
48
+ this.zipFilePath = path_1.default.resolve(this.tmpPath, `${this.name}.zip`);
49
+ const zipOption = {
50
+ dirPath: this.funcPath,
51
+ outputPath: this.zipFilePath,
52
+ ignore: this.ignore
53
+ };
54
+ if (this.incrementalPath) {
55
+ zipOption.pattern = this.incrementalPath;
56
+ }
57
+ await utils_1.compressToZip(zipOption);
58
+ }
59
+ // 获取 Java 代码
60
+ getJavaFile() {
61
+ const { funcPath } = this;
62
+ // funcPath 可能以 .jar 或 .zip 结尾
63
+ const filePath = funcPath.replace(/\.jar$|\.zip$/g, '');
64
+ // Java 代码为 jar 或 zip 包
65
+ const jarExist = utils_1.checkFullAccess(`${filePath}.jar`);
66
+ const zipExist = utils_1.checkFullAccess(`${filePath}.zip`);
67
+ if (!jarExist && !zipExist) {
68
+ throw new error_1.CloudBaseError('未找到部署函数的 Jar 或者 ZIP 格式文件!');
69
+ }
70
+ this.zipFilePath = jarExist ? `${filePath}.jar` : `${filePath}.zip`;
71
+ }
72
+ async build() {
73
+ if (this.codeType === CodeType.JavaFile) {
74
+ try {
75
+ await this.getJavaFile();
76
+ }
77
+ catch (e) {
78
+ this.clean();
79
+ throw new error_1.CloudBaseError(`函数代码打包失败:${e.message}`, {
80
+ code: e.code
81
+ });
82
+ }
83
+ }
84
+ if (this.codeType === CodeType.File) {
85
+ try {
86
+ await this.compressFiles();
87
+ }
88
+ catch (e) {
89
+ this.clean();
90
+ throw new error_1.CloudBaseError(`函数代码打包失败:${e.message}`, {
91
+ code: e.code
92
+ });
93
+ }
94
+ }
95
+ }
96
+ // 函数压缩后的代码大于 10M,建议使用 COS 上传(当前暂不支持)
97
+ async isBigFile() {
98
+ if (!this.zipFilePath) {
99
+ await this.build();
100
+ }
101
+ const promiseStat = util_1.default.promisify(fs_1.default.stat);
102
+ const fileStats = await promiseStat(this.zipFilePath);
103
+ return fileStats.size > exports.BIG_FILE_SIZE;
104
+ }
105
+ // API 最大 50MB
106
+ async isReachMaxSize() {
107
+ if (!this.zipFilePath) {
108
+ await this.build();
109
+ }
110
+ const promiseStat = util_1.default.promisify(fs_1.default.stat);
111
+ const fileStats = await promiseStat(this.zipFilePath);
112
+ return fileStats.size > exports.API_MAX_SIZE;
113
+ }
114
+ async getBase64Code() {
115
+ // 将 zip 文件转换成 base64
116
+ const base64 = fs_1.default.readFileSync(this.zipFilePath).toString('base64');
117
+ // 非 Java 函数清除打包文件
118
+ if (this.codeType !== CodeType.JavaFile) {
119
+ await this.clean();
120
+ }
121
+ return base64;
122
+ }
123
+ async clean() {
124
+ // allow deleting the current working directory and outside
125
+ this.tmpPath && del_1.default.sync([this.tmpPath], { force: true });
126
+ return;
127
+ }
128
+ }
129
+ exports.FunctionPacker = FunctionPacker;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,461 @@
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.HostingService = void 0;
13
+ const fs_1 = __importDefault(require("fs"));
14
+ const path_1 = __importDefault(require("path"));
15
+ const make_dir_1 = __importDefault(require("make-dir"));
16
+ const error_1 = require("../error");
17
+ const utils_1 = require("../utils");
18
+ const parallel_1 = require("../utils/parallel");
19
+ const envDomainCache = new Map();
20
+ const HostingStatusMap = {
21
+ init: '初始化中',
22
+ process: '处理中',
23
+ online: '上线',
24
+ destroying: '销毁中',
25
+ offline: '下线',
26
+ create_fail: '初始化失败',
27
+ destroy_fail: '销毁失败' // eslint-disable-line
28
+ };
29
+ class HostingService {
30
+ constructor(environment) {
31
+ this.environment = environment;
32
+ this.tcbService = new utils_1.CloudService(environment.cloudBaseContext, 'tcb', '2018-06-08');
33
+ this.cdnService = new utils_1.CloudService(environment.cloudBaseContext, 'cdn', '2018-06-06');
34
+ }
35
+ /**
36
+ * 获取 hosting 信息
37
+ */
38
+ async getInfo() {
39
+ const { envId } = this.getHostingConfig();
40
+ const { Data } = await this.tcbService.request('DescribeStaticStore', {
41
+ EnvId: envId
42
+ });
43
+ return Data;
44
+ }
45
+ /**
46
+ * 开启 hosting 服务,异步任务
47
+ */
48
+ async enableService() {
49
+ const { envId } = this.getHostingConfig();
50
+ const hostings = await this.getInfo();
51
+ // hosting 服务已开启
52
+ if (hostings === null || hostings === void 0 ? void 0 : hostings.length) {
53
+ const website = hostings[0];
54
+ // offline 状态的服务可重新开启
55
+ if (website.Status !== 'offline') {
56
+ throw new error_1.CloudBaseError('静态网站服务已开启,请勿重复操作!');
57
+ }
58
+ }
59
+ const res = await this.tcbService.request('CreateStaticStore', {
60
+ EnvId: envId
61
+ });
62
+ const code = res.Result === 'succ' ? 0 : -1;
63
+ return {
64
+ code,
65
+ requestId: res.RequestId
66
+ };
67
+ }
68
+ async findFiles(options) {
69
+ const hosting = await this.checkStatus();
70
+ const { Bucket, Regoin } = hosting;
71
+ const { maxKeys, marker, prefix } = options;
72
+ const storageService = await this.environment.getStorageService();
73
+ const res = await storageService.getBucket({
74
+ bucket: Bucket,
75
+ region: Regoin,
76
+ maxKeys,
77
+ marker,
78
+ prefix
79
+ });
80
+ return res;
81
+ }
82
+ /**
83
+ * 展示文件列表
84
+ */
85
+ async listFiles() {
86
+ const hosting = await this.checkStatus();
87
+ const { Bucket, Regoin } = hosting;
88
+ const storageService = await this.environment.getStorageService();
89
+ const list = await storageService.walkCloudDirCustom({
90
+ prefix: '',
91
+ bucket: Bucket,
92
+ region: Regoin
93
+ });
94
+ return list;
95
+ }
96
+ /**
97
+ * 销毁静态托管服务
98
+ */
99
+ async destroyService() {
100
+ const { envId } = this.getHostingConfig();
101
+ const files = await this.listFiles();
102
+ if (files === null || files === void 0 ? void 0 : files.length) {
103
+ throw new error_1.CloudBaseError('静态网站文件不为空,无法销毁!', {
104
+ code: 'INVALID_OPERATION'
105
+ });
106
+ }
107
+ const hostings = await this.getInfo();
108
+ if (!hostings || !hostings.length) {
109
+ throw new error_1.CloudBaseError('静态网站服务未开启!', {
110
+ code: 'INVALID_OPERATION'
111
+ });
112
+ }
113
+ const website = hostings[0];
114
+ // destroy_fail 状态可重试
115
+ if (website.Status !== 'online' && website.Status !== 'destroy_fail') {
116
+ throw new error_1.CloudBaseError(`静态网站服务【${HostingStatusMap[website.Status]}】,无法进行此操作!`, {
117
+ code: 'INVALID_OPERATION'
118
+ });
119
+ }
120
+ const res = await this.tcbService.request('DestroyStaticStore', {
121
+ EnvId: envId
122
+ });
123
+ const code = res.Result === 'succ' ? 0 : -1;
124
+ return {
125
+ code,
126
+ requestId: res.RequestId
127
+ };
128
+ }
129
+ /**
130
+ * 支持上传单个文件,文件夹,或多个文件
131
+ * @param options
132
+ */
133
+ async uploadFiles(options) {
134
+ const { localPath, cloudPath, files = [], onProgress, onFileFinish, parallel = 20, ignore, retryCount, retryInterval } = options;
135
+ const hosting = await this.checkStatus();
136
+ const { Bucket, Regoin } = hosting;
137
+ const storageService = await this.environment.getStorageService();
138
+ let uploadFiles = Array.isArray(files) ? files : [];
139
+ // localPath 存在,上传文件夹/文件
140
+ if (localPath) {
141
+ const resolvePath = path_1.default.resolve(localPath);
142
+ // 检查路径是否存在
143
+ utils_1.checkReadable(resolvePath, true);
144
+ if (utils_1.isDirectory(resolvePath)) {
145
+ return storageService.uploadDirectoryCustom({
146
+ localPath: resolvePath,
147
+ cloudPath,
148
+ bucket: Bucket,
149
+ region: Regoin,
150
+ onProgress,
151
+ onFileFinish,
152
+ fileId: false,
153
+ ignore,
154
+ retryCount,
155
+ retryInterval,
156
+ });
157
+ }
158
+ else {
159
+ // 文件上传统一通过批量上传接口
160
+ const assignCloudPath = cloudPath || path_1.default.parse(resolvePath).base;
161
+ uploadFiles.push({
162
+ localPath: resolvePath,
163
+ cloudPath: assignCloudPath
164
+ });
165
+ }
166
+ }
167
+ // 文件上传统一通过批量上传接口
168
+ return storageService.uploadFilesCustom({
169
+ ignore,
170
+ parallel,
171
+ onProgress,
172
+ onFileFinish,
173
+ bucket: Bucket,
174
+ region: Regoin,
175
+ files: uploadFiles,
176
+ fileId: false,
177
+ retryCount,
178
+ retryInterval,
179
+ });
180
+ }
181
+ /**
182
+ * 删除文件或文件夹
183
+ * @param options
184
+ */
185
+ async deleteFiles(options) {
186
+ const { cloudPath, isDir } = options;
187
+ const hosting = await this.checkStatus();
188
+ const { Bucket, Regoin } = hosting;
189
+ const storageService = await this.environment.getStorageService();
190
+ if (isDir) {
191
+ return storageService.deleteDirectoryCustom({
192
+ cloudPath,
193
+ bucket: Bucket,
194
+ region: Regoin
195
+ });
196
+ }
197
+ else {
198
+ try {
199
+ await storageService.deleteFileCustom([cloudPath], Bucket, Regoin);
200
+ return {
201
+ Deleted: [{ Key: cloudPath }],
202
+ Error: []
203
+ };
204
+ }
205
+ catch (e) {
206
+ return {
207
+ Deleted: [],
208
+ Error: [e]
209
+ };
210
+ }
211
+ }
212
+ }
213
+ /**
214
+ * 下载文件
215
+ * @param {string} cloudPath 云端文件路径
216
+ * @param {string} localPath 文件本地存储路径,文件需指定文件名称
217
+ * @returns {Promise<NodeJS.ReadableStream>}
218
+ */
219
+ async downloadFile(options) {
220
+ const { cloudPath, localPath } = options;
221
+ const resolveLocalPath = path_1.default.resolve(localPath);
222
+ const fileDir = path_1.default.dirname(localPath);
223
+ utils_1.checkFullAccess(fileDir, true);
224
+ const envConfig = this.environment.lazyEnvironmentConfig;
225
+ const cacheHosting = envDomainCache.get(envConfig.EnvId);
226
+ let CdnDomain;
227
+ // 2 分钟有效
228
+ if ((cacheHosting === null || cacheHosting === void 0 ? void 0 : cacheHosting.cacheTime) && Number(cacheHosting === null || cacheHosting === void 0 ? void 0 : cacheHosting.cacheTime) + 120000 < Date.now()) {
229
+ console.log('cache');
230
+ CdnDomain = cacheHosting.CdnDomain;
231
+ }
232
+ else {
233
+ const hosting = await this.checkStatus();
234
+ CdnDomain = hosting.CdnDomain;
235
+ envDomainCache.set(envConfig.EnvId, Object.assign(Object.assign({}, hosting), { cacheTime: Date.now() }));
236
+ }
237
+ const url = new URL(cloudPath, `https://${CdnDomain}`).toString();
238
+ const { proxy } = await this.environment.getAuthConfig();
239
+ const res = await utils_1.fetchStream(url, {}, proxy);
240
+ // localPath 不存在时,返回 ReadableStream
241
+ if (!localPath) {
242
+ return res.body;
243
+ }
244
+ const dest = fs_1.default.createWriteStream(resolveLocalPath);
245
+ res.body.pipe(dest);
246
+ // 写完成后返回
247
+ return new Promise(resolve => {
248
+ dest.on('close', () => {
249
+ // 返回文件地址
250
+ resolve(resolveLocalPath);
251
+ });
252
+ });
253
+ }
254
+ /**
255
+ * 下载文件夹
256
+ * @param {string} cloudPath 云端文件路径
257
+ * @param {string} localPath 本地文件夹存储路径
258
+ * @returns {Promise<(NodeJS.ReadableStream | string)[]>}
259
+ */
260
+ async downloadDirectory(options) {
261
+ const { cloudPath, localPath } = options;
262
+ const resolveLocalPath = path_1.default.resolve(localPath);
263
+ const hosting = await this.checkStatus();
264
+ const { Bucket, Regoin } = hosting;
265
+ const cloudDirectoryKey = this.getCloudKey(cloudPath);
266
+ const storageService = await this.environment.getStorageService();
267
+ const files = await storageService.walkCloudDirCustom({
268
+ prefix: cloudDirectoryKey,
269
+ bucket: Bucket,
270
+ region: Regoin
271
+ });
272
+ const tasks = files.map(file => async () => {
273
+ const fileRelativePath = file.Key.replace(cloudDirectoryKey, '');
274
+ // 空路径和文件夹跳过
275
+ if (!fileRelativePath || /\/$/g.test(fileRelativePath)) {
276
+ return;
277
+ }
278
+ const localFilePath = path_1.default.join(resolveLocalPath, fileRelativePath);
279
+ // 创建文件的父文件夹
280
+ const fileDir = path_1.default.dirname(localFilePath);
281
+ await make_dir_1.default(fileDir);
282
+ return this.downloadFile({
283
+ cloudPath: file.Key,
284
+ localPath: localFilePath
285
+ });
286
+ });
287
+ // 下载请求
288
+ const creatingDirController = new parallel_1.AsyncTaskParallelController(20, 50);
289
+ creatingDirController.loadTasks(tasks);
290
+ await creatingDirController.run();
291
+ }
292
+ // 遍历文件
293
+ async walkLocalDir(envId, dir) {
294
+ const storageService = await this.environment.getStorageService();
295
+ return storageService.walkLocalDir(dir);
296
+ }
297
+ /**
298
+ * 绑定自定义域名
299
+ * @param {IBindDomainOptions} options
300
+ * @returns
301
+ * @memberof HostingService
302
+ */
303
+ async CreateHostingDomain(options) {
304
+ const { envId } = this.getHostingConfig();
305
+ const { certId, domain } = options;
306
+ const res = await this.tcbService.request('CreateHostingDomain', {
307
+ EnvId: envId,
308
+ Domain: domain,
309
+ CertId: certId
310
+ });
311
+ return res;
312
+ }
313
+ /**
314
+ * 删除托管域名
315
+ *
316
+ * @param {IBindDomainOptions} options
317
+ * @returns
318
+ * @memberof HostingService
319
+ */
320
+ async deleteHostingDomain(options) {
321
+ const { envId } = this.getHostingConfig();
322
+ const { domain } = options;
323
+ return this.tcbService.request('DeleteHostingDomain', {
324
+ EnvId: envId,
325
+ Domain: domain
326
+ });
327
+ }
328
+ /**
329
+ * 查询域名状态信息
330
+ * @param options
331
+ */
332
+ async tcbCheckResource(options) {
333
+ return this.cdnService.request('TcbCheckResource', {
334
+ Domains: options.domains
335
+ });
336
+ }
337
+ /**
338
+ * 域名配置变更
339
+ * @param options
340
+ */
341
+ async tcbModifyAttribute(options) {
342
+ const { domain, domainId, domainConfig } = options;
343
+ const res = await this.cdnService.request('TcbModifyAttribute', {
344
+ Domain: domain,
345
+ DomainId: domainId,
346
+ DomainConfig: domainConfig
347
+ });
348
+ return res;
349
+ }
350
+ /**
351
+ * 查询静态网站配置
352
+ * @memberof HostingService
353
+ */
354
+ async getWebsiteConfig() {
355
+ const hosting = await this.checkStatus();
356
+ const { Bucket, Regoin } = hosting;
357
+ const storageService = await this.environment.getStorageService();
358
+ const res = await storageService.getWebsiteConfig({ bucket: Bucket, region: Regoin });
359
+ return res;
360
+ }
361
+ /**
362
+ * 配置静态网站文档
363
+ * @param options
364
+ */
365
+ async setWebsiteDocument(options) {
366
+ const { indexDocument, errorDocument, routingRules } = options;
367
+ const hosting = await this.checkStatus();
368
+ const { Bucket, Regoin } = hosting;
369
+ const storageService = await this.environment.getStorageService();
370
+ const res = await storageService.putBucketWebsite({
371
+ bucket: Bucket,
372
+ region: Regoin,
373
+ indexDocument,
374
+ errorDocument,
375
+ routingRules
376
+ });
377
+ return res;
378
+ }
379
+ /**
380
+ * 检查 hosting 服务状态
381
+ */
382
+ async checkStatus() {
383
+ const hostings = await this.getInfo();
384
+ if (!hostings || !hostings.length) {
385
+ throw new error_1.CloudBaseError(`您还没有开启静态网站服务,请先到云开发控制台开启静态网站服务!`, {
386
+ code: 'INVALID_OPERATION'
387
+ });
388
+ }
389
+ const website = hostings[0];
390
+ if (website.Status !== 'online') {
391
+ throw new error_1.CloudBaseError(`静态网站服务【${HostingStatusMap[website.Status]}】,无法进行此操作!`, {
392
+ code: 'INVALID_OPERATION'
393
+ });
394
+ }
395
+ return website;
396
+ }
397
+ /**
398
+ * 获取配置
399
+ */
400
+ getHostingConfig() {
401
+ var _a;
402
+ const envConfig = this.environment.lazyEnvironmentConfig;
403
+ const appId = (_a = envConfig.Storages[0]) === null || _a === void 0 ? void 0 : _a.AppId;
404
+ const { proxy } = this.environment.cloudBaseContext;
405
+ return {
406
+ appId,
407
+ proxy,
408
+ envId: envConfig.EnvId
409
+ };
410
+ }
411
+ /**
412
+ * 将 cloudPath 转换成 cloudPath/ 形式
413
+ */
414
+ getCloudKey(cloudPath) {
415
+ if (!cloudPath) {
416
+ return '';
417
+ }
418
+ // 单个 / 转换成根目录
419
+ if (cloudPath === '/') {
420
+ return '';
421
+ }
422
+ return cloudPath[cloudPath.length - 1] === '/' ? cloudPath : `${cloudPath}/`;
423
+ }
424
+ }
425
+ __decorate([
426
+ utils_1.preLazy()
427
+ ], HostingService.prototype, "getInfo", null);
428
+ __decorate([
429
+ utils_1.preLazy()
430
+ ], HostingService.prototype, "enableService", null);
431
+ __decorate([
432
+ utils_1.preLazy()
433
+ ], HostingService.prototype, "listFiles", null);
434
+ __decorate([
435
+ utils_1.preLazy()
436
+ ], HostingService.prototype, "destroyService", null);
437
+ __decorate([
438
+ utils_1.preLazy()
439
+ ], HostingService.prototype, "uploadFiles", null);
440
+ __decorate([
441
+ utils_1.preLazy()
442
+ ], HostingService.prototype, "deleteFiles", null);
443
+ __decorate([
444
+ utils_1.preLazy()
445
+ ], HostingService.prototype, "downloadFile", null);
446
+ __decorate([
447
+ utils_1.preLazy()
448
+ ], HostingService.prototype, "downloadDirectory", null);
449
+ __decorate([
450
+ utils_1.preLazy()
451
+ ], HostingService.prototype, "walkLocalDir", null);
452
+ __decorate([
453
+ utils_1.preLazy()
454
+ ], HostingService.prototype, "CreateHostingDomain", null);
455
+ __decorate([
456
+ utils_1.preLazy()
457
+ ], HostingService.prototype, "deleteHostingDomain", null);
458
+ __decorate([
459
+ utils_1.preLazy()
460
+ ], HostingService.prototype, "checkStatus", null);
461
+ exports.HostingService = HostingService;
package/lib/index.js ADDED
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ const context_1 = require("./context");
3
+ const environmentManager_1 = require("./environmentManager");
4
+ class CloudBase {
5
+ constructor(config = {}) {
6
+ this.cloudBaseConfig = {};
7
+ let { secretId, secretKey, token, envId, proxy, region, envType } = config;
8
+ // config 中传入的 secretId secretkey 必须同时存在
9
+ if ((secretId && !secretKey) || (!secretId && secretKey)) {
10
+ throw new Error('secretId and secretKey must be a pair');
11
+ }
12
+ this.cloudBaseConfig = {
13
+ secretId,
14
+ secretKey,
15
+ token,
16
+ envId,
17
+ envType,
18
+ proxy,
19
+ region
20
+ };
21
+ // 初始化 context
22
+ this.context = new context_1.CloudBaseContext(this.cloudBaseConfig);
23
+ this.environmentManager = new environmentManager_1.EnvironmentManager(this.context);
24
+ this.environmentManager.add(envId || '');
25
+ }
26
+ /**
27
+ * init 初始化 为单例
28
+ *
29
+ * @static
30
+ * @param {ManagerConfig} config
31
+ * @returns {CloudBase}
32
+ * @memberof CloudBase
33
+ */
34
+ static init(config) {
35
+ if (!CloudBase.cloudBase) {
36
+ CloudBase.cloudBase = new CloudBase(config);
37
+ }
38
+ return CloudBase.cloudBase;
39
+ }
40
+ addEnvironment(envId) {
41
+ this.environmentManager.add(envId);
42
+ }
43
+ currentEnvironment() {
44
+ return this.environmentManager.getCurrentEnv();
45
+ }
46
+ get functions() {
47
+ return this.currentEnvironment().getFunctionService();
48
+ }
49
+ get storage() {
50
+ return this.currentEnvironment().getStorageService();
51
+ }
52
+ get database() {
53
+ return this.currentEnvironment().getDatabaseService();
54
+ }
55
+ get hosting() {
56
+ return this.currentEnvironment().getHostingService();
57
+ }
58
+ get access() {
59
+ return this.currentEnvironment().getAccessService();
60
+ }
61
+ get cloudApp() {
62
+ return this.currentEnvironment().getCloudBaseRunService();
63
+ }
64
+ commonService(service, version) {
65
+ return this.currentEnvironment().getCommonService(service, version);
66
+ }
67
+ get env() {
68
+ return this.currentEnvironment().getEnvService();
69
+ }
70
+ get third() {
71
+ return this.currentEnvironment().getThirdService();
72
+ }
73
+ get user() {
74
+ return this.currentEnvironment().getUserService();
75
+ }
76
+ getEnvironmentManager() {
77
+ return this.environmentManager;
78
+ }
79
+ getManagerConfig() {
80
+ return this.cloudBaseConfig;
81
+ }
82
+ }
83
+ module.exports = CloudBase;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });