@strapi/cloud-cli 0.0.0-next.c27880c9af0e2c29e6d6512b0d5fbaa6b506acdc → 0.0.0-next.d7fa025a4eacdc27490fb1629b0efb93e3cb58b9

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 (45) hide show
  1. package/LICENSE +18 -3
  2. package/dist/index.js +610 -295
  3. package/dist/index.js.map +1 -1
  4. package/dist/index.mjs +610 -292
  5. package/dist/index.mjs.map +1 -1
  6. package/dist/src/create-project/action.d.ts +1 -1
  7. package/dist/src/create-project/action.d.ts.map +1 -1
  8. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts +3 -0
  9. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts.map +1 -0
  10. package/dist/src/create-project/utils/project-questions.utils.d.ts +20 -0
  11. package/dist/src/create-project/utils/project-questions.utils.d.ts.map +1 -0
  12. package/dist/src/deploy-project/action.d.ts.map +1 -1
  13. package/dist/src/index.d.ts +2 -0
  14. package/dist/src/index.d.ts.map +1 -1
  15. package/dist/src/link/action.d.ts +4 -0
  16. package/dist/src/link/action.d.ts.map +1 -0
  17. package/dist/src/link/command.d.ts +7 -0
  18. package/dist/src/link/command.d.ts.map +1 -0
  19. package/dist/src/link/index.d.ts +7 -0
  20. package/dist/src/link/index.d.ts.map +1 -0
  21. package/dist/src/list-projects/action.d.ts +4 -0
  22. package/dist/src/list-projects/action.d.ts.map +1 -0
  23. package/dist/src/list-projects/command.d.ts +7 -0
  24. package/dist/src/list-projects/command.d.ts.map +1 -0
  25. package/dist/src/list-projects/index.d.ts +7 -0
  26. package/dist/src/list-projects/index.d.ts.map +1 -0
  27. package/dist/src/login/action.d.ts +2 -2
  28. package/dist/src/login/action.d.ts.map +1 -1
  29. package/dist/src/logout/action.d.ts.map +1 -1
  30. package/dist/src/services/build-logs.d.ts.map +1 -1
  31. package/dist/src/services/cli-api.d.ts +22 -8
  32. package/dist/src/services/cli-api.d.ts.map +1 -1
  33. package/dist/src/services/strapi-info-save.d.ts +1 -1
  34. package/dist/src/services/strapi-info-save.d.ts.map +1 -1
  35. package/dist/src/services/token.d.ts +1 -1
  36. package/dist/src/services/token.d.ts.map +1 -1
  37. package/dist/src/types.d.ts +1 -0
  38. package/dist/src/types.d.ts.map +1 -1
  39. package/dist/src/utils/analytics.d.ts +4 -0
  40. package/dist/src/utils/analytics.d.ts.map +1 -0
  41. package/dist/src/utils/compress-files.d.ts.map +1 -1
  42. package/dist/src/utils/pkg.d.ts.map +1 -1
  43. package/package.json +6 -5
  44. package/dist/src/utils/tests/compress-files.test.d.ts +0 -2
  45. package/dist/src/utils/tests/compress-files.test.d.ts.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,12 +1,12 @@
1
1
  import crypto$1 from "crypto";
2
- import fse from "fs-extra";
2
+ import * as fse from "fs-extra";
3
+ import fse__default from "fs-extra";
3
4
  import * as path from "path";
4
5
  import path__default from "path";
5
6
  import chalk from "chalk";
6
7
  import axios, { AxiosError } from "axios";
7
8
  import * as crypto from "node:crypto";
8
9
  import { env } from "@strapi/utils";
9
- import * as fs from "fs";
10
10
  import * as tar from "tar";
11
11
  import { minimatch } from "minimatch";
12
12
  import inquirer from "inquirer";
@@ -18,10 +18,9 @@ import jwt from "jsonwebtoken";
18
18
  import stringify from "fast-safe-stringify";
19
19
  import ora from "ora";
20
20
  import * as cliProgress from "cli-progress";
21
- import EventSource from "eventsource";
22
- import fs$1 from "fs/promises";
23
21
  import pkgUp from "pkg-up";
24
22
  import * as yup from "yup";
23
+ import EventSource from "eventsource";
25
24
  const apiConfig = {
26
25
  apiBaseUrl: env("STRAPI_CLI_CLOUD_API", "https://cloud-cli-api.strapi.io"),
27
26
  dashboardBaseUrl: env("STRAPI_CLI_CLOUD_DASHBOARD", "https://cloud.strapi.io")
@@ -40,23 +39,6 @@ const IGNORED_PATTERNS = [
40
39
  "**/.idea/**",
41
40
  "**/.vscode/**"
42
41
  ];
43
- const getFiles = (dirPath, ignorePatterns = [], arrayOfFiles = [], subfolder = "") => {
44
- const entries = fs.readdirSync(path.join(dirPath, subfolder));
45
- entries.forEach((entry) => {
46
- const entryPathFromRoot = path.join(subfolder, entry);
47
- const entryPath = path.relative(dirPath, entryPathFromRoot);
48
- const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
49
- if (isIgnored) {
50
- return;
51
- }
52
- if (fs.statSync(entryPath).isDirectory()) {
53
- getFiles(dirPath, ignorePatterns, arrayOfFiles, entryPathFromRoot);
54
- } else {
55
- arrayOfFiles.push(entryPath);
56
- }
57
- });
58
- return arrayOfFiles;
59
- };
60
42
  const isIgnoredFile = (folderPath, file, ignorePatterns) => {
61
43
  ignorePatterns.push(...IGNORED_PATTERNS);
62
44
  const relativeFilePath = path.join(folderPath, file);
@@ -74,16 +56,35 @@ const isIgnoredFile = (folderPath, file, ignorePatterns) => {
74
56
  }
75
57
  return isIgnored;
76
58
  };
77
- const readGitignore = (folderPath) => {
59
+ const getFiles = async (dirPath, ignorePatterns = [], subfolder = "") => {
60
+ const arrayOfFiles = [];
61
+ const entries = await fse.readdir(path.join(dirPath, subfolder));
62
+ for (const entry of entries) {
63
+ const entryPathFromRoot = path.join(subfolder, entry);
64
+ const entryPath = path.relative(dirPath, entryPathFromRoot);
65
+ const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
66
+ if (!isIgnored) {
67
+ if (fse.statSync(entryPath).isDirectory()) {
68
+ const subFiles = await getFiles(dirPath, ignorePatterns, entryPathFromRoot);
69
+ arrayOfFiles.push(...subFiles);
70
+ } else {
71
+ arrayOfFiles.push(entryPath);
72
+ }
73
+ }
74
+ }
75
+ return arrayOfFiles;
76
+ };
77
+ const readGitignore = async (folderPath) => {
78
78
  const gitignorePath = path.resolve(folderPath, ".gitignore");
79
- if (!fs.existsSync(gitignorePath))
79
+ const pathExist = await fse.pathExists(gitignorePath);
80
+ if (!pathExist)
80
81
  return [];
81
- const gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
82
+ const gitignoreContent = await fse.readFile(gitignorePath, "utf8");
82
83
  return gitignoreContent.split(/\r?\n/).filter((line) => Boolean(line.trim()) && !line.startsWith("#"));
83
84
  };
84
85
  const compressFilesToTar = async (storagePath, folderToCompress, filename) => {
85
- const ignorePatterns = readGitignore(folderToCompress);
86
- const filesToCompress = getFiles(folderToCompress, ignorePatterns);
86
+ const ignorePatterns = await readGitignore(folderToCompress);
87
+ const filesToCompress = await getFiles(folderToCompress, ignorePatterns);
87
88
  return tar.c(
88
89
  {
89
90
  gzip: true,
@@ -96,7 +97,7 @@ const APP_FOLDER_NAME = "com.strapi.cli";
96
97
  const CONFIG_FILENAME = "config.json";
97
98
  async function checkDirectoryExists(directoryPath) {
98
99
  try {
99
- const fsStat = await fse.lstat(directoryPath);
100
+ const fsStat = await fse__default.lstat(directoryPath);
100
101
  return fsStat.isDirectory();
101
102
  } catch (e) {
102
103
  return false;
@@ -104,14 +105,14 @@ async function checkDirectoryExists(directoryPath) {
104
105
  }
105
106
  async function getTmpStoragePath() {
106
107
  const storagePath = path__default.join(os.tmpdir(), APP_FOLDER_NAME);
107
- await fse.ensureDir(storagePath);
108
+ await fse__default.ensureDir(storagePath);
108
109
  return storagePath;
109
110
  }
110
111
  async function getConfigPath() {
111
112
  const configDirs = XDGAppPaths(APP_FOLDER_NAME).configDirs();
112
113
  const configPath = configDirs.find(checkDirectoryExists);
113
114
  if (!configPath) {
114
- await fse.ensureDir(configDirs[0]);
115
+ await fse__default.ensureDir(configDirs[0]);
115
116
  return configDirs[0];
116
117
  }
117
118
  return configPath;
@@ -119,9 +120,9 @@ async function getConfigPath() {
119
120
  async function getLocalConfig() {
120
121
  const configPath = await getConfigPath();
121
122
  const configFilePath = path__default.join(configPath, CONFIG_FILENAME);
122
- await fse.ensureFile(configFilePath);
123
+ await fse__default.ensureFile(configFilePath);
123
124
  try {
124
- return await fse.readJSON(configFilePath, { encoding: "utf8", throws: true });
125
+ return await fse__default.readJSON(configFilePath, { encoding: "utf8", throws: true });
125
126
  } catch (e) {
126
127
  return {};
127
128
  }
@@ -129,10 +130,10 @@ async function getLocalConfig() {
129
130
  async function saveLocalConfig(data) {
130
131
  const configPath = await getConfigPath();
131
132
  const configFilePath = path__default.join(configPath, CONFIG_FILENAME);
132
- await fse.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
133
+ await fse__default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
133
134
  }
134
135
  const name = "@strapi/cloud-cli";
135
- const version = "4.25.1";
136
+ const version = "4.25.7";
136
137
  const description = "Commands to interact with the Strapi Cloud";
137
138
  const keywords = [
138
139
  "strapi",
@@ -173,10 +174,11 @@ const scripts = {
173
174
  build: "pack-up build",
174
175
  clean: "run -T rimraf ./dist",
175
176
  lint: "run -T eslint .",
177
+ "test:unit": "run -T jest",
176
178
  watch: "pack-up watch"
177
179
  };
178
180
  const dependencies = {
179
- "@strapi/utils": "4.25.1",
181
+ "@strapi/utils": "4.25.7",
180
182
  axios: "1.6.0",
181
183
  chalk: "4.1.2",
182
184
  "cli-progress": "3.12.0",
@@ -201,8 +203,8 @@ const devDependencies = {
201
203
  "@types/cli-progress": "3.11.5",
202
204
  "@types/eventsource": "1.1.15",
203
205
  "@types/lodash": "^4.14.191",
204
- "eslint-config-custom": "4.25.1",
205
- tsconfig: "4.25.1"
206
+ "eslint-config-custom": "4.25.7",
207
+ tsconfig: "4.25.7"
206
208
  };
207
209
  const engines = {
208
210
  node: ">=18.0.0 <=20.x.x",
@@ -231,7 +233,7 @@ const packageJson = {
231
233
  engines
232
234
  };
233
235
  const VERSION = "v1";
234
- async function cloudApiFactory(token) {
236
+ async function cloudApiFactory({ logger }, token) {
235
237
  const localConfig = await getLocalConfig();
236
238
  const customHeaders = {
237
239
  "x-device-id": localConfig.deviceId,
@@ -255,7 +257,7 @@ async function cloudApiFactory(token) {
255
257
  deploy({ filePath, project }, { onUploadProgress }) {
256
258
  return axiosCloudAPI.post(
257
259
  `/deploy/${project.name}`,
258
- { file: fse.createReadStream(filePath) },
260
+ { file: fse__default.createReadStream(filePath) },
259
261
  {
260
262
  headers: {
261
263
  "Content-Type": "multipart/form-data"
@@ -284,11 +286,47 @@ async function cloudApiFactory(token) {
284
286
  getUserInfo() {
285
287
  return axiosCloudAPI.get("/user");
286
288
  },
287
- config() {
288
- return axiosCloudAPI.get("/config");
289
+ async config() {
290
+ try {
291
+ const response = await axiosCloudAPI.get("/config");
292
+ if (response.status !== 200) {
293
+ throw new Error("Error fetching cloud CLI config from the server.");
294
+ }
295
+ return response;
296
+ } catch (error) {
297
+ logger.debug(
298
+ "🥲 Oops! Couldn't retrieve the cloud CLI config from the server. Please try again."
299
+ );
300
+ throw error;
301
+ }
302
+ },
303
+ async listProjects() {
304
+ try {
305
+ const response = await axiosCloudAPI.get("/projects");
306
+ if (response.status !== 200) {
307
+ throw new Error("Error fetching cloud projects from the server.");
308
+ }
309
+ return response;
310
+ } catch (error) {
311
+ logger.debug(
312
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
313
+ );
314
+ throw error;
315
+ }
289
316
  },
290
- listProjects() {
291
- return axiosCloudAPI.get("/projects");
317
+ async listLinkProjects() {
318
+ try {
319
+ const response = await axiosCloudAPI.get("/projects/linkable");
320
+ if (response.status !== 200) {
321
+ throw new Error("Error fetching cloud projects from the server.");
322
+ }
323
+ return response;
324
+ } catch (error) {
325
+ logger.debug(
326
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
327
+ );
328
+ throw error;
329
+ }
292
330
  },
293
331
  track(event, payload = {}) {
294
332
  return axiosCloudAPI.post("/track", {
@@ -303,18 +341,18 @@ async function save(data, { directoryPath } = {}) {
303
341
  const alreadyInFileData = await retrieve({ directoryPath });
304
342
  const storedData = { ...alreadyInFileData, ...data };
305
343
  const pathToFile = path__default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
306
- await fse.ensureDir(path__default.dirname(pathToFile));
307
- await fse.writeJson(pathToFile, storedData, { encoding: "utf8" });
344
+ await fse__default.ensureDir(path__default.dirname(pathToFile));
345
+ await fse__default.writeJson(pathToFile, storedData, { encoding: "utf8" });
308
346
  }
309
347
  async function retrieve({
310
348
  directoryPath
311
349
  } = {}) {
312
350
  const pathToFile = path__default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
313
- const pathExists = await fse.pathExists(pathToFile);
351
+ const pathExists = await fse__default.pathExists(pathToFile);
314
352
  if (!pathExists) {
315
353
  return {};
316
354
  }
317
- return fse.readJSON(pathToFile, { encoding: "utf8" });
355
+ return fse__default.readJSON(pathToFile, { encoding: "utf8" });
318
356
  }
319
357
  const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
320
358
  __proto__: null,
@@ -324,7 +362,7 @@ const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defi
324
362
  }, Symbol.toStringTag, { value: "Module" }));
325
363
  let cliConfig;
326
364
  async function tokenServiceFactory({ logger }) {
327
- const cloudApiService = await cloudApiFactory();
365
+ const cloudApiService = await cloudApiFactory({ logger });
328
366
  async function saveToken(str) {
329
367
  const appConfig = await getLocalConfig();
330
368
  if (!appConfig) {
@@ -373,14 +411,17 @@ async function tokenServiceFactory({ logger }) {
373
411
  "There seems to be a problem with your login information. Please try logging in again."
374
412
  );
375
413
  }
414
+ return Promise.reject(new Error("Invalid token"));
376
415
  }
377
416
  return new Promise((resolve, reject) => {
378
417
  jwt.verify(idToken, getKey, (err) => {
379
418
  if (err) {
380
419
  reject(err);
381
- } else {
382
- resolve();
383
420
  }
421
+ if (decodedToken.payload.exp < Math.floor(Date.now() / 1e3)) {
422
+ reject(new Error("Token is expired"));
423
+ }
424
+ resolve();
384
425
  });
385
426
  });
386
427
  }
@@ -414,15 +455,15 @@ async function tokenServiceFactory({ logger }) {
414
455
  throw e;
415
456
  }
416
457
  }
417
- async function getValidToken() {
418
- const token = await retrieveToken();
419
- if (!token) {
420
- logger.log("No token found. Please login first.");
421
- return null;
422
- }
423
- if (!await isTokenValid(token)) {
424
- logger.log("Unable to proceed: Token is expired or not valid. Please login again.");
425
- return null;
458
+ async function getValidToken(ctx, loginAction2) {
459
+ let token = await retrieveToken();
460
+ while (!token || !await isTokenValid(token)) {
461
+ logger.log(
462
+ 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."
463
+ );
464
+ if (!await loginAction2(ctx))
465
+ return null;
466
+ token = await retrieveToken();
426
467
  }
427
468
  return token;
428
469
  }
@@ -556,17 +597,254 @@ const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePropert
556
597
  local: strapiInfoSave,
557
598
  tokenServiceFactory
558
599
  }, Symbol.toStringTag, { value: "Module" }));
559
- async function handleError(ctx, error) {
600
+ yup.object({
601
+ name: yup.string().required(),
602
+ exports: yup.lazy(
603
+ (value) => yup.object(
604
+ typeof value === "object" ? Object.entries(value).reduce((acc, [key, value2]) => {
605
+ if (typeof value2 === "object") {
606
+ acc[key] = yup.object({
607
+ types: yup.string().optional(),
608
+ source: yup.string().required(),
609
+ module: yup.string().optional(),
610
+ import: yup.string().required(),
611
+ require: yup.string().required(),
612
+ default: yup.string().required()
613
+ }).noUnknown(true);
614
+ } else {
615
+ acc[key] = yup.string().matches(/^\.\/.*\.json$/).required();
616
+ }
617
+ return acc;
618
+ }, {}) : void 0
619
+ ).optional()
620
+ )
621
+ });
622
+ const loadPkg = async ({ cwd, logger }) => {
623
+ const pkgPath = await pkgUp({ cwd });
624
+ if (!pkgPath) {
625
+ throw new Error("Could not find a package.json in the current directory");
626
+ }
627
+ const buffer = await fse.readFile(pkgPath);
628
+ const pkg = JSON.parse(buffer.toString());
629
+ logger.debug("Loaded package.json:", os.EOL, pkg);
630
+ return pkg;
631
+ };
632
+ async function getProjectNameFromPackageJson(ctx) {
633
+ try {
634
+ const packageJson2 = await loadPkg(ctx);
635
+ return packageJson2.name || "my-strapi-project";
636
+ } catch (e) {
637
+ return "my-strapi-project";
638
+ }
639
+ }
640
+ const trackEvent = async (ctx, cloudApiService, eventName, eventData) => {
641
+ try {
642
+ await cloudApiService.track(eventName, eventData);
643
+ } catch (e) {
644
+ ctx.logger.debug(`Failed to track ${eventName}`, e);
645
+ }
646
+ };
647
+ const openModule$1 = import("open");
648
+ async function promptLogin(ctx) {
649
+ const response = await inquirer.prompt([
650
+ {
651
+ type: "confirm",
652
+ name: "login",
653
+ message: "Would you like to login?"
654
+ }
655
+ ]);
656
+ if (response.login) {
657
+ const loginSuccessful = await loginAction(ctx);
658
+ return loginSuccessful;
659
+ }
660
+ return false;
661
+ }
662
+ async function loginAction(ctx) {
663
+ const { logger } = ctx;
560
664
  const tokenService = await tokenServiceFactory(ctx);
665
+ const existingToken = await tokenService.retrieveToken();
666
+ const cloudApiService = await cloudApiFactory(ctx, existingToken || void 0);
667
+ if (existingToken) {
668
+ const isTokenValid = await tokenService.isTokenValid(existingToken);
669
+ if (isTokenValid) {
670
+ try {
671
+ const userInfo = await cloudApiService.getUserInfo();
672
+ const { email } = userInfo.data.data;
673
+ if (email) {
674
+ logger.log(`You are already logged into your account (${email}).`);
675
+ } else {
676
+ logger.log("You are already logged in.");
677
+ }
678
+ logger.log(
679
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
680
+ );
681
+ logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
682
+ return true;
683
+ } catch (e) {
684
+ logger.debug("Failed to fetch user info", e);
685
+ }
686
+ }
687
+ }
688
+ let cliConfig2;
689
+ try {
690
+ logger.info("🔌 Connecting to the Strapi Cloud API...");
691
+ const config = await cloudApiService.config();
692
+ cliConfig2 = config.data;
693
+ } catch (e) {
694
+ logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
695
+ logger.debug(e);
696
+ return false;
697
+ }
698
+ await trackEvent(ctx, cloudApiService, "willLoginAttempt", {});
699
+ logger.debug("🔐 Creating device authentication request...", {
700
+ client_id: cliConfig2.clientId,
701
+ scope: cliConfig2.scope,
702
+ audience: cliConfig2.audience
703
+ });
704
+ const deviceAuthResponse = await axios.post(cliConfig2.deviceCodeAuthUrl, {
705
+ client_id: cliConfig2.clientId,
706
+ scope: cliConfig2.scope,
707
+ audience: cliConfig2.audience
708
+ }).catch((e) => {
709
+ logger.error("There was an issue with the authentication process. Please try again.");
710
+ if (e.message) {
711
+ logger.debug(e.message, e);
712
+ } else {
713
+ logger.debug(e);
714
+ }
715
+ });
716
+ openModule$1.then((open) => {
717
+ open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
718
+ logger.error("We encountered an issue opening the browser. Please try again later.");
719
+ logger.debug(e.message, e);
720
+ });
721
+ });
722
+ logger.log("If a browser tab does not open automatically, please follow the next steps:");
723
+ logger.log(
724
+ `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
725
+ );
726
+ logger.log(
727
+ `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
728
+ `
729
+ );
730
+ const tokenPayload = {
731
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
732
+ device_code: deviceAuthResponse.data.device_code,
733
+ client_id: cliConfig2.clientId
734
+ };
735
+ let isAuthenticated = false;
736
+ const authenticate = async () => {
737
+ const spinner = logger.spinner("Waiting for authentication");
738
+ spinner.start();
739
+ const spinnerFail = () => spinner.fail("Authentication failed!");
740
+ while (!isAuthenticated) {
741
+ try {
742
+ const tokenResponse = await axios.post(cliConfig2.tokenUrl, tokenPayload);
743
+ const authTokenData = tokenResponse.data;
744
+ if (tokenResponse.status === 200) {
745
+ try {
746
+ logger.debug("🔐 Validating token...");
747
+ await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
748
+ logger.debug("🔐 Token validation successful!");
749
+ } catch (e) {
750
+ logger.debug(e);
751
+ spinnerFail();
752
+ throw new Error("Unable to proceed: Token validation failed");
753
+ }
754
+ logger.debug("🔍 Fetching user information...");
755
+ const cloudApiServiceWithToken = await cloudApiFactory(ctx, authTokenData.access_token);
756
+ await cloudApiServiceWithToken.getUserInfo();
757
+ logger.debug("🔍 User information fetched successfully!");
758
+ try {
759
+ logger.debug("📝 Saving login information...");
760
+ await tokenService.saveToken(authTokenData.access_token);
761
+ logger.debug("📝 Login information saved successfully!");
762
+ isAuthenticated = true;
763
+ } catch (e) {
764
+ logger.error(
765
+ "There was a problem saving your login information. Please try logging in again."
766
+ );
767
+ logger.debug(e);
768
+ spinnerFail();
769
+ return false;
770
+ }
771
+ }
772
+ } catch (e) {
773
+ if (e.message === "Unable to proceed: Token validation failed") {
774
+ logger.error(
775
+ "There seems to be a problem with your login information. Please try logging in again."
776
+ );
777
+ spinnerFail();
778
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
779
+ return false;
780
+ }
781
+ if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
782
+ logger.debug(e);
783
+ spinnerFail();
784
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
785
+ return false;
786
+ }
787
+ await new Promise((resolve) => {
788
+ setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
789
+ });
790
+ }
791
+ }
792
+ spinner.succeed("Authentication successful!");
793
+ logger.log("You are now logged into Strapi Cloud.");
794
+ logger.log(
795
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
796
+ );
797
+ logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
798
+ await trackEvent(ctx, cloudApiService, "didLogin", { loginMethod: "cli" });
799
+ };
800
+ await authenticate();
801
+ return isAuthenticated;
802
+ }
803
+ function questionDefaultValuesMapper(questionsMap) {
804
+ return (questions) => {
805
+ return questions.map((question) => {
806
+ const questionName = question.name;
807
+ if (questionName in questionsMap) {
808
+ const questionDefault = questionsMap[questionName];
809
+ if (typeof questionDefault === "function") {
810
+ return {
811
+ ...question,
812
+ default: questionDefault(question)
813
+ };
814
+ }
815
+ return {
816
+ ...question,
817
+ default: questionDefault
818
+ };
819
+ }
820
+ return question;
821
+ });
822
+ };
823
+ }
824
+ function getDefaultsFromQuestions(questions) {
825
+ return questions.reduce((acc, question) => {
826
+ if (question.default && question.name) {
827
+ return { ...acc, [question.name]: question.default };
828
+ }
829
+ return acc;
830
+ }, {});
831
+ }
832
+ function getProjectNodeVersionDefault(question) {
833
+ const currentNodeVersion = process.versions.node.split(".")[0];
834
+ if (question.type === "list" && Array.isArray(question.choices)) {
835
+ const choice = question.choices.find((choice2) => choice2.value === currentNodeVersion);
836
+ if (choice) {
837
+ return choice.value;
838
+ }
839
+ }
840
+ return question.default;
841
+ }
842
+ async function handleError(ctx, error) {
561
843
  const { logger } = ctx;
562
844
  logger.debug(error);
563
845
  if (error instanceof AxiosError) {
564
846
  const errorMessage = typeof error.response?.data === "string" ? error.response.data : null;
565
847
  switch (error.response?.status) {
566
- case 401:
567
- logger.error("Your session has expired. Please log in again.");
568
- await tokenService.eraseToken();
569
- return;
570
848
  case 403:
571
849
  logger.error(
572
850
  errorMessage || "You do not have permission to create a project. Please contact support for assistance."
@@ -592,28 +870,53 @@ async function handleError(ctx, error) {
592
870
  "We encountered an issue while creating your project. Please try again in a moment. If the problem persists, contact support for assistance."
593
871
  );
594
872
  }
595
- const action$3 = async (ctx) => {
873
+ async function createProject$1(ctx, cloudApi, projectInput) {
596
874
  const { logger } = ctx;
597
- const { getValidToken } = await tokenServiceFactory(ctx);
598
- const token = await getValidToken();
875
+ const spinner = logger.spinner("Setting up your project...").start();
876
+ try {
877
+ const { data } = await cloudApi.createProject(projectInput);
878
+ await save({ project: data });
879
+ spinner.succeed("Project created successfully!");
880
+ return data;
881
+ } catch (e) {
882
+ spinner.fail("An error occurred while creating the project on Strapi Cloud.");
883
+ throw e;
884
+ }
885
+ }
886
+ const action$4 = async (ctx) => {
887
+ const { logger } = ctx;
888
+ const { getValidToken, eraseToken } = await tokenServiceFactory(ctx);
889
+ const token = await getValidToken(ctx, promptLogin);
599
890
  if (!token) {
600
891
  return;
601
892
  }
602
- const cloudApi = await cloudApiFactory(token);
893
+ const cloudApi = await cloudApiFactory(ctx, token);
603
894
  const { data: config } = await cloudApi.config();
604
- const { questions, defaults: defaultValues } = config.projectCreation;
895
+ const projectName = await getProjectNameFromPackageJson(ctx);
896
+ const defaultAnswersMapper = questionDefaultValuesMapper({
897
+ name: projectName,
898
+ nodeVersion: getProjectNodeVersionDefault
899
+ });
900
+ const questions = defaultAnswersMapper(config.projectCreation.questions);
901
+ const defaultValues = {
902
+ ...config.projectCreation.defaults,
903
+ ...getDefaultsFromQuestions(questions)
904
+ };
605
905
  const projectAnswersDefaulted = defaults(defaultValues);
606
906
  const projectAnswers = await inquirer.prompt(questions);
607
907
  const projectInput = projectAnswersDefaulted(projectAnswers);
608
- const spinner = logger.spinner("Setting up your project...").start();
609
908
  try {
610
- const { data } = await cloudApi.createProject(projectInput);
611
- await save({ project: data });
612
- spinner.succeed("Project created successfully!");
613
- return data;
909
+ return await createProject$1(ctx, cloudApi, projectInput);
614
910
  } catch (e) {
615
- spinner.fail("Failed to create project on Strapi Cloud.");
616
- await handleError(ctx, e);
911
+ if (e instanceof AxiosError && e.response?.status === 401) {
912
+ logger.warn("Oops! Your session has expired. Please log in again to retry.");
913
+ await eraseToken();
914
+ if (await promptLogin(ctx)) {
915
+ return await createProject$1(ctx, cloudApi, projectInput);
916
+ }
917
+ } else {
918
+ await handleError(ctx, e);
919
+ }
617
920
  }
618
921
  };
619
922
  function notificationServiceFactory({ logger }) {
@@ -647,38 +950,6 @@ function notificationServiceFactory({ logger }) {
647
950
  };
648
951
  };
649
952
  }
650
- yup.object({
651
- name: yup.string().required(),
652
- exports: yup.lazy(
653
- (value) => yup.object(
654
- typeof value === "object" ? Object.entries(value).reduce((acc, [key, value2]) => {
655
- if (typeof value2 === "object") {
656
- acc[key] = yup.object({
657
- types: yup.string().optional(),
658
- source: yup.string().required(),
659
- module: yup.string().optional(),
660
- import: yup.string().required(),
661
- require: yup.string().required(),
662
- default: yup.string().required()
663
- }).noUnknown(true);
664
- } else {
665
- acc[key] = yup.string().matches(/^\.\/.*\.json$/).required();
666
- }
667
- return acc;
668
- }, {}) : void 0
669
- ).optional()
670
- )
671
- });
672
- const loadPkg = async ({ cwd, logger }) => {
673
- const pkgPath = await pkgUp({ cwd });
674
- if (!pkgPath) {
675
- throw new Error("Could not find a package.json in the current directory");
676
- }
677
- const buffer = await fs$1.readFile(pkgPath);
678
- const pkg = JSON.parse(buffer.toString());
679
- logger.debug("Loaded package.json:", os.EOL, pkg);
680
- return pkg;
681
- };
682
953
  const buildLogsServiceFactory = ({ logger }) => {
683
954
  return async (url, token, cliConfig2) => {
684
955
  const CONN_TIMEOUT = Number(cliConfig2.buildLogsConnectionTimeout);
@@ -732,6 +1003,7 @@ const buildLogsServiceFactory = ({ logger }) => {
732
1003
  if (retries > MAX_RETRIES) {
733
1004
  spinner.fail("We were unable to connect to the server to get build logs at this time.");
734
1005
  es.close();
1006
+ clearExistingTimeout();
735
1007
  reject(new Error("Max retries reached"));
736
1008
  }
737
1009
  };
@@ -741,7 +1013,7 @@ const buildLogsServiceFactory = ({ logger }) => {
741
1013
  };
742
1014
  };
743
1015
  async function upload(ctx, project, token, maxProjectFileSize) {
744
- const cloudApi = await cloudApiFactory(token);
1016
+ const cloudApi = await cloudApiFactory(ctx, token);
745
1017
  try {
746
1018
  const storagePath = await getTmpStoragePath();
747
1019
  const projectFolder = path__default.resolve(process.cwd());
@@ -774,13 +1046,13 @@ async function upload(ctx, project, token, maxProjectFileSize) {
774
1046
  process.exit(1);
775
1047
  }
776
1048
  const tarFilePath = path__default.resolve(storagePath, compressedFilename);
777
- const fileStats = await fse.stat(tarFilePath);
1049
+ const fileStats = await fse__default.stat(tarFilePath);
778
1050
  if (fileStats.size > maxProjectFileSize) {
779
1051
  ctx.logger.log(
780
1052
  "Unable to proceed: Your project is too big to be transferred, please use a git repo instead."
781
1053
  );
782
1054
  try {
783
- await fse.remove(tarFilePath);
1055
+ await fse__default.remove(tarFilePath);
784
1056
  } catch (e) {
785
1057
  ctx.logger.log("Unable to remove file: ", tarFilePath);
786
1058
  ctx.logger.debug(e);
@@ -808,8 +1080,8 @@ async function upload(ctx, project, token, maxProjectFileSize) {
808
1080
  progressBar.stop();
809
1081
  if (e instanceof AxiosError && e.response?.data) {
810
1082
  if (e.response.status === 404) {
811
- ctx.logger.error(
812
- `The project does not exist. Remove the ${LOCAL_SAVE_FILENAME} file and try again.`
1083
+ ctx.logger.warn(
1084
+ `The project does not exist. Please link your local project to a Strapi Cloud project using the link command.`
813
1085
  );
814
1086
  } else {
815
1087
  ctx.logger.error(e.response.data);
@@ -819,7 +1091,7 @@ async function upload(ctx, project, token, maxProjectFileSize) {
819
1091
  }
820
1092
  ctx.logger.debug(e);
821
1093
  } finally {
822
- await fse.remove(tarFilePath);
1094
+ await fse__default.remove(tarFilePath);
823
1095
  }
824
1096
  process.exit(0);
825
1097
  } catch (e) {
@@ -832,7 +1104,7 @@ async function getProject(ctx) {
832
1104
  const { project } = await retrieve();
833
1105
  if (!project) {
834
1106
  try {
835
- return await action$3(ctx);
1107
+ return await action$4(ctx);
836
1108
  } catch (e) {
837
1109
  ctx.logger.error("An error occurred while deploying the project. Please try again later.");
838
1110
  ctx.logger.debug(e);
@@ -841,10 +1113,21 @@ async function getProject(ctx) {
841
1113
  }
842
1114
  return project;
843
1115
  }
844
- const action$2 = async (ctx) => {
1116
+ async function getConfig({
1117
+ ctx,
1118
+ cloudApiService
1119
+ }) {
1120
+ try {
1121
+ const { data: cliConfig2 } = await cloudApiService.config();
1122
+ return cliConfig2;
1123
+ } catch (e) {
1124
+ ctx.logger.debug("Failed to get cli config", e);
1125
+ return null;
1126
+ }
1127
+ }
1128
+ const action$3 = async (ctx) => {
845
1129
  const { getValidToken } = await tokenServiceFactory(ctx);
846
- const cloudApiService = await cloudApiFactory();
847
- const token = await getValidToken();
1130
+ const token = await getValidToken(ctx, promptLogin);
848
1131
  if (!token) {
849
1132
  return;
850
1133
  }
@@ -852,14 +1135,19 @@ const action$2 = async (ctx) => {
852
1135
  if (!project) {
853
1136
  return;
854
1137
  }
855
- try {
856
- await cloudApiService.track("willDeployWithCLI", { projectInternalName: project.name });
857
- } catch (e) {
858
- ctx.logger.debug("Failed to track willDeploy", e);
859
- }
1138
+ const cloudApiService = await cloudApiFactory(ctx);
1139
+ await trackEvent(ctx, cloudApiService, "willDeployWithCLI", {
1140
+ projectInternalName: project.name
1141
+ });
860
1142
  const notificationService = notificationServiceFactory(ctx);
861
1143
  const buildLogsService = buildLogsServiceFactory(ctx);
862
- const { data: cliConfig2 } = await cloudApiService.config();
1144
+ const cliConfig2 = await getConfig({ ctx, cloudApiService });
1145
+ if (!cliConfig2) {
1146
+ ctx.logger.error(
1147
+ "An error occurred while retrieving data from Strapi Cloud. Please try check your network or again later."
1148
+ );
1149
+ return;
1150
+ }
863
1151
  let maxSize = parseInt(cliConfig2.maxProjectFileSize, 10);
864
1152
  if (Number.isNaN(maxSize)) {
865
1153
  ctx.logger.debug(
@@ -881,10 +1169,11 @@ const action$2 = async (ctx) => {
881
1169
  chalk.underline(`${apiConfig.dashboardBaseUrl}/projects/${project.name}/deployments`)
882
1170
  );
883
1171
  } catch (e) {
1172
+ ctx.logger.debug(e);
884
1173
  if (e instanceof Error) {
885
1174
  ctx.logger.error(e.message);
886
1175
  } else {
887
- throw e;
1176
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
888
1177
  }
889
1178
  }
890
1179
  };
@@ -915,185 +1204,175 @@ const runAction = (name2, action2) => (...args) => {
915
1204
  process.exit(1);
916
1205
  });
917
1206
  };
918
- const command$3 = ({ command: command2, ctx }) => {
919
- command2.command("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").action(() => runAction("deploy", action$2)(ctx));
1207
+ const command$5 = ({ command: command2, ctx }) => {
1208
+ command2.command("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").action(() => runAction("deploy", action$3)(ctx));
920
1209
  };
921
1210
  const deployProject = {
922
1211
  name: "deploy-project",
923
1212
  description: "Deploy a Strapi Cloud project",
924
- action: action$2,
925
- command: command$3
1213
+ action: action$3,
1214
+ command: command$5
926
1215
  };
927
- const openModule = import("open");
928
- const action$1 = async (ctx) => {
929
- const { logger } = ctx;
930
- const tokenService = await tokenServiceFactory(ctx);
931
- const existingToken = await tokenService.retrieveToken();
932
- const cloudApiService = await cloudApiFactory(existingToken || void 0);
933
- const trackFailedLogin = async () => {
934
- try {
935
- await cloudApiService.track("didNotLogin", { loginMethod: "cli" });
936
- } catch (e) {
937
- logger.debug("Failed to track failed login", e);
938
- }
939
- };
940
- if (existingToken) {
941
- const isTokenValid = await tokenService.isTokenValid(existingToken);
942
- if (isTokenValid) {
943
- try {
944
- const userInfo = await cloudApiService.getUserInfo();
945
- const { email } = userInfo.data.data;
946
- if (email) {
947
- logger.log(`You are already logged into your account (${email}).`);
948
- } else {
949
- logger.log("You are already logged in.");
950
- }
951
- logger.log(
952
- "To access your dashboard, please copy and paste the following URL into your web browser:"
953
- );
954
- logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
955
- return true;
956
- } catch (e) {
957
- logger.debug("Failed to fetch user info", e);
1216
+ const QUIT_OPTION = "Quit";
1217
+ async function getExistingConfig(ctx) {
1218
+ try {
1219
+ return await retrieve();
1220
+ } catch (e) {
1221
+ ctx.logger.debug("Failed to get project config", e);
1222
+ ctx.logger.error("An error occurred while retrieving config data from your local project.");
1223
+ return null;
1224
+ }
1225
+ }
1226
+ async function promptForRelink(ctx, cloudApiService, existingConfig) {
1227
+ if (existingConfig && existingConfig.project) {
1228
+ const { shouldRelink } = await inquirer.prompt([
1229
+ {
1230
+ type: "confirm",
1231
+ name: "shouldRelink",
1232
+ message: `A project named ${chalk.cyan(
1233
+ existingConfig.project.displayName ? existingConfig.project.displayName : existingConfig.project.name
1234
+ )} is already linked to this local folder. Do you want to update the link?`,
1235
+ default: false
958
1236
  }
1237
+ ]);
1238
+ if (!shouldRelink) {
1239
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1240
+ currentProjectName: existingConfig.project?.name
1241
+ });
1242
+ return false;
959
1243
  }
960
1244
  }
961
- let cliConfig2;
1245
+ return true;
1246
+ }
1247
+ async function getProjectsList(ctx, cloudApiService, existingConfig) {
1248
+ const spinner = ctx.logger.spinner("Fetching your projects...\n").start();
962
1249
  try {
963
- logger.info("🔌 Connecting to the Strapi Cloud API...");
964
- const config = await cloudApiService.config();
965
- cliConfig2 = config.data;
1250
+ const {
1251
+ data: { data: projectList }
1252
+ } = await cloudApiService.listLinkProjects();
1253
+ spinner.succeed();
1254
+ if (!Array.isArray(projectList)) {
1255
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1256
+ return null;
1257
+ }
1258
+ const projects = projectList.filter(
1259
+ (project) => !(project.isMaintainer || project.name === existingConfig?.project?.name)
1260
+ ).map((project) => {
1261
+ return {
1262
+ name: project.displayName,
1263
+ value: { name: project.name, displayName: project.displayName }
1264
+ };
1265
+ });
1266
+ if (projects.length === 0) {
1267
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1268
+ return null;
1269
+ }
1270
+ return projects;
966
1271
  } catch (e) {
967
- logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
968
- logger.debug(e);
969
- return false;
1272
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1273
+ ctx.logger.debug("Failed to list projects", e);
1274
+ return null;
970
1275
  }
1276
+ }
1277
+ async function getUserSelection(ctx, projects) {
1278
+ const { logger } = ctx;
971
1279
  try {
972
- await cloudApiService.track("willLoginAttempt", {});
1280
+ const answer = await inquirer.prompt([
1281
+ {
1282
+ type: "list",
1283
+ name: "linkProject",
1284
+ message: "Which project do you want to link?",
1285
+ choices: [...projects, { name: chalk.grey(`(${QUIT_OPTION})`), value: null }]
1286
+ }
1287
+ ]);
1288
+ if (!answer.linkProject) {
1289
+ return null;
1290
+ }
1291
+ return answer;
973
1292
  } catch (e) {
974
- logger.debug("Failed to track login attempt", e);
1293
+ logger.debug("Failed to get user input", e);
1294
+ logger.error("An error occurred while trying to get your input.");
1295
+ return null;
975
1296
  }
976
- logger.debug("🔐 Creating device authentication request...", {
977
- client_id: cliConfig2.clientId,
978
- scope: cliConfig2.scope,
979
- audience: cliConfig2.audience
980
- });
981
- const deviceAuthResponse = await axios.post(cliConfig2.deviceCodeAuthUrl, {
982
- client_id: cliConfig2.clientId,
983
- scope: cliConfig2.scope,
984
- audience: cliConfig2.audience
985
- }).catch((e) => {
986
- logger.error("There was an issue with the authentication process. Please try again.");
987
- if (e.message) {
988
- logger.debug(e.message, e);
989
- } else {
990
- logger.debug(e);
991
- }
992
- });
993
- openModule.then((open) => {
994
- open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
995
- logger.error("We encountered an issue opening the browser. Please try again later.");
996
- logger.debug(e.message, e);
997
- });
998
- });
999
- logger.log("If a browser tab does not open automatically, please follow the next steps:");
1000
- logger.log(
1001
- `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
1002
- );
1003
- logger.log(
1004
- `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
1005
- `
1297
+ }
1298
+ const action$2 = async (ctx) => {
1299
+ const { getValidToken } = await tokenServiceFactory(ctx);
1300
+ const token = await getValidToken(ctx, promptLogin);
1301
+ const { logger } = ctx;
1302
+ if (!token) {
1303
+ return;
1304
+ }
1305
+ const cloudApiService = await cloudApiFactory(ctx, token);
1306
+ const existingConfig = await getExistingConfig(ctx);
1307
+ const shouldRelink = await promptForRelink(ctx, cloudApiService, existingConfig);
1308
+ if (!shouldRelink) {
1309
+ return;
1310
+ }
1311
+ await trackEvent(ctx, cloudApiService, "willLinkProject", {});
1312
+ const projects = await getProjectsList(
1313
+ ctx,
1314
+ cloudApiService,
1315
+ existingConfig
1006
1316
  );
1007
- const tokenPayload = {
1008
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1009
- device_code: deviceAuthResponse.data.device_code,
1010
- client_id: cliConfig2.clientId
1011
- };
1012
- let isAuthenticated = false;
1013
- const authenticate = async () => {
1014
- const spinner = logger.spinner("Waiting for authentication");
1015
- spinner.start();
1016
- const spinnerFail = () => spinner.fail("Authentication failed!");
1017
- while (!isAuthenticated) {
1018
- try {
1019
- const tokenResponse = await axios.post(cliConfig2.tokenUrl, tokenPayload);
1020
- const authTokenData = tokenResponse.data;
1021
- if (tokenResponse.status === 200) {
1022
- try {
1023
- logger.debug("🔐 Validating token...");
1024
- await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
1025
- logger.debug("🔐 Token validation successful!");
1026
- } catch (e) {
1027
- logger.debug(e);
1028
- spinnerFail();
1029
- throw new Error("Unable to proceed: Token validation failed");
1030
- }
1031
- logger.debug("🔍 Fetching user information...");
1032
- const cloudApiServiceWithToken = await cloudApiFactory(authTokenData.access_token);
1033
- await cloudApiServiceWithToken.getUserInfo();
1034
- logger.debug("🔍 User information fetched successfully!");
1035
- try {
1036
- logger.debug("📝 Saving login information...");
1037
- await tokenService.saveToken(authTokenData.access_token);
1038
- logger.debug("📝 Login information saved successfully!");
1039
- isAuthenticated = true;
1040
- } catch (e) {
1041
- logger.error(
1042
- "There was a problem saving your login information. Please try logging in again."
1043
- );
1044
- logger.debug(e);
1045
- spinnerFail();
1046
- return false;
1047
- }
1048
- }
1049
- } catch (e) {
1050
- if (e.message === "Unable to proceed: Token validation failed") {
1051
- logger.error(
1052
- "There seems to be a problem with your login information. Please try logging in again."
1053
- );
1054
- spinnerFail();
1055
- await trackFailedLogin();
1056
- return false;
1057
- }
1058
- if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
1059
- logger.debug(e);
1060
- spinnerFail();
1061
- await trackFailedLogin();
1062
- return false;
1063
- }
1064
- await new Promise((resolve) => {
1065
- setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
1066
- });
1317
+ if (!projects) {
1318
+ return;
1319
+ }
1320
+ const answer = await getUserSelection(ctx, projects);
1321
+ if (!answer) {
1322
+ return;
1323
+ }
1324
+ try {
1325
+ const { confirmAction } = await inquirer.prompt([
1326
+ {
1327
+ type: "confirm",
1328
+ name: "confirmAction",
1329
+ message: "Warning: Once linked, deploying from CLI will replace the existing project and its data. Confirm to proceed:",
1330
+ default: false
1067
1331
  }
1332
+ ]);
1333
+ if (!confirmAction) {
1334
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1335
+ cancelledProjectName: answer.linkProject.name,
1336
+ currentProjectName: existingConfig ? existingConfig.project?.name : null
1337
+ });
1338
+ return;
1068
1339
  }
1069
- spinner.succeed("Authentication successful!");
1070
- logger.log("You are now logged into Strapi Cloud.");
1071
- logger.log(
1072
- "To access your dashboard, please copy and paste the following URL into your web browser:"
1073
- );
1074
- logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
1075
- try {
1076
- await cloudApiService.track("didLogin", { loginMethod: "cli" });
1077
- } catch (e) {
1078
- logger.debug("Failed to track login", e);
1079
- }
1080
- };
1081
- await authenticate();
1082
- return isAuthenticated;
1340
+ await save({ project: answer.linkProject });
1341
+ logger.log(`Project ${chalk.cyan(answer.linkProject.displayName)} linked successfully.`);
1342
+ await trackEvent(ctx, cloudApiService, "didLinkProject", {
1343
+ projectInternalName: answer.linkProject
1344
+ });
1345
+ } catch (e) {
1346
+ logger.debug("Failed to link project", e);
1347
+ logger.error("An error occurred while linking the project.");
1348
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1349
+ projectInternalName: answer.linkProject
1350
+ });
1351
+ }
1083
1352
  };
1084
- const command$2 = ({ command: command2, ctx }) => {
1353
+ const command$4 = ({ command: command2, ctx }) => {
1354
+ command2.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$2)(ctx));
1355
+ };
1356
+ const link = {
1357
+ name: "link-project",
1358
+ description: "Link a local directory to a Strapi Cloud project",
1359
+ action: action$2,
1360
+ command: command$4
1361
+ };
1362
+ const command$3 = ({ command: command2, ctx }) => {
1085
1363
  command2.command("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1086
1364
  "after",
1087
1365
  "\nAfter running this command, you will be prompted to enter your authentication information."
1088
- ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", action$1)(ctx));
1366
+ ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", loginAction)(ctx));
1089
1367
  };
1090
1368
  const login = {
1091
1369
  name: "login",
1092
1370
  description: "Strapi Cloud Login",
1093
- action: action$1,
1094
- command: command$2
1371
+ action: loginAction,
1372
+ command: command$3
1095
1373
  };
1096
- const action = async (ctx) => {
1374
+ const openModule = import("open");
1375
+ const action$1 = async (ctx) => {
1097
1376
  const { logger } = ctx;
1098
1377
  const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx);
1099
1378
  const token = await retrieveToken();
@@ -1101,9 +1380,21 @@ const action = async (ctx) => {
1101
1380
  logger.log("You're already logged out.");
1102
1381
  return;
1103
1382
  }
1104
- const cloudApiService = await cloudApiFactory(token);
1383
+ const cloudApiService = await cloudApiFactory(ctx, token);
1384
+ const config = await cloudApiService.config();
1385
+ const cliConfig2 = config.data;
1105
1386
  try {
1106
1387
  await eraseToken();
1388
+ openModule.then((open) => {
1389
+ open.default(
1390
+ `${cliConfig2.baseUrl}/oidc/logout?client_id=${encodeURIComponent(
1391
+ cliConfig2.clientId
1392
+ )}&logout_hint=${encodeURIComponent(token)}
1393
+ `
1394
+ ).catch((e) => {
1395
+ logger.debug(e.message, e);
1396
+ });
1397
+ });
1107
1398
  logger.log(
1108
1399
  "🔌 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."
1109
1400
  );
@@ -1111,37 +1402,64 @@ const action = async (ctx) => {
1111
1402
  logger.error("🥲 Oops! Something went wrong while logging you out. Please try again.");
1112
1403
  logger.debug(e);
1113
1404
  }
1114
- try {
1115
- await cloudApiService.track("didLogout", { loginMethod: "cli" });
1116
- } catch (e) {
1117
- logger.debug("Failed to track logout event", e);
1118
- }
1405
+ await trackEvent(ctx, cloudApiService, "didLogout", { loginMethod: "cli" });
1119
1406
  };
1120
- const command$1 = ({ command: command2, ctx }) => {
1121
- command2.command("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)(ctx));
1407
+ const command$2 = ({ command: command2, ctx }) => {
1408
+ command2.command("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$1)(ctx));
1122
1409
  };
1123
1410
  const logout = {
1124
1411
  name: "logout",
1125
1412
  description: "Strapi Cloud Logout",
1126
- action,
1127
- command: command$1
1413
+ action: action$1,
1414
+ command: command$2
1128
1415
  };
1129
- const command = ({ command: command2, ctx }) => {
1130
- command2.command("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$3)(ctx));
1416
+ const command$1 = ({ command: command2, ctx }) => {
1417
+ command2.command("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$4)(ctx));
1131
1418
  };
1132
1419
  const createProject = {
1133
1420
  name: "create-project",
1134
1421
  description: "Create a new project",
1135
- action: action$3,
1422
+ action: action$4,
1423
+ command: command$1
1424
+ };
1425
+ const action = async (ctx) => {
1426
+ const { getValidToken } = await tokenServiceFactory(ctx);
1427
+ const token = await getValidToken(ctx, promptLogin);
1428
+ const { logger } = ctx;
1429
+ if (!token) {
1430
+ return;
1431
+ }
1432
+ const cloudApiService = await cloudApiFactory(ctx, token);
1433
+ const spinner = logger.spinner("Fetching your projects...").start();
1434
+ try {
1435
+ const {
1436
+ data: { data: projectList }
1437
+ } = await cloudApiService.listProjects();
1438
+ spinner.succeed();
1439
+ logger.log(projectList);
1440
+ } catch (e) {
1441
+ ctx.logger.debug("Failed to list projects", e);
1442
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1443
+ }
1444
+ };
1445
+ const command = ({ command: command2, ctx }) => {
1446
+ command2.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)(ctx));
1447
+ };
1448
+ const listProjects = {
1449
+ name: "list-projects",
1450
+ description: "List Strapi Cloud projects",
1451
+ action,
1136
1452
  command
1137
1453
  };
1138
1454
  const cli = {
1139
1455
  deployProject,
1456
+ link,
1140
1457
  login,
1141
1458
  logout,
1142
- createProject
1459
+ createProject,
1460
+ listProjects
1143
1461
  };
1144
- const cloudCommands = [deployProject, login, logout];
1462
+ const cloudCommands = [deployProject, link, login, logout, listProjects];
1145
1463
  async function initCloudCLIConfig() {
1146
1464
  const localConfig = await getLocalConfig();
1147
1465
  if (!localConfig.deviceId) {