@strapi/cloud-cli 5.0.0-rc.11 → 5.0.0-rc.13

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 (38) hide show
  1. package/dist/index.js +441 -142
  2. package/dist/index.js.map +1 -1
  3. package/dist/index.mjs +441 -139
  4. package/dist/index.mjs.map +1 -1
  5. package/dist/src/create-project/action.d.ts.map +1 -1
  6. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts +3 -0
  7. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts.map +1 -0
  8. package/dist/src/create-project/utils/project-questions.utils.d.ts +20 -0
  9. package/dist/src/create-project/utils/project-questions.utils.d.ts.map +1 -0
  10. package/dist/src/deploy-project/action.d.ts.map +1 -1
  11. package/dist/src/index.d.ts +2 -0
  12. package/dist/src/index.d.ts.map +1 -1
  13. package/dist/src/link/action.d.ts +4 -0
  14. package/dist/src/link/action.d.ts.map +1 -0
  15. package/dist/src/link/command.d.ts +7 -0
  16. package/dist/src/link/command.d.ts.map +1 -0
  17. package/dist/src/link/index.d.ts +7 -0
  18. package/dist/src/link/index.d.ts.map +1 -0
  19. package/dist/src/list-projects/action.d.ts +4 -0
  20. package/dist/src/list-projects/action.d.ts.map +1 -0
  21. package/dist/src/list-projects/command.d.ts +7 -0
  22. package/dist/src/list-projects/command.d.ts.map +1 -0
  23. package/dist/src/list-projects/index.d.ts +7 -0
  24. package/dist/src/list-projects/index.d.ts.map +1 -0
  25. package/dist/src/login/action.d.ts.map +1 -1
  26. package/dist/src/logout/action.d.ts.map +1 -1
  27. package/dist/src/services/build-logs.d.ts.map +1 -1
  28. package/dist/src/services/cli-api.d.ts +35 -7
  29. package/dist/src/services/cli-api.d.ts.map +1 -1
  30. package/dist/src/services/strapi-info-save.d.ts +1 -1
  31. package/dist/src/services/strapi-info-save.d.ts.map +1 -1
  32. package/dist/src/types.d.ts +1 -0
  33. package/dist/src/types.d.ts.map +1 -1
  34. package/dist/src/utils/analytics.d.ts +4 -0
  35. package/dist/src/utils/analytics.d.ts.map +1 -0
  36. package/dist/src/utils/compress-files.d.ts.map +1 -1
  37. package/dist/src/utils/pkg.d.ts.map +1 -1
  38. package/package.json +7 -6
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
  import { createCommand } from "commander";
26
25
  const apiConfig = {
27
26
  apiBaseUrl: env("STRAPI_CLI_CLOUD_API", "https://cloud-cli-api.strapi.io"),
@@ -41,23 +40,6 @@ const IGNORED_PATTERNS = [
41
40
  "**/.idea/**",
42
41
  "**/.vscode/**"
43
42
  ];
44
- const getFiles = (dirPath, ignorePatterns = [], arrayOfFiles = [], subfolder = "") => {
45
- const entries = fs.readdirSync(path.join(dirPath, subfolder));
46
- entries.forEach((entry) => {
47
- const entryPathFromRoot = path.join(subfolder, entry);
48
- const entryPath = path.relative(dirPath, entryPathFromRoot);
49
- const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
50
- if (isIgnored) {
51
- return;
52
- }
53
- if (fs.statSync(entryPath).isDirectory()) {
54
- getFiles(dirPath, ignorePatterns, arrayOfFiles, entryPathFromRoot);
55
- } else {
56
- arrayOfFiles.push(entryPath);
57
- }
58
- });
59
- return arrayOfFiles;
60
- };
61
43
  const isIgnoredFile = (folderPath, file, ignorePatterns) => {
62
44
  ignorePatterns.push(...IGNORED_PATTERNS);
63
45
  const relativeFilePath = path.join(folderPath, file);
@@ -75,16 +57,35 @@ const isIgnoredFile = (folderPath, file, ignorePatterns) => {
75
57
  }
76
58
  return isIgnored;
77
59
  };
78
- const readGitignore = (folderPath) => {
60
+ const getFiles = async (dirPath, ignorePatterns = [], subfolder = "") => {
61
+ const arrayOfFiles = [];
62
+ const entries = await fse.readdir(path.join(dirPath, subfolder));
63
+ for (const entry of entries) {
64
+ const entryPathFromRoot = path.join(subfolder, entry);
65
+ const entryPath = path.relative(dirPath, entryPathFromRoot);
66
+ const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
67
+ if (!isIgnored) {
68
+ if (fse.statSync(entryPath).isDirectory()) {
69
+ const subFiles = await getFiles(dirPath, ignorePatterns, entryPathFromRoot);
70
+ arrayOfFiles.push(...subFiles);
71
+ } else {
72
+ arrayOfFiles.push(entryPath);
73
+ }
74
+ }
75
+ }
76
+ return arrayOfFiles;
77
+ };
78
+ const readGitignore = async (folderPath) => {
79
79
  const gitignorePath = path.resolve(folderPath, ".gitignore");
80
- if (!fs.existsSync(gitignorePath))
80
+ const pathExist = await fse.pathExists(gitignorePath);
81
+ if (!pathExist)
81
82
  return [];
82
- const gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
83
+ const gitignoreContent = await fse.readFile(gitignorePath, "utf8");
83
84
  return gitignoreContent.split(/\r?\n/).filter((line) => Boolean(line.trim()) && !line.startsWith("#"));
84
85
  };
85
86
  const compressFilesToTar = async (storagePath, folderToCompress, filename) => {
86
- const ignorePatterns = readGitignore(folderToCompress);
87
- const filesToCompress = getFiles(folderToCompress, ignorePatterns);
87
+ const ignorePatterns = await readGitignore(folderToCompress);
88
+ const filesToCompress = await getFiles(folderToCompress, ignorePatterns);
88
89
  return tar.c(
89
90
  {
90
91
  gzip: true,
@@ -97,7 +98,7 @@ const APP_FOLDER_NAME = "com.strapi.cli";
97
98
  const CONFIG_FILENAME = "config.json";
98
99
  async function checkDirectoryExists(directoryPath) {
99
100
  try {
100
- const fsStat = await fse.lstat(directoryPath);
101
+ const fsStat = await fse__default.lstat(directoryPath);
101
102
  return fsStat.isDirectory();
102
103
  } catch (e) {
103
104
  return false;
@@ -105,14 +106,14 @@ async function checkDirectoryExists(directoryPath) {
105
106
  }
106
107
  async function getTmpStoragePath() {
107
108
  const storagePath = path__default.join(os.tmpdir(), APP_FOLDER_NAME);
108
- await fse.ensureDir(storagePath);
109
+ await fse__default.ensureDir(storagePath);
109
110
  return storagePath;
110
111
  }
111
112
  async function getConfigPath() {
112
113
  const configDirs = XDGAppPaths(APP_FOLDER_NAME).configDirs();
113
114
  const configPath = configDirs.find(checkDirectoryExists);
114
115
  if (!configPath) {
115
- await fse.ensureDir(configDirs[0]);
116
+ await fse__default.ensureDir(configDirs[0]);
116
117
  return configDirs[0];
117
118
  }
118
119
  return configPath;
@@ -120,9 +121,9 @@ async function getConfigPath() {
120
121
  async function getLocalConfig() {
121
122
  const configPath = await getConfigPath();
122
123
  const configFilePath = path__default.join(configPath, CONFIG_FILENAME);
123
- await fse.ensureFile(configFilePath);
124
+ await fse__default.ensureFile(configFilePath);
124
125
  try {
125
- return await fse.readJSON(configFilePath, { encoding: "utf8", throws: true });
126
+ return await fse__default.readJSON(configFilePath, { encoding: "utf8", throws: true });
126
127
  } catch (e) {
127
128
  return {};
128
129
  }
@@ -130,10 +131,10 @@ async function getLocalConfig() {
130
131
  async function saveLocalConfig(data) {
131
132
  const configPath = await getConfigPath();
132
133
  const configFilePath = path__default.join(configPath, CONFIG_FILENAME);
133
- await fse.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
134
+ await fse__default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
134
135
  }
135
136
  const name = "@strapi/cloud-cli";
136
- const version = "5.0.0-rc.10";
137
+ const version = "5.0.0-rc.12";
137
138
  const description = "Commands to interact with the Strapi Cloud";
138
139
  const keywords = [
139
140
  "strapi",
@@ -174,11 +175,12 @@ const scripts = {
174
175
  build: "pack-up build",
175
176
  clean: "run -T rimraf ./dist",
176
177
  lint: "run -T eslint .",
178
+ "test:unit": "run -T jest",
177
179
  watch: "pack-up watch"
178
180
  };
179
181
  const dependencies = {
180
182
  "@strapi/utils": "workspace:*",
181
- axios: "1.6.8",
183
+ axios: "1.7.4",
182
184
  chalk: "4.1.2",
183
185
  "cli-progress": "3.12.0",
184
186
  commander: "8.3.0",
@@ -256,7 +258,7 @@ async function cloudApiFactory({ logger }, token) {
256
258
  deploy({ filePath, project }, { onUploadProgress }) {
257
259
  return axiosCloudAPI.post(
258
260
  `/deploy/${project.name}`,
259
- { file: fse.createReadStream(filePath) },
261
+ { file: fse__default.createReadStream(filePath) },
260
262
  {
261
263
  headers: {
262
264
  "Content-Type": "multipart/form-data"
@@ -299,8 +301,47 @@ async function cloudApiFactory({ logger }, token) {
299
301
  throw error;
300
302
  }
301
303
  },
302
- listProjects() {
303
- return axiosCloudAPI.get("/projects");
304
+ async listProjects() {
305
+ try {
306
+ const response = await axiosCloudAPI.get("/projects");
307
+ if (response.status !== 200) {
308
+ throw new Error("Error fetching cloud projects from the server.");
309
+ }
310
+ return response;
311
+ } catch (error) {
312
+ logger.debug(
313
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
314
+ );
315
+ throw error;
316
+ }
317
+ },
318
+ async listLinkProjects() {
319
+ try {
320
+ const response = await axiosCloudAPI.get("/projects-linkable");
321
+ if (response.status !== 200) {
322
+ throw new Error("Error fetching cloud projects from the server.");
323
+ }
324
+ return response;
325
+ } catch (error) {
326
+ logger.debug(
327
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
328
+ );
329
+ throw error;
330
+ }
331
+ },
332
+ async getProject({ name: name2 }) {
333
+ try {
334
+ const response = await axiosCloudAPI.get(`/projects/${name2}`);
335
+ if (response.status !== 200) {
336
+ throw new Error("Error fetching project's details.");
337
+ }
338
+ return response;
339
+ } catch (error) {
340
+ logger.debug(
341
+ "🥲 Oops! There was a problem retrieving your project's details. Please try again."
342
+ );
343
+ throw error;
344
+ }
304
345
  },
305
346
  track(event, payload = {}) {
306
347
  return axiosCloudAPI.post("/track", {
@@ -315,18 +356,18 @@ async function save(data, { directoryPath } = {}) {
315
356
  const alreadyInFileData = await retrieve({ directoryPath });
316
357
  const storedData = { ...alreadyInFileData, ...data };
317
358
  const pathToFile = path__default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
318
- await fse.ensureDir(path__default.dirname(pathToFile));
319
- await fse.writeJson(pathToFile, storedData, { encoding: "utf8" });
359
+ await fse__default.ensureDir(path__default.dirname(pathToFile));
360
+ await fse__default.writeJson(pathToFile, storedData, { encoding: "utf8" });
320
361
  }
321
362
  async function retrieve({
322
363
  directoryPath
323
364
  } = {}) {
324
365
  const pathToFile = path__default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
325
- const pathExists = await fse.pathExists(pathToFile);
366
+ const pathExists = await fse__default.pathExists(pathToFile);
326
367
  if (!pathExists) {
327
368
  return {};
328
369
  }
329
- return fse.readJSON(pathToFile, { encoding: "utf8" });
370
+ return fse__default.readJSON(pathToFile, { encoding: "utf8" });
330
371
  }
331
372
  const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
332
373
  __proto__: null,
@@ -571,6 +612,56 @@ const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePropert
571
612
  local: strapiInfoSave,
572
613
  tokenServiceFactory
573
614
  }, Symbol.toStringTag, { value: "Module" }));
615
+ yup.object({
616
+ name: yup.string().required(),
617
+ exports: yup.lazy(
618
+ (value) => yup.object(
619
+ typeof value === "object" ? Object.entries(value).reduce(
620
+ (acc, [key, value2]) => {
621
+ if (typeof value2 === "object") {
622
+ acc[key] = yup.object({
623
+ types: yup.string().optional(),
624
+ source: yup.string().required(),
625
+ module: yup.string().optional(),
626
+ import: yup.string().required(),
627
+ require: yup.string().required(),
628
+ default: yup.string().required()
629
+ }).noUnknown(true);
630
+ } else {
631
+ acc[key] = yup.string().matches(/^\.\/.*\.json$/).required();
632
+ }
633
+ return acc;
634
+ },
635
+ {}
636
+ ) : void 0
637
+ ).optional()
638
+ )
639
+ });
640
+ const loadPkg = async ({ cwd, logger }) => {
641
+ const pkgPath = await pkgUp({ cwd });
642
+ if (!pkgPath) {
643
+ throw new Error("Could not find a package.json in the current directory");
644
+ }
645
+ const buffer = await fse.readFile(pkgPath);
646
+ const pkg = JSON.parse(buffer.toString());
647
+ logger.debug("Loaded package.json:", os.EOL, pkg);
648
+ return pkg;
649
+ };
650
+ async function getProjectNameFromPackageJson(ctx) {
651
+ try {
652
+ const packageJson2 = await loadPkg(ctx);
653
+ return packageJson2.name || "my-strapi-project";
654
+ } catch (e) {
655
+ return "my-strapi-project";
656
+ }
657
+ }
658
+ const trackEvent = async (ctx, cloudApiService, eventName, eventData) => {
659
+ try {
660
+ await cloudApiService.track(eventName, eventData);
661
+ } catch (e) {
662
+ ctx.logger.debug(`Failed to track ${eventName}`, e);
663
+ }
664
+ };
574
665
  const openModule$1 = import("open");
575
666
  async function promptLogin(ctx) {
576
667
  const response = await inquirer.prompt([
@@ -591,13 +682,6 @@ async function loginAction(ctx) {
591
682
  const tokenService = await tokenServiceFactory(ctx);
592
683
  const existingToken = await tokenService.retrieveToken();
593
684
  const cloudApiService = await cloudApiFactory(ctx, existingToken || void 0);
594
- const trackFailedLogin = async () => {
595
- try {
596
- await cloudApiService.track("didNotLogin", { loginMethod: "cli" });
597
- } catch (e) {
598
- logger.debug("Failed to track failed login", e);
599
- }
600
- };
601
685
  if (existingToken) {
602
686
  const isTokenValid = await tokenService.isTokenValid(existingToken);
603
687
  if (isTokenValid) {
@@ -629,11 +713,7 @@ async function loginAction(ctx) {
629
713
  logger.debug(e);
630
714
  return false;
631
715
  }
632
- try {
633
- await cloudApiService.track("willLoginAttempt", {});
634
- } catch (e) {
635
- logger.debug("Failed to track login attempt", e);
636
- }
716
+ await trackEvent(ctx, cloudApiService, "willLoginAttempt", {});
637
717
  logger.debug("🔐 Creating device authentication request...", {
638
718
  client_id: cliConfig2.clientId,
639
719
  scope: cliConfig2.scope,
@@ -713,13 +793,13 @@ async function loginAction(ctx) {
713
793
  "There seems to be a problem with your login information. Please try logging in again."
714
794
  );
715
795
  spinnerFail();
716
- await trackFailedLogin();
796
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
717
797
  return false;
718
798
  }
719
799
  if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
720
800
  logger.debug(e);
721
801
  spinnerFail();
722
- await trackFailedLogin();
802
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
723
803
  return false;
724
804
  }
725
805
  await new Promise((resolve) => {
@@ -733,15 +813,50 @@ async function loginAction(ctx) {
733
813
  "To access your dashboard, please copy and paste the following URL into your web browser:"
734
814
  );
735
815
  logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
736
- try {
737
- await cloudApiService.track("didLogin", { loginMethod: "cli" });
738
- } catch (e) {
739
- logger.debug("Failed to track login", e);
740
- }
816
+ await trackEvent(ctx, cloudApiService, "didLogin", { loginMethod: "cli" });
741
817
  };
742
818
  await authenticate();
743
819
  return isAuthenticated;
744
820
  }
821
+ function questionDefaultValuesMapper(questionsMap) {
822
+ return (questions) => {
823
+ return questions.map((question) => {
824
+ const questionName = question.name;
825
+ if (questionName in questionsMap) {
826
+ const questionDefault = questionsMap[questionName];
827
+ if (typeof questionDefault === "function") {
828
+ return {
829
+ ...question,
830
+ default: questionDefault(question)
831
+ };
832
+ }
833
+ return {
834
+ ...question,
835
+ default: questionDefault
836
+ };
837
+ }
838
+ return question;
839
+ });
840
+ };
841
+ }
842
+ function getDefaultsFromQuestions(questions) {
843
+ return questions.reduce((acc, question) => {
844
+ if (question.default && question.name) {
845
+ return { ...acc, [question.name]: question.default };
846
+ }
847
+ return acc;
848
+ }, {});
849
+ }
850
+ function getProjectNodeVersionDefault(question) {
851
+ const currentNodeVersion = process.versions.node.split(".")[0];
852
+ if (question.type === "list" && Array.isArray(question.choices)) {
853
+ const choice = question.choices.find((choice2) => choice2.value === currentNodeVersion);
854
+ if (choice) {
855
+ return choice.value;
856
+ }
857
+ }
858
+ return question.default;
859
+ }
745
860
  async function handleError(ctx, error) {
746
861
  const { logger } = ctx;
747
862
  logger.debug(error);
@@ -786,7 +901,7 @@ async function createProject$1(ctx, cloudApi, projectInput) {
786
901
  throw e;
787
902
  }
788
903
  }
789
- const action$2 = async (ctx) => {
904
+ const action$4 = async (ctx) => {
790
905
  const { logger } = ctx;
791
906
  const { getValidToken, eraseToken } = await tokenServiceFactory(ctx);
792
907
  const token = await getValidToken(ctx, promptLogin);
@@ -795,7 +910,16 @@ const action$2 = async (ctx) => {
795
910
  }
796
911
  const cloudApi = await cloudApiFactory(ctx, token);
797
912
  const { data: config } = await cloudApi.config();
798
- const { questions, defaults: defaultValues } = config.projectCreation;
913
+ const projectName = await getProjectNameFromPackageJson(ctx);
914
+ const defaultAnswersMapper = questionDefaultValuesMapper({
915
+ name: projectName,
916
+ nodeVersion: getProjectNodeVersionDefault
917
+ });
918
+ const questions = defaultAnswersMapper(config.projectCreation.questions);
919
+ const defaultValues = {
920
+ ...config.projectCreation.defaults,
921
+ ...getDefaultsFromQuestions(questions)
922
+ };
799
923
  const projectAnswersDefaulted = defaults(defaultValues);
800
924
  const projectAnswers = await inquirer.prompt(questions);
801
925
  const projectInput = projectAnswersDefaulted(projectAnswers);
@@ -844,41 +968,6 @@ function notificationServiceFactory({ logger }) {
844
968
  };
845
969
  };
846
970
  }
847
- yup.object({
848
- name: yup.string().required(),
849
- exports: yup.lazy(
850
- (value) => yup.object(
851
- typeof value === "object" ? Object.entries(value).reduce(
852
- (acc, [key, value2]) => {
853
- if (typeof value2 === "object") {
854
- acc[key] = yup.object({
855
- types: yup.string().optional(),
856
- source: yup.string().required(),
857
- module: yup.string().optional(),
858
- import: yup.string().required(),
859
- require: yup.string().required(),
860
- default: yup.string().required()
861
- }).noUnknown(true);
862
- } else {
863
- acc[key] = yup.string().matches(/^\.\/.*\.json$/).required();
864
- }
865
- return acc;
866
- },
867
- {}
868
- ) : void 0
869
- ).optional()
870
- )
871
- });
872
- const loadPkg = async ({ cwd, logger }) => {
873
- const pkgPath = await pkgUp({ cwd });
874
- if (!pkgPath) {
875
- throw new Error("Could not find a package.json in the current directory");
876
- }
877
- const buffer = await fs$1.readFile(pkgPath);
878
- const pkg = JSON.parse(buffer.toString());
879
- logger.debug("Loaded package.json:", os.EOL, pkg);
880
- return pkg;
881
- };
882
971
  const buildLogsServiceFactory = ({ logger }) => {
883
972
  return async (url, token, cliConfig2) => {
884
973
  const CONN_TIMEOUT = Number(cliConfig2.buildLogsConnectionTimeout);
@@ -932,6 +1021,7 @@ const buildLogsServiceFactory = ({ logger }) => {
932
1021
  if (retries > MAX_RETRIES) {
933
1022
  spinner.fail("We were unable to connect to the server to get build logs at this time.");
934
1023
  es.close();
1024
+ clearExistingTimeout();
935
1025
  reject(new Error("Max retries reached"));
936
1026
  }
937
1027
  };
@@ -974,13 +1064,13 @@ async function upload(ctx, project, token, maxProjectFileSize) {
974
1064
  process.exit(1);
975
1065
  }
976
1066
  const tarFilePath = path__default.resolve(storagePath, compressedFilename);
977
- const fileStats = await fse.stat(tarFilePath);
1067
+ const fileStats = await fse__default.stat(tarFilePath);
978
1068
  if (fileStats.size > maxProjectFileSize) {
979
1069
  ctx.logger.log(
980
1070
  "Unable to proceed: Your project is too big to be transferred, please use a git repo instead."
981
1071
  );
982
1072
  try {
983
- await fse.remove(tarFilePath);
1073
+ await fse__default.remove(tarFilePath);
984
1074
  } catch (e) {
985
1075
  ctx.logger.log("Unable to remove file: ", tarFilePath);
986
1076
  ctx.logger.debug(e);
@@ -1006,20 +1096,10 @@ async function upload(ctx, project, token, maxProjectFileSize) {
1006
1096
  return data.build_id;
1007
1097
  } catch (e) {
1008
1098
  progressBar.stop();
1009
- if (e instanceof AxiosError && e.response?.data) {
1010
- if (e.response.status === 404) {
1011
- ctx.logger.error(
1012
- `The project does not exist. Remove the ${LOCAL_SAVE_FILENAME} file and try again.`
1013
- );
1014
- } else {
1015
- ctx.logger.error(e.response.data);
1016
- }
1017
- } else {
1018
- ctx.logger.error("An error occurred while deploying the project. Please try again later.");
1019
- }
1099
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
1020
1100
  ctx.logger.debug(e);
1021
1101
  } finally {
1022
- await fse.remove(tarFilePath);
1102
+ await fse__default.remove(tarFilePath);
1023
1103
  }
1024
1104
  process.exit(0);
1025
1105
  } catch (e) {
@@ -1032,7 +1112,7 @@ async function getProject(ctx) {
1032
1112
  const { project } = await retrieve();
1033
1113
  if (!project) {
1034
1114
  try {
1035
- return await action$2(ctx);
1115
+ return await action$4(ctx);
1036
1116
  } catch (e) {
1037
1117
  ctx.logger.error("An error occurred while deploying the project. Please try again later.");
1038
1118
  ctx.logger.debug(e);
@@ -1041,7 +1121,19 @@ async function getProject(ctx) {
1041
1121
  }
1042
1122
  return project;
1043
1123
  }
1044
- const action$1 = async (ctx) => {
1124
+ async function getConfig({
1125
+ ctx,
1126
+ cloudApiService
1127
+ }) {
1128
+ try {
1129
+ const { data: cliConfig2 } = await cloudApiService.config();
1130
+ return cliConfig2;
1131
+ } catch (e) {
1132
+ ctx.logger.debug("Failed to get cli config", e);
1133
+ return null;
1134
+ }
1135
+ }
1136
+ const action$3 = async (ctx) => {
1045
1137
  const { getValidToken } = await tokenServiceFactory(ctx);
1046
1138
  const token = await getValidToken(ctx, promptLogin);
1047
1139
  if (!token) {
@@ -1051,15 +1143,51 @@ const action$1 = async (ctx) => {
1051
1143
  if (!project) {
1052
1144
  return;
1053
1145
  }
1054
- const cloudApiService = await cloudApiFactory(ctx);
1146
+ const cloudApiService = await cloudApiFactory(ctx, token);
1055
1147
  try {
1056
- await cloudApiService.track("willDeployWithCLI", { projectInternalName: project.name });
1148
+ const {
1149
+ data: { data: projectData, metadata }
1150
+ } = await cloudApiService.getProject({ name: project.name });
1151
+ const isProjectSuspended = projectData.suspendedAt;
1152
+ if (isProjectSuspended) {
1153
+ ctx.logger.log(
1154
+ "\n Oops! This project has been suspended. \n\n Please reactivate it from the dashboard to continue deploying: "
1155
+ );
1156
+ ctx.logger.log(chalk.underline(`${metadata.dashboardUrls.project}`));
1157
+ return;
1158
+ }
1057
1159
  } catch (e) {
1058
- ctx.logger.debug("Failed to track willDeploy", e);
1160
+ if (e instanceof AxiosError && e.response?.data) {
1161
+ if (e.response.status === 404) {
1162
+ ctx.logger.warn(
1163
+ `The project associated with this folder does not exist in Strapi Cloud.
1164
+ Please link your local project to an existing Strapi Cloud project using the ${chalk.cyan(
1165
+ "link"
1166
+ )} command before deploying.`
1167
+ );
1168
+ } else {
1169
+ ctx.logger.error(e.response.data);
1170
+ }
1171
+ } else {
1172
+ ctx.logger.error(
1173
+ "An error occurred while retrieving the project's information. Please try again later."
1174
+ );
1175
+ }
1176
+ ctx.logger.debug(e);
1177
+ return;
1059
1178
  }
1179
+ await trackEvent(ctx, cloudApiService, "willDeployWithCLI", {
1180
+ projectInternalName: project.name
1181
+ });
1060
1182
  const notificationService = notificationServiceFactory(ctx);
1061
1183
  const buildLogsService = buildLogsServiceFactory(ctx);
1062
- const { data: cliConfig2 } = await cloudApiService.config();
1184
+ const cliConfig2 = await getConfig({ ctx, cloudApiService });
1185
+ if (!cliConfig2) {
1186
+ ctx.logger.error(
1187
+ "An error occurred while retrieving data from Strapi Cloud. Please check your network or try again later."
1188
+ );
1189
+ return;
1190
+ }
1063
1191
  let maxSize = parseInt(cliConfig2.maxProjectFileSize, 10);
1064
1192
  if (Number.isNaN(maxSize)) {
1065
1193
  ctx.logger.debug(
@@ -1081,10 +1209,11 @@ const action$1 = async (ctx) => {
1081
1209
  chalk.underline(`${apiConfig.dashboardBaseUrl}/projects/${project.name}/deployments`)
1082
1210
  );
1083
1211
  } catch (e) {
1212
+ ctx.logger.debug(e);
1084
1213
  if (e instanceof Error) {
1085
1214
  ctx.logger.error(e.message);
1086
1215
  } else {
1087
- throw e;
1216
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
1088
1217
  }
1089
1218
  }
1090
1219
  };
@@ -1115,16 +1244,162 @@ const runAction = (name2, action2) => (...args) => {
1115
1244
  process.exit(1);
1116
1245
  });
1117
1246
  };
1118
- const command$3 = ({ ctx }) => {
1119
- return 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").action(() => runAction("deploy", action$1)(ctx));
1247
+ const command$5 = ({ ctx }) => {
1248
+ return 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").action(() => runAction("deploy", action$3)(ctx));
1120
1249
  };
1121
1250
  const deployProject = {
1122
1251
  name: "deploy-project",
1123
1252
  description: "Deploy a Strapi Cloud project",
1124
- action: action$1,
1125
- command: command$3
1253
+ action: action$3,
1254
+ command: command$5
1126
1255
  };
1127
- const command$2 = ({ ctx }) => {
1256
+ const QUIT_OPTION = "Quit";
1257
+ async function getExistingConfig(ctx) {
1258
+ try {
1259
+ return await retrieve();
1260
+ } catch (e) {
1261
+ ctx.logger.debug("Failed to get project config", e);
1262
+ ctx.logger.error("An error occurred while retrieving config data from your local project.");
1263
+ return null;
1264
+ }
1265
+ }
1266
+ async function promptForRelink(ctx, cloudApiService, existingConfig) {
1267
+ if (existingConfig && existingConfig.project) {
1268
+ const { shouldRelink } = await inquirer.prompt([
1269
+ {
1270
+ type: "confirm",
1271
+ name: "shouldRelink",
1272
+ message: `A project named ${chalk.cyan(
1273
+ existingConfig.project.displayName ? existingConfig.project.displayName : existingConfig.project.name
1274
+ )} is already linked to this local folder. Do you want to update the link?`,
1275
+ default: false
1276
+ }
1277
+ ]);
1278
+ if (!shouldRelink) {
1279
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1280
+ currentProjectName: existingConfig.project?.name
1281
+ });
1282
+ return false;
1283
+ }
1284
+ }
1285
+ return true;
1286
+ }
1287
+ async function getProjectsList(ctx, cloudApiService, existingConfig) {
1288
+ const spinner = ctx.logger.spinner("Fetching your projects...\n").start();
1289
+ try {
1290
+ const {
1291
+ data: { data: projectList }
1292
+ } = await cloudApiService.listLinkProjects();
1293
+ spinner.succeed();
1294
+ if (!Array.isArray(projectList)) {
1295
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1296
+ return null;
1297
+ }
1298
+ const projects = projectList.filter(
1299
+ (project) => !(project.isMaintainer || project.name === existingConfig?.project?.name)
1300
+ ).map((project) => {
1301
+ return {
1302
+ name: project.displayName,
1303
+ value: { name: project.name, displayName: project.displayName }
1304
+ };
1305
+ });
1306
+ if (projects.length === 0) {
1307
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1308
+ return null;
1309
+ }
1310
+ return projects;
1311
+ } catch (e) {
1312
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1313
+ ctx.logger.debug("Failed to list projects", e);
1314
+ return null;
1315
+ }
1316
+ }
1317
+ async function getUserSelection(ctx, projects) {
1318
+ const { logger } = ctx;
1319
+ try {
1320
+ const answer = await inquirer.prompt([
1321
+ {
1322
+ type: "list",
1323
+ name: "linkProject",
1324
+ message: "Which project do you want to link?",
1325
+ choices: [...projects, { name: chalk.grey(`(${QUIT_OPTION})`), value: null }]
1326
+ }
1327
+ ]);
1328
+ if (!answer.linkProject) {
1329
+ return null;
1330
+ }
1331
+ return answer;
1332
+ } catch (e) {
1333
+ logger.debug("Failed to get user input", e);
1334
+ logger.error("An error occurred while trying to get your input.");
1335
+ return null;
1336
+ }
1337
+ }
1338
+ const action$2 = async (ctx) => {
1339
+ const { getValidToken } = await tokenServiceFactory(ctx);
1340
+ const token = await getValidToken(ctx, promptLogin);
1341
+ const { logger } = ctx;
1342
+ if (!token) {
1343
+ return;
1344
+ }
1345
+ const cloudApiService = await cloudApiFactory(ctx, token);
1346
+ const existingConfig = await getExistingConfig(ctx);
1347
+ const shouldRelink = await promptForRelink(ctx, cloudApiService, existingConfig);
1348
+ if (!shouldRelink) {
1349
+ return;
1350
+ }
1351
+ await trackEvent(ctx, cloudApiService, "willLinkProject", {});
1352
+ const projects = await getProjectsList(
1353
+ ctx,
1354
+ cloudApiService,
1355
+ existingConfig
1356
+ );
1357
+ if (!projects) {
1358
+ return;
1359
+ }
1360
+ const answer = await getUserSelection(ctx, projects);
1361
+ if (!answer) {
1362
+ return;
1363
+ }
1364
+ try {
1365
+ const { confirmAction } = await inquirer.prompt([
1366
+ {
1367
+ type: "confirm",
1368
+ name: "confirmAction",
1369
+ message: "Warning: Once linked, deploying from CLI will replace the existing project and its data. Confirm to proceed:",
1370
+ default: false
1371
+ }
1372
+ ]);
1373
+ if (!confirmAction) {
1374
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1375
+ cancelledProjectName: answer.linkProject.name,
1376
+ currentProjectName: existingConfig ? existingConfig.project?.name : null
1377
+ });
1378
+ return;
1379
+ }
1380
+ await save({ project: answer.linkProject });
1381
+ logger.log(`Project ${chalk.cyan(answer.linkProject.displayName)} linked successfully.`);
1382
+ await trackEvent(ctx, cloudApiService, "didLinkProject", {
1383
+ projectInternalName: answer.linkProject
1384
+ });
1385
+ } catch (e) {
1386
+ logger.debug("Failed to link project", e);
1387
+ logger.error("An error occurred while linking the project.");
1388
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1389
+ projectInternalName: answer.linkProject
1390
+ });
1391
+ }
1392
+ };
1393
+ const command$4 = ({ command: command2, ctx }) => {
1394
+ 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));
1395
+ };
1396
+ const link = {
1397
+ name: "link-project",
1398
+ description: "Link a local directory to a Strapi Cloud project",
1399
+ action: action$2,
1400
+ command: command$4
1401
+ };
1402
+ const command$3 = ({ ctx }) => {
1128
1403
  return createCommand("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1129
1404
  "after",
1130
1405
  "\nAfter running this command, you will be prompted to enter your authentication information."
@@ -1134,10 +1409,10 @@ const login = {
1134
1409
  name: "login",
1135
1410
  description: "Strapi Cloud Login",
1136
1411
  action: loginAction,
1137
- command: command$2
1412
+ command: command$3
1138
1413
  };
1139
1414
  const openModule = import("open");
1140
- const action = async (ctx) => {
1415
+ const action$1 = async (ctx) => {
1141
1416
  const { logger } = ctx;
1142
1417
  const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx);
1143
1418
  const token = await retrieveToken();
@@ -1167,37 +1442,64 @@ const action = async (ctx) => {
1167
1442
  logger.error("🥲 Oops! Something went wrong while logging you out. Please try again.");
1168
1443
  logger.debug(e);
1169
1444
  }
1170
- try {
1171
- await cloudApiService.track("didLogout", { loginMethod: "cli" });
1172
- } catch (e) {
1173
- logger.debug("Failed to track logout event", e);
1174
- }
1445
+ await trackEvent(ctx, cloudApiService, "didLogout", { loginMethod: "cli" });
1175
1446
  };
1176
- const command$1 = ({ ctx }) => {
1177
- return 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)(ctx));
1447
+ const command$2 = ({ ctx }) => {
1448
+ return 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$1)(ctx));
1178
1449
  };
1179
1450
  const logout = {
1180
1451
  name: "logout",
1181
1452
  description: "Strapi Cloud Logout",
1182
- action,
1183
- command: command$1
1453
+ action: action$1,
1454
+ command: command$2
1184
1455
  };
1185
- const command = ({ ctx }) => {
1186
- return 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$2)(ctx));
1456
+ const command$1 = ({ ctx }) => {
1457
+ return 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$4)(ctx));
1187
1458
  };
1188
1459
  const createProject = {
1189
1460
  name: "create-project",
1190
1461
  description: "Create a new project",
1191
- action: action$2,
1462
+ action: action$4,
1463
+ command: command$1
1464
+ };
1465
+ const action = async (ctx) => {
1466
+ const { getValidToken } = await tokenServiceFactory(ctx);
1467
+ const token = await getValidToken(ctx, promptLogin);
1468
+ const { logger } = ctx;
1469
+ if (!token) {
1470
+ return;
1471
+ }
1472
+ const cloudApiService = await cloudApiFactory(ctx, token);
1473
+ const spinner = logger.spinner("Fetching your projects...").start();
1474
+ try {
1475
+ const {
1476
+ data: { data: projectList }
1477
+ } = await cloudApiService.listProjects();
1478
+ spinner.succeed();
1479
+ logger.log(projectList);
1480
+ } catch (e) {
1481
+ ctx.logger.debug("Failed to list projects", e);
1482
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1483
+ }
1484
+ };
1485
+ const command = ({ command: command2, ctx }) => {
1486
+ 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));
1487
+ };
1488
+ const listProjects = {
1489
+ name: "list-projects",
1490
+ description: "List Strapi Cloud projects",
1491
+ action,
1192
1492
  command
1193
1493
  };
1194
1494
  const cli = {
1195
1495
  deployProject,
1496
+ link,
1196
1497
  login,
1197
1498
  logout,
1198
- createProject
1499
+ createProject,
1500
+ listProjects
1199
1501
  };
1200
- const cloudCommands = [deployProject, login, logout];
1502
+ const cloudCommands = [deployProject, link, login, logout, listProjects];
1201
1503
  async function initCloudCLIConfig() {
1202
1504
  const localConfig = await getLocalConfig();
1203
1505
  if (!localConfig.deviceId) {