@cloudbase/cli 2.0.3 → 2.0.4-alpha.0

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 (199) hide show
  1. package/.editorconfig +9 -9
  2. package/.eslintignore +7 -7
  3. package/.eslintrc +35 -35
  4. package/.prettierrc.js +29 -29
  5. package/.vscode/launch.json +16 -16
  6. package/LICENSE +5 -5
  7. package/README.md +35 -35
  8. package/bin/cloudbase.js +5 -5
  9. package/bin/tcb.js +0 -0
  10. package/changelog.md +6 -6
  11. package/jest.config.js +17 -17
  12. package/lib/commands/account/login.js +18 -18
  13. package/lib/commands/storage/storage.js +1 -1
  14. package/lib/env/login.js +7 -7
  15. package/package.json +2 -2
  16. package/post-install.js +61 -61
  17. package/runtime/nodejs/bootstrap.js +255 -255
  18. package/runtime/nodejs/runtime.js +183 -183
  19. package/src/auth/index.ts +1 -1
  20. package/src/auth/login.ts +91 -91
  21. package/src/auth/logout.ts +7 -7
  22. package/src/commands/account/index.ts +2 -2
  23. package/src/commands/account/login.ts +192 -192
  24. package/src/commands/account/logout.ts +24 -24
  25. package/src/commands/env/base.ts +90 -90
  26. package/src/commands/env/create.ts +92 -92
  27. package/src/commands/env/domain.ts +186 -186
  28. package/src/commands/env/index.ts +4 -4
  29. package/src/commands/env/login.ts +235 -235
  30. package/src/commands/framework/index.ts +124 -124
  31. package/src/commands/functions/alias/getRoute.ts +76 -76
  32. package/src/commands/functions/alias/index.ts +2 -2
  33. package/src/commands/functions/alias/setRoute.ts +82 -82
  34. package/src/commands/functions/code-download.ts +100 -100
  35. package/src/commands/functions/code-update.ts +62 -62
  36. package/src/commands/functions/concurrency/delete.ts +45 -45
  37. package/src/commands/functions/concurrency/index.ts +2 -2
  38. package/src/commands/functions/concurrency/list.ts +58 -58
  39. package/src/commands/functions/concurrency/set.ts +47 -47
  40. package/src/commands/functions/config-update.ts +76 -76
  41. package/src/commands/functions/copy.ts +62 -62
  42. package/src/commands/functions/delete.ts +79 -79
  43. package/src/commands/functions/deploy.ts +293 -293
  44. package/src/commands/functions/detail.ts +138 -138
  45. package/src/commands/functions/index.ts +16 -16
  46. package/src/commands/functions/invoke.ts +121 -121
  47. package/src/commands/functions/layer/bind.ts +182 -182
  48. package/src/commands/functions/layer/common.ts +8 -8
  49. package/src/commands/functions/layer/create.ts +49 -49
  50. package/src/commands/functions/layer/delete.ts +73 -73
  51. package/src/commands/functions/layer/download.ts +92 -92
  52. package/src/commands/functions/layer/index.ts +7 -7
  53. package/src/commands/functions/layer/list.ts +94 -94
  54. package/src/commands/functions/layer/sort.ts +76 -76
  55. package/src/commands/functions/list.ts +68 -68
  56. package/src/commands/functions/log.ts +148 -148
  57. package/src/commands/functions/run.ts +249 -249
  58. package/src/commands/functions/trigger-create.ts +79 -79
  59. package/src/commands/functions/trigger-delete.ts +105 -105
  60. package/src/commands/functions/version/index.ts +1 -1
  61. package/src/commands/functions/version/list.ts +73 -73
  62. package/src/commands/functions/version/publish.ts +43 -43
  63. package/src/commands/gateway/create.ts +109 -109
  64. package/src/commands/gateway/delete.ts +81 -81
  65. package/src/commands/gateway/domain.ts +159 -159
  66. package/src/commands/gateway/index.ts +5 -5
  67. package/src/commands/gateway/list.ts +76 -76
  68. package/src/commands/gateway/switch.ts +107 -107
  69. package/src/commands/helpers/index.ts +2 -2
  70. package/src/commands/helpers/init.ts +431 -431
  71. package/src/commands/helpers/new.ts +117 -117
  72. package/src/commands/helpers/open.ts +67 -67
  73. package/src/commands/hosting/hosting.ts +360 -360
  74. package/src/commands/index.ts +13 -13
  75. package/src/commands/lowcode/app.ts +34 -34
  76. package/src/commands/lowcode/comps.ts +322 -322
  77. package/src/commands/lowcode/index.ts +1 -1
  78. package/src/commands/lowcode/utils.ts +24 -24
  79. package/src/commands/run/image/index.ts +4 -4
  80. package/src/commands/run/standalonegateway/common.ts +7 -7
  81. package/src/commands/run/standalonegateway/create.ts +85 -85
  82. package/src/commands/run/standalonegateway/destroy.ts +59 -59
  83. package/src/commands/run/standalonegateway/index.ts +4 -4
  84. package/src/commands/run/standalonegateway/list.ts +53 -53
  85. package/src/commands/run/standalonegateway/package.ts +62 -62
  86. package/src/commands/run/standalonegateway/turn.ts +63 -63
  87. package/src/commands/run/version/index.ts +4 -4
  88. package/src/commands/smart.ts +132 -132
  89. package/src/commands/storage/storage.ts +464 -464
  90. package/src/commands/third/thirdAttach.ts +49 -49
  91. package/src/completion/index.ts +13 -13
  92. package/src/decorators/captureError.ts +25 -25
  93. package/src/decorators/constants.ts +12 -12
  94. package/src/decorators/deprecate.ts +25 -25
  95. package/src/decorators/guard.ts +42 -42
  96. package/src/decorators/index.ts +7 -7
  97. package/src/decorators/injectParams.ts +54 -54
  98. package/src/decorators/params/common.ts +28 -28
  99. package/src/decorators/params/index.ts +35 -35
  100. package/src/env/domain.ts +33 -33
  101. package/src/env/index.ts +63 -63
  102. package/src/env/login.ts +80 -80
  103. package/src/error.ts +36 -36
  104. package/src/function/alias.ts +43 -43
  105. package/src/function/base.ts +253 -253
  106. package/src/function/code.ts +55 -55
  107. package/src/function/concurrency.ts +57 -57
  108. package/src/function/create.ts +78 -78
  109. package/src/function/delete.ts +42 -42
  110. package/src/function/index.ts +10 -10
  111. package/src/function/layer/attach.ts +68 -68
  112. package/src/function/layer/create.ts +63 -63
  113. package/src/function/layer/delete.ts +21 -21
  114. package/src/function/layer/download.ts +54 -54
  115. package/src/function/layer/index.ts +7 -7
  116. package/src/function/layer/list.ts +32 -32
  117. package/src/function/layer/sort.ts +24 -24
  118. package/src/function/trigger.ts +97 -97
  119. package/src/function/update.ts +35 -35
  120. package/src/function/version.ts +38 -38
  121. package/src/function/vpc.ts +22 -22
  122. package/src/gateway/index.ts +137 -137
  123. package/src/hosting.ts +212 -212
  124. package/src/index.ts +13 -13
  125. package/src/logger.ts +17 -17
  126. package/src/run/create.ts +23 -23
  127. package/src/run/delete.ts +15 -15
  128. package/src/run/image/build.ts +36 -36
  129. package/src/run/image/delete.ts +13 -13
  130. package/src/run/image/index.ts +3 -3
  131. package/src/run/image/info.ts +26 -26
  132. package/src/run/list.ts +29 -29
  133. package/src/run/repo.ts +24 -24
  134. package/src/run/standalonegateway/create.ts +24 -24
  135. package/src/run/standalonegateway/destroy.ts +19 -19
  136. package/src/run/standalonegateway/index.ts +4 -4
  137. package/src/run/standalonegateway/list.ts +74 -74
  138. package/src/run/standalonegateway/package/list.ts +24 -24
  139. package/src/run/standalonegateway/turn/index.ts +1 -1
  140. package/src/run/standalonegateway/turn/off.ts +19 -19
  141. package/src/run/standalonegateway/turn/on.ts +19 -19
  142. package/src/run/version/create.ts +68 -68
  143. package/src/run/version/delete.ts +15 -15
  144. package/src/run/version/index.ts +5 -5
  145. package/src/run/version/list.ts +16 -16
  146. package/src/run/version/modify.ts +16 -16
  147. package/src/run/version/repo.ts +27 -27
  148. package/src/run/version/update.ts +58 -58
  149. package/src/storage.ts +114 -114
  150. package/src/third/index.ts +12 -12
  151. package/src/utils/auth.ts +15 -15
  152. package/src/utils/cli-table.ts +23 -23
  153. package/src/utils/config.ts +39 -39
  154. package/src/utils/env.ts +244 -244
  155. package/src/utils/fs/del.ts +5 -5
  156. package/src/utils/fs/index.ts +71 -71
  157. package/src/utils/function-packer.ts +97 -97
  158. package/src/utils/log.ts +81 -81
  159. package/src/utils/net/cloud-api-request.ts +62 -62
  160. package/src/utils/net/credential.ts +53 -53
  161. package/src/utils/net/index.ts +4 -4
  162. package/src/utils/net/manager-service.ts +36 -36
  163. package/src/utils/net/proxy.ts +6 -6
  164. package/src/utils/notice.ts +28 -28
  165. package/src/utils/output/highlight.ts +5 -5
  166. package/src/utils/output/index.ts +2 -2
  167. package/src/utils/output/link.ts +10 -10
  168. package/src/utils/output/loading.ts +82 -82
  169. package/src/utils/parallel.ts +82 -82
  170. package/src/utils/platform/index.ts +2 -2
  171. package/src/utils/platform/mac.ts +21 -21
  172. package/src/utils/platform/os.ts +64 -64
  173. package/src/utils/platform/port.ts +10 -10
  174. package/src/utils/progress-bar.ts +38 -38
  175. package/src/utils/prompt/select.ts +59 -59
  176. package/src/utils/reporter/agree.ts +20 -20
  177. package/src/utils/reporter/download.ts +26 -26
  178. package/src/utils/reporter/index.ts +3 -3
  179. package/src/utils/reporter/usage.ts +20 -20
  180. package/src/utils/store/auth.ts +49 -49
  181. package/src/utils/store/common.ts +8 -8
  182. package/src/utils/store/db.ts +68 -68
  183. package/src/utils/store/index.ts +4 -4
  184. package/src/utils/store/usage.ts +12 -12
  185. package/src/utils/template.ts +170 -170
  186. package/src/utils/tools/encoding.ts +8 -8
  187. package/src/utils/tools/index.ts +4 -4
  188. package/src/utils/tools/object.ts +33 -33
  189. package/src/utils/tools/time.ts +38 -38
  190. package/src/utils/tools/uid.ts +19 -19
  191. package/templates/html/loginFail.html +90 -90
  192. package/templates/html/loginSuccess.html +86 -86
  193. package/templates/server/node/_gitignore +54 -54
  194. package/templates/server/node/cloudbaserc.json +10 -10
  195. package/templates/server/node/index.js +5 -5
  196. package/templates/server/node/package.json +9 -9
  197. package/tsconfig.json +19 -19
  198. package/tsconfig.test.json +13 -13
  199. package/.vscode/settings.json +0 -3
@@ -1,431 +1,431 @@
1
- import fs from 'fs'
2
- import _ from 'lodash'
3
- import open from 'open'
4
- import path from 'path'
5
- import chalk from 'chalk'
6
- import fse from 'fs-extra'
7
- import { prompt } from 'enquirer'
8
- import { searchConfig, unzipStream, getDataFromWeb, isCamRefused } from '@cloudbase/toolbox'
9
-
10
- import { Command, ICommand } from '../common'
11
- import { CloudBaseError } from '../../error'
12
- import { listEnvs, getEnvInfo } from '../../env'
13
- import {
14
- fetch,
15
- fetchStream,
16
- execWithLoading,
17
- checkFullAccess,
18
- getMangerService,
19
- checkAndGetCredential,
20
- templateDownloadReport
21
- } from '../../utils'
22
- import { login } from '../../auth'
23
- import { ENV_STATUS, STATUS_TEXT } from '../../constant'
24
- import { InjectParams, ArgsOptions, Log, Logger } from '../../decorators'
25
-
26
- // 云函数
27
- const listUrl = 'https://tcli.service.tcloudbase.com/templates'
28
-
29
- // 创建环境链接
30
- const consoleUrl = 'https://console.cloud.tencent.com/tcb/env/index?action=CreateEnv&from=cli'
31
-
32
- const CREATE_ENV = 'CREATE'
33
-
34
- const getTemplateAddress = (templatePath: string) =>
35
- `https://7463-tcli-1258016615.tcb.qcloud.la/cloudbase-templates/${templatePath}.zip`
36
-
37
- const ENV_INIT_TIP = '环境初始化中,预计需要三分钟'
38
-
39
- @ICommand()
40
- export class InitCommand extends Command {
41
- get options() {
42
- return {
43
- cmd: 'init',
44
- options: [
45
- {
46
- flags: '--template <template>',
47
- desc: '指定项目模板名称'
48
- },
49
- {
50
- flags: '--without-template',
51
- desc: '不使用模板,在当前项目初始化'
52
- },
53
- {
54
- flags: '--project <project>',
55
- desc: '指定项目名称'
56
- }
57
- ],
58
- desc: '创建并初始化一个新的云开发项目',
59
- requiredEnvId: false,
60
- withoutAuth: true
61
- }
62
- }
63
-
64
- @InjectParams()
65
- async execute(@ArgsOptions() options, @Log() log?: Logger) {
66
- console.log(
67
- chalk.bold.yellowBright(
68
- '\n',
69
- '⚠️ 此命令将被废弃,请使用新的命令 => tcb new <appName> [template]'
70
- ),
71
- '\n'
72
- )
73
-
74
- // 检查登录
75
- await this.checkLogin()
76
-
77
- // 检查是否开通 TCB 服务
78
- const isInitNow = await this.checkTcbService()
79
-
80
- let envData = []
81
-
82
- // 刚初始化服务,新创建的环境还未就绪
83
- if (isInitNow) {
84
- envData = await execWithLoading(
85
- () => {
86
- // 等待用户完成创建环境的流程
87
- return new Promise((resolve) => {
88
- const timer = setInterval(async () => {
89
- const envs = await listEnvs()
90
- if (envs.length) {
91
- clearInterval(timer)
92
- resolve(envs)
93
- }
94
- }, 2000)
95
- })
96
- },
97
- {
98
- startTip: '获取环境列表中'
99
- }
100
- )
101
- } else {
102
- // 选择环境
103
- envData = await execWithLoading(() => listEnvs(), {
104
- startTip: '获取环境列表中'
105
- })
106
- }
107
-
108
- envData = envData || []
109
-
110
- const envs: { name: string; value: string }[] = envData
111
- .map((item) => {
112
- let name = `${item.Alias} - [${item.EnvId}:${item.PackageName || '按量计费'}]`
113
- if (item.Status !== ENV_STATUS.NORMAL) {
114
- name += `(${STATUS_TEXT[item.Status]})`
115
- }
116
-
117
- return {
118
- name,
119
- value: item.EnvId
120
- }
121
- })
122
- .sort((prev, next) => prev.value.charCodeAt(0) - next.value.charCodeAt(0))
123
-
124
- const choices = [
125
- ...envs,
126
- {
127
- name: envData.length ? '创建新环境' : '无可用环境,创建新环境',
128
- value: CREATE_ENV
129
- }
130
- ]
131
-
132
- let { env } = await prompt<any>({
133
- choices,
134
- type: 'select',
135
- name: 'env',
136
- message: '选择关联环境',
137
- result(choice) {
138
- return this.map(choice)[choice]
139
- }
140
- })
141
-
142
- // 创建新环境
143
- if (env === CREATE_ENV) {
144
- log.success('已打开控制台,请前往控制台创建环境')
145
- // 从控制台获取创建环境生成的 envId
146
- const { envId } = await getDataFromWeb(
147
- (port) => `${consoleUrl}&port=${port}`,
148
- 'getData'
149
- )
150
- if (!envId) {
151
- throw new CloudBaseError('接收环境 Id 信息失败,请重新运行 init 命令!')
152
- }
153
- log.success(`创建环境成功,环境 Id: ${envId}`)
154
- env = envId
155
- }
156
-
157
- // 检查环境状态
158
- await this.checkEnvStatus(env)
159
-
160
- let projectName
161
- let projectPath
162
-
163
- if (!options.withoutTemplate) {
164
- // 拉取模板
165
- const templates = await execWithLoading(() => fetch(listUrl), {
166
- startTip: '拉取云开发模板列表中'
167
- })
168
-
169
- let templateName
170
- let tempateId
171
-
172
- // 确定模板名称
173
- if (options.template) {
174
- tempateId = options.template
175
- } else {
176
- let { selectTemplateName } = await prompt<any>({
177
- type: 'select',
178
- name: 'selectTemplateName',
179
- message: '选择云开发模板',
180
- choices: templates.map((item) => item.name)
181
- })
182
- templateName = selectTemplateName
183
- }
184
-
185
- const selectedTemplate = templateName
186
- ? templates.find((item) => item.name === templateName)
187
- : templates.find((item) => item.path === tempateId)
188
-
189
- if (!selectedTemplate) {
190
- log.info(`模板 \`${templateName || tempateId}\` 不存在`)
191
- return
192
- }
193
-
194
- // 确定项目名称
195
- if (options.project) {
196
- projectName = options.project
197
- } else {
198
- const { projectName: promptProjectName } = await prompt<any>({
199
- type: 'input',
200
- name: 'projectName',
201
- message: '请输入项目名称',
202
- initial: selectedTemplate.path
203
- })
204
-
205
- projectName = promptProjectName
206
- }
207
-
208
- // 确定项目权限
209
- projectPath = path.join(process.cwd(), projectName)
210
- if (checkFullAccess(projectPath)) {
211
- const { cover } = await prompt<any>({
212
- type: 'confirm',
213
- name: 'cover',
214
- message: `已存在同名文件夹:${projectName},是否覆盖?`,
215
- initial: false
216
- })
217
- // 不覆盖,操作终止
218
- if (!cover) {
219
- throw new CloudBaseError('操作终止!')
220
- } else {
221
- // 覆盖操作不会删除不冲突的文件夹或文件
222
- // 删除原有文件夹,防止生成的项目包含用户原有文件
223
- fse.removeSync(projectPath)
224
- }
225
- }
226
-
227
- await execWithLoading(
228
- async () => {
229
- await templateDownloadReport(selectedTemplate.path, selectedTemplate.name)
230
- await this.extractTemplate(
231
- projectPath,
232
- selectedTemplate.path,
233
- selectedTemplate.url
234
- )
235
- },
236
- {
237
- startTip: '下载文件中'
238
- }
239
- )
240
- } else {
241
- projectName = ''
242
- projectPath = path.join(process.cwd(), projectName)
243
- }
244
-
245
- // 配置文件初始化,写入环境id
246
- let filepath = (await searchConfig(projectPath))?.filepath
247
-
248
- // 配置文件未找到
249
- if (!filepath) {
250
- fs.writeFileSync(
251
- path.join(projectPath, 'cloudbaserc.json'),
252
- JSON.stringify({
253
- envId: env,
254
- version: '2.0',
255
- $schema: 'https://framework-1258016615.tcloudbaseapp.com/schema/latest.json'
256
- })
257
- )
258
- } else {
259
- const configContent = fs.readFileSync(filepath).toString()
260
- fs.writeFileSync(filepath, configContent.replace('{{envId}}', env))
261
- }
262
-
263
- // 成功提示
264
- this.initSuccessOutput(projectName)
265
- }
266
-
267
- // 检查登录
268
- @InjectParams()
269
- async checkLogin(@Log() log?: Logger) {
270
- const credential = await checkAndGetCredential()
271
- // 没有登录,拉起 Web 登录
272
- if (_.isEmpty(credential)) {
273
- log.info('你还没有登录,请在控制台中授权登录')
274
-
275
- const res = await execWithLoading(() => login(), {
276
- startTip: '获取授权中...',
277
- successTip: '授权登录成功!'
278
- })
279
-
280
- const envId = res?.credential?.envId
281
-
282
- // 登录返回 envId,检查环境初始化
283
- if (envId) {
284
- const env = await getEnvInfo(envId)
285
- if (env.Status === ENV_STATUS.UNAVAILABLE) {
286
- await this.checkEnvAvaliable(envId)
287
- }
288
- }
289
- }
290
- }
291
-
292
- // 检查环境的状态,是否可以正常使用
293
- @InjectParams()
294
- async checkEnvStatus(envId: string) {
295
- const env = await getEnvInfo(envId)
296
- if (env.Status === ENV_STATUS.UNAVAILABLE) {
297
- await this.checkEnvAvaliable(envId)
298
- } else if (env.Status !== ENV_STATUS.NORMAL) {
299
- throw new CloudBaseError('所有环境状态异常')
300
- }
301
- }
302
-
303
- // 检测环境是否可用
304
- @InjectParams()
305
- async checkEnvAvaliable(envId: string) {
306
- let count = 0
307
-
308
- await execWithLoading(
309
- (flush) => {
310
- const increase = setInterval(() => {
311
- flush(`${ENV_INIT_TIP} ${++count}S`)
312
- }, 1000)
313
-
314
- return new Promise<void>((resolve) => {
315
- const timer = setInterval(async () => {
316
- const env = await getEnvInfo(envId)
317
- // 环境初始化中
318
- if (env.Status === ENV_STATUS.NORMAL) {
319
- clearInterval(timer)
320
- clearInterval(increase)
321
- resolve()
322
- }
323
- }, 3000)
324
- })
325
- },
326
- {
327
- startTip: ENV_INIT_TIP,
328
- successTip: `环境 ${envId} 初始化成功`
329
- }
330
- )
331
- }
332
-
333
- // 检查 TCB 服务是否开通
334
- @InjectParams()
335
- async checkTcbService(@Log() log?: Logger): Promise<boolean> {
336
- const app = await getMangerService()
337
- let Initialized
338
- try {
339
- Initialized = (await app.env.checkTcbService()).Initialized
340
- } catch (e) {
341
- // 忽略 CAM 权限问题
342
- if (!isCamRefused(e)) {
343
- throw e
344
- }
345
- }
346
-
347
- if (!Initialized) {
348
- const { jump } = await prompt<any>({
349
- type: 'confirm',
350
- name: 'jump',
351
- message:
352
- '你还没有开通云开发服务,是否跳转到控制台开通云开发服务?(取消将无法继续操作)',
353
- initial: true
354
- })
355
-
356
- if (!jump) {
357
- throw new CloudBaseError('init 操作终止,请开通云开发服务后再进行操作!')
358
- }
359
-
360
- // 打开控制台
361
- open(consoleUrl)
362
- log.success('已打开云开发控制台,请登录并在云开发控制台中开通服务!')
363
-
364
- await execWithLoading(() => this.waitForServiceEnable(), {
365
- startTip: '等待云开发服务开通中',
366
- successTip: '云开发服务开通成功!'
367
- })
368
-
369
- // 返回一个是否刚初始化服务的标志
370
- return true
371
- }
372
-
373
- return false
374
- }
375
-
376
- async waitForServiceEnable(): Promise<void> {
377
- return new Promise((resolve) => {
378
- const timer = setInterval(async () => {
379
- const app = await getMangerService()
380
- try {
381
- const { Initialized } = await app.env.checkTcbService()
382
- if (Initialized) {
383
- clearInterval(timer)
384
- setTimeout(() => {
385
- // 服务初始化完成到环境创建完成有一定的延迟时间,延迟 5S 返回
386
- resolve()
387
- }, 5000)
388
- }
389
- } catch (e) {
390
- // 忽略 CAM 权限问题
391
- if (!isCamRefused(e)) {
392
- throw e
393
- }
394
- }
395
- }, 3000)
396
- })
397
- }
398
-
399
- async extractTemplate(projectPath: string, templatePath: string, remoteUrl?: string) {
400
- // 文件下载链接
401
- const url = remoteUrl || getTemplateAddress(templatePath)
402
-
403
- return fetchStream(url).then(async (res) => {
404
- if (!res) {
405
- throw new CloudBaseError('请求异常')
406
- }
407
-
408
- if (res.status !== 200) {
409
- throw new CloudBaseError('未找到文件')
410
- }
411
-
412
- // 解压缩文件
413
- await unzipStream(res.body, projectPath)
414
- })
415
- }
416
-
417
- // 项目初始化成功后打印提示语
418
- @InjectParams()
419
- initSuccessOutput(projectName, @Log() log?: Logger) {
420
- log.success(`初始化项目${projectName}成功!\n`)
421
-
422
- if (projectName) {
423
- const command = chalk.bold.cyan(`cd ${projectName}`)
424
- log.info(`👉 执行命令 ${command} 进入项目文件夹`)
425
- }
426
-
427
- log.info(
428
- `👉 开发完成后,执行命令 ${chalk.bold.cyan('cloudbase framework:deploy')} 一键部署`
429
- )
430
- }
431
- }
1
+ import fs from 'fs'
2
+ import _ from 'lodash'
3
+ import open from 'open'
4
+ import path from 'path'
5
+ import chalk from 'chalk'
6
+ import fse from 'fs-extra'
7
+ import { prompt } from 'enquirer'
8
+ import { searchConfig, unzipStream, getDataFromWeb, isCamRefused } from '@cloudbase/toolbox'
9
+
10
+ import { Command, ICommand } from '../common'
11
+ import { CloudBaseError } from '../../error'
12
+ import { listEnvs, getEnvInfo } from '../../env'
13
+ import {
14
+ fetch,
15
+ fetchStream,
16
+ execWithLoading,
17
+ checkFullAccess,
18
+ getMangerService,
19
+ checkAndGetCredential,
20
+ templateDownloadReport
21
+ } from '../../utils'
22
+ import { login } from '../../auth'
23
+ import { ENV_STATUS, STATUS_TEXT } from '../../constant'
24
+ import { InjectParams, ArgsOptions, Log, Logger } from '../../decorators'
25
+
26
+ // 云函数
27
+ const listUrl = 'https://tcli.service.tcloudbase.com/templates'
28
+
29
+ // 创建环境链接
30
+ const consoleUrl = 'https://console.cloud.tencent.com/tcb/env/index?action=CreateEnv&from=cli'
31
+
32
+ const CREATE_ENV = 'CREATE'
33
+
34
+ const getTemplateAddress = (templatePath: string) =>
35
+ `https://7463-tcli-1258016615.tcb.qcloud.la/cloudbase-templates/${templatePath}.zip`
36
+
37
+ const ENV_INIT_TIP = '环境初始化中,预计需要三分钟'
38
+
39
+ @ICommand()
40
+ export class InitCommand extends Command {
41
+ get options() {
42
+ return {
43
+ cmd: 'init',
44
+ options: [
45
+ {
46
+ flags: '--template <template>',
47
+ desc: '指定项目模板名称'
48
+ },
49
+ {
50
+ flags: '--without-template',
51
+ desc: '不使用模板,在当前项目初始化'
52
+ },
53
+ {
54
+ flags: '--project <project>',
55
+ desc: '指定项目名称'
56
+ }
57
+ ],
58
+ desc: '创建并初始化一个新的云开发项目',
59
+ requiredEnvId: false,
60
+ withoutAuth: true
61
+ }
62
+ }
63
+
64
+ @InjectParams()
65
+ async execute(@ArgsOptions() options, @Log() log?: Logger) {
66
+ console.log(
67
+ chalk.bold.yellowBright(
68
+ '\n',
69
+ '⚠️ 此命令将被废弃,请使用新的命令 => tcb new <appName> [template]'
70
+ ),
71
+ '\n'
72
+ )
73
+
74
+ // 检查登录
75
+ await this.checkLogin()
76
+
77
+ // 检查是否开通 TCB 服务
78
+ const isInitNow = await this.checkTcbService()
79
+
80
+ let envData = []
81
+
82
+ // 刚初始化服务,新创建的环境还未就绪
83
+ if (isInitNow) {
84
+ envData = await execWithLoading(
85
+ () => {
86
+ // 等待用户完成创建环境的流程
87
+ return new Promise((resolve) => {
88
+ const timer = setInterval(async () => {
89
+ const envs = await listEnvs()
90
+ if (envs.length) {
91
+ clearInterval(timer)
92
+ resolve(envs)
93
+ }
94
+ }, 2000)
95
+ })
96
+ },
97
+ {
98
+ startTip: '获取环境列表中'
99
+ }
100
+ )
101
+ } else {
102
+ // 选择环境
103
+ envData = await execWithLoading(() => listEnvs(), {
104
+ startTip: '获取环境列表中'
105
+ })
106
+ }
107
+
108
+ envData = envData || []
109
+
110
+ const envs: { name: string; value: string }[] = envData
111
+ .map((item) => {
112
+ let name = `${item.Alias} - [${item.EnvId}:${item.PackageName || '按量计费'}]`
113
+ if (item.Status !== ENV_STATUS.NORMAL) {
114
+ name += `(${STATUS_TEXT[item.Status]})`
115
+ }
116
+
117
+ return {
118
+ name,
119
+ value: item.EnvId
120
+ }
121
+ })
122
+ .sort((prev, next) => prev.value.charCodeAt(0) - next.value.charCodeAt(0))
123
+
124
+ const choices = [
125
+ ...envs,
126
+ {
127
+ name: envData.length ? '创建新环境' : '无可用环境,创建新环境',
128
+ value: CREATE_ENV
129
+ }
130
+ ]
131
+
132
+ let { env } = await prompt<any>({
133
+ choices,
134
+ type: 'select',
135
+ name: 'env',
136
+ message: '选择关联环境',
137
+ result(choice) {
138
+ return this.map(choice)[choice]
139
+ }
140
+ })
141
+
142
+ // 创建新环境
143
+ if (env === CREATE_ENV) {
144
+ log.success('已打开控制台,请前往控制台创建环境')
145
+ // 从控制台获取创建环境生成的 envId
146
+ const { envId } = await getDataFromWeb(
147
+ (port) => `${consoleUrl}&port=${port}`,
148
+ 'getData'
149
+ )
150
+ if (!envId) {
151
+ throw new CloudBaseError('接收环境 Id 信息失败,请重新运行 init 命令!')
152
+ }
153
+ log.success(`创建环境成功,环境 Id: ${envId}`)
154
+ env = envId
155
+ }
156
+
157
+ // 检查环境状态
158
+ await this.checkEnvStatus(env)
159
+
160
+ let projectName
161
+ let projectPath
162
+
163
+ if (!options.withoutTemplate) {
164
+ // 拉取模板
165
+ const templates = await execWithLoading(() => fetch(listUrl), {
166
+ startTip: '拉取云开发模板列表中'
167
+ })
168
+
169
+ let templateName
170
+ let tempateId
171
+
172
+ // 确定模板名称
173
+ if (options.template) {
174
+ tempateId = options.template
175
+ } else {
176
+ let { selectTemplateName } = await prompt<any>({
177
+ type: 'select',
178
+ name: 'selectTemplateName',
179
+ message: '选择云开发模板',
180
+ choices: templates.map((item) => item.name)
181
+ })
182
+ templateName = selectTemplateName
183
+ }
184
+
185
+ const selectedTemplate = templateName
186
+ ? templates.find((item) => item.name === templateName)
187
+ : templates.find((item) => item.path === tempateId)
188
+
189
+ if (!selectedTemplate) {
190
+ log.info(`模板 \`${templateName || tempateId}\` 不存在`)
191
+ return
192
+ }
193
+
194
+ // 确定项目名称
195
+ if (options.project) {
196
+ projectName = options.project
197
+ } else {
198
+ const { projectName: promptProjectName } = await prompt<any>({
199
+ type: 'input',
200
+ name: 'projectName',
201
+ message: '请输入项目名称',
202
+ initial: selectedTemplate.path
203
+ })
204
+
205
+ projectName = promptProjectName
206
+ }
207
+
208
+ // 确定项目权限
209
+ projectPath = path.join(process.cwd(), projectName)
210
+ if (checkFullAccess(projectPath)) {
211
+ const { cover } = await prompt<any>({
212
+ type: 'confirm',
213
+ name: 'cover',
214
+ message: `已存在同名文件夹:${projectName},是否覆盖?`,
215
+ initial: false
216
+ })
217
+ // 不覆盖,操作终止
218
+ if (!cover) {
219
+ throw new CloudBaseError('操作终止!')
220
+ } else {
221
+ // 覆盖操作不会删除不冲突的文件夹或文件
222
+ // 删除原有文件夹,防止生成的项目包含用户原有文件
223
+ fse.removeSync(projectPath)
224
+ }
225
+ }
226
+
227
+ await execWithLoading(
228
+ async () => {
229
+ await templateDownloadReport(selectedTemplate.path, selectedTemplate.name)
230
+ await this.extractTemplate(
231
+ projectPath,
232
+ selectedTemplate.path,
233
+ selectedTemplate.url
234
+ )
235
+ },
236
+ {
237
+ startTip: '下载文件中'
238
+ }
239
+ )
240
+ } else {
241
+ projectName = ''
242
+ projectPath = path.join(process.cwd(), projectName)
243
+ }
244
+
245
+ // 配置文件初始化,写入环境id
246
+ let filepath = (await searchConfig(projectPath))?.filepath
247
+
248
+ // 配置文件未找到
249
+ if (!filepath) {
250
+ fs.writeFileSync(
251
+ path.join(projectPath, 'cloudbaserc.json'),
252
+ JSON.stringify({
253
+ envId: env,
254
+ version: '2.0',
255
+ $schema: 'https://framework-1258016615.tcloudbaseapp.com/schema/latest.json'
256
+ })
257
+ )
258
+ } else {
259
+ const configContent = fs.readFileSync(filepath).toString()
260
+ fs.writeFileSync(filepath, configContent.replace('{{envId}}', env))
261
+ }
262
+
263
+ // 成功提示
264
+ this.initSuccessOutput(projectName)
265
+ }
266
+
267
+ // 检查登录
268
+ @InjectParams()
269
+ async checkLogin(@Log() log?: Logger) {
270
+ const credential = await checkAndGetCredential()
271
+ // 没有登录,拉起 Web 登录
272
+ if (_.isEmpty(credential)) {
273
+ log.info('你还没有登录,请在控制台中授权登录')
274
+
275
+ const res = await execWithLoading(() => login(), {
276
+ startTip: '获取授权中...',
277
+ successTip: '授权登录成功!'
278
+ })
279
+
280
+ const envId = res?.credential?.envId
281
+
282
+ // 登录返回 envId,检查环境初始化
283
+ if (envId) {
284
+ const env = await getEnvInfo(envId)
285
+ if (env.Status === ENV_STATUS.UNAVAILABLE) {
286
+ await this.checkEnvAvaliable(envId)
287
+ }
288
+ }
289
+ }
290
+ }
291
+
292
+ // 检查环境的状态,是否可以正常使用
293
+ @InjectParams()
294
+ async checkEnvStatus(envId: string) {
295
+ const env = await getEnvInfo(envId)
296
+ if (env.Status === ENV_STATUS.UNAVAILABLE) {
297
+ await this.checkEnvAvaliable(envId)
298
+ } else if (env.Status !== ENV_STATUS.NORMAL) {
299
+ throw new CloudBaseError('所有环境状态异常')
300
+ }
301
+ }
302
+
303
+ // 检测环境是否可用
304
+ @InjectParams()
305
+ async checkEnvAvaliable(envId: string) {
306
+ let count = 0
307
+
308
+ await execWithLoading(
309
+ (flush) => {
310
+ const increase = setInterval(() => {
311
+ flush(`${ENV_INIT_TIP} ${++count}S`)
312
+ }, 1000)
313
+
314
+ return new Promise<void>((resolve) => {
315
+ const timer = setInterval(async () => {
316
+ const env = await getEnvInfo(envId)
317
+ // 环境初始化中
318
+ if (env.Status === ENV_STATUS.NORMAL) {
319
+ clearInterval(timer)
320
+ clearInterval(increase)
321
+ resolve()
322
+ }
323
+ }, 3000)
324
+ })
325
+ },
326
+ {
327
+ startTip: ENV_INIT_TIP,
328
+ successTip: `环境 ${envId} 初始化成功`
329
+ }
330
+ )
331
+ }
332
+
333
+ // 检查 TCB 服务是否开通
334
+ @InjectParams()
335
+ async checkTcbService(@Log() log?: Logger): Promise<boolean> {
336
+ const app = await getMangerService()
337
+ let Initialized
338
+ try {
339
+ Initialized = (await app.env.checkTcbService()).Initialized
340
+ } catch (e) {
341
+ // 忽略 CAM 权限问题
342
+ if (!isCamRefused(e)) {
343
+ throw e
344
+ }
345
+ }
346
+
347
+ if (!Initialized) {
348
+ const { jump } = await prompt<any>({
349
+ type: 'confirm',
350
+ name: 'jump',
351
+ message:
352
+ '你还没有开通云开发服务,是否跳转到控制台开通云开发服务?(取消将无法继续操作)',
353
+ initial: true
354
+ })
355
+
356
+ if (!jump) {
357
+ throw new CloudBaseError('init 操作终止,请开通云开发服务后再进行操作!')
358
+ }
359
+
360
+ // 打开控制台
361
+ open(consoleUrl)
362
+ log.success('已打开云开发控制台,请登录并在云开发控制台中开通服务!')
363
+
364
+ await execWithLoading(() => this.waitForServiceEnable(), {
365
+ startTip: '等待云开发服务开通中',
366
+ successTip: '云开发服务开通成功!'
367
+ })
368
+
369
+ // 返回一个是否刚初始化服务的标志
370
+ return true
371
+ }
372
+
373
+ return false
374
+ }
375
+
376
+ async waitForServiceEnable(): Promise<void> {
377
+ return new Promise((resolve) => {
378
+ const timer = setInterval(async () => {
379
+ const app = await getMangerService()
380
+ try {
381
+ const { Initialized } = await app.env.checkTcbService()
382
+ if (Initialized) {
383
+ clearInterval(timer)
384
+ setTimeout(() => {
385
+ // 服务初始化完成到环境创建完成有一定的延迟时间,延迟 5S 返回
386
+ resolve()
387
+ }, 5000)
388
+ }
389
+ } catch (e) {
390
+ // 忽略 CAM 权限问题
391
+ if (!isCamRefused(e)) {
392
+ throw e
393
+ }
394
+ }
395
+ }, 3000)
396
+ })
397
+ }
398
+
399
+ async extractTemplate(projectPath: string, templatePath: string, remoteUrl?: string) {
400
+ // 文件下载链接
401
+ const url = remoteUrl || getTemplateAddress(templatePath)
402
+
403
+ return fetchStream(url).then(async (res) => {
404
+ if (!res) {
405
+ throw new CloudBaseError('请求异常')
406
+ }
407
+
408
+ if (res.status !== 200) {
409
+ throw new CloudBaseError('未找到文件')
410
+ }
411
+
412
+ // 解压缩文件
413
+ await unzipStream(res.body, projectPath)
414
+ })
415
+ }
416
+
417
+ // 项目初始化成功后打印提示语
418
+ @InjectParams()
419
+ initSuccessOutput(projectName, @Log() log?: Logger) {
420
+ log.success(`初始化项目${projectName}成功!\n`)
421
+
422
+ if (projectName) {
423
+ const command = chalk.bold.cyan(`cd ${projectName}`)
424
+ log.info(`👉 执行命令 ${command} 进入项目文件夹`)
425
+ }
426
+
427
+ log.info(
428
+ `👉 开发完成后,执行命令 ${chalk.bold.cyan('cloudbase framework:deploy')} 一键部署`
429
+ )
430
+ }
431
+ }