@strapi/cloud-cli 0.0.0-next.b11829e6c6aacb45bc1ec2f341609d04d88080d2 → 0.0.0-next.c6549bf210addfc92e2ffc84d41d7629cc3c3363

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +18 -3
  2. package/dist/index.js +664 -313
  3. package/dist/index.js.map +1 -1
  4. package/dist/index.mjs +654 -300
  5. package/dist/index.mjs.map +1 -1
  6. package/dist/src/create-project/action.d.ts +1 -1
  7. package/dist/src/create-project/action.d.ts.map +1 -1
  8. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts +3 -0
  9. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts.map +1 -0
  10. package/dist/src/create-project/utils/project-questions.utils.d.ts +20 -0
  11. package/dist/src/create-project/utils/project-questions.utils.d.ts.map +1 -0
  12. package/dist/src/deploy-project/action.d.ts.map +1 -1
  13. package/dist/src/index.d.ts +2 -0
  14. package/dist/src/index.d.ts.map +1 -1
  15. package/dist/src/link/action.d.ts +4 -0
  16. package/dist/src/link/action.d.ts.map +1 -0
  17. package/dist/src/link/command.d.ts +7 -0
  18. package/dist/src/link/command.d.ts.map +1 -0
  19. package/dist/src/link/index.d.ts +7 -0
  20. package/dist/src/link/index.d.ts.map +1 -0
  21. package/dist/src/list-projects/action.d.ts +4 -0
  22. package/dist/src/list-projects/action.d.ts.map +1 -0
  23. package/dist/src/list-projects/command.d.ts +7 -0
  24. package/dist/src/list-projects/command.d.ts.map +1 -0
  25. package/dist/src/list-projects/index.d.ts +7 -0
  26. package/dist/src/list-projects/index.d.ts.map +1 -0
  27. package/dist/src/login/action.d.ts +2 -2
  28. package/dist/src/login/action.d.ts.map +1 -1
  29. package/dist/src/logout/action.d.ts.map +1 -1
  30. package/dist/src/services/build-logs.d.ts.map +1 -1
  31. package/dist/src/services/cli-api.d.ts +38 -8
  32. package/dist/src/services/cli-api.d.ts.map +1 -1
  33. package/dist/src/services/strapi-info-save.d.ts +1 -1
  34. package/dist/src/services/strapi-info-save.d.ts.map +1 -1
  35. package/dist/src/services/token.d.ts +1 -1
  36. package/dist/src/services/token.d.ts.map +1 -1
  37. package/dist/src/types.d.ts +1 -0
  38. package/dist/src/types.d.ts.map +1 -1
  39. package/dist/src/utils/analytics.d.ts +4 -0
  40. package/dist/src/utils/analytics.d.ts.map +1 -0
  41. package/dist/src/utils/compress-files.d.ts.map +1 -1
  42. package/dist/src/utils/pkg.d.ts.map +1 -1
  43. package/package.json +7 -6
  44. package/dist/src/utils/tests/compress-files.test.d.ts +0 -2
  45. package/dist/src/utils/tests/compress-files.test.d.ts.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,12 +1,12 @@
1
1
  import crypto$1 from "crypto";
2
- import fse from "fs-extra";
2
+ import * as fse from "fs-extra";
3
+ import fse__default from "fs-extra";
3
4
  import * as path from "path";
4
5
  import path__default from "path";
5
6
  import chalk from "chalk";
6
7
  import axios, { AxiosError } from "axios";
7
8
  import * as crypto from "node:crypto";
8
9
  import { env } from "@strapi/utils";
9
- import * as fs from "fs";
10
10
  import * as tar from "tar";
11
11
  import { minimatch } from "minimatch";
12
12
  import inquirer from "inquirer";
@@ -18,10 +18,9 @@ import jwt from "jsonwebtoken";
18
18
  import stringify from "fast-safe-stringify";
19
19
  import ora from "ora";
20
20
  import * as cliProgress from "cli-progress";
21
- import EventSource from "eventsource";
22
- import fs$1 from "fs/promises";
23
21
  import pkgUp from "pkg-up";
24
22
  import * as yup from "yup";
23
+ import EventSource from "eventsource";
25
24
  const apiConfig = {
26
25
  apiBaseUrl: env("STRAPI_CLI_CLOUD_API", "https://cloud-cli-api.strapi.io"),
27
26
  dashboardBaseUrl: env("STRAPI_CLI_CLOUD_DASHBOARD", "https://cloud.strapi.io")
@@ -40,23 +39,6 @@ const IGNORED_PATTERNS = [
40
39
  "**/.idea/**",
41
40
  "**/.vscode/**"
42
41
  ];
43
- const getFiles = (dirPath, ignorePatterns = [], arrayOfFiles = [], subfolder = "") => {
44
- const entries = fs.readdirSync(path.join(dirPath, subfolder));
45
- entries.forEach((entry) => {
46
- const entryPathFromRoot = path.join(subfolder, entry);
47
- const entryPath = path.relative(dirPath, entryPathFromRoot);
48
- const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
49
- if (isIgnored) {
50
- return;
51
- }
52
- if (fs.statSync(entryPath).isDirectory()) {
53
- getFiles(dirPath, ignorePatterns, arrayOfFiles, entryPathFromRoot);
54
- } else {
55
- arrayOfFiles.push(entryPath);
56
- }
57
- });
58
- return arrayOfFiles;
59
- };
60
42
  const isIgnoredFile = (folderPath, file, ignorePatterns) => {
61
43
  ignorePatterns.push(...IGNORED_PATTERNS);
62
44
  const relativeFilePath = path.join(folderPath, file);
@@ -74,16 +56,35 @@ const isIgnoredFile = (folderPath, file, ignorePatterns) => {
74
56
  }
75
57
  return isIgnored;
76
58
  };
77
- const readGitignore = (folderPath) => {
59
+ const getFiles = async (dirPath, ignorePatterns = [], subfolder = "") => {
60
+ const arrayOfFiles = [];
61
+ const entries = await fse.readdir(path.join(dirPath, subfolder));
62
+ for (const entry of entries) {
63
+ const entryPathFromRoot = path.join(subfolder, entry);
64
+ const entryPath = path.relative(dirPath, entryPathFromRoot);
65
+ const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
66
+ if (!isIgnored) {
67
+ if (fse.statSync(entryPath).isDirectory()) {
68
+ const subFiles = await getFiles(dirPath, ignorePatterns, entryPathFromRoot);
69
+ arrayOfFiles.push(...subFiles);
70
+ } else {
71
+ arrayOfFiles.push(entryPath);
72
+ }
73
+ }
74
+ }
75
+ return arrayOfFiles;
76
+ };
77
+ const readGitignore = async (folderPath) => {
78
78
  const gitignorePath = path.resolve(folderPath, ".gitignore");
79
- if (!fs.existsSync(gitignorePath))
79
+ const pathExist = await fse.pathExists(gitignorePath);
80
+ if (!pathExist)
80
81
  return [];
81
- const gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
82
+ const gitignoreContent = await fse.readFile(gitignorePath, "utf8");
82
83
  return gitignoreContent.split(/\r?\n/).filter((line) => Boolean(line.trim()) && !line.startsWith("#"));
83
84
  };
84
85
  const compressFilesToTar = async (storagePath, folderToCompress, filename) => {
85
- const ignorePatterns = readGitignore(folderToCompress);
86
- const filesToCompress = getFiles(folderToCompress, ignorePatterns);
86
+ const ignorePatterns = await readGitignore(folderToCompress);
87
+ const filesToCompress = await getFiles(folderToCompress, ignorePatterns);
87
88
  return tar.c(
88
89
  {
89
90
  gzip: true,
@@ -96,7 +97,7 @@ const APP_FOLDER_NAME = "com.strapi.cli";
96
97
  const CONFIG_FILENAME = "config.json";
97
98
  async function checkDirectoryExists(directoryPath) {
98
99
  try {
99
- const fsStat = await fse.lstat(directoryPath);
100
+ const fsStat = await fse__default.lstat(directoryPath);
100
101
  return fsStat.isDirectory();
101
102
  } catch (e) {
102
103
  return false;
@@ -104,14 +105,14 @@ async function checkDirectoryExists(directoryPath) {
104
105
  }
105
106
  async function getTmpStoragePath() {
106
107
  const storagePath = path__default.join(os.tmpdir(), APP_FOLDER_NAME);
107
- await fse.ensureDir(storagePath);
108
+ await fse__default.ensureDir(storagePath);
108
109
  return storagePath;
109
110
  }
110
111
  async function getConfigPath() {
111
112
  const configDirs = XDGAppPaths(APP_FOLDER_NAME).configDirs();
112
113
  const configPath = configDirs.find(checkDirectoryExists);
113
114
  if (!configPath) {
114
- await fse.ensureDir(configDirs[0]);
115
+ await fse__default.ensureDir(configDirs[0]);
115
116
  return configDirs[0];
116
117
  }
117
118
  return configPath;
@@ -119,9 +120,9 @@ async function getConfigPath() {
119
120
  async function getLocalConfig() {
120
121
  const configPath = await getConfigPath();
121
122
  const configFilePath = path__default.join(configPath, CONFIG_FILENAME);
122
- await fse.ensureFile(configFilePath);
123
+ await fse__default.ensureFile(configFilePath);
123
124
  try {
124
- return await fse.readJSON(configFilePath, { encoding: "utf8", throws: true });
125
+ return await fse__default.readJSON(configFilePath, { encoding: "utf8", throws: true });
125
126
  } catch (e) {
126
127
  return {};
127
128
  }
@@ -129,10 +130,10 @@ async function getLocalConfig() {
129
130
  async function saveLocalConfig(data) {
130
131
  const configPath = await getConfigPath();
131
132
  const configFilePath = path__default.join(configPath, CONFIG_FILENAME);
132
- await fse.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
133
+ await fse__default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
133
134
  }
134
135
  const name = "@strapi/cloud-cli";
135
- const version = "4.25.0";
136
+ const version = "4.25.9";
136
137
  const description = "Commands to interact with the Strapi Cloud";
137
138
  const keywords = [
138
139
  "strapi",
@@ -173,11 +174,12 @@ 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.0",
180
- axios: "1.6.0",
181
+ "@strapi/utils": "4.25.9",
182
+ axios: "1.7.4",
181
183
  chalk: "4.1.2",
182
184
  "cli-progress": "3.12.0",
183
185
  commander: "8.3.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.0",
205
- tsconfig: "4.25.0"
206
+ "eslint-config-custom": "4.25.9",
207
+ tsconfig: "4.25.9"
206
208
  };
207
209
  const engines = {
208
210
  node: ">=18.0.0 <=20.x.x",
@@ -231,7 +233,7 @@ const packageJson = {
231
233
  engines
232
234
  };
233
235
  const VERSION = "v1";
234
- async function cloudApiFactory(token) {
236
+ async function cloudApiFactory({ logger }, token) {
235
237
  const localConfig = await getLocalConfig();
236
238
  const customHeaders = {
237
239
  "x-device-id": localConfig.deviceId,
@@ -255,7 +257,7 @@ async function cloudApiFactory(token) {
255
257
  deploy({ filePath, project }, { onUploadProgress }) {
256
258
  return axiosCloudAPI.post(
257
259
  `/deploy/${project.name}`,
258
- { file: fse.createReadStream(filePath) },
260
+ { file: fse__default.createReadStream(filePath) },
259
261
  {
260
262
  headers: {
261
263
  "Content-Type": "multipart/form-data"
@@ -284,11 +286,61 @@ async function cloudApiFactory(token) {
284
286
  getUserInfo() {
285
287
  return axiosCloudAPI.get("/user");
286
288
  },
287
- config() {
288
- return axiosCloudAPI.get("/config");
289
+ async config() {
290
+ try {
291
+ const response = await axiosCloudAPI.get("/config");
292
+ if (response.status !== 200) {
293
+ throw new Error("Error fetching cloud CLI config from the server.");
294
+ }
295
+ return response;
296
+ } catch (error) {
297
+ logger.debug(
298
+ "🥲 Oops! Couldn't retrieve the cloud CLI config from the server. Please try again."
299
+ );
300
+ throw error;
301
+ }
302
+ },
303
+ async listProjects() {
304
+ try {
305
+ const response = await axiosCloudAPI.get("/projects");
306
+ if (response.status !== 200) {
307
+ throw new Error("Error fetching cloud projects from the server.");
308
+ }
309
+ return response;
310
+ } catch (error) {
311
+ logger.debug(
312
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
313
+ );
314
+ throw error;
315
+ }
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
+ }
289
330
  },
290
- listProjects() {
291
- return axiosCloudAPI.get("/projects");
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
+ }
292
344
  },
293
345
  track(event, payload = {}) {
294
346
  return axiosCloudAPI.post("/track", {
@@ -303,18 +355,18 @@ async function save(data, { directoryPath } = {}) {
303
355
  const alreadyInFileData = await retrieve({ directoryPath });
304
356
  const storedData = { ...alreadyInFileData, ...data };
305
357
  const pathToFile = path__default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
306
- await fse.ensureDir(path__default.dirname(pathToFile));
307
- await fse.writeJson(pathToFile, storedData, { encoding: "utf8" });
358
+ await fse__default.ensureDir(path__default.dirname(pathToFile));
359
+ await fse__default.writeJson(pathToFile, storedData, { encoding: "utf8" });
308
360
  }
309
361
  async function retrieve({
310
362
  directoryPath
311
363
  } = {}) {
312
364
  const pathToFile = path__default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
313
- const pathExists = await fse.pathExists(pathToFile);
365
+ const pathExists = await fse__default.pathExists(pathToFile);
314
366
  if (!pathExists) {
315
367
  return {};
316
368
  }
317
- return fse.readJSON(pathToFile, { encoding: "utf8" });
369
+ return fse__default.readJSON(pathToFile, { encoding: "utf8" });
318
370
  }
319
371
  const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
320
372
  __proto__: null,
@@ -324,7 +376,7 @@ const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defi
324
376
  }, Symbol.toStringTag, { value: "Module" }));
325
377
  let cliConfig;
326
378
  async function tokenServiceFactory({ logger }) {
327
- const cloudApiService = await cloudApiFactory();
379
+ const cloudApiService = await cloudApiFactory({ logger });
328
380
  async function saveToken(str) {
329
381
  const appConfig = await getLocalConfig();
330
382
  if (!appConfig) {
@@ -373,14 +425,17 @@ async function tokenServiceFactory({ logger }) {
373
425
  "There seems to be a problem with your login information. Please try logging in again."
374
426
  );
375
427
  }
428
+ return Promise.reject(new Error("Invalid token"));
376
429
  }
377
430
  return new Promise((resolve, reject) => {
378
431
  jwt.verify(idToken, getKey, (err) => {
379
432
  if (err) {
380
433
  reject(err);
381
- } else {
382
- resolve();
383
434
  }
435
+ if (decodedToken.payload.exp < Math.floor(Date.now() / 1e3)) {
436
+ reject(new Error("Token is expired"));
437
+ }
438
+ resolve();
384
439
  });
385
440
  });
386
441
  }
@@ -414,15 +469,15 @@ async function tokenServiceFactory({ logger }) {
414
469
  throw e;
415
470
  }
416
471
  }
417
- async function getValidToken() {
418
- const token = await retrieveToken();
419
- if (!token) {
420
- logger.log("No token found. Please login first.");
421
- return null;
422
- }
423
- if (!await isTokenValid(token)) {
424
- logger.log("Unable to proceed: Token is expired or not valid. Please login again.");
425
- return null;
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();
426
481
  }
427
482
  return token;
428
483
  }
@@ -556,17 +611,254 @@ const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePropert
556
611
  local: strapiInfoSave,
557
612
  tokenServiceFactory
558
613
  }, Symbol.toStringTag, { value: "Module" }));
559
- async function handleError(ctx, error) {
614
+ yup.object({
615
+ name: yup.string().required(),
616
+ exports: yup.lazy(
617
+ (value) => yup.object(
618
+ typeof value === "object" ? Object.entries(value).reduce((acc, [key, value2]) => {
619
+ if (typeof value2 === "object") {
620
+ acc[key] = yup.object({
621
+ types: yup.string().optional(),
622
+ source: yup.string().required(),
623
+ module: yup.string().optional(),
624
+ import: yup.string().required(),
625
+ require: yup.string().required(),
626
+ default: yup.string().required()
627
+ }).noUnknown(true);
628
+ } else {
629
+ acc[key] = yup.string().matches(/^\.\/.*\.json$/).required();
630
+ }
631
+ return acc;
632
+ }, {}) : void 0
633
+ ).optional()
634
+ )
635
+ });
636
+ const loadPkg = async ({ cwd, logger }) => {
637
+ const pkgPath = await pkgUp({ cwd });
638
+ if (!pkgPath) {
639
+ throw new Error("Could not find a package.json in the current directory");
640
+ }
641
+ const buffer = await fse.readFile(pkgPath);
642
+ const pkg = JSON.parse(buffer.toString());
643
+ logger.debug("Loaded package.json:", os.EOL, pkg);
644
+ return pkg;
645
+ };
646
+ async function getProjectNameFromPackageJson(ctx) {
647
+ try {
648
+ const packageJson2 = await loadPkg(ctx);
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?"
668
+ }
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;
560
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) {
684
+ try {
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) {
561
857
  const { logger } = ctx;
562
858
  logger.debug(error);
563
859
  if (error instanceof AxiosError) {
564
860
  const errorMessage = typeof error.response?.data === "string" ? error.response.data : null;
565
861
  switch (error.response?.status) {
566
- case 401:
567
- logger.error("Your session has expired. Please log in again.");
568
- await tokenService.eraseToken();
569
- return;
570
862
  case 403:
571
863
  logger.error(
572
864
  errorMessage || "You do not have permission to create a project. Please contact support for assistance."
@@ -592,29 +884,54 @@ async function handleError(ctx, error) {
592
884
  "We encountered an issue while creating your project. Please try again in a moment. If the problem persists, contact support for assistance."
593
885
  );
594
886
  }
595
- const action$3 = async (ctx) => {
887
+ async function createProject$1(ctx, cloudApi, projectInput) {
596
888
  const { logger } = ctx;
597
- const { getValidToken } = await tokenServiceFactory(ctx);
598
- const token = await getValidToken();
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);
599
904
  if (!token) {
600
905
  return;
601
906
  }
602
- const cloudApi = await cloudApiFactory(token);
907
+ const cloudApi = await cloudApiFactory(ctx, token);
603
908
  const { data: config } = await cloudApi.config();
604
- const { questions, defaults: defaultValues } = config.projectCreation;
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
+ };
605
919
  const projectAnswersDefaulted = defaults(defaultValues);
606
920
  const projectAnswers = await inquirer.prompt(questions);
607
921
  const projectInput = projectAnswersDefaulted(projectAnswers);
608
- const spinner = logger.spinner("Setting up your project...").start();
609
922
  try {
610
- const { data } = await cloudApi.createProject(projectInput);
611
- await save({ project: data });
612
- spinner.succeed("Project created successfully!");
613
- return data;
923
+ return await createProject$1(ctx, cloudApi, projectInput);
614
924
  } catch (e) {
615
- spinner.fail("Failed to create project on Strapi Cloud.");
616
- await handleError(ctx, e);
617
- }
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
+ }
618
935
  };
619
936
  function notificationServiceFactory({ logger }) {
620
937
  return (url, token, cliConfig2) => {
@@ -647,38 +964,6 @@ function notificationServiceFactory({ logger }) {
647
964
  };
648
965
  };
649
966
  }
650
- yup.object({
651
- name: yup.string().required(),
652
- exports: yup.lazy(
653
- (value) => yup.object(
654
- typeof value === "object" ? Object.entries(value).reduce((acc, [key, value2]) => {
655
- if (typeof value2 === "object") {
656
- acc[key] = yup.object({
657
- types: yup.string().optional(),
658
- source: yup.string().required(),
659
- module: yup.string().optional(),
660
- import: yup.string().required(),
661
- require: yup.string().required(),
662
- default: yup.string().required()
663
- }).noUnknown(true);
664
- } else {
665
- acc[key] = yup.string().matches(/^\.\/.*\.json$/).required();
666
- }
667
- return acc;
668
- }, {}) : void 0
669
- ).optional()
670
- )
671
- });
672
- const loadPkg = async ({ cwd, logger }) => {
673
- const pkgPath = await pkgUp({ cwd });
674
- if (!pkgPath) {
675
- throw new Error("Could not find a package.json in the current directory");
676
- }
677
- const buffer = await fs$1.readFile(pkgPath);
678
- const pkg = JSON.parse(buffer.toString());
679
- logger.debug("Loaded package.json:", os.EOL, pkg);
680
- return pkg;
681
- };
682
967
  const buildLogsServiceFactory = ({ logger }) => {
683
968
  return async (url, token, cliConfig2) => {
684
969
  const CONN_TIMEOUT = Number(cliConfig2.buildLogsConnectionTimeout);
@@ -732,6 +1017,7 @@ const buildLogsServiceFactory = ({ logger }) => {
732
1017
  if (retries > MAX_RETRIES) {
733
1018
  spinner.fail("We were unable to connect to the server to get build logs at this time.");
734
1019
  es.close();
1020
+ clearExistingTimeout();
735
1021
  reject(new Error("Max retries reached"));
736
1022
  }
737
1023
  };
@@ -741,7 +1027,7 @@ const buildLogsServiceFactory = ({ logger }) => {
741
1027
  };
742
1028
  };
743
1029
  async function upload(ctx, project, token, maxProjectFileSize) {
744
- const cloudApi = await cloudApiFactory(token);
1030
+ const cloudApi = await cloudApiFactory(ctx, token);
745
1031
  try {
746
1032
  const storagePath = await getTmpStoragePath();
747
1033
  const projectFolder = path__default.resolve(process.cwd());
@@ -774,13 +1060,13 @@ async function upload(ctx, project, token, maxProjectFileSize) {
774
1060
  process.exit(1);
775
1061
  }
776
1062
  const tarFilePath = path__default.resolve(storagePath, compressedFilename);
777
- const fileStats = await fse.stat(tarFilePath);
1063
+ const fileStats = await fse__default.stat(tarFilePath);
778
1064
  if (fileStats.size > maxProjectFileSize) {
779
1065
  ctx.logger.log(
780
1066
  "Unable to proceed: Your project is too big to be transferred, please use a git repo instead."
781
1067
  );
782
1068
  try {
783
- await fse.remove(tarFilePath);
1069
+ await fse__default.remove(tarFilePath);
784
1070
  } catch (e) {
785
1071
  ctx.logger.log("Unable to remove file: ", tarFilePath);
786
1072
  ctx.logger.debug(e);
@@ -806,20 +1092,10 @@ async function upload(ctx, project, token, maxProjectFileSize) {
806
1092
  return data.build_id;
807
1093
  } catch (e) {
808
1094
  progressBar.stop();
809
- if (e instanceof AxiosError && e.response?.data) {
810
- if (e.response.status === 404) {
811
- ctx.logger.error(
812
- `The project does not exist. Remove the ${LOCAL_SAVE_FILENAME} file and try again.`
813
- );
814
- } else {
815
- ctx.logger.error(e.response.data);
816
- }
817
- } else {
818
- ctx.logger.error("An error occurred while deploying the project. Please try again later.");
819
- }
1095
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
820
1096
  ctx.logger.debug(e);
821
1097
  } finally {
822
- await fse.remove(tarFilePath);
1098
+ await fse__default.remove(tarFilePath);
823
1099
  }
824
1100
  process.exit(0);
825
1101
  } catch (e) {
@@ -832,7 +1108,7 @@ async function getProject(ctx) {
832
1108
  const { project } = await retrieve();
833
1109
  if (!project) {
834
1110
  try {
835
- return await action$3(ctx);
1111
+ return await action$4(ctx);
836
1112
  } catch (e) {
837
1113
  ctx.logger.error("An error occurred while deploying the project. Please try again later.");
838
1114
  ctx.logger.debug(e);
@@ -841,10 +1117,21 @@ async function getProject(ctx) {
841
1117
  }
842
1118
  return project;
843
1119
  }
844
- 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) => {
845
1133
  const { getValidToken } = await tokenServiceFactory(ctx);
846
- const cloudApiService = await cloudApiFactory();
847
- const token = await getValidToken();
1134
+ const token = await getValidToken(ctx, promptLogin);
848
1135
  if (!token) {
849
1136
  return;
850
1137
  }
@@ -852,14 +1139,51 @@ const action$2 = async (ctx) => {
852
1139
  if (!project) {
853
1140
  return;
854
1141
  }
1142
+ const cloudApiService = await cloudApiFactory(ctx, token);
855
1143
  try {
856
- 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
+ }
857
1155
  } catch (e) {
858
- 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;
859
1174
  }
1175
+ await trackEvent(ctx, cloudApiService, "willDeployWithCLI", {
1176
+ projectInternalName: project.name
1177
+ });
860
1178
  const notificationService = notificationServiceFactory(ctx);
861
1179
  const buildLogsService = buildLogsServiceFactory(ctx);
862
- 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
+ }
863
1187
  let maxSize = parseInt(cliConfig2.maxProjectFileSize, 10);
864
1188
  if (Number.isNaN(maxSize)) {
865
1189
  ctx.logger.debug(
@@ -881,10 +1205,11 @@ const action$2 = async (ctx) => {
881
1205
  chalk.underline(`${apiConfig.dashboardBaseUrl}/projects/${project.name}/deployments`)
882
1206
  );
883
1207
  } catch (e) {
1208
+ ctx.logger.debug(e);
884
1209
  if (e instanceof Error) {
885
1210
  ctx.logger.error(e.message);
886
1211
  } else {
887
- throw e;
1212
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
888
1213
  }
889
1214
  }
890
1215
  };
@@ -915,185 +1240,175 @@ const runAction = (name2, action2) => (...args) => {
915
1240
  process.exit(1);
916
1241
  });
917
1242
  };
918
- const command$3 = ({ command: command2, ctx }) => {
919
- command2.command("cloud:deploy").alias("deploy").description("Deploy a Strapi Cloud project").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("deploy", action$2)(ctx));
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));
920
1245
  };
921
1246
  const deployProject = {
922
1247
  name: "deploy-project",
923
1248
  description: "Deploy a Strapi Cloud project",
924
- action: action$2,
925
- command: command$3
1249
+ action: action$3,
1250
+ command: command$5
926
1251
  };
927
- const openModule = import("open");
928
- const action$1 = async (ctx) => {
929
- const { logger } = ctx;
930
- const tokenService = await tokenServiceFactory(ctx);
931
- const existingToken = await tokenService.retrieveToken();
932
- const cloudApiService = await cloudApiFactory(existingToken || void 0);
933
- const trackFailedLogin = async () => {
934
- try {
935
- await cloudApiService.track("didNotLogin", { loginMethod: "cli" });
936
- } catch (e) {
937
- logger.debug("Failed to track failed login", e);
938
- }
939
- };
940
- if (existingToken) {
941
- const isTokenValid = await tokenService.isTokenValid(existingToken);
942
- if (isTokenValid) {
943
- try {
944
- const userInfo = await cloudApiService.getUserInfo();
945
- const { email } = userInfo.data.data;
946
- if (email) {
947
- logger.log(`You are already logged into your account (${email}).`);
948
- } else {
949
- logger.log("You are already logged in.");
950
- }
951
- logger.log(
952
- "To access your dashboard, please copy and paste the following URL into your web browser:"
953
- );
954
- logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
955
- return true;
956
- } catch (e) {
957
- logger.debug("Failed to fetch user info", e);
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
958
1272
  }
1273
+ ]);
1274
+ if (!shouldRelink) {
1275
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1276
+ currentProjectName: existingConfig.project?.name
1277
+ });
1278
+ return false;
959
1279
  }
960
1280
  }
961
- let cliConfig2;
1281
+ return true;
1282
+ }
1283
+ async function getProjectsList(ctx, cloudApiService, existingConfig) {
1284
+ const spinner = ctx.logger.spinner("Fetching your projects...\n").start();
962
1285
  try {
963
- logger.info("🔌 Connecting to the Strapi Cloud API...");
964
- const config = await cloudApiService.config();
965
- 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;
966
1307
  } catch (e) {
967
- logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
968
- logger.debug(e);
969
- 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;
970
1311
  }
1312
+ }
1313
+ async function getUserSelection(ctx, projects) {
1314
+ const { logger } = ctx;
971
1315
  try {
972
- 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;
973
1328
  } catch (e) {
974
- 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;
975
1332
  }
976
- logger.debug("🔐 Creating device authentication request...", {
977
- client_id: cliConfig2.clientId,
978
- scope: cliConfig2.scope,
979
- audience: cliConfig2.audience
980
- });
981
- const deviceAuthResponse = await axios.post(cliConfig2.deviceCodeAuthUrl, {
982
- client_id: cliConfig2.clientId,
983
- scope: cliConfig2.scope,
984
- audience: cliConfig2.audience
985
- }).catch((e) => {
986
- logger.error("There was an issue with the authentication process. Please try again.");
987
- if (e.message) {
988
- logger.debug(e.message, e);
989
- } else {
990
- logger.debug(e);
991
- }
992
- });
993
- openModule.then((open) => {
994
- open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
995
- logger.error("We encountered an issue opening the browser. Please try again later.");
996
- logger.debug(e.message, e);
997
- });
998
- });
999
- logger.log("If a browser tab does not open automatically, please follow the next steps:");
1000
- logger.log(
1001
- `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
1002
- );
1003
- logger.log(
1004
- `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
1005
- `
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
1006
1352
  );
1007
- const tokenPayload = {
1008
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1009
- device_code: deviceAuthResponse.data.device_code,
1010
- client_id: cliConfig2.clientId
1011
- };
1012
- let isAuthenticated = false;
1013
- const authenticate = async () => {
1014
- const spinner = logger.spinner("Waiting for authentication");
1015
- spinner.start();
1016
- const spinnerFail = () => spinner.fail("Authentication failed!");
1017
- while (!isAuthenticated) {
1018
- try {
1019
- const tokenResponse = await axios.post(cliConfig2.tokenUrl, tokenPayload);
1020
- const authTokenData = tokenResponse.data;
1021
- if (tokenResponse.status === 200) {
1022
- try {
1023
- logger.debug("🔐 Validating token...");
1024
- await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
1025
- logger.debug("🔐 Token validation successful!");
1026
- } catch (e) {
1027
- logger.debug(e);
1028
- spinnerFail();
1029
- throw new Error("Unable to proceed: Token validation failed");
1030
- }
1031
- logger.debug("🔍 Fetching user information...");
1032
- const cloudApiServiceWithToken = await cloudApiFactory(authTokenData.access_token);
1033
- await cloudApiServiceWithToken.getUserInfo();
1034
- logger.debug("🔍 User information fetched successfully!");
1035
- try {
1036
- logger.debug("📝 Saving login information...");
1037
- await tokenService.saveToken(authTokenData.access_token);
1038
- logger.debug("📝 Login information saved successfully!");
1039
- isAuthenticated = true;
1040
- } catch (e) {
1041
- logger.error(
1042
- "There was a problem saving your login information. Please try logging in again."
1043
- );
1044
- logger.debug(e);
1045
- spinnerFail();
1046
- return false;
1047
- }
1048
- }
1049
- } catch (e) {
1050
- if (e.message === "Unable to proceed: Token validation failed") {
1051
- logger.error(
1052
- "There seems to be a problem with your login information. Please try logging in again."
1053
- );
1054
- spinnerFail();
1055
- await trackFailedLogin();
1056
- return false;
1057
- }
1058
- if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
1059
- logger.debug(e);
1060
- spinnerFail();
1061
- await trackFailedLogin();
1062
- return false;
1063
- }
1064
- await new Promise((resolve) => {
1065
- setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
1066
- });
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
1067
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;
1068
1375
  }
1069
- spinner.succeed("Authentication successful!");
1070
- logger.log("You are now logged into Strapi Cloud.");
1071
- logger.log(
1072
- "To access your dashboard, please copy and paste the following URL into your web browser:"
1073
- );
1074
- logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
1075
- try {
1076
- await cloudApiService.track("didLogin", { loginMethod: "cli" });
1077
- } catch (e) {
1078
- logger.debug("Failed to track login", e);
1079
- }
1080
- };
1081
- await authenticate();
1082
- return isAuthenticated;
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
+ }
1083
1388
  };
1084
- 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 }) => {
1085
1399
  command2.command("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1086
1400
  "after",
1087
1401
  "\nAfter running this command, you will be prompted to enter your authentication information."
1088
- ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", action$1)(ctx));
1402
+ ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", loginAction)(ctx));
1089
1403
  };
1090
1404
  const login = {
1091
1405
  name: "login",
1092
1406
  description: "Strapi Cloud Login",
1093
- action: action$1,
1094
- command: command$2
1407
+ action: loginAction,
1408
+ command: command$3
1095
1409
  };
1096
- const action = async (ctx) => {
1410
+ const openModule = import("open");
1411
+ const action$1 = async (ctx) => {
1097
1412
  const { logger } = ctx;
1098
1413
  const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx);
1099
1414
  const token = await retrieveToken();
@@ -1101,9 +1416,21 @@ const action = async (ctx) => {
1101
1416
  logger.log("You're already logged out.");
1102
1417
  return;
1103
1418
  }
1104
- const cloudApiService = await cloudApiFactory(token);
1419
+ const cloudApiService = await cloudApiFactory(ctx, token);
1420
+ const config = await cloudApiService.config();
1421
+ const cliConfig2 = config.data;
1105
1422
  try {
1106
1423
  await eraseToken();
1424
+ openModule.then((open) => {
1425
+ open.default(
1426
+ `${cliConfig2.baseUrl}/oidc/logout?client_id=${encodeURIComponent(
1427
+ cliConfig2.clientId
1428
+ )}&logout_hint=${encodeURIComponent(token)}
1429
+ `
1430
+ ).catch((e) => {
1431
+ logger.debug(e.message, e);
1432
+ });
1433
+ });
1107
1434
  logger.log(
1108
1435
  "🔌 You have been logged out from the CLI. If you are on a shared computer, please make sure to log out from the Strapi Cloud Dashboard as well."
1109
1436
  );
@@ -1111,37 +1438,64 @@ const action = async (ctx) => {
1111
1438
  logger.error("🥲 Oops! Something went wrong while logging you out. Please try again.");
1112
1439
  logger.debug(e);
1113
1440
  }
1114
- try {
1115
- await cloudApiService.track("didLogout", { loginMethod: "cli" });
1116
- } catch (e) {
1117
- logger.debug("Failed to track logout event", e);
1118
- }
1441
+ await trackEvent(ctx, cloudApiService, "didLogout", { loginMethod: "cli" });
1119
1442
  };
1120
- const command$1 = ({ command: command2, ctx }) => {
1121
- command2.command("cloud:logout").alias("logout").description("Strapi Cloud Logout").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("logout", action)(ctx));
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));
1122
1445
  };
1123
1446
  const logout = {
1124
1447
  name: "logout",
1125
1448
  description: "Strapi Cloud Logout",
1126
- action,
1127
- command: command$1
1449
+ action: action$1,
1450
+ command: command$2
1128
1451
  };
1129
- const command = ({ command: command2, ctx }) => {
1130
- command2.command("cloud:create-project").description("Create a Strapi Cloud project").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("cloud:create-project", action$3)(ctx));
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));
1131
1454
  };
1132
1455
  const createProject = {
1133
1456
  name: "create-project",
1134
1457
  description: "Create a new project",
1135
- 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,
1136
1488
  command
1137
1489
  };
1138
1490
  const cli = {
1139
1491
  deployProject,
1492
+ link,
1140
1493
  login,
1141
1494
  logout,
1142
- createProject
1495
+ createProject,
1496
+ listProjects
1143
1497
  };
1144
- const cloudCommands = [deployProject, login, logout];
1498
+ const cloudCommands = [deployProject, link, login, logout, listProjects];
1145
1499
  async function initCloudCLIConfig() {
1146
1500
  const localConfig = await getLocalConfig();
1147
1501
  if (!localConfig.deviceId) {