@strapi/cloud-cli 5.9.0 → 5.10.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.
@@ -0,0 +1,1896 @@
1
+ 'use strict';
2
+
3
+ var crypto$1 = require('crypto');
4
+ var fse = require('fs-extra');
5
+ var inquirer = require('inquirer');
6
+ var boxen = require('boxen');
7
+ var path = require('path');
8
+ var chalk = require('chalk');
9
+ var axios = require('axios');
10
+ var crypto = require('node:crypto');
11
+ var utils = require('@strapi/utils');
12
+ var tar = require('tar');
13
+ var minimatch = require('minimatch');
14
+ var fp = require('lodash/fp');
15
+ var os = require('os');
16
+ var XDGAppPaths = require('xdg-app-paths');
17
+ var lodash = require('lodash');
18
+ var jwksClient = require('jwks-rsa');
19
+ var jwt = require('jsonwebtoken');
20
+ var stringify = require('fast-safe-stringify');
21
+ var ora = require('ora');
22
+ var cliProgress = require('cli-progress');
23
+ var pkgUp = require('pkg-up');
24
+ var yup = require('yup');
25
+ var EventSource = require('eventsource');
26
+ var commander = require('commander');
27
+
28
+ function _interopNamespaceDefault(e) {
29
+ var n = Object.create(null);
30
+ if (e) {
31
+ Object.keys(e).forEach(function (k) {
32
+ if (k !== 'default') {
33
+ var d = Object.getOwnPropertyDescriptor(e, k);
34
+ Object.defineProperty(n, k, d.get ? d : {
35
+ enumerable: true,
36
+ get: function () { return e[k]; }
37
+ });
38
+ }
39
+ });
40
+ }
41
+ n.default = e;
42
+ return Object.freeze(n);
43
+ }
44
+
45
+ var fse__namespace = /*#__PURE__*/_interopNamespaceDefault(fse);
46
+ var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
47
+ var crypto__namespace = /*#__PURE__*/_interopNamespaceDefault(crypto);
48
+ var tar__namespace = /*#__PURE__*/_interopNamespaceDefault(tar);
49
+ var cliProgress__namespace = /*#__PURE__*/_interopNamespaceDefault(cliProgress);
50
+ var yup__namespace = /*#__PURE__*/_interopNamespaceDefault(yup);
51
+
52
+ const apiConfig = {
53
+ apiBaseUrl: utils.env('STRAPI_CLI_CLOUD_API', 'https://cloud-cli-api.strapi.io'),
54
+ dashboardBaseUrl: utils.env('STRAPI_CLI_CLOUD_DASHBOARD', 'https://cloud.strapi.io')
55
+ };
56
+
57
+ const IGNORED_PATTERNS = [
58
+ '**/.git/**',
59
+ '**/node_modules/**',
60
+ '**/build/**',
61
+ '**/dist/**',
62
+ '**/.cache/**',
63
+ '**/.circleci/**',
64
+ '**/.github/**',
65
+ '**/.gitignore',
66
+ '**/.gitkeep',
67
+ '**/.gitlab-ci.yml',
68
+ '**/.idea/**',
69
+ '**/.vscode/**'
70
+ ];
71
+ const isIgnoredFile = (folderPath, file, ignorePatterns)=>{
72
+ ignorePatterns.push(...IGNORED_PATTERNS);
73
+ const relativeFilePath = path__namespace.join(folderPath, file);
74
+ let isIgnored = false;
75
+ for (const pattern of ignorePatterns){
76
+ if (pattern.startsWith('!')) {
77
+ if (minimatch.minimatch(relativeFilePath, pattern.slice(1), {
78
+ matchBase: true,
79
+ dot: true
80
+ })) {
81
+ return false;
82
+ }
83
+ } else if (minimatch.minimatch(relativeFilePath, pattern, {
84
+ matchBase: true,
85
+ dot: true
86
+ })) {
87
+ if (path__namespace.basename(file) !== '.gitkeep') {
88
+ isIgnored = true;
89
+ }
90
+ }
91
+ }
92
+ return isIgnored;
93
+ };
94
+ const getFiles = async (dirPath, ignorePatterns = [], subfolder = '')=>{
95
+ const arrayOfFiles = [];
96
+ const entries = await fse__namespace.readdir(path__namespace.join(dirPath, subfolder));
97
+ for (const entry of entries){
98
+ const entryPathFromRoot = path__namespace.join(subfolder, entry);
99
+ const entryPath = path__namespace.relative(dirPath, entryPathFromRoot);
100
+ const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
101
+ if (!isIgnored) {
102
+ if (fse__namespace.statSync(entryPath).isDirectory()) {
103
+ const subFiles = await getFiles(dirPath, ignorePatterns, entryPathFromRoot);
104
+ arrayOfFiles.push(...subFiles);
105
+ } else {
106
+ arrayOfFiles.push(entryPath);
107
+ }
108
+ }
109
+ }
110
+ return arrayOfFiles;
111
+ };
112
+ const readGitignore = async (folderPath)=>{
113
+ const gitignorePath = path__namespace.resolve(folderPath, '.gitignore');
114
+ const pathExist = await fse__namespace.pathExists(gitignorePath);
115
+ if (!pathExist) return [];
116
+ const gitignoreContent = await fse__namespace.readFile(gitignorePath, 'utf8');
117
+ return gitignoreContent.split(/\r?\n/).filter((line)=>Boolean(line.trim()) && !line.startsWith('#'));
118
+ };
119
+ const compressFilesToTar = async (storagePath, folderToCompress, filename)=>{
120
+ const ignorePatterns = await readGitignore(folderToCompress);
121
+ const filesToCompress = await getFiles(folderToCompress, ignorePatterns);
122
+ return tar__namespace.c({
123
+ gzip: true,
124
+ file: path__namespace.resolve(storagePath, filename)
125
+ }, filesToCompress);
126
+ };
127
+
128
+ const APP_FOLDER_NAME = 'com.strapi.cli';
129
+ const CONFIG_FILENAME = 'config.json';
130
+ async function checkDirectoryExists(directoryPath) {
131
+ try {
132
+ const fsStat = await fse.lstat(directoryPath);
133
+ return fsStat.isDirectory();
134
+ } catch (e) {
135
+ return false;
136
+ }
137
+ }
138
+ // Determine storage path based on the operating system
139
+ async function getTmpStoragePath() {
140
+ const storagePath = path.join(os.tmpdir(), APP_FOLDER_NAME);
141
+ await fse.ensureDir(storagePath);
142
+ return storagePath;
143
+ }
144
+ async function getConfigPath() {
145
+ const configDirs = XDGAppPaths(APP_FOLDER_NAME).configDirs();
146
+ const configPath = configDirs.find(checkDirectoryExists);
147
+ if (!configPath) {
148
+ await fse.ensureDir(configDirs[0]);
149
+ return configDirs[0];
150
+ }
151
+ return configPath;
152
+ }
153
+ async function getLocalConfig$1() {
154
+ const configPath = await getConfigPath();
155
+ const configFilePath = path.join(configPath, CONFIG_FILENAME);
156
+ await fse.ensureFile(configFilePath);
157
+ try {
158
+ return await fse.readJSON(configFilePath, {
159
+ encoding: 'utf8',
160
+ throws: true
161
+ });
162
+ } catch (e) {
163
+ return {};
164
+ }
165
+ }
166
+ async function saveLocalConfig(data) {
167
+ const configPath = await getConfigPath();
168
+ const configFilePath = path.join(configPath, CONFIG_FILENAME);
169
+ await fse.writeJson(configFilePath, data, {
170
+ encoding: 'utf8',
171
+ spaces: 2,
172
+ mode: 0o600
173
+ });
174
+ }
175
+
176
+ var name = "@strapi/cloud-cli";
177
+ var version = "5.10.0";
178
+ var description = "Commands to interact with the Strapi Cloud";
179
+ var keywords = [
180
+ "strapi",
181
+ "cloud",
182
+ "cli"
183
+ ];
184
+ var homepage = "https://strapi.io";
185
+ var bugs = {
186
+ url: "https://github.com/strapi/strapi/issues"
187
+ };
188
+ var repository = {
189
+ type: "git",
190
+ url: "git://github.com/strapi/strapi.git"
191
+ };
192
+ var license = "SEE LICENSE IN LICENSE";
193
+ var author = {
194
+ name: "Strapi Solutions SAS",
195
+ email: "hi@strapi.io",
196
+ url: "https://strapi.io"
197
+ };
198
+ var maintainers = [
199
+ {
200
+ name: "Strapi Solutions SAS",
201
+ email: "hi@strapi.io",
202
+ url: "https://strapi.io"
203
+ }
204
+ ];
205
+ var main = "./dist/index.js";
206
+ var module$1 = "./dist/index.mjs";
207
+ var source = "./src/index.ts";
208
+ var types = "./dist/src/index.d.ts";
209
+ var bin = "./bin/index.js";
210
+ var files = [
211
+ "./dist",
212
+ "./bin"
213
+ ];
214
+ var scripts = {
215
+ build: "run -T npm-run-all clean --parallel build:code build:types",
216
+ "build:code": "run -T rollup -c",
217
+ "build:types": "run -T tsc -p tsconfig.build.json --emitDeclarationOnly",
218
+ clean: "run -T rimraf ./dist",
219
+ lint: "run -T eslint .",
220
+ "test:unit": "run -T jest",
221
+ watch: "run -T rollup -c -w"
222
+ };
223
+ var dependencies = {
224
+ "@strapi/utils": "5.10.0",
225
+ axios: "1.7.4",
226
+ boxen: "5.1.2",
227
+ chalk: "4.1.2",
228
+ "cli-progress": "3.12.0",
229
+ commander: "8.3.0",
230
+ eventsource: "2.0.2",
231
+ "fast-safe-stringify": "2.1.1",
232
+ "fs-extra": "11.2.0",
233
+ inquirer: "8.2.5",
234
+ jsonwebtoken: "9.0.0",
235
+ "jwks-rsa": "3.1.0",
236
+ lodash: "4.17.21",
237
+ minimatch: "9.0.3",
238
+ open: "8.4.0",
239
+ ora: "5.4.1",
240
+ "pkg-up": "3.1.0",
241
+ tar: "6.2.1",
242
+ "xdg-app-paths": "8.3.0",
243
+ yup: "0.32.9"
244
+ };
245
+ var devDependencies = {
246
+ "@types/cli-progress": "3.11.5",
247
+ "@types/eventsource": "1.1.15",
248
+ "@types/lodash": "^4.14.191",
249
+ "eslint-config-custom": "5.10.0",
250
+ tsconfig: "5.10.0"
251
+ };
252
+ var engines = {
253
+ node: ">=18.0.0 <=22.x.x",
254
+ npm: ">=6.0.0"
255
+ };
256
+ var packageJson = {
257
+ name: name,
258
+ version: version,
259
+ description: description,
260
+ keywords: keywords,
261
+ homepage: homepage,
262
+ bugs: bugs,
263
+ repository: repository,
264
+ license: license,
265
+ author: author,
266
+ maintainers: maintainers,
267
+ main: main,
268
+ module: module$1,
269
+ source: source,
270
+ types: types,
271
+ bin: bin,
272
+ files: files,
273
+ scripts: scripts,
274
+ dependencies: dependencies,
275
+ devDependencies: devDependencies,
276
+ engines: engines
277
+ };
278
+
279
+ const VERSION = 'v1';
280
+ async function cloudApiFactory({ logger }, token) {
281
+ const localConfig = await getLocalConfig$1();
282
+ const customHeaders = {
283
+ 'x-device-id': localConfig.deviceId,
284
+ 'x-app-version': packageJson.version,
285
+ 'x-os-name': os.type(),
286
+ 'x-os-version': os.version(),
287
+ 'x-language': Intl.DateTimeFormat().resolvedOptions().locale,
288
+ 'x-node-version': process.versions.node
289
+ };
290
+ const axiosCloudAPI = axios.create({
291
+ baseURL: `${apiConfig.apiBaseUrl}/${VERSION}`,
292
+ headers: {
293
+ 'Content-Type': 'application/json',
294
+ ...customHeaders
295
+ }
296
+ });
297
+ if (token) {
298
+ axiosCloudAPI.defaults.headers.Authorization = `Bearer ${token}`;
299
+ }
300
+ return {
301
+ deploy ({ filePath, project }, { onUploadProgress }) {
302
+ return axiosCloudAPI.post(`/deploy/${project.name}`, {
303
+ file: fse.createReadStream(filePath),
304
+ targetEnvironment: project.targetEnvironment
305
+ }, {
306
+ headers: {
307
+ 'Content-Type': 'multipart/form-data'
308
+ },
309
+ onUploadProgress
310
+ });
311
+ },
312
+ async createProject ({ name, nodeVersion, region, plan }) {
313
+ const response = await axiosCloudAPI.post('/project', {
314
+ projectName: name,
315
+ region,
316
+ nodeVersion,
317
+ plan
318
+ });
319
+ return {
320
+ data: {
321
+ id: response.data.id,
322
+ name: response.data.name,
323
+ nodeVersion: response.data.nodeVersion,
324
+ region: response.data.region
325
+ },
326
+ status: response.status
327
+ };
328
+ },
329
+ getUserInfo () {
330
+ return axiosCloudAPI.get('/user');
331
+ },
332
+ async config () {
333
+ try {
334
+ const response = await axiosCloudAPI.get('/config');
335
+ if (response.status !== 200) {
336
+ throw new Error('Error fetching cloud CLI config from the server.');
337
+ }
338
+ return response;
339
+ } catch (error) {
340
+ logger.debug("🥲 Oops! Couldn't retrieve the cloud CLI config from the server. Please try again.");
341
+ throw error;
342
+ }
343
+ },
344
+ async listProjects () {
345
+ try {
346
+ const response = await axiosCloudAPI.get('/projects');
347
+ if (response.status !== 200) {
348
+ throw new Error('Error fetching cloud projects from the server.');
349
+ }
350
+ return response;
351
+ } catch (error) {
352
+ logger.debug("🥲 Oops! Couldn't retrieve your project's list from the server. Please try again.");
353
+ throw error;
354
+ }
355
+ },
356
+ async listLinkProjects () {
357
+ try {
358
+ const response = await axiosCloudAPI.get('/projects-linkable');
359
+ if (response.status !== 200) {
360
+ throw new Error('Error fetching cloud projects from the server.');
361
+ }
362
+ return response;
363
+ } catch (error) {
364
+ logger.debug("🥲 Oops! Couldn't retrieve your project's list from the server. Please try again.");
365
+ throw error;
366
+ }
367
+ },
368
+ async listEnvironments ({ name }) {
369
+ try {
370
+ const response = await axiosCloudAPI.get(`/projects/${name}/environments`);
371
+ if (response.status !== 200) {
372
+ throw new Error('Error fetching cloud environments from the server.');
373
+ }
374
+ return response;
375
+ } catch (error) {
376
+ logger.debug("🥲 Oops! Couldn't retrieve your project's environments from the server. Please try again.");
377
+ throw error;
378
+ }
379
+ },
380
+ async listLinkEnvironments ({ name }) {
381
+ try {
382
+ const response = await axiosCloudAPI.get(`/projects/${name}/environments-linkable`);
383
+ if (response.status !== 200) {
384
+ throw new Error('Error fetching cloud environments from the server.');
385
+ }
386
+ return response;
387
+ } catch (error) {
388
+ logger.debug("🥲 Oops! Couldn't retrieve your project's environments from the server. Please try again.");
389
+ throw error;
390
+ }
391
+ },
392
+ async getProject ({ name }) {
393
+ try {
394
+ const response = await axiosCloudAPI.get(`/projects/${name}`);
395
+ if (response.status !== 200) {
396
+ throw new Error("Error fetching project's details.");
397
+ }
398
+ return response;
399
+ } catch (error) {
400
+ logger.debug("🥲 Oops! There was a problem retrieving your project's details. Please try again.");
401
+ throw error;
402
+ }
403
+ },
404
+ track (event, payload = {}) {
405
+ return axiosCloudAPI.post('/track', {
406
+ event,
407
+ payload
408
+ });
409
+ }
410
+ };
411
+ }
412
+
413
+ const LOCAL_SAVE_FILENAME = '.strapi-cloud.json';
414
+ const getFilePath = (directoryPath)=>path.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
415
+ async function save(data, { directoryPath } = {}) {
416
+ const pathToFile = getFilePath(directoryPath);
417
+ // Ensure the directory exists and creates it if not
418
+ await fse.ensureDir(path.dirname(pathToFile));
419
+ await fse.writeJson(pathToFile, data, {
420
+ encoding: 'utf8'
421
+ });
422
+ }
423
+ async function retrieve({ directoryPath } = {}) {
424
+ const pathToFile = getFilePath(directoryPath);
425
+ const pathExists = await fse.pathExists(pathToFile);
426
+ if (!pathExists) {
427
+ return {};
428
+ }
429
+ return fse.readJSON(pathToFile, {
430
+ encoding: 'utf8'
431
+ });
432
+ }
433
+ async function patch(patchData, { directoryPath } = {}) {
434
+ const pathToFile = getFilePath(directoryPath);
435
+ const existingData = await retrieve({
436
+ directoryPath
437
+ });
438
+ if (!existingData) {
439
+ throw new Error('No configuration data found to patch.');
440
+ }
441
+ const newData = lodash.merge(existingData, patchData);
442
+ await fse.writeJson(pathToFile, newData, {
443
+ encoding: 'utf8'
444
+ });
445
+ }
446
+ async function deleteConfig({ directoryPath } = {}) {
447
+ const pathToFile = getFilePath(directoryPath);
448
+ const pathExists = await fse.pathExists(pathToFile);
449
+ if (pathExists) {
450
+ await fse.remove(pathToFile);
451
+ }
452
+ }
453
+
454
+ var strapiInfoSave = /*#__PURE__*/Object.freeze({
455
+ __proto__: null,
456
+ LOCAL_SAVE_FILENAME: LOCAL_SAVE_FILENAME,
457
+ deleteConfig: deleteConfig,
458
+ patch: patch,
459
+ retrieve: retrieve,
460
+ save: save
461
+ });
462
+
463
+ let cliConfig;
464
+ async function tokenServiceFactory({ logger }) {
465
+ const cloudApiService = await cloudApiFactory({
466
+ logger
467
+ });
468
+ async function saveToken(str) {
469
+ const appConfig = await getLocalConfig$1();
470
+ if (!appConfig) {
471
+ logger.error('There was a problem saving your token. Please try again.');
472
+ return;
473
+ }
474
+ appConfig.token = str;
475
+ try {
476
+ await saveLocalConfig(appConfig);
477
+ } catch (e) {
478
+ logger.debug(e);
479
+ logger.error('There was a problem saving your token. Please try again.');
480
+ }
481
+ }
482
+ async function retrieveToken() {
483
+ const appConfig = await getLocalConfig$1();
484
+ if (appConfig.token) {
485
+ // check if token is still valid
486
+ if (await isTokenValid(appConfig.token)) {
487
+ return appConfig.token;
488
+ }
489
+ }
490
+ return undefined;
491
+ }
492
+ async function validateToken(idToken, jwksUrl) {
493
+ const client = jwksClient({
494
+ jwksUri: jwksUrl
495
+ });
496
+ // Get the Key from the JWKS using the token header's Key ID (kid)
497
+ const getKey = (header, callback)=>{
498
+ client.getSigningKey(header.kid, (e, key)=>{
499
+ if (e) {
500
+ callback(e);
501
+ } else if (key) {
502
+ const publicKey = 'publicKey' in key ? key.publicKey : key.rsaPublicKey;
503
+ callback(null, publicKey);
504
+ } else {
505
+ callback(new Error('Key not found'));
506
+ }
507
+ });
508
+ };
509
+ const decodedToken = jwt.decode(idToken, {
510
+ complete: true
511
+ });
512
+ if (!decodedToken) {
513
+ if (typeof idToken === 'undefined' || idToken === '') {
514
+ logger.warn('You need to be logged in to use this feature. Please log in and try again.');
515
+ } else {
516
+ logger.error('There seems to be a problem with your login information. Please try logging in again.');
517
+ }
518
+ return Promise.reject(new Error('Invalid token'));
519
+ }
520
+ // Verify the JWT token signature using the JWKS Key
521
+ return new Promise((resolve, reject)=>{
522
+ jwt.verify(idToken, getKey, (err)=>{
523
+ if (err) {
524
+ reject(err);
525
+ }
526
+ if (decodedToken.payload.exp < Math.floor(Date.now() / 1000)) {
527
+ reject(new Error('Token is expired'));
528
+ }
529
+ resolve();
530
+ });
531
+ });
532
+ }
533
+ async function isTokenValid(token) {
534
+ try {
535
+ const config = await cloudApiService.config();
536
+ cliConfig = config.data;
537
+ if (token) {
538
+ await validateToken(token, cliConfig.jwksUrl);
539
+ return true;
540
+ }
541
+ return false;
542
+ } catch (e) {
543
+ logger.debug(e);
544
+ return false;
545
+ }
546
+ }
547
+ async function eraseToken() {
548
+ const appConfig = await getLocalConfig$1();
549
+ if (!appConfig) {
550
+ return;
551
+ }
552
+ delete appConfig.token;
553
+ try {
554
+ await saveLocalConfig(appConfig);
555
+ } catch (e) {
556
+ logger.debug(e);
557
+ logger.error('There was an issue removing your login information. Please try logging out again.');
558
+ throw e;
559
+ }
560
+ }
561
+ async function getValidToken(ctx, loginAction) {
562
+ let token = await retrieveToken();
563
+ while(!token || !await isTokenValid(token)){
564
+ logger.log(token ? 'Oops! Your token seems expired or invalid. Please login again.' : "We couldn't find a valid token. You need to be logged in to use this feature.");
565
+ if (!await loginAction(ctx)) return null;
566
+ token = await retrieveToken();
567
+ }
568
+ return token;
569
+ }
570
+ return {
571
+ saveToken,
572
+ retrieveToken,
573
+ validateToken,
574
+ isTokenValid,
575
+ eraseToken,
576
+ getValidToken
577
+ };
578
+ }
579
+
580
+ const stringifyArg = (arg)=>{
581
+ return typeof arg === 'object' ? stringify(arg) : arg;
582
+ };
583
+ const createLogger = (options = {})=>{
584
+ const { silent = false, debug = false, timestamp = true } = options;
585
+ const state = {
586
+ errors: 0,
587
+ warning: 0
588
+ };
589
+ return {
590
+ get warnings () {
591
+ return state.warning;
592
+ },
593
+ get errors () {
594
+ return state.errors;
595
+ },
596
+ async debug (...args) {
597
+ if (silent || !debug) {
598
+ return;
599
+ }
600
+ console.log(chalk.cyan(`[DEBUG]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
601
+ },
602
+ info (...args) {
603
+ if (silent) {
604
+ return;
605
+ }
606
+ console.info(chalk.blue(`[INFO]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
607
+ },
608
+ log (...args) {
609
+ if (silent) {
610
+ return;
611
+ }
612
+ console.info(chalk.blue(`${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
613
+ },
614
+ success (...args) {
615
+ if (silent) {
616
+ return;
617
+ }
618
+ console.info(chalk.green(`[SUCCESS]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
619
+ },
620
+ warn (...args) {
621
+ state.warning += 1;
622
+ if (silent) {
623
+ return;
624
+ }
625
+ console.warn(chalk.yellow(`[WARN]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
626
+ },
627
+ error (...args) {
628
+ state.errors += 1;
629
+ if (silent) {
630
+ return;
631
+ }
632
+ console.error(chalk.red(`[ERROR]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
633
+ },
634
+ // @ts-expect-error – returning a subpart of ora is fine because the types tell us what is what.
635
+ spinner (text) {
636
+ if (silent) {
637
+ return {
638
+ succeed () {
639
+ return this;
640
+ },
641
+ fail () {
642
+ return this;
643
+ },
644
+ start () {
645
+ return this;
646
+ },
647
+ text: '',
648
+ isSpinning: false
649
+ };
650
+ }
651
+ return ora(text);
652
+ },
653
+ progressBar (totalSize, text) {
654
+ if (silent) {
655
+ return {
656
+ start () {
657
+ return this;
658
+ },
659
+ stop () {
660
+ return this;
661
+ },
662
+ update () {
663
+ return this;
664
+ }
665
+ };
666
+ }
667
+ const progressBar = new cliProgress__namespace.SingleBar({
668
+ format: `${text ? `${text} |` : ''}${chalk.green('{bar}')}| {percentage}%`,
669
+ barCompleteChar: '\u2588',
670
+ barIncompleteChar: '\u2591',
671
+ hideCursor: true,
672
+ forceRedraw: true
673
+ });
674
+ progressBar.start(totalSize, 0);
675
+ return progressBar;
676
+ }
677
+ };
678
+ };
679
+
680
+ var index = /*#__PURE__*/Object.freeze({
681
+ __proto__: null,
682
+ cloudApiFactory: cloudApiFactory,
683
+ createLogger: createLogger,
684
+ local: strapiInfoSave,
685
+ tokenServiceFactory: tokenServiceFactory
686
+ });
687
+
688
+ yup__namespace.object({
689
+ name: yup__namespace.string().required(),
690
+ exports: yup__namespace.lazy((value)=>yup__namespace.object(typeof value === 'object' ? Object.entries(value).reduce((acc, [key, value])=>{
691
+ if (typeof value === 'object') {
692
+ acc[key] = yup__namespace.object({
693
+ types: yup__namespace.string().optional(),
694
+ source: yup__namespace.string().required(),
695
+ module: yup__namespace.string().optional(),
696
+ import: yup__namespace.string().required(),
697
+ require: yup__namespace.string().required(),
698
+ default: yup__namespace.string().required()
699
+ }).noUnknown(true);
700
+ } else {
701
+ acc[key] = yup__namespace.string().matches(/^\.\/.*\.json$/).required();
702
+ }
703
+ return acc;
704
+ }, {}) : undefined).optional())
705
+ });
706
+ /**
707
+ * @description being a task to load the package.json starting from the current working directory
708
+ * using a shallow find for the package.json and `fs` to read the file. If no package.json is found,
709
+ * the process will throw with an appropriate error message.
710
+ */ const loadPkg = async ({ cwd, logger })=>{
711
+ const pkgPath = await pkgUp({
712
+ cwd
713
+ });
714
+ if (!pkgPath) {
715
+ throw new Error('Could not find a package.json in the current directory');
716
+ }
717
+ const buffer = await fse__namespace.readFile(pkgPath);
718
+ const pkg = JSON.parse(buffer.toString());
719
+ logger.debug('Loaded package.json:', os.EOL, pkg);
720
+ return pkg;
721
+ };
722
+
723
+ async function getProjectNameFromPackageJson(ctx) {
724
+ try {
725
+ const packageJson = await loadPkg(ctx);
726
+ return packageJson.name || 'my-strapi-project';
727
+ } catch (e) {
728
+ return 'my-strapi-project';
729
+ }
730
+ }
731
+
732
+ const trackEvent = async (ctx, cloudApiService, eventName, eventData)=>{
733
+ try {
734
+ await cloudApiService.track(eventName, eventData);
735
+ } catch (e) {
736
+ ctx.logger.debug(`Failed to track ${eventName}`, e);
737
+ }
738
+ };
739
+
740
+ const openModule$1 = import('open');
741
+ async function promptLogin(ctx) {
742
+ const response = await inquirer.prompt([
743
+ {
744
+ type: 'confirm',
745
+ name: 'login',
746
+ message: 'Would you like to login?'
747
+ }
748
+ ]);
749
+ if (response.login) {
750
+ const loginSuccessful = await loginAction(ctx);
751
+ return loginSuccessful;
752
+ }
753
+ return false;
754
+ }
755
+ async function loginAction(ctx) {
756
+ const { logger } = ctx;
757
+ const tokenService = await tokenServiceFactory(ctx);
758
+ const existingToken = await tokenService.retrieveToken();
759
+ const cloudApiService = await cloudApiFactory(ctx, existingToken || undefined);
760
+ if (existingToken) {
761
+ const isTokenValid = await tokenService.isTokenValid(existingToken);
762
+ if (isTokenValid) {
763
+ try {
764
+ const userInfo = await cloudApiService.getUserInfo();
765
+ const { email } = userInfo.data.data;
766
+ if (email) {
767
+ logger.log(`You are already logged into your account (${email}).`);
768
+ } else {
769
+ logger.log('You are already logged in.');
770
+ }
771
+ logger.log('To access your dashboard, please copy and paste the following URL into your web browser:');
772
+ logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
773
+ return true;
774
+ } catch (e) {
775
+ logger.debug('Failed to fetch user info', e);
776
+ }
777
+ }
778
+ }
779
+ let cliConfig;
780
+ try {
781
+ logger.info('🔌 Connecting to the Strapi Cloud API...');
782
+ const config = await cloudApiService.config();
783
+ cliConfig = config.data;
784
+ } catch (e) {
785
+ logger.error('🥲 Oops! Something went wrong while logging you in. Please try again.');
786
+ logger.debug(e);
787
+ return false;
788
+ }
789
+ await trackEvent(ctx, cloudApiService, 'willLoginAttempt', {});
790
+ logger.debug('🔐 Creating device authentication request...', {
791
+ client_id: cliConfig.clientId,
792
+ scope: cliConfig.scope,
793
+ audience: cliConfig.audience
794
+ });
795
+ const deviceAuthResponse = await axios.post(cliConfig.deviceCodeAuthUrl, {
796
+ client_id: cliConfig.clientId,
797
+ scope: cliConfig.scope,
798
+ audience: cliConfig.audience
799
+ }).catch((e)=>{
800
+ logger.error('There was an issue with the authentication process. Please try again.');
801
+ if (e.message) {
802
+ logger.debug(e.message, e);
803
+ } else {
804
+ logger.debug(e);
805
+ }
806
+ });
807
+ openModule$1.then((open)=>{
808
+ open.default(deviceAuthResponse.data.verification_uri_complete).catch((e)=>{
809
+ logger.error('We encountered an issue opening the browser. Please try again later.');
810
+ logger.debug(e.message, e);
811
+ });
812
+ });
813
+ logger.log('If a browser tab does not open automatically, please follow the next steps:');
814
+ logger.log(`1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`);
815
+ logger.log(`2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.\n`);
816
+ const tokenPayload = {
817
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
818
+ device_code: deviceAuthResponse.data.device_code,
819
+ client_id: cliConfig.clientId
820
+ };
821
+ let isAuthenticated = false;
822
+ const authenticate = async ()=>{
823
+ const spinner = logger.spinner('Waiting for authentication');
824
+ spinner.start();
825
+ const spinnerFail = ()=>spinner.fail('Authentication failed!');
826
+ while(!isAuthenticated){
827
+ try {
828
+ const tokenResponse = await axios.post(cliConfig.tokenUrl, tokenPayload);
829
+ const authTokenData = tokenResponse.data;
830
+ if (tokenResponse.status === 200) {
831
+ // Token validation
832
+ try {
833
+ logger.debug('🔐 Validating token...');
834
+ await tokenService.validateToken(authTokenData.id_token, cliConfig.jwksUrl);
835
+ logger.debug('🔐 Token validation successful!');
836
+ } catch (e) {
837
+ logger.debug(e);
838
+ spinnerFail();
839
+ throw new Error('Unable to proceed: Token validation failed');
840
+ }
841
+ logger.debug('🔍 Fetching user information...');
842
+ const cloudApiServiceWithToken = await cloudApiFactory(ctx, authTokenData.access_token);
843
+ // Call to get user info to create the user in DB if not exists
844
+ await cloudApiServiceWithToken.getUserInfo();
845
+ logger.debug('🔍 User information fetched successfully!');
846
+ try {
847
+ logger.debug('📝 Saving login information...');
848
+ await tokenService.saveToken(authTokenData.access_token);
849
+ logger.debug('📝 Login information saved successfully!');
850
+ isAuthenticated = true;
851
+ } catch (e) {
852
+ logger.error('There was a problem saving your login information. Please try logging in again.');
853
+ logger.debug(e);
854
+ spinnerFail();
855
+ return false;
856
+ }
857
+ }
858
+ } catch (e) {
859
+ if (e.message === 'Unable to proceed: Token validation failed') {
860
+ logger.error('There seems to be a problem with your login information. Please try logging in again.');
861
+ spinnerFail();
862
+ await trackEvent(ctx, cloudApiService, 'didNotLogin', {
863
+ loginMethod: 'cli'
864
+ });
865
+ return false;
866
+ }
867
+ if (e.response?.data.error && ![
868
+ 'authorization_pending',
869
+ 'slow_down'
870
+ ].includes(e.response.data.error)) {
871
+ logger.debug(e);
872
+ spinnerFail();
873
+ await trackEvent(ctx, cloudApiService, 'didNotLogin', {
874
+ loginMethod: 'cli'
875
+ });
876
+ return false;
877
+ }
878
+ // Await interval before retrying
879
+ await new Promise((resolve)=>{
880
+ setTimeout(resolve, deviceAuthResponse.data.interval * 1000);
881
+ });
882
+ }
883
+ }
884
+ spinner.succeed('Authentication successful!');
885
+ logger.log('You are now logged into Strapi Cloud.');
886
+ logger.log('To access your dashboard, please copy and paste the following URL into your web browser:');
887
+ logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
888
+ await trackEvent(ctx, cloudApiService, 'didLogin', {
889
+ loginMethod: 'cli'
890
+ });
891
+ };
892
+ await authenticate();
893
+ return isAuthenticated;
894
+ }
895
+
896
+ /**
897
+ * Apply default values to questions based on the provided mapper
898
+ * @param questionsMap - A partial object with keys matching the ProjectAnswers keys and values being the default value or a function to get the default value
899
+ */ function questionDefaultValuesMapper(questionsMap) {
900
+ return (questions)=>{
901
+ return questions.map((question)=>{
902
+ const questionName = question.name;
903
+ // If the question is part of the mapper, apply the default value
904
+ if (questionName in questionsMap) {
905
+ const questionDefault = questionsMap[questionName];
906
+ // If the default value is a function, call it with the question and get the default value
907
+ if (typeof questionDefault === 'function') {
908
+ return {
909
+ ...question,
910
+ default: questionDefault(question)
911
+ };
912
+ }
913
+ // else we consider it as a static value
914
+ return {
915
+ ...question,
916
+ default: questionDefault
917
+ };
918
+ }
919
+ // If the question is not part of the mapper, return the question as is
920
+ return question;
921
+ });
922
+ };
923
+ }
924
+ /**
925
+ * Get default values from questions
926
+ * @param questions - An array of questions for project creation
927
+ */ function getDefaultsFromQuestions(questions) {
928
+ return questions.reduce((acc, question)=>{
929
+ if (question.default && question.name) {
930
+ return {
931
+ ...acc,
932
+ [question.name]: question.default
933
+ };
934
+ }
935
+ return acc;
936
+ }, {});
937
+ }
938
+ /**
939
+ * Get the default node version based on the current node version if it is in the list of choices
940
+ * @param question - The question for the node version in project creation
941
+ */ function getProjectNodeVersionDefault(question) {
942
+ const currentNodeVersion = process.versions.node.split('.')[0];
943
+ // Node Version question is set up as a list, but the type of inquirer is dynamic and the question can change in the future (it comes from API)
944
+ if (question.type === 'list' && Array.isArray(question.choices)) {
945
+ const choice = question.choices.find((choice)=>choice.value === currentNodeVersion);
946
+ if (choice) {
947
+ return choice.value;
948
+ }
949
+ }
950
+ return question.default;
951
+ }
952
+
953
+ async function handleError(ctx, error) {
954
+ const { logger } = ctx;
955
+ logger.debug(error);
956
+ if (error instanceof axios.AxiosError) {
957
+ const errorMessage = typeof error.response?.data === 'string' ? error.response.data : null;
958
+ switch(error.response?.status){
959
+ case 403:
960
+ logger.error(errorMessage || 'You do not have permission to create a project. Please contact support for assistance.');
961
+ return;
962
+ case 400:
963
+ logger.error(errorMessage || 'Invalid input. Please check your inputs and try again.');
964
+ return;
965
+ case 503:
966
+ logger.error('Strapi Cloud project creation is currently unavailable. Please try again later.');
967
+ return;
968
+ default:
969
+ if (errorMessage) {
970
+ logger.error(errorMessage);
971
+ return;
972
+ }
973
+ break;
974
+ }
975
+ }
976
+ logger.error('We encountered an issue while creating your project. Please try again in a moment. If the problem persists, contact support for assistance.');
977
+ }
978
+ async function createProject$1(ctx, cloudApi, projectInput) {
979
+ const { logger } = ctx;
980
+ const spinner = logger.spinner('Setting up your project...').start();
981
+ try {
982
+ const { data } = await cloudApi.createProject(projectInput);
983
+ await save({
984
+ project: data
985
+ });
986
+ spinner.succeed('Project created successfully!');
987
+ return data;
988
+ } catch (e) {
989
+ spinner.fail('An error occurred while creating the project on Strapi Cloud.');
990
+ throw e;
991
+ }
992
+ }
993
+ var action$6 = (async (ctx)=>{
994
+ const { logger } = ctx;
995
+ const { getValidToken, eraseToken } = await tokenServiceFactory(ctx);
996
+ const token = await getValidToken(ctx, promptLogin);
997
+ if (!token) {
998
+ return;
999
+ }
1000
+ const cloudApi = await cloudApiFactory(ctx, token);
1001
+ const { data: config } = await cloudApi.config();
1002
+ const projectName = await getProjectNameFromPackageJson(ctx);
1003
+ const defaultAnswersMapper = questionDefaultValuesMapper({
1004
+ name: projectName,
1005
+ nodeVersion: getProjectNodeVersionDefault
1006
+ });
1007
+ const questions = defaultAnswersMapper(config.projectCreation.questions);
1008
+ const defaultValues = {
1009
+ ...config.projectCreation.defaults,
1010
+ ...getDefaultsFromQuestions(questions)
1011
+ };
1012
+ const projectAnswersDefaulted = fp.defaults(defaultValues);
1013
+ const projectAnswers = await inquirer.prompt(questions);
1014
+ const projectInput = projectAnswersDefaulted(projectAnswers);
1015
+ try {
1016
+ return await createProject$1(ctx, cloudApi, projectInput);
1017
+ } catch (e) {
1018
+ if (e instanceof axios.AxiosError && e.response?.status === 401) {
1019
+ logger.warn('Oops! Your session has expired. Please log in again to retry.');
1020
+ await eraseToken();
1021
+ if (await promptLogin(ctx)) {
1022
+ return await createProject$1(ctx, cloudApi, projectInput);
1023
+ }
1024
+ } else {
1025
+ await handleError(ctx, e);
1026
+ }
1027
+ }
1028
+ });
1029
+
1030
+ function notificationServiceFactory({ logger }) {
1031
+ return (url, token, cliConfig)=>{
1032
+ const CONN_TIMEOUT = Number(cliConfig.notificationsConnectionTimeout);
1033
+ const es = new EventSource(url, {
1034
+ headers: {
1035
+ Authorization: `Bearer ${token}`
1036
+ }
1037
+ });
1038
+ let timeoutId;
1039
+ const resetTimeout = ()=>{
1040
+ clearTimeout(timeoutId);
1041
+ timeoutId = setTimeout(()=>{
1042
+ logger.log('We were unable to connect to the server at this time. This could be due to a temporary issue. Please try again in a moment.');
1043
+ es.close();
1044
+ }, CONN_TIMEOUT); // 5 minutes
1045
+ };
1046
+ es.onopen = resetTimeout;
1047
+ es.onmessage = (event)=>{
1048
+ resetTimeout();
1049
+ const data = JSON.parse(event.data);
1050
+ if (data.message) {
1051
+ logger.log(data.message);
1052
+ }
1053
+ // Close connection when a specific event is received
1054
+ if (data.event === 'deploymentFinished' || data.event === 'deploymentFailed') {
1055
+ es.close();
1056
+ }
1057
+ };
1058
+ };
1059
+ }
1060
+
1061
+ const buildLogsServiceFactory = ({ logger })=>{
1062
+ return async (url, token, cliConfig)=>{
1063
+ const CONN_TIMEOUT = Number(cliConfig.buildLogsConnectionTimeout);
1064
+ const MAX_RETRIES = Number(cliConfig.buildLogsMaxRetries);
1065
+ return new Promise((resolve, reject)=>{
1066
+ let timeoutId = null;
1067
+ let retries = 0;
1068
+ const connect = (url)=>{
1069
+ const spinner = logger.spinner('Connecting to server to get build logs');
1070
+ spinner.start();
1071
+ const es = new EventSource(`${url}`, {
1072
+ headers: {
1073
+ Authorization: `Bearer ${token}`
1074
+ }
1075
+ });
1076
+ const clearExistingTimeout = ()=>{
1077
+ if (timeoutId) {
1078
+ clearTimeout(timeoutId);
1079
+ }
1080
+ };
1081
+ const resetTimeout = ()=>{
1082
+ clearExistingTimeout();
1083
+ timeoutId = setTimeout(()=>{
1084
+ if (spinner.isSpinning) {
1085
+ spinner.fail('We were unable to connect to the server to get build logs at this time. This could be due to a temporary issue.');
1086
+ }
1087
+ es.close();
1088
+ reject(new Error('Connection timed out'));
1089
+ }, CONN_TIMEOUT);
1090
+ };
1091
+ es.onopen = resetTimeout;
1092
+ es.addEventListener('finished', (event)=>{
1093
+ const data = JSON.parse(event.data);
1094
+ logger.log(data.msg);
1095
+ es.close();
1096
+ clearExistingTimeout();
1097
+ resolve(null);
1098
+ });
1099
+ es.addEventListener('log', (event)=>{
1100
+ if (spinner.isSpinning) {
1101
+ spinner.succeed();
1102
+ }
1103
+ resetTimeout();
1104
+ const data = JSON.parse(event.data);
1105
+ logger.log(data.msg);
1106
+ });
1107
+ es.onerror = async ()=>{
1108
+ retries += 1;
1109
+ if (retries > MAX_RETRIES) {
1110
+ spinner.fail('We were unable to connect to the server to get build logs at this time.');
1111
+ es.close();
1112
+ clearExistingTimeout(); // Important to clear the event loop from remaining timeout - avoid to wait for nothing while the timeout is running
1113
+ reject(new Error('Max retries reached'));
1114
+ }
1115
+ };
1116
+ };
1117
+ connect(url);
1118
+ });
1119
+ };
1120
+ };
1121
+
1122
+ const boxenOptions = {
1123
+ padding: 1,
1124
+ margin: 1,
1125
+ align: 'center',
1126
+ borderColor: 'yellow',
1127
+ borderStyle: 'round'
1128
+ };
1129
+ const QUIT_OPTION$2 = 'Quit';
1130
+ async function promptForEnvironment(environments) {
1131
+ const choices = environments.map((env)=>({
1132
+ name: env,
1133
+ value: env
1134
+ }));
1135
+ const { selectedEnvironment } = await inquirer.prompt([
1136
+ {
1137
+ type: 'list',
1138
+ name: 'selectedEnvironment',
1139
+ message: 'Select the environment to deploy:',
1140
+ choices: [
1141
+ ...choices,
1142
+ {
1143
+ name: chalk.grey(`(${QUIT_OPTION$2})`),
1144
+ value: null
1145
+ }
1146
+ ]
1147
+ }
1148
+ ]);
1149
+ if (selectedEnvironment === null) {
1150
+ process.exit(1);
1151
+ }
1152
+ return selectedEnvironment;
1153
+ }
1154
+ async function upload(ctx, project, token, maxProjectFileSize) {
1155
+ const cloudApi = await cloudApiFactory(ctx, token);
1156
+ try {
1157
+ const storagePath = await getTmpStoragePath();
1158
+ const projectFolder = path.resolve(process.cwd());
1159
+ const packageJson = await loadPkg(ctx);
1160
+ if (!packageJson) {
1161
+ ctx.logger.error('Unable to deploy the project. Please make sure the package.json file is correctly formatted.');
1162
+ return;
1163
+ }
1164
+ ctx.logger.log('📦 Compressing project...');
1165
+ // hash packageJson.name to avoid conflicts
1166
+ const hashname = crypto__namespace.createHash('sha512').update(packageJson.name).digest('hex');
1167
+ const compressedFilename = `${hashname}.tar.gz`;
1168
+ try {
1169
+ ctx.logger.debug('Compression parameters\n', `Storage path: ${storagePath}\n`, `Project folder: ${projectFolder}\n`, `Compressed filename: ${compressedFilename}`);
1170
+ await compressFilesToTar(storagePath, projectFolder, compressedFilename);
1171
+ ctx.logger.log('📦 Project compressed successfully!');
1172
+ } catch (e) {
1173
+ ctx.logger.error('⚠️ Project compression failed. Try again later or check for large/incompatible files.');
1174
+ ctx.logger.debug(e);
1175
+ process.exit(1);
1176
+ }
1177
+ const tarFilePath = path.resolve(storagePath, compressedFilename);
1178
+ const fileStats = await fse.stat(tarFilePath);
1179
+ if (fileStats.size > maxProjectFileSize) {
1180
+ ctx.logger.log('Unable to proceed: Your project is too big to be transferred, please use a git repo instead.');
1181
+ try {
1182
+ await fse.remove(tarFilePath);
1183
+ } catch (e) {
1184
+ ctx.logger.log('Unable to remove file: ', tarFilePath);
1185
+ ctx.logger.debug(e);
1186
+ }
1187
+ return;
1188
+ }
1189
+ ctx.logger.info('🚀 Uploading project...');
1190
+ const progressBar = ctx.logger.progressBar(100, 'Upload Progress');
1191
+ try {
1192
+ const { data } = await cloudApi.deploy({
1193
+ filePath: tarFilePath,
1194
+ project
1195
+ }, {
1196
+ onUploadProgress (progressEvent) {
1197
+ const total = progressEvent.total || fileStats.size;
1198
+ const percentage = Math.round(progressEvent.loaded * 100 / total);
1199
+ progressBar.update(percentage);
1200
+ }
1201
+ });
1202
+ progressBar.update(100);
1203
+ progressBar.stop();
1204
+ ctx.logger.success('✨ Upload finished!');
1205
+ return data.build_id;
1206
+ } catch (e) {
1207
+ progressBar.stop();
1208
+ ctx.logger.error('An error occurred while deploying the project. Please try again later.');
1209
+ ctx.logger.debug(e);
1210
+ } finally{
1211
+ await fse.remove(tarFilePath);
1212
+ }
1213
+ process.exit(0);
1214
+ } catch (e) {
1215
+ ctx.logger.error('An error occurred while deploying the project. Please try again later.');
1216
+ ctx.logger.debug(e);
1217
+ process.exit(1);
1218
+ }
1219
+ }
1220
+ async function getProject(ctx) {
1221
+ const { project } = await retrieve();
1222
+ if (!project) {
1223
+ try {
1224
+ return await action$6(ctx);
1225
+ } catch (e) {
1226
+ ctx.logger.error('An error occurred while deploying the project. Please try again later.');
1227
+ ctx.logger.debug(e);
1228
+ process.exit(1);
1229
+ }
1230
+ }
1231
+ return project;
1232
+ }
1233
+ async function getConfig({ ctx, cloudApiService }) {
1234
+ try {
1235
+ const { data: cliConfig } = await cloudApiService.config();
1236
+ return cliConfig;
1237
+ } catch (e) {
1238
+ ctx.logger.debug('Failed to get cli config', e);
1239
+ return null;
1240
+ }
1241
+ }
1242
+ function validateEnvironment(ctx, environment, environments) {
1243
+ if (!environments.includes(environment)) {
1244
+ ctx.logger.error(`Environment ${environment} does not exist.`);
1245
+ process.exit(1);
1246
+ }
1247
+ }
1248
+ async function getTargetEnvironment(ctx, opts, project, environments) {
1249
+ if (opts.env) {
1250
+ validateEnvironment(ctx, opts.env, environments);
1251
+ return opts.env;
1252
+ }
1253
+ if (project.targetEnvironment) {
1254
+ return project.targetEnvironment;
1255
+ }
1256
+ if (environments.length > 1) {
1257
+ return promptForEnvironment(environments);
1258
+ }
1259
+ return environments[0];
1260
+ }
1261
+ function hasPendingOrLiveDeployment(environments, targetEnvironment) {
1262
+ const environment = environments.find((env)=>env.name === targetEnvironment);
1263
+ if (!environment) {
1264
+ throw new Error(`Environment details ${targetEnvironment} not found.`);
1265
+ }
1266
+ return environment.hasPendingDeployment || environment.hasLiveDeployment || false;
1267
+ }
1268
+ var action$5 = (async (ctx, opts)=>{
1269
+ const { getValidToken } = await tokenServiceFactory(ctx);
1270
+ const token = await getValidToken(ctx, promptLogin);
1271
+ if (!token) {
1272
+ return;
1273
+ }
1274
+ const project = await getProject(ctx);
1275
+ if (!project) {
1276
+ return;
1277
+ }
1278
+ const cloudApiService = await cloudApiFactory(ctx, token);
1279
+ let projectData;
1280
+ let environments;
1281
+ let environmentsDetails;
1282
+ try {
1283
+ const { data: { data, metadata } } = await cloudApiService.getProject({
1284
+ name: project.name
1285
+ });
1286
+ projectData = data;
1287
+ environments = projectData.environments;
1288
+ environmentsDetails = projectData.environmentsDetails;
1289
+ const isProjectSuspended = projectData.suspendedAt;
1290
+ if (isProjectSuspended) {
1291
+ ctx.logger.log('\n Oops! This project has been suspended. \n\n Please reactivate it from the dashboard to continue deploying: ');
1292
+ ctx.logger.log(chalk.underline(`${metadata.dashboardUrls.project}`));
1293
+ return;
1294
+ }
1295
+ } catch (e) {
1296
+ if (e instanceof axios.AxiosError && e.response?.data) {
1297
+ if (e.response.status === 404) {
1298
+ ctx.logger.warn(`The project associated with this folder does not exist in Strapi Cloud. \nPlease link your local project to an existing Strapi Cloud project using the ${chalk.cyan('link')} command before deploying.`);
1299
+ } else {
1300
+ ctx.logger.error(e.response.data);
1301
+ }
1302
+ } else {
1303
+ ctx.logger.error("An error occurred while retrieving the project's information. Please try again later.");
1304
+ }
1305
+ ctx.logger.debug(e);
1306
+ return;
1307
+ }
1308
+ await trackEvent(ctx, cloudApiService, 'willDeployWithCLI', {
1309
+ projectInternalName: project.name
1310
+ });
1311
+ const notificationService = notificationServiceFactory(ctx);
1312
+ const buildLogsService = buildLogsServiceFactory(ctx);
1313
+ const cliConfig = await getConfig({
1314
+ ctx,
1315
+ cloudApiService
1316
+ });
1317
+ if (!cliConfig) {
1318
+ ctx.logger.error('An error occurred while retrieving data from Strapi Cloud. Please check your network or try again later.');
1319
+ return;
1320
+ }
1321
+ let maxSize = parseInt(cliConfig.maxProjectFileSize, 10);
1322
+ if (Number.isNaN(maxSize)) {
1323
+ ctx.logger.debug('An error occurred while parsing the maxProjectFileSize. Using default value.');
1324
+ maxSize = 100000000;
1325
+ }
1326
+ project.targetEnvironment = await getTargetEnvironment(ctx, opts, project, environments);
1327
+ if (!opts.force) {
1328
+ const shouldDisplayWarning = hasPendingOrLiveDeployment(environmentsDetails, project.targetEnvironment);
1329
+ if (shouldDisplayWarning) {
1330
+ ctx.logger.log(boxen(cliConfig.projectDeployment.confirmationText, boxenOptions));
1331
+ const { confirm } = await inquirer.prompt([
1332
+ {
1333
+ type: 'confirm',
1334
+ name: 'confirm',
1335
+ message: `Do you want to proceed with deployment to ${chalk.cyan(projectData.displayName)} on ${chalk.cyan(project.targetEnvironment)} environment?`
1336
+ }
1337
+ ]);
1338
+ if (!confirm) {
1339
+ process.exit(1);
1340
+ }
1341
+ }
1342
+ }
1343
+ const buildId = await upload(ctx, project, token, maxSize);
1344
+ if (!buildId) {
1345
+ return;
1346
+ }
1347
+ try {
1348
+ ctx.logger.log(`🚀 Deploying project to ${chalk.cyan(project.targetEnvironment ?? `production`)} environment...`);
1349
+ notificationService(`${apiConfig.apiBaseUrl}/notifications`, token, cliConfig);
1350
+ await buildLogsService(`${apiConfig.apiBaseUrl}/v1/logs/${buildId}`, token, cliConfig);
1351
+ ctx.logger.log('Visit the following URL for deployment logs. Your deployment will be available here shortly.');
1352
+ ctx.logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects/${project.name}/deployments`));
1353
+ } catch (e) {
1354
+ ctx.logger.debug(e);
1355
+ if (e instanceof Error) {
1356
+ ctx.logger.error(e.message);
1357
+ } else {
1358
+ ctx.logger.error('An error occurred while deploying the project. Please try again later.');
1359
+ }
1360
+ }
1361
+ });
1362
+
1363
+ // TODO: Remove duplicated code by extracting to a shared package
1364
+ const assertCwdContainsStrapiProject = (name)=>{
1365
+ const logErrorAndExit = ()=>{
1366
+ console.log(`You need to run ${chalk.yellow(`strapi ${name}`)} in a Strapi project. Make sure you are in the right directory.`);
1367
+ process.exit(1);
1368
+ };
1369
+ try {
1370
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
1371
+ const pkgJSON = require(`${process.cwd()}/package.json`);
1372
+ if (!fp.has('dependencies.@strapi/strapi', pkgJSON) && !fp.has('devDependencies.@strapi/strapi', pkgJSON)) {
1373
+ logErrorAndExit();
1374
+ }
1375
+ } catch (err) {
1376
+ logErrorAndExit();
1377
+ }
1378
+ };
1379
+ const runAction = (name, action)=>(...args)=>{
1380
+ assertCwdContainsStrapiProject(name);
1381
+ Promise.resolve().then(()=>{
1382
+ return action(...args);
1383
+ }).catch((error)=>{
1384
+ console.error(error);
1385
+ process.exit(1);
1386
+ });
1387
+ };
1388
+
1389
+ /**
1390
+ * `$ deploy project to the cloud`
1391
+ */ const command$7 = ({ ctx })=>{
1392
+ return commander.createCommand('cloud:deploy').alias('deploy').description('Deploy a Strapi Cloud project').option('-d, --debug', 'Enable debugging mode with verbose logs').option('-s, --silent', "Don't log anything").option('-f, --force', 'Skip confirmation to deploy').option('-e, --env <name>', 'Specify the environment to deploy').action((opts)=>runAction('deploy', action$5)(ctx, opts));
1393
+ };
1394
+
1395
+ var deployProject = {
1396
+ name: 'deploy-project',
1397
+ description: 'Deploy a Strapi Cloud project',
1398
+ action: action$5,
1399
+ command: command$7
1400
+ };
1401
+
1402
+ async function getLocalConfig(ctx) {
1403
+ try {
1404
+ return await retrieve();
1405
+ } catch (e) {
1406
+ ctx.logger.debug('Failed to get project config', e);
1407
+ ctx.logger.error('An error occurred while retrieving config data from your local project.');
1408
+ return null;
1409
+ }
1410
+ }
1411
+ async function getLocalProject(ctx) {
1412
+ const localConfig = await getLocalConfig(ctx);
1413
+ if (!localConfig || !localConfig.project) {
1414
+ ctx.logger.warn(`\nWe couldn't find a valid local project config.\nPlease link your local project to an existing Strapi Cloud project using the ${chalk.cyan('link')} command.`);
1415
+ process.exit(1);
1416
+ }
1417
+ return localConfig.project;
1418
+ }
1419
+
1420
+ const QUIT_OPTION$1 = 'Quit';
1421
+ async function promptForRelink(ctx, cloudApiService, existingConfig) {
1422
+ if (existingConfig && existingConfig.project) {
1423
+ const { shouldRelink } = await inquirer.prompt([
1424
+ {
1425
+ type: 'confirm',
1426
+ name: 'shouldRelink',
1427
+ message: `A project named ${chalk.cyan(existingConfig.project.displayName ? existingConfig.project.displayName : existingConfig.project.name)} is already linked to this local folder. Do you want to update the link?`,
1428
+ default: false
1429
+ }
1430
+ ]);
1431
+ if (!shouldRelink) {
1432
+ await trackEvent(ctx, cloudApiService, 'didNotLinkProject', {
1433
+ currentProjectName: existingConfig.project?.name
1434
+ });
1435
+ return false;
1436
+ }
1437
+ }
1438
+ return true;
1439
+ }
1440
+ async function getProjectsList(ctx, cloudApiService, existingConfig) {
1441
+ const spinner = ctx.logger.spinner('Fetching your projects...\n').start();
1442
+ try {
1443
+ const { data: { data: projectList } } = await cloudApiService.listLinkProjects();
1444
+ spinner.succeed();
1445
+ if (!Array.isArray(projectList)) {
1446
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud.");
1447
+ return null;
1448
+ }
1449
+ const projects = projectList.filter((project)=>!(project.isMaintainer || project.name === existingConfig?.project?.name)).map((project)=>{
1450
+ return {
1451
+ name: project.displayName,
1452
+ value: {
1453
+ name: project.name,
1454
+ displayName: project.displayName
1455
+ }
1456
+ };
1457
+ });
1458
+ if (projects.length === 0) {
1459
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud.");
1460
+ return null;
1461
+ }
1462
+ return projects;
1463
+ } catch (e) {
1464
+ spinner.fail('An error occurred while fetching your projects from Strapi Cloud.');
1465
+ ctx.logger.debug('Failed to list projects', e);
1466
+ return null;
1467
+ }
1468
+ }
1469
+ async function getUserSelection(ctx, projects) {
1470
+ const { logger } = ctx;
1471
+ try {
1472
+ const answer = await inquirer.prompt([
1473
+ {
1474
+ type: 'list',
1475
+ name: 'linkProject',
1476
+ message: 'Which project do you want to link?',
1477
+ choices: [
1478
+ ...projects,
1479
+ {
1480
+ name: chalk.grey(`(${QUIT_OPTION$1})`),
1481
+ value: null
1482
+ }
1483
+ ]
1484
+ }
1485
+ ]);
1486
+ if (!answer.linkProject) {
1487
+ return null;
1488
+ }
1489
+ return answer;
1490
+ } catch (e) {
1491
+ logger.debug('Failed to get user input', e);
1492
+ logger.error('An error occurred while trying to get your input.');
1493
+ return null;
1494
+ }
1495
+ }
1496
+ var action$4 = (async (ctx)=>{
1497
+ const { getValidToken } = await tokenServiceFactory(ctx);
1498
+ const token = await getValidToken(ctx, promptLogin);
1499
+ const { logger } = ctx;
1500
+ if (!token) {
1501
+ return;
1502
+ }
1503
+ const cloudApiService = await cloudApiFactory(ctx, token);
1504
+ const existingConfig = await getLocalConfig(ctx);
1505
+ const shouldRelink = await promptForRelink(ctx, cloudApiService, existingConfig);
1506
+ if (!shouldRelink) {
1507
+ return;
1508
+ }
1509
+ await trackEvent(ctx, cloudApiService, 'willLinkProject', {});
1510
+ const projects = await getProjectsList(ctx, cloudApiService, existingConfig);
1511
+ if (!projects) {
1512
+ return;
1513
+ }
1514
+ const answer = await getUserSelection(ctx, projects);
1515
+ if (!answer) {
1516
+ return;
1517
+ }
1518
+ try {
1519
+ const { confirmAction } = await inquirer.prompt([
1520
+ {
1521
+ type: 'confirm',
1522
+ name: 'confirmAction',
1523
+ message: 'Warning: Once linked, deploying from CLI will replace the existing project and its data. Confirm to proceed:',
1524
+ default: false
1525
+ }
1526
+ ]);
1527
+ if (!confirmAction) {
1528
+ await trackEvent(ctx, cloudApiService, 'didNotLinkProject', {
1529
+ cancelledProjectName: answer.linkProject.name,
1530
+ currentProjectName: existingConfig ? existingConfig.project?.name : null
1531
+ });
1532
+ return;
1533
+ }
1534
+ await save({
1535
+ project: answer.linkProject
1536
+ });
1537
+ logger.log(` You have successfully linked your project to ${chalk.cyan(answer.linkProject.displayName)}. You are now able to deploy your project.`);
1538
+ await trackEvent(ctx, cloudApiService, 'didLinkProject', {
1539
+ projectInternalName: answer.linkProject
1540
+ });
1541
+ } catch (e) {
1542
+ logger.debug('Failed to link project', e);
1543
+ logger.error('An error occurred while linking the project.');
1544
+ await trackEvent(ctx, cloudApiService, 'didNotLinkProject', {
1545
+ projectInternalName: answer.linkProject
1546
+ });
1547
+ }
1548
+ });
1549
+
1550
+ /**
1551
+ * `$ link local directory to project of the cloud`
1552
+ */ const command$6 = ({ command, ctx })=>{
1553
+ command.command('cloud:link').alias('link').description('Link a local directory to a Strapi Cloud project').option('-d, --debug', 'Enable debugging mode with verbose logs').option('-s, --silent', "Don't log anything").action(()=>runAction('link', action$4)(ctx));
1554
+ };
1555
+
1556
+ var link = {
1557
+ name: 'link-project',
1558
+ description: 'Link a local directory to a Strapi Cloud project',
1559
+ action: action$4,
1560
+ command: command$6
1561
+ };
1562
+
1563
+ /**
1564
+ * `$ cloud device flow login`
1565
+ */ const command$5 = ({ ctx })=>{
1566
+ return commander.createCommand('cloud:login').alias('login').description('Strapi Cloud Login').addHelpText('after', '\nAfter running this command, you will be prompted to enter your authentication information.').option('-d, --debug', 'Enable debugging mode with verbose logs').option('-s, --silent', "Don't log anything").action(()=>runAction('login', loginAction)(ctx));
1567
+ };
1568
+
1569
+ var login = {
1570
+ name: 'login',
1571
+ description: 'Strapi Cloud Login',
1572
+ action: loginAction,
1573
+ command: command$5
1574
+ };
1575
+
1576
+ const openModule = import('open');
1577
+ var action$3 = (async (ctx)=>{
1578
+ const { logger } = ctx;
1579
+ const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx);
1580
+ const token = await retrieveToken();
1581
+ if (!token) {
1582
+ logger.log("You're already logged out.");
1583
+ return;
1584
+ }
1585
+ const cloudApiService = await cloudApiFactory(ctx, token);
1586
+ const config = await cloudApiService.config();
1587
+ const cliConfig = config.data;
1588
+ try {
1589
+ await eraseToken();
1590
+ openModule.then((open)=>{
1591
+ open.default(`${cliConfig.baseUrl}/oidc/logout?client_id=${encodeURIComponent(cliConfig.clientId)}&logout_hint=${encodeURIComponent(token)}
1592
+ `).catch((e)=>{
1593
+ // Failing to open the logout URL is not a critical error, so we just log it
1594
+ logger.debug(e.message, e);
1595
+ });
1596
+ });
1597
+ logger.log('🔌 You have been logged out from the CLI. If you are on a shared computer, please make sure to log out from the Strapi Cloud Dashboard as well.');
1598
+ } catch (e) {
1599
+ logger.error('🥲 Oops! Something went wrong while logging you out. Please try again.');
1600
+ logger.debug(e);
1601
+ }
1602
+ await trackEvent(ctx, cloudApiService, 'didLogout', {
1603
+ loginMethod: 'cli'
1604
+ });
1605
+ });
1606
+
1607
+ /**
1608
+ * `$ cloud device flow logout`
1609
+ */ const command$4 = ({ ctx })=>{
1610
+ return commander.createCommand('cloud:logout').alias('logout').description('Strapi Cloud Logout').option('-d, --debug', 'Enable debugging mode with verbose logs').option('-s, --silent', "Don't log anything").action(()=>runAction('logout', action$3)(ctx));
1611
+ };
1612
+
1613
+ var logout = {
1614
+ name: 'logout',
1615
+ description: 'Strapi Cloud Logout',
1616
+ action: action$3,
1617
+ command: command$4
1618
+ };
1619
+
1620
+ /**
1621
+ * `$ create project in Strapi cloud`
1622
+ */ const command$3 = ({ ctx })=>{
1623
+ return commander.createCommand('cloud:create-project').description('Create a Strapi Cloud project').option('-d, --debug', 'Enable debugging mode with verbose logs').option('-s, --silent', "Don't log anything").action(()=>runAction('cloud:create-project', action$6)(ctx));
1624
+ };
1625
+
1626
+ var createProject = {
1627
+ name: 'create-project',
1628
+ description: 'Create a new project',
1629
+ action: action$6,
1630
+ command: command$3
1631
+ };
1632
+
1633
+ var action$2 = (async (ctx)=>{
1634
+ const { getValidToken } = await tokenServiceFactory(ctx);
1635
+ const token = await getValidToken(ctx, promptLogin);
1636
+ const { logger } = ctx;
1637
+ if (!token) {
1638
+ return;
1639
+ }
1640
+ const cloudApiService = await cloudApiFactory(ctx, token);
1641
+ const spinner = logger.spinner('Fetching your projects...').start();
1642
+ try {
1643
+ const { data: { data: projectList } } = await cloudApiService.listProjects();
1644
+ spinner.succeed();
1645
+ logger.log(projectList);
1646
+ } catch (e) {
1647
+ ctx.logger.debug('Failed to list projects', e);
1648
+ spinner.fail('An error occurred while fetching your projects from Strapi Cloud.');
1649
+ }
1650
+ });
1651
+
1652
+ /**
1653
+ * `$ list project from the cloud`
1654
+ */ const command$2 = ({ command, ctx })=>{
1655
+ command.command('cloud:projects').alias('projects').description('List Strapi Cloud projects').option('-d, --debug', 'Enable debugging mode with verbose logs').option('-s, --silent', "Don't log anything").action(()=>runAction('projects', action$2)(ctx));
1656
+ };
1657
+
1658
+ var listProjects = {
1659
+ name: 'list-projects',
1660
+ description: 'List Strapi Cloud projects',
1661
+ action: action$2,
1662
+ command: command$2
1663
+ };
1664
+
1665
+ var action$1 = (async (ctx)=>{
1666
+ const { getValidToken } = await tokenServiceFactory(ctx);
1667
+ const token = await getValidToken(ctx, promptLogin);
1668
+ const { logger } = ctx;
1669
+ if (!token) {
1670
+ return;
1671
+ }
1672
+ const project = await getLocalProject(ctx);
1673
+ if (!project) {
1674
+ ctx.logger.debug(`No valid local project configuration was found.`);
1675
+ return;
1676
+ }
1677
+ const cloudApiService = await cloudApiFactory(ctx, token);
1678
+ const spinner = logger.spinner('Fetching environments...').start();
1679
+ await trackEvent(ctx, cloudApiService, 'willListEnvironment', {
1680
+ projectInternalName: project.name
1681
+ });
1682
+ try {
1683
+ const { data: { data: environmentsList } } = await cloudApiService.listEnvironments({
1684
+ name: project.name
1685
+ });
1686
+ spinner.succeed();
1687
+ logger.log(environmentsList);
1688
+ await trackEvent(ctx, cloudApiService, 'didListEnvironment', {
1689
+ projectInternalName: project.name
1690
+ });
1691
+ } catch (e) {
1692
+ if (e.response && e.response.status === 404) {
1693
+ spinner.succeed();
1694
+ logger.warn(`\nThe project associated with this folder does not exist in Strapi Cloud. \nPlease link your local project to an existing Strapi Cloud project using the ${chalk.cyan('link')} command`);
1695
+ } else {
1696
+ spinner.fail('An error occurred while fetching environments data from Strapi Cloud.');
1697
+ logger.debug('Failed to list environments', e);
1698
+ }
1699
+ await trackEvent(ctx, cloudApiService, 'didNotListEnvironment', {
1700
+ projectInternalName: project.name
1701
+ });
1702
+ }
1703
+ });
1704
+
1705
+ function defineCloudNamespace(command, ctx) {
1706
+ const cloud = command.command('cloud').description('Manage Strapi Cloud projects');
1707
+ // Define cloud namespace aliases:
1708
+ cloud.command('environments').description('Alias for cloud environment list').action(()=>runAction('list', action$1)(ctx));
1709
+ return cloud;
1710
+ }
1711
+
1712
+ let environmentCmd = null;
1713
+ const initializeEnvironmentCommand = (command, ctx)=>{
1714
+ if (!environmentCmd) {
1715
+ const cloud = defineCloudNamespace(command, ctx);
1716
+ environmentCmd = cloud.command('environment').description('Manage environments');
1717
+ }
1718
+ return environmentCmd;
1719
+ };
1720
+
1721
+ const command$1 = ({ command, ctx })=>{
1722
+ const environmentCmd = initializeEnvironmentCommand(command, ctx);
1723
+ environmentCmd.command('list').description('List Strapi Cloud project environments').option('-d, --debug', 'Enable debugging mode with verbose logs').option('-s, --silent', "Don't log anything").action(()=>runAction('list', action$1)(ctx));
1724
+ };
1725
+
1726
+ var listEnvironments = {
1727
+ name: 'list-environments',
1728
+ description: 'List Strapi Cloud environments',
1729
+ action: action$1,
1730
+ command: command$1
1731
+ };
1732
+
1733
+ const QUIT_OPTION = 'Quit';
1734
+ var action = (async (ctx)=>{
1735
+ const { getValidToken } = await tokenServiceFactory(ctx);
1736
+ const token = await getValidToken(ctx, promptLogin);
1737
+ const { logger } = ctx;
1738
+ if (!token) {
1739
+ return;
1740
+ }
1741
+ const project = await getLocalProject(ctx);
1742
+ if (!project) {
1743
+ logger.debug(`No valid local project configuration was found.`);
1744
+ return;
1745
+ }
1746
+ const cloudApiService = await cloudApiFactory(ctx, token);
1747
+ const environments = await getEnvironmentsList(ctx, cloudApiService, project);
1748
+ if (!environments) {
1749
+ logger.debug(`Fetching environments failed.`);
1750
+ return;
1751
+ }
1752
+ if (environments.length === 0) {
1753
+ logger.log(`The only available environment is already linked. You can add a new one from your project settings on the Strapi Cloud dashboard.`);
1754
+ return;
1755
+ }
1756
+ const answer = await promptUserForEnvironment(ctx, environments);
1757
+ if (!answer) {
1758
+ return;
1759
+ }
1760
+ await trackEvent(ctx, cloudApiService, 'willLinkEnvironment', {
1761
+ projectName: project.name,
1762
+ environmentName: answer.targetEnvironment
1763
+ });
1764
+ try {
1765
+ await patch({
1766
+ project: {
1767
+ targetEnvironment: answer.targetEnvironment
1768
+ }
1769
+ });
1770
+ } catch (e) {
1771
+ await trackEvent(ctx, cloudApiService, 'didNotLinkEnvironment', {
1772
+ projectName: project.name,
1773
+ environmentName: answer.targetEnvironment
1774
+ });
1775
+ logger.debug('Failed to link environment', e);
1776
+ logger.error('Failed to link the environment. If this issue persists, try re-linking your project or contact support.');
1777
+ process.exit(1);
1778
+ }
1779
+ logger.log(` You have successfully linked your project to ${chalk.cyan(answer.targetEnvironment)}, on ${chalk.cyan(project.displayName)}. You are now able to deploy your project.`);
1780
+ await trackEvent(ctx, cloudApiService, 'didLinkEnvironment', {
1781
+ projectName: project.name,
1782
+ environmentName: answer.targetEnvironment
1783
+ });
1784
+ });
1785
+ async function promptUserForEnvironment(ctx, environments) {
1786
+ const { logger } = ctx;
1787
+ try {
1788
+ const answer = await inquirer.prompt([
1789
+ {
1790
+ type: 'list',
1791
+ name: 'targetEnvironment',
1792
+ message: 'Which environment do you want to link?',
1793
+ choices: [
1794
+ ...environments,
1795
+ {
1796
+ name: chalk.grey(`(${QUIT_OPTION})`),
1797
+ value: null
1798
+ }
1799
+ ]
1800
+ }
1801
+ ]);
1802
+ if (!answer.targetEnvironment) {
1803
+ return null;
1804
+ }
1805
+ return answer;
1806
+ } catch (e) {
1807
+ logger.debug('Failed to get user input', e);
1808
+ logger.error('An error occurred while trying to get your environment selection.');
1809
+ return null;
1810
+ }
1811
+ }
1812
+ async function getEnvironmentsList(ctx, cloudApiService, project) {
1813
+ const spinner = ctx.logger.spinner('Fetching environments...\n').start();
1814
+ try {
1815
+ const { data: { data: environmentsList } } = await cloudApiService.listLinkEnvironments({
1816
+ name: project.name
1817
+ });
1818
+ if (!Array.isArray(environmentsList) || environmentsList.length === 0) {
1819
+ throw new Error('Environments not found in server response');
1820
+ }
1821
+ spinner.succeed();
1822
+ return environmentsList.filter((environment)=>environment.name !== project.targetEnvironment);
1823
+ } catch (e) {
1824
+ if (e.response && e.response.status === 404) {
1825
+ spinner.succeed();
1826
+ ctx.logger.warn(`\nThe project associated with this folder does not exist in Strapi Cloud. \nPlease link your local project to an existing Strapi Cloud project using the ${chalk.cyan('link')} command.`);
1827
+ } else {
1828
+ spinner.fail('An error occurred while fetching environments data from Strapi Cloud.');
1829
+ ctx.logger.debug('Failed to list environments', e);
1830
+ }
1831
+ }
1832
+ }
1833
+
1834
+ const command = ({ command, ctx })=>{
1835
+ const environmentCmd = initializeEnvironmentCommand(command, ctx);
1836
+ environmentCmd.command('link').description('Link project to a specific Strapi Cloud project environment').option('-d, --debug', 'Enable debugging mode with verbose logs').option('-s, --silent', "Don't log anything").action(()=>runAction('link', action)(ctx));
1837
+ };
1838
+
1839
+ var linkEnvironment = {
1840
+ name: 'link-environment',
1841
+ description: 'Link Strapi Cloud environment to a local project',
1842
+ action,
1843
+ command
1844
+ };
1845
+
1846
+ const cli = {
1847
+ deployProject,
1848
+ link,
1849
+ login,
1850
+ logout,
1851
+ createProject,
1852
+ linkEnvironment,
1853
+ listProjects,
1854
+ listEnvironments
1855
+ };
1856
+ const cloudCommands = [
1857
+ deployProject,
1858
+ link,
1859
+ login,
1860
+ logout,
1861
+ linkEnvironment,
1862
+ listProjects,
1863
+ listEnvironments
1864
+ ];
1865
+ async function initCloudCLIConfig() {
1866
+ const localConfig = await getLocalConfig$1();
1867
+ if (!localConfig.deviceId) {
1868
+ localConfig.deviceId = crypto$1.randomUUID();
1869
+ }
1870
+ await saveLocalConfig(localConfig);
1871
+ }
1872
+ async function buildStrapiCloudCommands({ command, ctx, argv }) {
1873
+ await initCloudCLIConfig();
1874
+ // Load all commands
1875
+ for (const cloudCommand of cloudCommands){
1876
+ try {
1877
+ // Add this command to the Commander command object
1878
+ const subCommand = await cloudCommand.command({
1879
+ command,
1880
+ ctx,
1881
+ argv
1882
+ });
1883
+ if (subCommand) {
1884
+ command.addCommand(subCommand);
1885
+ }
1886
+ } catch (e) {
1887
+ console.error(`Failed to load command ${cloudCommand.name}`, e);
1888
+ }
1889
+ }
1890
+ }
1891
+
1892
+ exports.buildStrapiCloudCommands = buildStrapiCloudCommands;
1893
+ exports.cli = cli;
1894
+ exports.createLogger = createLogger;
1895
+ exports.index = index;
1896
+ //# sourceMappingURL=index-Cq5rtMZ4.js.map