@strapi/cloud-cli 0.0.0-next.af9f5eed766381838931b23118affc1c765c5d88 → 0.0.0-next.aff9d09e4edf4d38b8a0de5abf83d79bedb28313

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 (44) hide show
  1. package/dist/index.js +761 -434
  2. package/dist/index.js.map +1 -1
  3. package/dist/index.mjs +763 -433
  4. package/dist/index.mjs.map +1 -1
  5. package/dist/src/create-project/action.d.ts +1 -1
  6. package/dist/src/create-project/action.d.ts.map +1 -1
  7. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts +3 -0
  8. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts.map +1 -0
  9. package/dist/src/create-project/utils/project-questions.utils.d.ts +20 -0
  10. package/dist/src/create-project/utils/project-questions.utils.d.ts.map +1 -0
  11. package/dist/src/deploy-project/action.d.ts.map +1 -1
  12. package/dist/src/index.d.ts +2 -0
  13. package/dist/src/index.d.ts.map +1 -1
  14. package/dist/src/link/action.d.ts +4 -0
  15. package/dist/src/link/action.d.ts.map +1 -0
  16. package/dist/src/link/command.d.ts +7 -0
  17. package/dist/src/link/command.d.ts.map +1 -0
  18. package/dist/src/link/index.d.ts +7 -0
  19. package/dist/src/link/index.d.ts.map +1 -0
  20. package/dist/src/list-projects/action.d.ts +4 -0
  21. package/dist/src/list-projects/action.d.ts.map +1 -0
  22. package/dist/src/list-projects/command.d.ts +7 -0
  23. package/dist/src/list-projects/command.d.ts.map +1 -0
  24. package/dist/src/list-projects/index.d.ts +7 -0
  25. package/dist/src/list-projects/index.d.ts.map +1 -0
  26. package/dist/src/login/action.d.ts +2 -2
  27. package/dist/src/login/action.d.ts.map +1 -1
  28. package/dist/src/logout/action.d.ts.map +1 -1
  29. package/dist/src/services/build-logs.d.ts.map +1 -1
  30. package/dist/src/services/cli-api.d.ts +35 -7
  31. package/dist/src/services/cli-api.d.ts.map +1 -1
  32. package/dist/src/services/strapi-info-save.d.ts +1 -1
  33. package/dist/src/services/strapi-info-save.d.ts.map +1 -1
  34. package/dist/src/services/token.d.ts +1 -1
  35. package/dist/src/services/token.d.ts.map +1 -1
  36. package/dist/src/types.d.ts +1 -0
  37. package/dist/src/types.d.ts.map +1 -1
  38. package/dist/src/utils/analytics.d.ts +4 -0
  39. package/dist/src/utils/analytics.d.ts.map +1 -0
  40. package/dist/src/utils/compress-files.d.ts.map +1 -1
  41. package/dist/src/utils/pkg.d.ts.map +1 -1
  42. package/package.json +6 -5
  43. package/dist/src/utils/tests/compress-files.test.d.ts +0 -2
  44. 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.8";
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.8",
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.8",
207
+ tsconfig: "4.25.8"
206
208
  };
207
209
  const engines = {
208
210
  node: ">=18.0.0 <=20.x.x",
@@ -255,7 +257,7 @@ async function cloudApiFactory({ logger }, 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"
@@ -298,8 +300,47 @@ async function cloudApiFactory({ logger }, token) {
298
300
  throw error;
299
301
  }
300
302
  },
301
- listProjects() {
302
- return axiosCloudAPI.get("/projects");
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
+ }
316
+ },
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
+ }
330
+ },
331
+ async getProject({ name: name2 }) {
332
+ try {
333
+ const response = await axiosCloudAPI.get(`/projects/${name2}`);
334
+ if (response.status !== 200) {
335
+ throw new Error("Error fetching project's details.");
336
+ }
337
+ return response;
338
+ } catch (error) {
339
+ logger.debug(
340
+ "🥲 Oops! There was a problem retrieving your project's details. Please try again."
341
+ );
342
+ throw error;
343
+ }
303
344
  },
304
345
  track(event, payload = {}) {
305
346
  return axiosCloudAPI.post("/track", {
@@ -314,18 +355,18 @@ async function save(data, { directoryPath } = {}) {
314
355
  const alreadyInFileData = await retrieve({ directoryPath });
315
356
  const storedData = { ...alreadyInFileData, ...data };
316
357
  const pathToFile = path__default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
317
- await fse.ensureDir(path__default.dirname(pathToFile));
318
- await fse.writeJson(pathToFile, storedData, { encoding: "utf8" });
358
+ await fse__default.ensureDir(path__default.dirname(pathToFile));
359
+ await fse__default.writeJson(pathToFile, storedData, { encoding: "utf8" });
319
360
  }
320
361
  async function retrieve({
321
362
  directoryPath
322
363
  } = {}) {
323
364
  const pathToFile = path__default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
324
- const pathExists = await fse.pathExists(pathToFile);
365
+ const pathExists = await fse__default.pathExists(pathToFile);
325
366
  if (!pathExists) {
326
367
  return {};
327
368
  }
328
- return fse.readJSON(pathToFile, { encoding: "utf8" });
369
+ return fse__default.readJSON(pathToFile, { encoding: "utf8" });
329
370
  }
330
371
  const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
331
372
  __proto__: null,
@@ -384,14 +425,17 @@ async function tokenServiceFactory({ logger }) {
384
425
  "There seems to be a problem with your login information. Please try logging in again."
385
426
  );
386
427
  }
428
+ return Promise.reject(new Error("Invalid token"));
387
429
  }
388
430
  return new Promise((resolve, reject) => {
389
431
  jwt.verify(idToken, getKey, (err) => {
390
432
  if (err) {
391
433
  reject(err);
392
- } else {
393
- resolve();
394
434
  }
435
+ if (decodedToken.payload.exp < Math.floor(Date.now() / 1e3)) {
436
+ reject(new Error("Token is expired"));
437
+ }
438
+ resolve();
395
439
  });
396
440
  });
397
441
  }
@@ -425,15 +469,15 @@ async function tokenServiceFactory({ logger }) {
425
469
  throw e;
426
470
  }
427
471
  }
428
- async function getValidToken() {
429
- const token = await retrieveToken();
430
- if (!token) {
431
- logger.log("No token found. Please login first.");
432
- return null;
433
- }
434
- if (!await isTokenValid(token)) {
435
- logger.log("Unable to proceed: Token is expired or not valid. Please login again.");
436
- return null;
472
+ async function getValidToken(ctx, loginAction2) {
473
+ let token = await retrieveToken();
474
+ while (!token || !await isTokenValid(token)) {
475
+ logger.log(
476
+ 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."
477
+ );
478
+ if (!await loginAction2(ctx))
479
+ return null;
480
+ token = await retrieveToken();
437
481
  }
438
482
  return token;
439
483
  }
@@ -567,97 +611,6 @@ const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePropert
567
611
  local: strapiInfoSave,
568
612
  tokenServiceFactory
569
613
  }, Symbol.toStringTag, { value: "Module" }));
570
- async function handleError(ctx, error) {
571
- const tokenService = await tokenServiceFactory(ctx);
572
- const { logger } = ctx;
573
- logger.debug(error);
574
- if (error instanceof AxiosError) {
575
- const errorMessage = typeof error.response?.data === "string" ? error.response.data : null;
576
- switch (error.response?.status) {
577
- case 401:
578
- logger.error("Your session has expired. Please log in again.");
579
- await tokenService.eraseToken();
580
- return;
581
- case 403:
582
- logger.error(
583
- errorMessage || "You do not have permission to create a project. Please contact support for assistance."
584
- );
585
- return;
586
- case 400:
587
- logger.error(errorMessage || "Invalid input. Please check your inputs and try again.");
588
- return;
589
- case 503:
590
- logger.error(
591
- "Strapi Cloud project creation is currently unavailable. Please try again later."
592
- );
593
- return;
594
- default:
595
- if (errorMessage) {
596
- logger.error(errorMessage);
597
- return;
598
- }
599
- break;
600
- }
601
- }
602
- logger.error(
603
- "We encountered an issue while creating your project. Please try again in a moment. If the problem persists, contact support for assistance."
604
- );
605
- }
606
- const action$3 = async (ctx) => {
607
- const { logger } = ctx;
608
- const { getValidToken } = await tokenServiceFactory(ctx);
609
- const token = await getValidToken();
610
- if (!token) {
611
- return;
612
- }
613
- const cloudApi = await cloudApiFactory(ctx, token);
614
- const { data: config } = await cloudApi.config();
615
- const { questions, defaults: defaultValues } = config.projectCreation;
616
- const projectAnswersDefaulted = defaults(defaultValues);
617
- const projectAnswers = await inquirer.prompt(questions);
618
- const projectInput = projectAnswersDefaulted(projectAnswers);
619
- const spinner = logger.spinner("Setting up your project...").start();
620
- try {
621
- const { data } = await cloudApi.createProject(projectInput);
622
- await save({ project: data });
623
- spinner.succeed("Project created successfully!");
624
- return data;
625
- } catch (e) {
626
- spinner.fail("Failed to create project on Strapi Cloud.");
627
- await handleError(ctx, e);
628
- }
629
- };
630
- function notificationServiceFactory({ logger }) {
631
- return (url, token, cliConfig2) => {
632
- const CONN_TIMEOUT = Number(cliConfig2.notificationsConnectionTimeout);
633
- const es = new EventSource(url, {
634
- headers: {
635
- Authorization: `Bearer ${token}`
636
- }
637
- });
638
- let timeoutId;
639
- const resetTimeout = () => {
640
- clearTimeout(timeoutId);
641
- timeoutId = setTimeout(() => {
642
- logger.log(
643
- "We were unable to connect to the server at this time. This could be due to a temporary issue. Please try again in a moment."
644
- );
645
- es.close();
646
- }, CONN_TIMEOUT);
647
- };
648
- es.onopen = resetTimeout;
649
- es.onmessage = (event) => {
650
- resetTimeout();
651
- const data = JSON.parse(event.data);
652
- if (data.message) {
653
- logger.log(data.message);
654
- }
655
- if (data.event === "deploymentFinished" || data.event === "deploymentFailed") {
656
- es.close();
657
- }
658
- };
659
- };
660
- }
661
614
  yup.object({
662
615
  name: yup.string().required(),
663
616
  exports: yup.lazy(
@@ -685,115 +638,437 @@ const loadPkg = async ({ cwd, logger }) => {
685
638
  if (!pkgPath) {
686
639
  throw new Error("Could not find a package.json in the current directory");
687
640
  }
688
- const buffer = await fs$1.readFile(pkgPath);
641
+ const buffer = await fse.readFile(pkgPath);
689
642
  const pkg = JSON.parse(buffer.toString());
690
643
  logger.debug("Loaded package.json:", os.EOL, pkg);
691
644
  return pkg;
692
645
  };
693
- const buildLogsServiceFactory = ({ logger }) => {
694
- return async (url, token, cliConfig2) => {
695
- const CONN_TIMEOUT = Number(cliConfig2.buildLogsConnectionTimeout);
696
- const MAX_RETRIES = Number(cliConfig2.buildLogsMaxRetries);
697
- return new Promise((resolve, reject) => {
698
- let timeoutId = null;
699
- let retries = 0;
700
- const connect = (url2) => {
701
- const spinner = logger.spinner("Connecting to server to get build logs");
702
- spinner.start();
703
- const es = new EventSource(`${url2}`, {
704
- headers: {
705
- Authorization: `Bearer ${token}`
706
- }
707
- });
708
- const clearExistingTimeout = () => {
709
- if (timeoutId) {
710
- clearTimeout(timeoutId);
711
- }
712
- };
713
- const resetTimeout = () => {
714
- clearExistingTimeout();
715
- timeoutId = setTimeout(() => {
716
- if (spinner.isSpinning) {
717
- spinner.fail(
718
- "We were unable to connect to the server to get build logs at this time. This could be due to a temporary issue."
719
- );
720
- }
721
- es.close();
722
- reject(new Error("Connection timed out"));
723
- }, CONN_TIMEOUT);
724
- };
725
- es.onopen = resetTimeout;
726
- es.addEventListener("finished", (event) => {
727
- const data = JSON.parse(event.data);
728
- logger.log(data.msg);
729
- es.close();
730
- clearExistingTimeout();
731
- resolve(null);
732
- });
733
- es.addEventListener("log", (event) => {
734
- if (spinner.isSpinning) {
735
- spinner.succeed();
736
- }
737
- resetTimeout();
738
- const data = JSON.parse(event.data);
739
- logger.log(data.msg);
740
- });
741
- es.onerror = async () => {
742
- retries += 1;
743
- if (retries > MAX_RETRIES) {
744
- spinner.fail("We were unable to connect to the server to get build logs at this time.");
745
- es.close();
746
- reject(new Error("Max retries reached"));
747
- }
748
- };
749
- };
750
- connect(url);
751
- });
752
- };
753
- };
754
- async function upload(ctx, project, token, maxProjectFileSize) {
755
- const cloudApi = await cloudApiFactory(ctx, token);
646
+ async function getProjectNameFromPackageJson(ctx) {
756
647
  try {
757
- const storagePath = await getTmpStoragePath();
758
- const projectFolder = path__default.resolve(process.cwd());
759
648
  const packageJson2 = await loadPkg(ctx);
760
- if (!packageJson2) {
761
- ctx.logger.error(
762
- "Unable to deploy the project. Please make sure the package.json file is correctly formatted."
763
- );
764
- return;
765
- }
766
- ctx.logger.log("📦 Compressing project...");
767
- const hashname = crypto.createHash("sha512").update(packageJson2.name).digest("hex");
768
- const compressedFilename = `${hashname}.tar.gz`;
769
- try {
770
- ctx.logger.debug(
771
- "Compression parameters\n",
772
- `Storage path: ${storagePath}
773
- `,
774
- `Project folder: ${projectFolder}
775
- `,
776
- `Compressed filename: ${compressedFilename}`
777
- );
778
- await compressFilesToTar(storagePath, projectFolder, compressedFilename);
779
- ctx.logger.log("📦 Project compressed successfully!");
780
- } catch (e) {
781
- ctx.logger.error(
782
- "⚠️ Project compression failed. Try again later or check for large/incompatible files."
783
- );
784
- ctx.logger.debug(e);
785
- process.exit(1);
649
+ return packageJson2.name || "my-strapi-project";
650
+ } catch (e) {
651
+ return "my-strapi-project";
652
+ }
653
+ }
654
+ const trackEvent = async (ctx, cloudApiService, eventName, eventData) => {
655
+ try {
656
+ await cloudApiService.track(eventName, eventData);
657
+ } catch (e) {
658
+ ctx.logger.debug(`Failed to track ${eventName}`, e);
659
+ }
660
+ };
661
+ const openModule$1 = import("open");
662
+ async function promptLogin(ctx) {
663
+ const response = await inquirer.prompt([
664
+ {
665
+ type: "confirm",
666
+ name: "login",
667
+ message: "Would you like to login?"
786
668
  }
787
- const tarFilePath = path__default.resolve(storagePath, compressedFilename);
788
- const fileStats = await fse.stat(tarFilePath);
789
- if (fileStats.size > maxProjectFileSize) {
790
- ctx.logger.log(
791
- "Unable to proceed: Your project is too big to be transferred, please use a git repo instead."
792
- );
669
+ ]);
670
+ if (response.login) {
671
+ const loginSuccessful = await loginAction(ctx);
672
+ return loginSuccessful;
673
+ }
674
+ return false;
675
+ }
676
+ async function loginAction(ctx) {
677
+ const { logger } = ctx;
678
+ const tokenService = await tokenServiceFactory(ctx);
679
+ const existingToken = await tokenService.retrieveToken();
680
+ const cloudApiService = await cloudApiFactory(ctx, existingToken || void 0);
681
+ if (existingToken) {
682
+ const isTokenValid = await tokenService.isTokenValid(existingToken);
683
+ if (isTokenValid) {
793
684
  try {
794
- await fse.remove(tarFilePath);
795
- } catch (e) {
796
- ctx.logger.log("Unable to remove file: ", tarFilePath);
685
+ const userInfo = await cloudApiService.getUserInfo();
686
+ const { email } = userInfo.data.data;
687
+ if (email) {
688
+ logger.log(`You are already logged into your account (${email}).`);
689
+ } else {
690
+ logger.log("You are already logged in.");
691
+ }
692
+ logger.log(
693
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
694
+ );
695
+ logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
696
+ return true;
697
+ } catch (e) {
698
+ logger.debug("Failed to fetch user info", e);
699
+ }
700
+ }
701
+ }
702
+ let cliConfig2;
703
+ try {
704
+ logger.info("🔌 Connecting to the Strapi Cloud API...");
705
+ const config = await cloudApiService.config();
706
+ cliConfig2 = config.data;
707
+ } catch (e) {
708
+ logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
709
+ logger.debug(e);
710
+ return false;
711
+ }
712
+ await trackEvent(ctx, cloudApiService, "willLoginAttempt", {});
713
+ logger.debug("🔐 Creating device authentication request...", {
714
+ client_id: cliConfig2.clientId,
715
+ scope: cliConfig2.scope,
716
+ audience: cliConfig2.audience
717
+ });
718
+ const deviceAuthResponse = await axios.post(cliConfig2.deviceCodeAuthUrl, {
719
+ client_id: cliConfig2.clientId,
720
+ scope: cliConfig2.scope,
721
+ audience: cliConfig2.audience
722
+ }).catch((e) => {
723
+ logger.error("There was an issue with the authentication process. Please try again.");
724
+ if (e.message) {
725
+ logger.debug(e.message, e);
726
+ } else {
727
+ logger.debug(e);
728
+ }
729
+ });
730
+ openModule$1.then((open) => {
731
+ open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
732
+ logger.error("We encountered an issue opening the browser. Please try again later.");
733
+ logger.debug(e.message, e);
734
+ });
735
+ });
736
+ logger.log("If a browser tab does not open automatically, please follow the next steps:");
737
+ logger.log(
738
+ `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
739
+ );
740
+ logger.log(
741
+ `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
742
+ `
743
+ );
744
+ const tokenPayload = {
745
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
746
+ device_code: deviceAuthResponse.data.device_code,
747
+ client_id: cliConfig2.clientId
748
+ };
749
+ let isAuthenticated = false;
750
+ const authenticate = async () => {
751
+ const spinner = logger.spinner("Waiting for authentication");
752
+ spinner.start();
753
+ const spinnerFail = () => spinner.fail("Authentication failed!");
754
+ while (!isAuthenticated) {
755
+ try {
756
+ const tokenResponse = await axios.post(cliConfig2.tokenUrl, tokenPayload);
757
+ const authTokenData = tokenResponse.data;
758
+ if (tokenResponse.status === 200) {
759
+ try {
760
+ logger.debug("🔐 Validating token...");
761
+ await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
762
+ logger.debug("🔐 Token validation successful!");
763
+ } catch (e) {
764
+ logger.debug(e);
765
+ spinnerFail();
766
+ throw new Error("Unable to proceed: Token validation failed");
767
+ }
768
+ logger.debug("🔍 Fetching user information...");
769
+ const cloudApiServiceWithToken = await cloudApiFactory(ctx, authTokenData.access_token);
770
+ await cloudApiServiceWithToken.getUserInfo();
771
+ logger.debug("🔍 User information fetched successfully!");
772
+ try {
773
+ logger.debug("📝 Saving login information...");
774
+ await tokenService.saveToken(authTokenData.access_token);
775
+ logger.debug("📝 Login information saved successfully!");
776
+ isAuthenticated = true;
777
+ } catch (e) {
778
+ logger.error(
779
+ "There was a problem saving your login information. Please try logging in again."
780
+ );
781
+ logger.debug(e);
782
+ spinnerFail();
783
+ return false;
784
+ }
785
+ }
786
+ } catch (e) {
787
+ if (e.message === "Unable to proceed: Token validation failed") {
788
+ logger.error(
789
+ "There seems to be a problem with your login information. Please try logging in again."
790
+ );
791
+ spinnerFail();
792
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
793
+ return false;
794
+ }
795
+ if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
796
+ logger.debug(e);
797
+ spinnerFail();
798
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
799
+ return false;
800
+ }
801
+ await new Promise((resolve) => {
802
+ setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
803
+ });
804
+ }
805
+ }
806
+ spinner.succeed("Authentication successful!");
807
+ logger.log("You are now logged into Strapi Cloud.");
808
+ logger.log(
809
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
810
+ );
811
+ logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
812
+ await trackEvent(ctx, cloudApiService, "didLogin", { loginMethod: "cli" });
813
+ };
814
+ await authenticate();
815
+ return isAuthenticated;
816
+ }
817
+ function questionDefaultValuesMapper(questionsMap) {
818
+ return (questions) => {
819
+ return questions.map((question) => {
820
+ const questionName = question.name;
821
+ if (questionName in questionsMap) {
822
+ const questionDefault = questionsMap[questionName];
823
+ if (typeof questionDefault === "function") {
824
+ return {
825
+ ...question,
826
+ default: questionDefault(question)
827
+ };
828
+ }
829
+ return {
830
+ ...question,
831
+ default: questionDefault
832
+ };
833
+ }
834
+ return question;
835
+ });
836
+ };
837
+ }
838
+ function getDefaultsFromQuestions(questions) {
839
+ return questions.reduce((acc, question) => {
840
+ if (question.default && question.name) {
841
+ return { ...acc, [question.name]: question.default };
842
+ }
843
+ return acc;
844
+ }, {});
845
+ }
846
+ function getProjectNodeVersionDefault(question) {
847
+ const currentNodeVersion = process.versions.node.split(".")[0];
848
+ if (question.type === "list" && Array.isArray(question.choices)) {
849
+ const choice = question.choices.find((choice2) => choice2.value === currentNodeVersion);
850
+ if (choice) {
851
+ return choice.value;
852
+ }
853
+ }
854
+ return question.default;
855
+ }
856
+ async function handleError(ctx, error) {
857
+ const { logger } = ctx;
858
+ logger.debug(error);
859
+ if (error instanceof AxiosError) {
860
+ const errorMessage = typeof error.response?.data === "string" ? error.response.data : null;
861
+ switch (error.response?.status) {
862
+ case 403:
863
+ logger.error(
864
+ errorMessage || "You do not have permission to create a project. Please contact support for assistance."
865
+ );
866
+ return;
867
+ case 400:
868
+ logger.error(errorMessage || "Invalid input. Please check your inputs and try again.");
869
+ return;
870
+ case 503:
871
+ logger.error(
872
+ "Strapi Cloud project creation is currently unavailable. Please try again later."
873
+ );
874
+ return;
875
+ default:
876
+ if (errorMessage) {
877
+ logger.error(errorMessage);
878
+ return;
879
+ }
880
+ break;
881
+ }
882
+ }
883
+ logger.error(
884
+ "We encountered an issue while creating your project. Please try again in a moment. If the problem persists, contact support for assistance."
885
+ );
886
+ }
887
+ async function createProject$1(ctx, cloudApi, projectInput) {
888
+ const { logger } = ctx;
889
+ const spinner = logger.spinner("Setting up your project...").start();
890
+ try {
891
+ const { data } = await cloudApi.createProject(projectInput);
892
+ await save({ project: data });
893
+ spinner.succeed("Project created successfully!");
894
+ return data;
895
+ } catch (e) {
896
+ spinner.fail("An error occurred while creating the project on Strapi Cloud.");
897
+ throw e;
898
+ }
899
+ }
900
+ const action$4 = async (ctx) => {
901
+ const { logger } = ctx;
902
+ const { getValidToken, eraseToken } = await tokenServiceFactory(ctx);
903
+ const token = await getValidToken(ctx, promptLogin);
904
+ if (!token) {
905
+ return;
906
+ }
907
+ const cloudApi = await cloudApiFactory(ctx, token);
908
+ const { data: config } = await cloudApi.config();
909
+ const projectName = await getProjectNameFromPackageJson(ctx);
910
+ const defaultAnswersMapper = questionDefaultValuesMapper({
911
+ name: projectName,
912
+ nodeVersion: getProjectNodeVersionDefault
913
+ });
914
+ const questions = defaultAnswersMapper(config.projectCreation.questions);
915
+ const defaultValues = {
916
+ ...config.projectCreation.defaults,
917
+ ...getDefaultsFromQuestions(questions)
918
+ };
919
+ const projectAnswersDefaulted = defaults(defaultValues);
920
+ const projectAnswers = await inquirer.prompt(questions);
921
+ const projectInput = projectAnswersDefaulted(projectAnswers);
922
+ try {
923
+ return await createProject$1(ctx, cloudApi, projectInput);
924
+ } catch (e) {
925
+ if (e instanceof AxiosError && e.response?.status === 401) {
926
+ logger.warn("Oops! Your session has expired. Please log in again to retry.");
927
+ await eraseToken();
928
+ if (await promptLogin(ctx)) {
929
+ return await createProject$1(ctx, cloudApi, projectInput);
930
+ }
931
+ } else {
932
+ await handleError(ctx, e);
933
+ }
934
+ }
935
+ };
936
+ function notificationServiceFactory({ logger }) {
937
+ return (url, token, cliConfig2) => {
938
+ const CONN_TIMEOUT = Number(cliConfig2.notificationsConnectionTimeout);
939
+ const es = new EventSource(url, {
940
+ headers: {
941
+ Authorization: `Bearer ${token}`
942
+ }
943
+ });
944
+ let timeoutId;
945
+ const resetTimeout = () => {
946
+ clearTimeout(timeoutId);
947
+ timeoutId = setTimeout(() => {
948
+ logger.log(
949
+ "We were unable to connect to the server at this time. This could be due to a temporary issue. Please try again in a moment."
950
+ );
951
+ es.close();
952
+ }, CONN_TIMEOUT);
953
+ };
954
+ es.onopen = resetTimeout;
955
+ es.onmessage = (event) => {
956
+ resetTimeout();
957
+ const data = JSON.parse(event.data);
958
+ if (data.message) {
959
+ logger.log(data.message);
960
+ }
961
+ if (data.event === "deploymentFinished" || data.event === "deploymentFailed") {
962
+ es.close();
963
+ }
964
+ };
965
+ };
966
+ }
967
+ const buildLogsServiceFactory = ({ logger }) => {
968
+ return async (url, token, cliConfig2) => {
969
+ const CONN_TIMEOUT = Number(cliConfig2.buildLogsConnectionTimeout);
970
+ const MAX_RETRIES = Number(cliConfig2.buildLogsMaxRetries);
971
+ return new Promise((resolve, reject) => {
972
+ let timeoutId = null;
973
+ let retries = 0;
974
+ const connect = (url2) => {
975
+ const spinner = logger.spinner("Connecting to server to get build logs");
976
+ spinner.start();
977
+ const es = new EventSource(`${url2}`, {
978
+ headers: {
979
+ Authorization: `Bearer ${token}`
980
+ }
981
+ });
982
+ const clearExistingTimeout = () => {
983
+ if (timeoutId) {
984
+ clearTimeout(timeoutId);
985
+ }
986
+ };
987
+ const resetTimeout = () => {
988
+ clearExistingTimeout();
989
+ timeoutId = setTimeout(() => {
990
+ if (spinner.isSpinning) {
991
+ spinner.fail(
992
+ "We were unable to connect to the server to get build logs at this time. This could be due to a temporary issue."
993
+ );
994
+ }
995
+ es.close();
996
+ reject(new Error("Connection timed out"));
997
+ }, CONN_TIMEOUT);
998
+ };
999
+ es.onopen = resetTimeout;
1000
+ es.addEventListener("finished", (event) => {
1001
+ const data = JSON.parse(event.data);
1002
+ logger.log(data.msg);
1003
+ es.close();
1004
+ clearExistingTimeout();
1005
+ resolve(null);
1006
+ });
1007
+ es.addEventListener("log", (event) => {
1008
+ if (spinner.isSpinning) {
1009
+ spinner.succeed();
1010
+ }
1011
+ resetTimeout();
1012
+ const data = JSON.parse(event.data);
1013
+ logger.log(data.msg);
1014
+ });
1015
+ es.onerror = async () => {
1016
+ retries += 1;
1017
+ if (retries > MAX_RETRIES) {
1018
+ spinner.fail("We were unable to connect to the server to get build logs at this time.");
1019
+ es.close();
1020
+ clearExistingTimeout();
1021
+ reject(new Error("Max retries reached"));
1022
+ }
1023
+ };
1024
+ };
1025
+ connect(url);
1026
+ });
1027
+ };
1028
+ };
1029
+ async function upload(ctx, project, token, maxProjectFileSize) {
1030
+ const cloudApi = await cloudApiFactory(ctx, token);
1031
+ try {
1032
+ const storagePath = await getTmpStoragePath();
1033
+ const projectFolder = path__default.resolve(process.cwd());
1034
+ const packageJson2 = await loadPkg(ctx);
1035
+ if (!packageJson2) {
1036
+ ctx.logger.error(
1037
+ "Unable to deploy the project. Please make sure the package.json file is correctly formatted."
1038
+ );
1039
+ return;
1040
+ }
1041
+ ctx.logger.log("📦 Compressing project...");
1042
+ const hashname = crypto.createHash("sha512").update(packageJson2.name).digest("hex");
1043
+ const compressedFilename = `${hashname}.tar.gz`;
1044
+ try {
1045
+ ctx.logger.debug(
1046
+ "Compression parameters\n",
1047
+ `Storage path: ${storagePath}
1048
+ `,
1049
+ `Project folder: ${projectFolder}
1050
+ `,
1051
+ `Compressed filename: ${compressedFilename}`
1052
+ );
1053
+ await compressFilesToTar(storagePath, projectFolder, compressedFilename);
1054
+ ctx.logger.log("📦 Project compressed successfully!");
1055
+ } catch (e) {
1056
+ ctx.logger.error(
1057
+ "⚠️ Project compression failed. Try again later or check for large/incompatible files."
1058
+ );
1059
+ ctx.logger.debug(e);
1060
+ process.exit(1);
1061
+ }
1062
+ const tarFilePath = path__default.resolve(storagePath, compressedFilename);
1063
+ const fileStats = await fse__default.stat(tarFilePath);
1064
+ if (fileStats.size > maxProjectFileSize) {
1065
+ ctx.logger.log(
1066
+ "Unable to proceed: Your project is too big to be transferred, please use a git repo instead."
1067
+ );
1068
+ try {
1069
+ await fse__default.remove(tarFilePath);
1070
+ } catch (e) {
1071
+ ctx.logger.log("Unable to remove file: ", tarFilePath);
797
1072
  ctx.logger.debug(e);
798
1073
  }
799
1074
  return;
@@ -817,20 +1092,10 @@ async function upload(ctx, project, token, maxProjectFileSize) {
817
1092
  return data.build_id;
818
1093
  } catch (e) {
819
1094
  progressBar.stop();
820
- if (e instanceof AxiosError && e.response?.data) {
821
- if (e.response.status === 404) {
822
- ctx.logger.error(
823
- `The project does not exist. Remove the ${LOCAL_SAVE_FILENAME} file and try again.`
824
- );
825
- } else {
826
- ctx.logger.error(e.response.data);
827
- }
828
- } else {
829
- ctx.logger.error("An error occurred while deploying the project. Please try again later.");
830
- }
1095
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
831
1096
  ctx.logger.debug(e);
832
1097
  } finally {
833
- await fse.remove(tarFilePath);
1098
+ await fse__default.remove(tarFilePath);
834
1099
  }
835
1100
  process.exit(0);
836
1101
  } catch (e) {
@@ -843,7 +1108,7 @@ async function getProject(ctx) {
843
1108
  const { project } = await retrieve();
844
1109
  if (!project) {
845
1110
  try {
846
- return await action$3(ctx);
1111
+ return await action$4(ctx);
847
1112
  } catch (e) {
848
1113
  ctx.logger.error("An error occurred while deploying the project. Please try again later.");
849
1114
  ctx.logger.debug(e);
@@ -852,10 +1117,21 @@ async function getProject(ctx) {
852
1117
  }
853
1118
  return project;
854
1119
  }
855
- const action$2 = async (ctx) => {
1120
+ async function getConfig({
1121
+ ctx,
1122
+ cloudApiService
1123
+ }) {
1124
+ try {
1125
+ const { data: cliConfig2 } = await cloudApiService.config();
1126
+ return cliConfig2;
1127
+ } catch (e) {
1128
+ ctx.logger.debug("Failed to get cli config", e);
1129
+ return null;
1130
+ }
1131
+ }
1132
+ const action$3 = async (ctx) => {
856
1133
  const { getValidToken } = await tokenServiceFactory(ctx);
857
- const cloudApiService = await cloudApiFactory(ctx);
858
- const token = await getValidToken();
1134
+ const token = await getValidToken(ctx, promptLogin);
859
1135
  if (!token) {
860
1136
  return;
861
1137
  }
@@ -863,14 +1139,51 @@ const action$2 = async (ctx) => {
863
1139
  if (!project) {
864
1140
  return;
865
1141
  }
1142
+ const cloudApiService = await cloudApiFactory(ctx, token);
866
1143
  try {
867
- await cloudApiService.track("willDeployWithCLI", { projectInternalName: project.name });
1144
+ const {
1145
+ data: { data: projectData, metadata }
1146
+ } = await cloudApiService.getProject({ name: project.name });
1147
+ const isProjectSuspended = projectData.suspendedAt;
1148
+ if (isProjectSuspended) {
1149
+ ctx.logger.log(
1150
+ "\n Oops! This project has been suspended. \n\n Please reactivate it from the dashboard to continue deploying: "
1151
+ );
1152
+ ctx.logger.log(chalk.underline(`${metadata.dashboardUrls.project}`));
1153
+ return;
1154
+ }
868
1155
  } catch (e) {
869
- ctx.logger.debug("Failed to track willDeploy", e);
1156
+ if (e instanceof AxiosError && e.response?.data) {
1157
+ if (e.response.status === 404) {
1158
+ ctx.logger.warn(
1159
+ `The project associated with this folder does not exist in Strapi Cloud.
1160
+ Please link your local project to an existing Strapi Cloud project using the ${chalk.cyan(
1161
+ "link"
1162
+ )} command before deploying.`
1163
+ );
1164
+ } else {
1165
+ ctx.logger.error(e.response.data);
1166
+ }
1167
+ } else {
1168
+ ctx.logger.error(
1169
+ "An error occurred while retrieving the project's information. Please try again later."
1170
+ );
1171
+ }
1172
+ ctx.logger.debug(e);
1173
+ return;
870
1174
  }
1175
+ await trackEvent(ctx, cloudApiService, "willDeployWithCLI", {
1176
+ projectInternalName: project.name
1177
+ });
871
1178
  const notificationService = notificationServiceFactory(ctx);
872
1179
  const buildLogsService = buildLogsServiceFactory(ctx);
873
- const { data: cliConfig2 } = await cloudApiService.config();
1180
+ const cliConfig2 = await getConfig({ ctx, cloudApiService });
1181
+ if (!cliConfig2) {
1182
+ ctx.logger.error(
1183
+ "An error occurred while retrieving data from Strapi Cloud. Please check your network or try again later."
1184
+ );
1185
+ return;
1186
+ }
874
1187
  let maxSize = parseInt(cliConfig2.maxProjectFileSize, 10);
875
1188
  if (Number.isNaN(maxSize)) {
876
1189
  ctx.logger.debug(
@@ -892,10 +1205,11 @@ const action$2 = async (ctx) => {
892
1205
  chalk.underline(`${apiConfig.dashboardBaseUrl}/projects/${project.name}/deployments`)
893
1206
  );
894
1207
  } catch (e) {
1208
+ ctx.logger.debug(e);
895
1209
  if (e instanceof Error) {
896
1210
  ctx.logger.error(e.message);
897
1211
  } else {
898
- throw e;
1212
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
899
1213
  }
900
1214
  }
901
1215
  };
@@ -926,186 +1240,175 @@ const runAction = (name2, action2) => (...args) => {
926
1240
  process.exit(1);
927
1241
  });
928
1242
  };
929
- const command$3 = ({ command: command2, ctx }) => {
930
- 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));
1243
+ const command$5 = ({ command: command2, ctx }) => {
1244
+ 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));
931
1245
  };
932
1246
  const deployProject = {
933
1247
  name: "deploy-project",
934
1248
  description: "Deploy a Strapi Cloud project",
935
- action: action$2,
936
- command: command$3
1249
+ action: action$3,
1250
+ command: command$5
937
1251
  };
938
- const openModule$1 = import("open");
939
- const action$1 = async (ctx) => {
940
- const { logger } = ctx;
941
- const tokenService = await tokenServiceFactory(ctx);
942
- const existingToken = await tokenService.retrieveToken();
943
- const cloudApiService = await cloudApiFactory(ctx, existingToken || void 0);
944
- const trackFailedLogin = async () => {
945
- try {
946
- await cloudApiService.track("didNotLogin", { loginMethod: "cli" });
947
- } catch (e) {
948
- logger.debug("Failed to track failed login", e);
949
- }
950
- };
951
- if (existingToken) {
952
- const isTokenValid = await tokenService.isTokenValid(existingToken);
953
- if (isTokenValid) {
954
- try {
955
- const userInfo = await cloudApiService.getUserInfo();
956
- const { email } = userInfo.data.data;
957
- if (email) {
958
- logger.log(`You are already logged into your account (${email}).`);
959
- } else {
960
- logger.log("You are already logged in.");
961
- }
962
- logger.log(
963
- "To access your dashboard, please copy and paste the following URL into your web browser:"
964
- );
965
- logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
966
- return true;
967
- } catch (e) {
968
- logger.debug("Failed to fetch user info", e);
1252
+ const QUIT_OPTION = "Quit";
1253
+ async function getExistingConfig(ctx) {
1254
+ try {
1255
+ return await retrieve();
1256
+ } catch (e) {
1257
+ ctx.logger.debug("Failed to get project config", e);
1258
+ ctx.logger.error("An error occurred while retrieving config data from your local project.");
1259
+ return null;
1260
+ }
1261
+ }
1262
+ async function promptForRelink(ctx, cloudApiService, existingConfig) {
1263
+ if (existingConfig && existingConfig.project) {
1264
+ const { shouldRelink } = await inquirer.prompt([
1265
+ {
1266
+ type: "confirm",
1267
+ name: "shouldRelink",
1268
+ message: `A project named ${chalk.cyan(
1269
+ existingConfig.project.displayName ? existingConfig.project.displayName : existingConfig.project.name
1270
+ )} is already linked to this local folder. Do you want to update the link?`,
1271
+ default: false
969
1272
  }
1273
+ ]);
1274
+ if (!shouldRelink) {
1275
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1276
+ currentProjectName: existingConfig.project?.name
1277
+ });
1278
+ return false;
970
1279
  }
971
1280
  }
972
- let cliConfig2;
1281
+ return true;
1282
+ }
1283
+ async function getProjectsList(ctx, cloudApiService, existingConfig) {
1284
+ const spinner = ctx.logger.spinner("Fetching your projects...\n").start();
973
1285
  try {
974
- logger.info("🔌 Connecting to the Strapi Cloud API...");
975
- const config = await cloudApiService.config();
976
- cliConfig2 = config.data;
1286
+ const {
1287
+ data: { data: projectList }
1288
+ } = await cloudApiService.listLinkProjects();
1289
+ spinner.succeed();
1290
+ if (!Array.isArray(projectList)) {
1291
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1292
+ return null;
1293
+ }
1294
+ const projects = projectList.filter(
1295
+ (project) => !(project.isMaintainer || project.name === existingConfig?.project?.name)
1296
+ ).map((project) => {
1297
+ return {
1298
+ name: project.displayName,
1299
+ value: { name: project.name, displayName: project.displayName }
1300
+ };
1301
+ });
1302
+ if (projects.length === 0) {
1303
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1304
+ return null;
1305
+ }
1306
+ return projects;
977
1307
  } catch (e) {
978
- logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
979
- logger.debug(e);
980
- return false;
1308
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1309
+ ctx.logger.debug("Failed to list projects", e);
1310
+ return null;
981
1311
  }
1312
+ }
1313
+ async function getUserSelection(ctx, projects) {
1314
+ const { logger } = ctx;
982
1315
  try {
983
- await cloudApiService.track("willLoginAttempt", {});
1316
+ const answer = await inquirer.prompt([
1317
+ {
1318
+ type: "list",
1319
+ name: "linkProject",
1320
+ message: "Which project do you want to link?",
1321
+ choices: [...projects, { name: chalk.grey(`(${QUIT_OPTION})`), value: null }]
1322
+ }
1323
+ ]);
1324
+ if (!answer.linkProject) {
1325
+ return null;
1326
+ }
1327
+ return answer;
984
1328
  } catch (e) {
985
- logger.debug("Failed to track login attempt", e);
1329
+ logger.debug("Failed to get user input", e);
1330
+ logger.error("An error occurred while trying to get your input.");
1331
+ return null;
986
1332
  }
987
- logger.debug("🔐 Creating device authentication request...", {
988
- client_id: cliConfig2.clientId,
989
- scope: cliConfig2.scope,
990
- audience: cliConfig2.audience
991
- });
992
- const deviceAuthResponse = await axios.post(cliConfig2.deviceCodeAuthUrl, {
993
- client_id: cliConfig2.clientId,
994
- scope: cliConfig2.scope,
995
- audience: cliConfig2.audience
996
- }).catch((e) => {
997
- logger.error("There was an issue with the authentication process. Please try again.");
998
- if (e.message) {
999
- logger.debug(e.message, e);
1000
- } else {
1001
- logger.debug(e);
1002
- }
1003
- });
1004
- openModule$1.then((open) => {
1005
- open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
1006
- logger.error("We encountered an issue opening the browser. Please try again later.");
1007
- logger.debug(e.message, e);
1008
- });
1009
- });
1010
- logger.log("If a browser tab does not open automatically, please follow the next steps:");
1011
- logger.log(
1012
- `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
1013
- );
1014
- logger.log(
1015
- `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
1016
- `
1333
+ }
1334
+ const action$2 = async (ctx) => {
1335
+ const { getValidToken } = await tokenServiceFactory(ctx);
1336
+ const token = await getValidToken(ctx, promptLogin);
1337
+ const { logger } = ctx;
1338
+ if (!token) {
1339
+ return;
1340
+ }
1341
+ const cloudApiService = await cloudApiFactory(ctx, token);
1342
+ const existingConfig = await getExistingConfig(ctx);
1343
+ const shouldRelink = await promptForRelink(ctx, cloudApiService, existingConfig);
1344
+ if (!shouldRelink) {
1345
+ return;
1346
+ }
1347
+ await trackEvent(ctx, cloudApiService, "willLinkProject", {});
1348
+ const projects = await getProjectsList(
1349
+ ctx,
1350
+ cloudApiService,
1351
+ existingConfig
1017
1352
  );
1018
- const tokenPayload = {
1019
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1020
- device_code: deviceAuthResponse.data.device_code,
1021
- client_id: cliConfig2.clientId
1022
- };
1023
- let isAuthenticated = false;
1024
- const authenticate = async () => {
1025
- const spinner = logger.spinner("Waiting for authentication");
1026
- spinner.start();
1027
- const spinnerFail = () => spinner.fail("Authentication failed!");
1028
- while (!isAuthenticated) {
1029
- try {
1030
- const tokenResponse = await axios.post(cliConfig2.tokenUrl, tokenPayload);
1031
- const authTokenData = tokenResponse.data;
1032
- if (tokenResponse.status === 200) {
1033
- try {
1034
- logger.debug("🔐 Validating token...");
1035
- await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
1036
- logger.debug("🔐 Token validation successful!");
1037
- } catch (e) {
1038
- logger.debug(e);
1039
- spinnerFail();
1040
- throw new Error("Unable to proceed: Token validation failed");
1041
- }
1042
- logger.debug("🔍 Fetching user information...");
1043
- const cloudApiServiceWithToken = await cloudApiFactory(ctx, authTokenData.access_token);
1044
- await cloudApiServiceWithToken.getUserInfo();
1045
- logger.debug("🔍 User information fetched successfully!");
1046
- try {
1047
- logger.debug("📝 Saving login information...");
1048
- await tokenService.saveToken(authTokenData.access_token);
1049
- logger.debug("📝 Login information saved successfully!");
1050
- isAuthenticated = true;
1051
- } catch (e) {
1052
- logger.error(
1053
- "There was a problem saving your login information. Please try logging in again."
1054
- );
1055
- logger.debug(e);
1056
- spinnerFail();
1057
- return false;
1058
- }
1059
- }
1060
- } catch (e) {
1061
- if (e.message === "Unable to proceed: Token validation failed") {
1062
- logger.error(
1063
- "There seems to be a problem with your login information. Please try logging in again."
1064
- );
1065
- spinnerFail();
1066
- await trackFailedLogin();
1067
- return false;
1068
- }
1069
- if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
1070
- logger.debug(e);
1071
- spinnerFail();
1072
- await trackFailedLogin();
1073
- return false;
1074
- }
1075
- await new Promise((resolve) => {
1076
- setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
1077
- });
1353
+ if (!projects) {
1354
+ return;
1355
+ }
1356
+ const answer = await getUserSelection(ctx, projects);
1357
+ if (!answer) {
1358
+ return;
1359
+ }
1360
+ try {
1361
+ const { confirmAction } = await inquirer.prompt([
1362
+ {
1363
+ type: "confirm",
1364
+ name: "confirmAction",
1365
+ message: "Warning: Once linked, deploying from CLI will replace the existing project and its data. Confirm to proceed:",
1366
+ default: false
1078
1367
  }
1368
+ ]);
1369
+ if (!confirmAction) {
1370
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1371
+ cancelledProjectName: answer.linkProject.name,
1372
+ currentProjectName: existingConfig ? existingConfig.project?.name : null
1373
+ });
1374
+ return;
1079
1375
  }
1080
- spinner.succeed("Authentication successful!");
1081
- logger.log("You are now logged into Strapi Cloud.");
1082
- logger.log(
1083
- "To access your dashboard, please copy and paste the following URL into your web browser:"
1084
- );
1085
- logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
1086
- try {
1087
- await cloudApiService.track("didLogin", { loginMethod: "cli" });
1088
- } catch (e) {
1089
- logger.debug("Failed to track login", e);
1090
- }
1091
- };
1092
- await authenticate();
1093
- return isAuthenticated;
1376
+ await save({ project: answer.linkProject });
1377
+ logger.log(`Project ${chalk.cyan(answer.linkProject.displayName)} linked successfully.`);
1378
+ await trackEvent(ctx, cloudApiService, "didLinkProject", {
1379
+ projectInternalName: answer.linkProject
1380
+ });
1381
+ } catch (e) {
1382
+ logger.debug("Failed to link project", e);
1383
+ logger.error("An error occurred while linking the project.");
1384
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1385
+ projectInternalName: answer.linkProject
1386
+ });
1387
+ }
1094
1388
  };
1095
- const command$2 = ({ command: command2, ctx }) => {
1389
+ const command$4 = ({ command: command2, ctx }) => {
1390
+ 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));
1391
+ };
1392
+ const link = {
1393
+ name: "link-project",
1394
+ description: "Link a local directory to a Strapi Cloud project",
1395
+ action: action$2,
1396
+ command: command$4
1397
+ };
1398
+ const command$3 = ({ command: command2, ctx }) => {
1096
1399
  command2.command("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1097
1400
  "after",
1098
1401
  "\nAfter running this command, you will be prompted to enter your authentication information."
1099
- ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", action$1)(ctx));
1402
+ ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", loginAction)(ctx));
1100
1403
  };
1101
1404
  const login = {
1102
1405
  name: "login",
1103
1406
  description: "Strapi Cloud Login",
1104
- action: action$1,
1105
- command: command$2
1407
+ action: loginAction,
1408
+ command: command$3
1106
1409
  };
1107
1410
  const openModule = import("open");
1108
- const action = async (ctx) => {
1411
+ const action$1 = async (ctx) => {
1109
1412
  const { logger } = ctx;
1110
1413
  const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx);
1111
1414
  const token = await retrieveToken();
@@ -1135,37 +1438,64 @@ const action = async (ctx) => {
1135
1438
  logger.error("🥲 Oops! Something went wrong while logging you out. Please try again.");
1136
1439
  logger.debug(e);
1137
1440
  }
1138
- try {
1139
- await cloudApiService.track("didLogout", { loginMethod: "cli" });
1140
- } catch (e) {
1141
- logger.debug("Failed to track logout event", e);
1142
- }
1441
+ await trackEvent(ctx, cloudApiService, "didLogout", { loginMethod: "cli" });
1143
1442
  };
1144
- const command$1 = ({ command: command2, ctx }) => {
1145
- 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));
1443
+ const command$2 = ({ command: command2, ctx }) => {
1444
+ 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));
1146
1445
  };
1147
1446
  const logout = {
1148
1447
  name: "logout",
1149
1448
  description: "Strapi Cloud Logout",
1150
- action,
1151
- command: command$1
1449
+ action: action$1,
1450
+ command: command$2
1152
1451
  };
1153
- const command = ({ command: command2, ctx }) => {
1154
- 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));
1452
+ const command$1 = ({ command: command2, ctx }) => {
1453
+ 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));
1155
1454
  };
1156
1455
  const createProject = {
1157
1456
  name: "create-project",
1158
1457
  description: "Create a new project",
1159
- action: action$3,
1458
+ action: action$4,
1459
+ command: command$1
1460
+ };
1461
+ const action = async (ctx) => {
1462
+ const { getValidToken } = await tokenServiceFactory(ctx);
1463
+ const token = await getValidToken(ctx, promptLogin);
1464
+ const { logger } = ctx;
1465
+ if (!token) {
1466
+ return;
1467
+ }
1468
+ const cloudApiService = await cloudApiFactory(ctx, token);
1469
+ const spinner = logger.spinner("Fetching your projects...").start();
1470
+ try {
1471
+ const {
1472
+ data: { data: projectList }
1473
+ } = await cloudApiService.listProjects();
1474
+ spinner.succeed();
1475
+ logger.log(projectList);
1476
+ } catch (e) {
1477
+ ctx.logger.debug("Failed to list projects", e);
1478
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1479
+ }
1480
+ };
1481
+ const command = ({ command: command2, ctx }) => {
1482
+ 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));
1483
+ };
1484
+ const listProjects = {
1485
+ name: "list-projects",
1486
+ description: "List Strapi Cloud projects",
1487
+ action,
1160
1488
  command
1161
1489
  };
1162
1490
  const cli = {
1163
1491
  deployProject,
1492
+ link,
1164
1493
  login,
1165
1494
  logout,
1166
- createProject
1495
+ createProject,
1496
+ listProjects
1167
1497
  };
1168
- const cloudCommands = [deployProject, login, logout];
1498
+ const cloudCommands = [deployProject, link, login, logout, listProjects];
1169
1499
  async function initCloudCLIConfig() {
1170
1500
  const localConfig = await getLocalConfig();
1171
1501
  if (!localConfig.deviceId) {