@strapi/cloud-cli 0.0.0-next.84f5cfd43cfdb85f000d388b196a36d874382dab → 0.0.0-next.852f43d1ddd36786b695b80b6dbef65a785954e4

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 (40) 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
  39. package/dist/src/utils/tests/compress-files.test.d.ts +0 -2
  40. package/dist/src/utils/tests/compress-files.test.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -29,7 +29,6 @@ const chalk = require("chalk");
29
29
  const axios = require("axios");
30
30
  const crypto = require("node:crypto");
31
31
  const utils = require("@strapi/utils");
32
- const fs = require("fs");
33
32
  const tar = require("tar");
34
33
  const minimatch = require("minimatch");
35
34
  const inquirer = require("inquirer");
@@ -41,10 +40,9 @@ const jwt = require("jsonwebtoken");
41
40
  const stringify = require("fast-safe-stringify");
42
41
  const ora = require("ora");
43
42
  const cliProgress = require("cli-progress");
44
- const EventSource = require("eventsource");
45
- const fs$1 = require("fs/promises");
46
43
  const pkgUp = require("pkg-up");
47
44
  const yup = require("yup");
45
+ const EventSource = require("eventsource");
48
46
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
49
47
  function _interopNamespace(e) {
50
48
  if (e && e.__esModule)
@@ -65,12 +63,11 @@ function _interopNamespace(e) {
65
63
  return Object.freeze(n);
66
64
  }
67
65
  const crypto__default = /* @__PURE__ */ _interopDefault(crypto$1);
68
- const fse__default = /* @__PURE__ */ _interopDefault(fse);
66
+ const fse__namespace = /* @__PURE__ */ _interopNamespace(fse);
69
67
  const path__namespace = /* @__PURE__ */ _interopNamespace(path);
70
68
  const chalk__default = /* @__PURE__ */ _interopDefault(chalk);
71
69
  const axios__default = /* @__PURE__ */ _interopDefault(axios);
72
70
  const crypto__namespace = /* @__PURE__ */ _interopNamespace(crypto);
73
- const fs__namespace = /* @__PURE__ */ _interopNamespace(fs);
74
71
  const tar__namespace = /* @__PURE__ */ _interopNamespace(tar);
75
72
  const inquirer__default = /* @__PURE__ */ _interopDefault(inquirer);
76
73
  const os__default = /* @__PURE__ */ _interopDefault(os);
@@ -80,10 +77,9 @@ const jwt__default = /* @__PURE__ */ _interopDefault(jwt);
80
77
  const stringify__default = /* @__PURE__ */ _interopDefault(stringify);
81
78
  const ora__default = /* @__PURE__ */ _interopDefault(ora);
82
79
  const cliProgress__namespace = /* @__PURE__ */ _interopNamespace(cliProgress);
83
- const EventSource__default = /* @__PURE__ */ _interopDefault(EventSource);
84
- const fs__default = /* @__PURE__ */ _interopDefault(fs$1);
85
80
  const pkgUp__default = /* @__PURE__ */ _interopDefault(pkgUp);
86
81
  const yup__namespace = /* @__PURE__ */ _interopNamespace(yup);
82
+ const EventSource__default = /* @__PURE__ */ _interopDefault(EventSource);
87
83
  const apiConfig = {
88
84
  apiBaseUrl: utils.env("STRAPI_CLI_CLOUD_API", "https://cloud-cli-api.strapi.io"),
89
85
  dashboardBaseUrl: utils.env("STRAPI_CLI_CLOUD_DASHBOARD", "https://cloud.strapi.io")
@@ -102,23 +98,6 @@ const IGNORED_PATTERNS = [
102
98
  "**/.idea/**",
103
99
  "**/.vscode/**"
104
100
  ];
105
- const getFiles = (dirPath, ignorePatterns = [], arrayOfFiles = [], subfolder = "") => {
106
- const entries = fs__namespace.readdirSync(path__namespace.join(dirPath, subfolder));
107
- entries.forEach((entry) => {
108
- const entryPathFromRoot = path__namespace.join(subfolder, entry);
109
- const entryPath = path__namespace.relative(dirPath, entryPathFromRoot);
110
- const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
111
- if (isIgnored) {
112
- return;
113
- }
114
- if (fs__namespace.statSync(entryPath).isDirectory()) {
115
- getFiles(dirPath, ignorePatterns, arrayOfFiles, entryPathFromRoot);
116
- } else {
117
- arrayOfFiles.push(entryPath);
118
- }
119
- });
120
- return arrayOfFiles;
121
- };
122
101
  const isIgnoredFile = (folderPath, file, ignorePatterns) => {
123
102
  ignorePatterns.push(...IGNORED_PATTERNS);
124
103
  const relativeFilePath = path__namespace.join(folderPath, file);
@@ -136,16 +115,35 @@ const isIgnoredFile = (folderPath, file, ignorePatterns) => {
136
115
  }
137
116
  return isIgnored;
138
117
  };
139
- const readGitignore = (folderPath) => {
118
+ const getFiles = async (dirPath, ignorePatterns = [], subfolder = "") => {
119
+ const arrayOfFiles = [];
120
+ const entries = await fse__namespace.readdir(path__namespace.join(dirPath, subfolder));
121
+ for (const entry of entries) {
122
+ const entryPathFromRoot = path__namespace.join(subfolder, entry);
123
+ const entryPath = path__namespace.relative(dirPath, entryPathFromRoot);
124
+ const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
125
+ if (!isIgnored) {
126
+ if (fse__namespace.statSync(entryPath).isDirectory()) {
127
+ const subFiles = await getFiles(dirPath, ignorePatterns, entryPathFromRoot);
128
+ arrayOfFiles.push(...subFiles);
129
+ } else {
130
+ arrayOfFiles.push(entryPath);
131
+ }
132
+ }
133
+ }
134
+ return arrayOfFiles;
135
+ };
136
+ const readGitignore = async (folderPath) => {
140
137
  const gitignorePath = path__namespace.resolve(folderPath, ".gitignore");
141
- if (!fs__namespace.existsSync(gitignorePath))
138
+ const pathExist = await fse__namespace.pathExists(gitignorePath);
139
+ if (!pathExist)
142
140
  return [];
143
- const gitignoreContent = fs__namespace.readFileSync(gitignorePath, "utf8");
141
+ const gitignoreContent = await fse__namespace.readFile(gitignorePath, "utf8");
144
142
  return gitignoreContent.split(/\r?\n/).filter((line) => Boolean(line.trim()) && !line.startsWith("#"));
145
143
  };
146
144
  const compressFilesToTar = async (storagePath, folderToCompress, filename) => {
147
- const ignorePatterns = readGitignore(folderToCompress);
148
- const filesToCompress = getFiles(folderToCompress, ignorePatterns);
145
+ const ignorePatterns = await readGitignore(folderToCompress);
146
+ const filesToCompress = await getFiles(folderToCompress, ignorePatterns);
149
147
  return tar__namespace.c(
150
148
  {
151
149
  gzip: true,
@@ -158,7 +156,7 @@ const APP_FOLDER_NAME = "com.strapi.cli";
158
156
  const CONFIG_FILENAME = "config.json";
159
157
  async function checkDirectoryExists(directoryPath) {
160
158
  try {
161
- const fsStat = await fse__default.default.lstat(directoryPath);
159
+ const fsStat = await fse__namespace.default.lstat(directoryPath);
162
160
  return fsStat.isDirectory();
163
161
  } catch (e) {
164
162
  return false;
@@ -166,14 +164,14 @@ async function checkDirectoryExists(directoryPath) {
166
164
  }
167
165
  async function getTmpStoragePath() {
168
166
  const storagePath = path__namespace.default.join(os__default.default.tmpdir(), APP_FOLDER_NAME);
169
- await fse__default.default.ensureDir(storagePath);
167
+ await fse__namespace.default.ensureDir(storagePath);
170
168
  return storagePath;
171
169
  }
172
170
  async function getConfigPath() {
173
171
  const configDirs = XDGAppPaths__default.default(APP_FOLDER_NAME).configDirs();
174
172
  const configPath = configDirs.find(checkDirectoryExists);
175
173
  if (!configPath) {
176
- await fse__default.default.ensureDir(configDirs[0]);
174
+ await fse__namespace.default.ensureDir(configDirs[0]);
177
175
  return configDirs[0];
178
176
  }
179
177
  return configPath;
@@ -181,9 +179,9 @@ async function getConfigPath() {
181
179
  async function getLocalConfig() {
182
180
  const configPath = await getConfigPath();
183
181
  const configFilePath = path__namespace.default.join(configPath, CONFIG_FILENAME);
184
- await fse__default.default.ensureFile(configFilePath);
182
+ await fse__namespace.default.ensureFile(configFilePath);
185
183
  try {
186
- return await fse__default.default.readJSON(configFilePath, { encoding: "utf8", throws: true });
184
+ return await fse__namespace.default.readJSON(configFilePath, { encoding: "utf8", throws: true });
187
185
  } catch (e) {
188
186
  return {};
189
187
  }
@@ -191,10 +189,10 @@ async function getLocalConfig() {
191
189
  async function saveLocalConfig(data) {
192
190
  const configPath = await getConfigPath();
193
191
  const configFilePath = path__namespace.default.join(configPath, CONFIG_FILENAME);
194
- await fse__default.default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
192
+ await fse__namespace.default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
195
193
  }
196
194
  const name = "@strapi/cloud-cli";
197
- const version = "4.25.1";
195
+ const version = "4.25.10";
198
196
  const description = "Commands to interact with the Strapi Cloud";
199
197
  const keywords = [
200
198
  "strapi",
@@ -235,11 +233,12 @@ const scripts = {
235
233
  build: "pack-up build",
236
234
  clean: "run -T rimraf ./dist",
237
235
  lint: "run -T eslint .",
236
+ "test:unit": "run -T jest",
238
237
  watch: "pack-up watch"
239
238
  };
240
239
  const dependencies = {
241
- "@strapi/utils": "4.25.1",
242
- axios: "1.6.0",
240
+ "@strapi/utils": "4.25.10",
241
+ axios: "1.7.4",
243
242
  chalk: "4.1.2",
244
243
  "cli-progress": "3.12.0",
245
244
  commander: "8.3.0",
@@ -263,8 +262,8 @@ const devDependencies = {
263
262
  "@types/cli-progress": "3.11.5",
264
263
  "@types/eventsource": "1.1.15",
265
264
  "@types/lodash": "^4.14.191",
266
- "eslint-config-custom": "4.25.1",
267
- tsconfig: "4.25.1"
265
+ "eslint-config-custom": "4.25.10",
266
+ tsconfig: "4.25.10"
268
267
  };
269
268
  const engines = {
270
269
  node: ">=18.0.0 <=20.x.x",
@@ -317,7 +316,7 @@ async function cloudApiFactory({ logger }, token) {
317
316
  deploy({ filePath, project }, { onUploadProgress }) {
318
317
  return axiosCloudAPI.post(
319
318
  `/deploy/${project.name}`,
320
- { file: fse__default.default.createReadStream(filePath) },
319
+ { file: fse__namespace.default.createReadStream(filePath) },
321
320
  {
322
321
  headers: {
323
322
  "Content-Type": "multipart/form-data"
@@ -360,8 +359,47 @@ async function cloudApiFactory({ logger }, token) {
360
359
  throw error;
361
360
  }
362
361
  },
363
- listProjects() {
364
- return axiosCloudAPI.get("/projects");
362
+ async listProjects() {
363
+ try {
364
+ const response = await axiosCloudAPI.get("/projects");
365
+ if (response.status !== 200) {
366
+ throw new Error("Error fetching cloud projects from the server.");
367
+ }
368
+ return response;
369
+ } catch (error) {
370
+ logger.debug(
371
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
372
+ );
373
+ throw error;
374
+ }
375
+ },
376
+ async listLinkProjects() {
377
+ try {
378
+ const response = await axiosCloudAPI.get("/projects-linkable");
379
+ if (response.status !== 200) {
380
+ throw new Error("Error fetching cloud projects from the server.");
381
+ }
382
+ return response;
383
+ } catch (error) {
384
+ logger.debug(
385
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
386
+ );
387
+ throw error;
388
+ }
389
+ },
390
+ async getProject({ name: name2 }) {
391
+ try {
392
+ const response = await axiosCloudAPI.get(`/projects/${name2}`);
393
+ if (response.status !== 200) {
394
+ throw new Error("Error fetching project's details.");
395
+ }
396
+ return response;
397
+ } catch (error) {
398
+ logger.debug(
399
+ "🥲 Oops! There was a problem retrieving your project's details. Please try again."
400
+ );
401
+ throw error;
402
+ }
365
403
  },
366
404
  track(event, payload = {}) {
367
405
  return axiosCloudAPI.post("/track", {
@@ -376,18 +414,18 @@ async function save(data, { directoryPath } = {}) {
376
414
  const alreadyInFileData = await retrieve({ directoryPath });
377
415
  const storedData = { ...alreadyInFileData, ...data };
378
416
  const pathToFile = path__namespace.default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
379
- await fse__default.default.ensureDir(path__namespace.default.dirname(pathToFile));
380
- await fse__default.default.writeJson(pathToFile, storedData, { encoding: "utf8" });
417
+ await fse__namespace.default.ensureDir(path__namespace.default.dirname(pathToFile));
418
+ await fse__namespace.default.writeJson(pathToFile, storedData, { encoding: "utf8" });
381
419
  }
382
420
  async function retrieve({
383
421
  directoryPath
384
422
  } = {}) {
385
423
  const pathToFile = path__namespace.default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
386
- const pathExists = await fse__default.default.pathExists(pathToFile);
424
+ const pathExists = await fse__namespace.default.pathExists(pathToFile);
387
425
  if (!pathExists) {
388
426
  return {};
389
427
  }
390
- return fse__default.default.readJSON(pathToFile, { encoding: "utf8" });
428
+ return fse__namespace.default.readJSON(pathToFile, { encoding: "utf8" });
391
429
  }
392
430
  const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
393
431
  __proto__: null,
@@ -632,6 +670,53 @@ const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePropert
632
670
  local: strapiInfoSave,
633
671
  tokenServiceFactory
634
672
  }, Symbol.toStringTag, { value: "Module" }));
673
+ yup__namespace.object({
674
+ name: yup__namespace.string().required(),
675
+ exports: yup__namespace.lazy(
676
+ (value) => yup__namespace.object(
677
+ typeof value === "object" ? Object.entries(value).reduce((acc, [key, value2]) => {
678
+ if (typeof value2 === "object") {
679
+ acc[key] = yup__namespace.object({
680
+ types: yup__namespace.string().optional(),
681
+ source: yup__namespace.string().required(),
682
+ module: yup__namespace.string().optional(),
683
+ import: yup__namespace.string().required(),
684
+ require: yup__namespace.string().required(),
685
+ default: yup__namespace.string().required()
686
+ }).noUnknown(true);
687
+ } else {
688
+ acc[key] = yup__namespace.string().matches(/^\.\/.*\.json$/).required();
689
+ }
690
+ return acc;
691
+ }, {}) : void 0
692
+ ).optional()
693
+ )
694
+ });
695
+ const loadPkg = async ({ cwd, logger }) => {
696
+ const pkgPath = await pkgUp__default.default({ cwd });
697
+ if (!pkgPath) {
698
+ throw new Error("Could not find a package.json in the current directory");
699
+ }
700
+ const buffer = await fse__namespace.readFile(pkgPath);
701
+ const pkg = JSON.parse(buffer.toString());
702
+ logger.debug("Loaded package.json:", os__default.default.EOL, pkg);
703
+ return pkg;
704
+ };
705
+ async function getProjectNameFromPackageJson(ctx) {
706
+ try {
707
+ const packageJson2 = await loadPkg(ctx);
708
+ return packageJson2.name || "my-strapi-project";
709
+ } catch (e) {
710
+ return "my-strapi-project";
711
+ }
712
+ }
713
+ const trackEvent = async (ctx, cloudApiService, eventName, eventData) => {
714
+ try {
715
+ await cloudApiService.track(eventName, eventData);
716
+ } catch (e) {
717
+ ctx.logger.debug(`Failed to track ${eventName}`, e);
718
+ }
719
+ };
635
720
  const openModule$1 = import("open");
636
721
  async function promptLogin(ctx) {
637
722
  const response = await inquirer__default.default.prompt([
@@ -652,13 +737,6 @@ async function loginAction(ctx) {
652
737
  const tokenService = await tokenServiceFactory(ctx);
653
738
  const existingToken = await tokenService.retrieveToken();
654
739
  const cloudApiService = await cloudApiFactory(ctx, existingToken || void 0);
655
- const trackFailedLogin = async () => {
656
- try {
657
- await cloudApiService.track("didNotLogin", { loginMethod: "cli" });
658
- } catch (e) {
659
- logger.debug("Failed to track failed login", e);
660
- }
661
- };
662
740
  if (existingToken) {
663
741
  const isTokenValid = await tokenService.isTokenValid(existingToken);
664
742
  if (isTokenValid) {
@@ -690,11 +768,7 @@ async function loginAction(ctx) {
690
768
  logger.debug(e);
691
769
  return false;
692
770
  }
693
- try {
694
- await cloudApiService.track("willLoginAttempt", {});
695
- } catch (e) {
696
- logger.debug("Failed to track login attempt", e);
697
- }
771
+ await trackEvent(ctx, cloudApiService, "willLoginAttempt", {});
698
772
  logger.debug("🔐 Creating device authentication request...", {
699
773
  client_id: cliConfig2.clientId,
700
774
  scope: cliConfig2.scope,
@@ -774,13 +848,13 @@ async function loginAction(ctx) {
774
848
  "There seems to be a problem with your login information. Please try logging in again."
775
849
  );
776
850
  spinnerFail();
777
- await trackFailedLogin();
851
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
778
852
  return false;
779
853
  }
780
854
  if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
781
855
  logger.debug(e);
782
856
  spinnerFail();
783
- await trackFailedLogin();
857
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
784
858
  return false;
785
859
  }
786
860
  await new Promise((resolve) => {
@@ -794,15 +868,50 @@ async function loginAction(ctx) {
794
868
  "To access your dashboard, please copy and paste the following URL into your web browser:"
795
869
  );
796
870
  logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
797
- try {
798
- await cloudApiService.track("didLogin", { loginMethod: "cli" });
799
- } catch (e) {
800
- logger.debug("Failed to track login", e);
801
- }
871
+ await trackEvent(ctx, cloudApiService, "didLogin", { loginMethod: "cli" });
802
872
  };
803
873
  await authenticate();
804
874
  return isAuthenticated;
805
875
  }
876
+ function questionDefaultValuesMapper(questionsMap) {
877
+ return (questions) => {
878
+ return questions.map((question) => {
879
+ const questionName = question.name;
880
+ if (questionName in questionsMap) {
881
+ const questionDefault = questionsMap[questionName];
882
+ if (typeof questionDefault === "function") {
883
+ return {
884
+ ...question,
885
+ default: questionDefault(question)
886
+ };
887
+ }
888
+ return {
889
+ ...question,
890
+ default: questionDefault
891
+ };
892
+ }
893
+ return question;
894
+ });
895
+ };
896
+ }
897
+ function getDefaultsFromQuestions(questions) {
898
+ return questions.reduce((acc, question) => {
899
+ if (question.default && question.name) {
900
+ return { ...acc, [question.name]: question.default };
901
+ }
902
+ return acc;
903
+ }, {});
904
+ }
905
+ function getProjectNodeVersionDefault(question) {
906
+ const currentNodeVersion = process.versions.node.split(".")[0];
907
+ if (question.type === "list" && Array.isArray(question.choices)) {
908
+ const choice = question.choices.find((choice2) => choice2.value === currentNodeVersion);
909
+ if (choice) {
910
+ return choice.value;
911
+ }
912
+ }
913
+ return question.default;
914
+ }
806
915
  async function handleError(ctx, error) {
807
916
  const { logger } = ctx;
808
917
  logger.debug(error);
@@ -847,7 +956,7 @@ async function createProject$1(ctx, cloudApi, projectInput) {
847
956
  throw e;
848
957
  }
849
958
  }
850
- const action$2 = async (ctx) => {
959
+ const action$4 = async (ctx) => {
851
960
  const { logger } = ctx;
852
961
  const { getValidToken, eraseToken } = await tokenServiceFactory(ctx);
853
962
  const token = await getValidToken(ctx, promptLogin);
@@ -856,7 +965,16 @@ const action$2 = async (ctx) => {
856
965
  }
857
966
  const cloudApi = await cloudApiFactory(ctx, token);
858
967
  const { data: config } = await cloudApi.config();
859
- const { questions, defaults: defaultValues } = config.projectCreation;
968
+ const projectName = await getProjectNameFromPackageJson(ctx);
969
+ const defaultAnswersMapper = questionDefaultValuesMapper({
970
+ name: projectName,
971
+ nodeVersion: getProjectNodeVersionDefault
972
+ });
973
+ const questions = defaultAnswersMapper(config.projectCreation.questions);
974
+ const defaultValues = {
975
+ ...config.projectCreation.defaults,
976
+ ...getDefaultsFromQuestions(questions)
977
+ };
860
978
  const projectAnswersDefaulted = fp.defaults(defaultValues);
861
979
  const projectAnswers = await inquirer__default.default.prompt(questions);
862
980
  const projectInput = projectAnswersDefaulted(projectAnswers);
@@ -905,38 +1023,6 @@ function notificationServiceFactory({ logger }) {
905
1023
  };
906
1024
  };
907
1025
  }
908
- yup__namespace.object({
909
- name: yup__namespace.string().required(),
910
- exports: yup__namespace.lazy(
911
- (value) => yup__namespace.object(
912
- typeof value === "object" ? Object.entries(value).reduce((acc, [key, value2]) => {
913
- if (typeof value2 === "object") {
914
- acc[key] = yup__namespace.object({
915
- types: yup__namespace.string().optional(),
916
- source: yup__namespace.string().required(),
917
- module: yup__namespace.string().optional(),
918
- import: yup__namespace.string().required(),
919
- require: yup__namespace.string().required(),
920
- default: yup__namespace.string().required()
921
- }).noUnknown(true);
922
- } else {
923
- acc[key] = yup__namespace.string().matches(/^\.\/.*\.json$/).required();
924
- }
925
- return acc;
926
- }, {}) : void 0
927
- ).optional()
928
- )
929
- });
930
- const loadPkg = async ({ cwd, logger }) => {
931
- const pkgPath = await pkgUp__default.default({ cwd });
932
- if (!pkgPath) {
933
- throw new Error("Could not find a package.json in the current directory");
934
- }
935
- const buffer = await fs__default.default.readFile(pkgPath);
936
- const pkg = JSON.parse(buffer.toString());
937
- logger.debug("Loaded package.json:", os__default.default.EOL, pkg);
938
- return pkg;
939
- };
940
1026
  const buildLogsServiceFactory = ({ logger }) => {
941
1027
  return async (url, token, cliConfig2) => {
942
1028
  const CONN_TIMEOUT = Number(cliConfig2.buildLogsConnectionTimeout);
@@ -990,6 +1076,7 @@ const buildLogsServiceFactory = ({ logger }) => {
990
1076
  if (retries > MAX_RETRIES) {
991
1077
  spinner.fail("We were unable to connect to the server to get build logs at this time.");
992
1078
  es.close();
1079
+ clearExistingTimeout();
993
1080
  reject(new Error("Max retries reached"));
994
1081
  }
995
1082
  };
@@ -1032,13 +1119,13 @@ async function upload(ctx, project, token, maxProjectFileSize) {
1032
1119
  process.exit(1);
1033
1120
  }
1034
1121
  const tarFilePath = path__namespace.default.resolve(storagePath, compressedFilename);
1035
- const fileStats = await fse__default.default.stat(tarFilePath);
1122
+ const fileStats = await fse__namespace.default.stat(tarFilePath);
1036
1123
  if (fileStats.size > maxProjectFileSize) {
1037
1124
  ctx.logger.log(
1038
1125
  "Unable to proceed: Your project is too big to be transferred, please use a git repo instead."
1039
1126
  );
1040
1127
  try {
1041
- await fse__default.default.remove(tarFilePath);
1128
+ await fse__namespace.default.remove(tarFilePath);
1042
1129
  } catch (e) {
1043
1130
  ctx.logger.log("Unable to remove file: ", tarFilePath);
1044
1131
  ctx.logger.debug(e);
@@ -1064,20 +1151,10 @@ async function upload(ctx, project, token, maxProjectFileSize) {
1064
1151
  return data.build_id;
1065
1152
  } catch (e) {
1066
1153
  progressBar.stop();
1067
- if (e instanceof axios.AxiosError && e.response?.data) {
1068
- if (e.response.status === 404) {
1069
- ctx.logger.error(
1070
- `The project does not exist. Remove the ${LOCAL_SAVE_FILENAME} file and try again.`
1071
- );
1072
- } else {
1073
- ctx.logger.error(e.response.data);
1074
- }
1075
- } else {
1076
- ctx.logger.error("An error occurred while deploying the project. Please try again later.");
1077
- }
1154
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
1078
1155
  ctx.logger.debug(e);
1079
1156
  } finally {
1080
- await fse__default.default.remove(tarFilePath);
1157
+ await fse__namespace.default.remove(tarFilePath);
1081
1158
  }
1082
1159
  process.exit(0);
1083
1160
  } catch (e) {
@@ -1090,7 +1167,7 @@ async function getProject(ctx) {
1090
1167
  const { project } = await retrieve();
1091
1168
  if (!project) {
1092
1169
  try {
1093
- return await action$2(ctx);
1170
+ return await action$4(ctx);
1094
1171
  } catch (e) {
1095
1172
  ctx.logger.error("An error occurred while deploying the project. Please try again later.");
1096
1173
  ctx.logger.debug(e);
@@ -1099,7 +1176,19 @@ async function getProject(ctx) {
1099
1176
  }
1100
1177
  return project;
1101
1178
  }
1102
- const action$1 = async (ctx) => {
1179
+ async function getConfig({
1180
+ ctx,
1181
+ cloudApiService
1182
+ }) {
1183
+ try {
1184
+ const { data: cliConfig2 } = await cloudApiService.config();
1185
+ return cliConfig2;
1186
+ } catch (e) {
1187
+ ctx.logger.debug("Failed to get cli config", e);
1188
+ return null;
1189
+ }
1190
+ }
1191
+ const action$3 = async (ctx) => {
1103
1192
  const { getValidToken } = await tokenServiceFactory(ctx);
1104
1193
  const token = await getValidToken(ctx, promptLogin);
1105
1194
  if (!token) {
@@ -1109,15 +1198,51 @@ const action$1 = async (ctx) => {
1109
1198
  if (!project) {
1110
1199
  return;
1111
1200
  }
1112
- const cloudApiService = await cloudApiFactory(ctx);
1201
+ const cloudApiService = await cloudApiFactory(ctx, token);
1113
1202
  try {
1114
- await cloudApiService.track("willDeployWithCLI", { projectInternalName: project.name });
1203
+ const {
1204
+ data: { data: projectData, metadata }
1205
+ } = await cloudApiService.getProject({ name: project.name });
1206
+ const isProjectSuspended = projectData.suspendedAt;
1207
+ if (isProjectSuspended) {
1208
+ ctx.logger.log(
1209
+ "\n Oops! This project has been suspended. \n\n Please reactivate it from the dashboard to continue deploying: "
1210
+ );
1211
+ ctx.logger.log(chalk__default.default.underline(`${metadata.dashboardUrls.project}`));
1212
+ return;
1213
+ }
1115
1214
  } catch (e) {
1116
- ctx.logger.debug("Failed to track willDeploy", e);
1215
+ if (e instanceof axios.AxiosError && e.response?.data) {
1216
+ if (e.response.status === 404) {
1217
+ ctx.logger.warn(
1218
+ `The project associated with this folder does not exist in Strapi Cloud.
1219
+ Please link your local project to an existing Strapi Cloud project using the ${chalk__default.default.cyan(
1220
+ "link"
1221
+ )} command before deploying.`
1222
+ );
1223
+ } else {
1224
+ ctx.logger.error(e.response.data);
1225
+ }
1226
+ } else {
1227
+ ctx.logger.error(
1228
+ "An error occurred while retrieving the project's information. Please try again later."
1229
+ );
1230
+ }
1231
+ ctx.logger.debug(e);
1232
+ return;
1117
1233
  }
1234
+ await trackEvent(ctx, cloudApiService, "willDeployWithCLI", {
1235
+ projectInternalName: project.name
1236
+ });
1118
1237
  const notificationService = notificationServiceFactory(ctx);
1119
1238
  const buildLogsService = buildLogsServiceFactory(ctx);
1120
- const { data: cliConfig2 } = await cloudApiService.config();
1239
+ const cliConfig2 = await getConfig({ ctx, cloudApiService });
1240
+ if (!cliConfig2) {
1241
+ ctx.logger.error(
1242
+ "An error occurred while retrieving data from Strapi Cloud. Please check your network or try again later."
1243
+ );
1244
+ return;
1245
+ }
1121
1246
  let maxSize = parseInt(cliConfig2.maxProjectFileSize, 10);
1122
1247
  if (Number.isNaN(maxSize)) {
1123
1248
  ctx.logger.debug(
@@ -1139,10 +1264,11 @@ const action$1 = async (ctx) => {
1139
1264
  chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects/${project.name}/deployments`)
1140
1265
  );
1141
1266
  } catch (e) {
1267
+ ctx.logger.debug(e);
1142
1268
  if (e instanceof Error) {
1143
1269
  ctx.logger.error(e.message);
1144
1270
  } else {
1145
- throw e;
1271
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
1146
1272
  }
1147
1273
  }
1148
1274
  };
@@ -1173,16 +1299,162 @@ const runAction = (name2, action2) => (...args) => {
1173
1299
  process.exit(1);
1174
1300
  });
1175
1301
  };
1176
- const command$3 = ({ command: command2, ctx }) => {
1177
- 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$1)(ctx));
1302
+ const command$5 = ({ command: command2, ctx }) => {
1303
+ 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));
1178
1304
  };
1179
1305
  const deployProject = {
1180
1306
  name: "deploy-project",
1181
1307
  description: "Deploy a Strapi Cloud project",
1182
- action: action$1,
1183
- command: command$3
1308
+ action: action$3,
1309
+ command: command$5
1184
1310
  };
1185
- const command$2 = ({ command: command2, ctx }) => {
1311
+ const QUIT_OPTION = "Quit";
1312
+ async function getExistingConfig(ctx) {
1313
+ try {
1314
+ return await retrieve();
1315
+ } catch (e) {
1316
+ ctx.logger.debug("Failed to get project config", e);
1317
+ ctx.logger.error("An error occurred while retrieving config data from your local project.");
1318
+ return null;
1319
+ }
1320
+ }
1321
+ async function promptForRelink(ctx, cloudApiService, existingConfig) {
1322
+ if (existingConfig && existingConfig.project) {
1323
+ const { shouldRelink } = await inquirer__default.default.prompt([
1324
+ {
1325
+ type: "confirm",
1326
+ name: "shouldRelink",
1327
+ message: `A project named ${chalk__default.default.cyan(
1328
+ existingConfig.project.displayName ? existingConfig.project.displayName : existingConfig.project.name
1329
+ )} is already linked to this local folder. Do you want to update the link?`,
1330
+ default: false
1331
+ }
1332
+ ]);
1333
+ if (!shouldRelink) {
1334
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1335
+ currentProjectName: existingConfig.project?.name
1336
+ });
1337
+ return false;
1338
+ }
1339
+ }
1340
+ return true;
1341
+ }
1342
+ async function getProjectsList(ctx, cloudApiService, existingConfig) {
1343
+ const spinner = ctx.logger.spinner("Fetching your projects...\n").start();
1344
+ try {
1345
+ const {
1346
+ data: { data: projectList }
1347
+ } = await cloudApiService.listLinkProjects();
1348
+ spinner.succeed();
1349
+ if (!Array.isArray(projectList)) {
1350
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1351
+ return null;
1352
+ }
1353
+ const projects = projectList.filter(
1354
+ (project) => !(project.isMaintainer || project.name === existingConfig?.project?.name)
1355
+ ).map((project) => {
1356
+ return {
1357
+ name: project.displayName,
1358
+ value: { name: project.name, displayName: project.displayName }
1359
+ };
1360
+ });
1361
+ if (projects.length === 0) {
1362
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1363
+ return null;
1364
+ }
1365
+ return projects;
1366
+ } catch (e) {
1367
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1368
+ ctx.logger.debug("Failed to list projects", e);
1369
+ return null;
1370
+ }
1371
+ }
1372
+ async function getUserSelection(ctx, projects) {
1373
+ const { logger } = ctx;
1374
+ try {
1375
+ const answer = await inquirer__default.default.prompt([
1376
+ {
1377
+ type: "list",
1378
+ name: "linkProject",
1379
+ message: "Which project do you want to link?",
1380
+ choices: [...projects, { name: chalk__default.default.grey(`(${QUIT_OPTION})`), value: null }]
1381
+ }
1382
+ ]);
1383
+ if (!answer.linkProject) {
1384
+ return null;
1385
+ }
1386
+ return answer;
1387
+ } catch (e) {
1388
+ logger.debug("Failed to get user input", e);
1389
+ logger.error("An error occurred while trying to get your input.");
1390
+ return null;
1391
+ }
1392
+ }
1393
+ const action$2 = async (ctx) => {
1394
+ const { getValidToken } = await tokenServiceFactory(ctx);
1395
+ const token = await getValidToken(ctx, promptLogin);
1396
+ const { logger } = ctx;
1397
+ if (!token) {
1398
+ return;
1399
+ }
1400
+ const cloudApiService = await cloudApiFactory(ctx, token);
1401
+ const existingConfig = await getExistingConfig(ctx);
1402
+ const shouldRelink = await promptForRelink(ctx, cloudApiService, existingConfig);
1403
+ if (!shouldRelink) {
1404
+ return;
1405
+ }
1406
+ await trackEvent(ctx, cloudApiService, "willLinkProject", {});
1407
+ const projects = await getProjectsList(
1408
+ ctx,
1409
+ cloudApiService,
1410
+ existingConfig
1411
+ );
1412
+ if (!projects) {
1413
+ return;
1414
+ }
1415
+ const answer = await getUserSelection(ctx, projects);
1416
+ if (!answer) {
1417
+ return;
1418
+ }
1419
+ try {
1420
+ const { confirmAction } = await inquirer__default.default.prompt([
1421
+ {
1422
+ type: "confirm",
1423
+ name: "confirmAction",
1424
+ message: "Warning: Once linked, deploying from CLI will replace the existing project and its data. Confirm to proceed:",
1425
+ default: false
1426
+ }
1427
+ ]);
1428
+ if (!confirmAction) {
1429
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1430
+ cancelledProjectName: answer.linkProject.name,
1431
+ currentProjectName: existingConfig ? existingConfig.project?.name : null
1432
+ });
1433
+ return;
1434
+ }
1435
+ await save({ project: answer.linkProject });
1436
+ logger.log(`Project ${chalk__default.default.cyan(answer.linkProject.displayName)} linked successfully.`);
1437
+ await trackEvent(ctx, cloudApiService, "didLinkProject", {
1438
+ projectInternalName: answer.linkProject
1439
+ });
1440
+ } catch (e) {
1441
+ logger.debug("Failed to link project", e);
1442
+ logger.error("An error occurred while linking the project.");
1443
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1444
+ projectInternalName: answer.linkProject
1445
+ });
1446
+ }
1447
+ };
1448
+ const command$4 = ({ command: command2, ctx }) => {
1449
+ 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));
1450
+ };
1451
+ const link = {
1452
+ name: "link-project",
1453
+ description: "Link a local directory to a Strapi Cloud project",
1454
+ action: action$2,
1455
+ command: command$4
1456
+ };
1457
+ const command$3 = ({ command: command2, ctx }) => {
1186
1458
  command2.command("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1187
1459
  "after",
1188
1460
  "\nAfter running this command, you will be prompted to enter your authentication information."
@@ -1192,10 +1464,10 @@ const login = {
1192
1464
  name: "login",
1193
1465
  description: "Strapi Cloud Login",
1194
1466
  action: loginAction,
1195
- command: command$2
1467
+ command: command$3
1196
1468
  };
1197
1469
  const openModule = import("open");
1198
- const action = async (ctx) => {
1470
+ const action$1 = async (ctx) => {
1199
1471
  const { logger } = ctx;
1200
1472
  const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx);
1201
1473
  const token = await retrieveToken();
@@ -1225,37 +1497,64 @@ const action = async (ctx) => {
1225
1497
  logger.error("🥲 Oops! Something went wrong while logging you out. Please try again.");
1226
1498
  logger.debug(e);
1227
1499
  }
1228
- try {
1229
- await cloudApiService.track("didLogout", { loginMethod: "cli" });
1230
- } catch (e) {
1231
- logger.debug("Failed to track logout event", e);
1232
- }
1500
+ await trackEvent(ctx, cloudApiService, "didLogout", { loginMethod: "cli" });
1233
1501
  };
1234
- const command$1 = ({ command: command2, ctx }) => {
1235
- 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));
1502
+ const command$2 = ({ command: command2, ctx }) => {
1503
+ 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));
1236
1504
  };
1237
1505
  const logout = {
1238
1506
  name: "logout",
1239
1507
  description: "Strapi Cloud Logout",
1240
- action,
1241
- command: command$1
1508
+ action: action$1,
1509
+ command: command$2
1242
1510
  };
1243
- const command = ({ command: command2, ctx }) => {
1244
- 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$2)(ctx));
1511
+ const command$1 = ({ command: command2, ctx }) => {
1512
+ 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));
1245
1513
  };
1246
1514
  const createProject = {
1247
1515
  name: "create-project",
1248
1516
  description: "Create a new project",
1249
- action: action$2,
1517
+ action: action$4,
1518
+ command: command$1
1519
+ };
1520
+ const action = async (ctx) => {
1521
+ const { getValidToken } = await tokenServiceFactory(ctx);
1522
+ const token = await getValidToken(ctx, promptLogin);
1523
+ const { logger } = ctx;
1524
+ if (!token) {
1525
+ return;
1526
+ }
1527
+ const cloudApiService = await cloudApiFactory(ctx, token);
1528
+ const spinner = logger.spinner("Fetching your projects...").start();
1529
+ try {
1530
+ const {
1531
+ data: { data: projectList }
1532
+ } = await cloudApiService.listProjects();
1533
+ spinner.succeed();
1534
+ logger.log(projectList);
1535
+ } catch (e) {
1536
+ ctx.logger.debug("Failed to list projects", e);
1537
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1538
+ }
1539
+ };
1540
+ const command = ({ command: command2, ctx }) => {
1541
+ 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));
1542
+ };
1543
+ const listProjects = {
1544
+ name: "list-projects",
1545
+ description: "List Strapi Cloud projects",
1546
+ action,
1250
1547
  command
1251
1548
  };
1252
1549
  const cli = {
1253
1550
  deployProject,
1551
+ link,
1254
1552
  login,
1255
1553
  logout,
1256
- createProject
1554
+ createProject,
1555
+ listProjects
1257
1556
  };
1258
- const cloudCommands = [deployProject, login, logout];
1557
+ const cloudCommands = [deployProject, link, login, logout, listProjects];
1259
1558
  async function initCloudCLIConfig() {
1260
1559
  const localConfig = await getLocalConfig();
1261
1560
  if (!localConfig.deviceId) {