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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +18 -3
  2. package/dist/index.js +610 -295
  3. package/dist/index.js.map +1 -1
  4. package/dist/index.mjs +610 -292
  5. package/dist/index.mjs.map +1 -1
  6. package/dist/src/create-project/action.d.ts +1 -1
  7. package/dist/src/create-project/action.d.ts.map +1 -1
  8. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts +3 -0
  9. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts.map +1 -0
  10. package/dist/src/create-project/utils/project-questions.utils.d.ts +20 -0
  11. package/dist/src/create-project/utils/project-questions.utils.d.ts.map +1 -0
  12. package/dist/src/deploy-project/action.d.ts.map +1 -1
  13. package/dist/src/index.d.ts +2 -0
  14. package/dist/src/index.d.ts.map +1 -1
  15. package/dist/src/link/action.d.ts +4 -0
  16. package/dist/src/link/action.d.ts.map +1 -0
  17. package/dist/src/link/command.d.ts +7 -0
  18. package/dist/src/link/command.d.ts.map +1 -0
  19. package/dist/src/link/index.d.ts +7 -0
  20. package/dist/src/link/index.d.ts.map +1 -0
  21. package/dist/src/list-projects/action.d.ts +4 -0
  22. package/dist/src/list-projects/action.d.ts.map +1 -0
  23. package/dist/src/list-projects/command.d.ts +7 -0
  24. package/dist/src/list-projects/command.d.ts.map +1 -0
  25. package/dist/src/list-projects/index.d.ts +7 -0
  26. package/dist/src/list-projects/index.d.ts.map +1 -0
  27. package/dist/src/login/action.d.ts +2 -2
  28. package/dist/src/login/action.d.ts.map +1 -1
  29. package/dist/src/logout/action.d.ts.map +1 -1
  30. package/dist/src/services/build-logs.d.ts.map +1 -1
  31. package/dist/src/services/cli-api.d.ts +22 -8
  32. package/dist/src/services/cli-api.d.ts.map +1 -1
  33. package/dist/src/services/strapi-info-save.d.ts +1 -1
  34. package/dist/src/services/strapi-info-save.d.ts.map +1 -1
  35. package/dist/src/services/token.d.ts +1 -1
  36. package/dist/src/services/token.d.ts.map +1 -1
  37. package/dist/src/types.d.ts +1 -0
  38. package/dist/src/types.d.ts.map +1 -1
  39. package/dist/src/utils/analytics.d.ts +4 -0
  40. package/dist/src/utils/analytics.d.ts.map +1 -0
  41. package/dist/src/utils/compress-files.d.ts.map +1 -1
  42. package/dist/src/utils/pkg.d.ts.map +1 -1
  43. package/package.json +6 -5
  44. package/dist/src/utils/tests/compress-files.test.d.ts +0 -2
  45. package/dist/src/utils/tests/compress-files.test.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -29,7 +29,6 @@ const chalk = require("chalk");
29
29
  const axios = require("axios");
30
30
  const crypto = require("node:crypto");
31
31
  const utils = require("@strapi/utils");
32
- const fs = require("fs");
33
32
  const tar = require("tar");
34
33
  const minimatch = require("minimatch");
35
34
  const inquirer = require("inquirer");
@@ -41,10 +40,9 @@ const jwt = require("jsonwebtoken");
41
40
  const stringify = require("fast-safe-stringify");
42
41
  const ora = require("ora");
43
42
  const cliProgress = require("cli-progress");
44
- const EventSource = require("eventsource");
45
- const fs$1 = require("fs/promises");
46
43
  const pkgUp = require("pkg-up");
47
44
  const yup = require("yup");
45
+ const EventSource = require("eventsource");
48
46
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
49
47
  function _interopNamespace(e) {
50
48
  if (e && e.__esModule)
@@ -65,12 +63,11 @@ function _interopNamespace(e) {
65
63
  return Object.freeze(n);
66
64
  }
67
65
  const crypto__default = /* @__PURE__ */ _interopDefault(crypto$1);
68
- const fse__default = /* @__PURE__ */ _interopDefault(fse);
66
+ const fse__namespace = /* @__PURE__ */ _interopNamespace(fse);
69
67
  const path__namespace = /* @__PURE__ */ _interopNamespace(path);
70
68
  const chalk__default = /* @__PURE__ */ _interopDefault(chalk);
71
69
  const axios__default = /* @__PURE__ */ _interopDefault(axios);
72
70
  const crypto__namespace = /* @__PURE__ */ _interopNamespace(crypto);
73
- const fs__namespace = /* @__PURE__ */ _interopNamespace(fs);
74
71
  const tar__namespace = /* @__PURE__ */ _interopNamespace(tar);
75
72
  const inquirer__default = /* @__PURE__ */ _interopDefault(inquirer);
76
73
  const os__default = /* @__PURE__ */ _interopDefault(os);
@@ -80,10 +77,9 @@ const jwt__default = /* @__PURE__ */ _interopDefault(jwt);
80
77
  const stringify__default = /* @__PURE__ */ _interopDefault(stringify);
81
78
  const ora__default = /* @__PURE__ */ _interopDefault(ora);
82
79
  const cliProgress__namespace = /* @__PURE__ */ _interopNamespace(cliProgress);
83
- const EventSource__default = /* @__PURE__ */ _interopDefault(EventSource);
84
- const fs__default = /* @__PURE__ */ _interopDefault(fs$1);
85
80
  const pkgUp__default = /* @__PURE__ */ _interopDefault(pkgUp);
86
81
  const yup__namespace = /* @__PURE__ */ _interopNamespace(yup);
82
+ const EventSource__default = /* @__PURE__ */ _interopDefault(EventSource);
87
83
  const apiConfig = {
88
84
  apiBaseUrl: utils.env("STRAPI_CLI_CLOUD_API", "https://cloud-cli-api.strapi.io"),
89
85
  dashboardBaseUrl: utils.env("STRAPI_CLI_CLOUD_DASHBOARD", "https://cloud.strapi.io")
@@ -102,23 +98,6 @@ const IGNORED_PATTERNS = [
102
98
  "**/.idea/**",
103
99
  "**/.vscode/**"
104
100
  ];
105
- const getFiles = (dirPath, ignorePatterns = [], arrayOfFiles = [], subfolder = "") => {
106
- const entries = fs__namespace.readdirSync(path__namespace.join(dirPath, subfolder));
107
- entries.forEach((entry) => {
108
- const entryPathFromRoot = path__namespace.join(subfolder, entry);
109
- const entryPath = path__namespace.relative(dirPath, entryPathFromRoot);
110
- const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
111
- if (isIgnored) {
112
- return;
113
- }
114
- if (fs__namespace.statSync(entryPath).isDirectory()) {
115
- getFiles(dirPath, ignorePatterns, arrayOfFiles, entryPathFromRoot);
116
- } else {
117
- arrayOfFiles.push(entryPath);
118
- }
119
- });
120
- return arrayOfFiles;
121
- };
122
101
  const isIgnoredFile = (folderPath, file, ignorePatterns) => {
123
102
  ignorePatterns.push(...IGNORED_PATTERNS);
124
103
  const relativeFilePath = path__namespace.join(folderPath, file);
@@ -136,16 +115,35 @@ const isIgnoredFile = (folderPath, file, ignorePatterns) => {
136
115
  }
137
116
  return isIgnored;
138
117
  };
139
- const readGitignore = (folderPath) => {
118
+ const getFiles = async (dirPath, ignorePatterns = [], subfolder = "") => {
119
+ const arrayOfFiles = [];
120
+ const entries = await fse__namespace.readdir(path__namespace.join(dirPath, subfolder));
121
+ for (const entry of entries) {
122
+ const entryPathFromRoot = path__namespace.join(subfolder, entry);
123
+ const entryPath = path__namespace.relative(dirPath, entryPathFromRoot);
124
+ const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
125
+ if (!isIgnored) {
126
+ if (fse__namespace.statSync(entryPath).isDirectory()) {
127
+ const subFiles = await getFiles(dirPath, ignorePatterns, entryPathFromRoot);
128
+ arrayOfFiles.push(...subFiles);
129
+ } else {
130
+ arrayOfFiles.push(entryPath);
131
+ }
132
+ }
133
+ }
134
+ return arrayOfFiles;
135
+ };
136
+ const readGitignore = async (folderPath) => {
140
137
  const gitignorePath = path__namespace.resolve(folderPath, ".gitignore");
141
- if (!fs__namespace.existsSync(gitignorePath))
138
+ const pathExist = await fse__namespace.pathExists(gitignorePath);
139
+ if (!pathExist)
142
140
  return [];
143
- const gitignoreContent = fs__namespace.readFileSync(gitignorePath, "utf8");
141
+ const gitignoreContent = await fse__namespace.readFile(gitignorePath, "utf8");
144
142
  return gitignoreContent.split(/\r?\n/).filter((line) => Boolean(line.trim()) && !line.startsWith("#"));
145
143
  };
146
144
  const compressFilesToTar = async (storagePath, folderToCompress, filename) => {
147
- const ignorePatterns = readGitignore(folderToCompress);
148
- const filesToCompress = getFiles(folderToCompress, ignorePatterns);
145
+ const ignorePatterns = await readGitignore(folderToCompress);
146
+ const filesToCompress = await getFiles(folderToCompress, ignorePatterns);
149
147
  return tar__namespace.c(
150
148
  {
151
149
  gzip: true,
@@ -158,7 +156,7 @@ const APP_FOLDER_NAME = "com.strapi.cli";
158
156
  const CONFIG_FILENAME = "config.json";
159
157
  async function checkDirectoryExists(directoryPath) {
160
158
  try {
161
- const fsStat = await fse__default.default.lstat(directoryPath);
159
+ const fsStat = await fse__namespace.default.lstat(directoryPath);
162
160
  return fsStat.isDirectory();
163
161
  } catch (e) {
164
162
  return false;
@@ -166,14 +164,14 @@ async function checkDirectoryExists(directoryPath) {
166
164
  }
167
165
  async function getTmpStoragePath() {
168
166
  const storagePath = path__namespace.default.join(os__default.default.tmpdir(), APP_FOLDER_NAME);
169
- await fse__default.default.ensureDir(storagePath);
167
+ await fse__namespace.default.ensureDir(storagePath);
170
168
  return storagePath;
171
169
  }
172
170
  async function getConfigPath() {
173
171
  const configDirs = XDGAppPaths__default.default(APP_FOLDER_NAME).configDirs();
174
172
  const configPath = configDirs.find(checkDirectoryExists);
175
173
  if (!configPath) {
176
- await fse__default.default.ensureDir(configDirs[0]);
174
+ await fse__namespace.default.ensureDir(configDirs[0]);
177
175
  return configDirs[0];
178
176
  }
179
177
  return configPath;
@@ -181,9 +179,9 @@ async function getConfigPath() {
181
179
  async function getLocalConfig() {
182
180
  const configPath = await getConfigPath();
183
181
  const configFilePath = path__namespace.default.join(configPath, CONFIG_FILENAME);
184
- await fse__default.default.ensureFile(configFilePath);
182
+ await fse__namespace.default.ensureFile(configFilePath);
185
183
  try {
186
- return await fse__default.default.readJSON(configFilePath, { encoding: "utf8", throws: true });
184
+ return await fse__namespace.default.readJSON(configFilePath, { encoding: "utf8", throws: true });
187
185
  } catch (e) {
188
186
  return {};
189
187
  }
@@ -191,10 +189,10 @@ async function getLocalConfig() {
191
189
  async function saveLocalConfig(data) {
192
190
  const configPath = await getConfigPath();
193
191
  const configFilePath = path__namespace.default.join(configPath, CONFIG_FILENAME);
194
- await fse__default.default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
192
+ await fse__namespace.default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
195
193
  }
196
194
  const name = "@strapi/cloud-cli";
197
- const version = "4.25.1";
195
+ const version = "4.25.7";
198
196
  const description = "Commands to interact with the Strapi Cloud";
199
197
  const keywords = [
200
198
  "strapi",
@@ -235,10 +233,11 @@ const scripts = {
235
233
  build: "pack-up build",
236
234
  clean: "run -T rimraf ./dist",
237
235
  lint: "run -T eslint .",
236
+ "test:unit": "run -T jest",
238
237
  watch: "pack-up watch"
239
238
  };
240
239
  const dependencies = {
241
- "@strapi/utils": "4.25.1",
240
+ "@strapi/utils": "4.25.7",
242
241
  axios: "1.6.0",
243
242
  chalk: "4.1.2",
244
243
  "cli-progress": "3.12.0",
@@ -263,8 +262,8 @@ const devDependencies = {
263
262
  "@types/cli-progress": "3.11.5",
264
263
  "@types/eventsource": "1.1.15",
265
264
  "@types/lodash": "^4.14.191",
266
- "eslint-config-custom": "4.25.1",
267
- tsconfig: "4.25.1"
265
+ "eslint-config-custom": "4.25.7",
266
+ tsconfig: "4.25.7"
268
267
  };
269
268
  const engines = {
270
269
  node: ">=18.0.0 <=20.x.x",
@@ -293,7 +292,7 @@ const packageJson = {
293
292
  engines
294
293
  };
295
294
  const VERSION = "v1";
296
- async function cloudApiFactory(token) {
295
+ async function cloudApiFactory({ logger }, token) {
297
296
  const localConfig = await getLocalConfig();
298
297
  const customHeaders = {
299
298
  "x-device-id": localConfig.deviceId,
@@ -317,7 +316,7 @@ async function cloudApiFactory(token) {
317
316
  deploy({ filePath, project }, { onUploadProgress }) {
318
317
  return axiosCloudAPI.post(
319
318
  `/deploy/${project.name}`,
320
- { file: fse__default.default.createReadStream(filePath) },
319
+ { file: fse__namespace.default.createReadStream(filePath) },
321
320
  {
322
321
  headers: {
323
322
  "Content-Type": "multipart/form-data"
@@ -346,11 +345,47 @@ async function cloudApiFactory(token) {
346
345
  getUserInfo() {
347
346
  return axiosCloudAPI.get("/user");
348
347
  },
349
- config() {
350
- return axiosCloudAPI.get("/config");
348
+ async config() {
349
+ try {
350
+ const response = await axiosCloudAPI.get("/config");
351
+ if (response.status !== 200) {
352
+ throw new Error("Error fetching cloud CLI config from the server.");
353
+ }
354
+ return response;
355
+ } catch (error) {
356
+ logger.debug(
357
+ "🥲 Oops! Couldn't retrieve the cloud CLI config from the server. Please try again."
358
+ );
359
+ throw error;
360
+ }
361
+ },
362
+ async listProjects() {
363
+ try {
364
+ const response = await axiosCloudAPI.get("/projects");
365
+ if (response.status !== 200) {
366
+ throw new Error("Error fetching cloud projects from the server.");
367
+ }
368
+ return response;
369
+ } catch (error) {
370
+ logger.debug(
371
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
372
+ );
373
+ throw error;
374
+ }
351
375
  },
352
- listProjects() {
353
- return axiosCloudAPI.get("/projects");
376
+ async listLinkProjects() {
377
+ try {
378
+ const response = await axiosCloudAPI.get("/projects/linkable");
379
+ if (response.status !== 200) {
380
+ throw new Error("Error fetching cloud projects from the server.");
381
+ }
382
+ return response;
383
+ } catch (error) {
384
+ logger.debug(
385
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
386
+ );
387
+ throw error;
388
+ }
354
389
  },
355
390
  track(event, payload = {}) {
356
391
  return axiosCloudAPI.post("/track", {
@@ -365,18 +400,18 @@ async function save(data, { directoryPath } = {}) {
365
400
  const alreadyInFileData = await retrieve({ directoryPath });
366
401
  const storedData = { ...alreadyInFileData, ...data };
367
402
  const pathToFile = path__namespace.default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
368
- await fse__default.default.ensureDir(path__namespace.default.dirname(pathToFile));
369
- await fse__default.default.writeJson(pathToFile, storedData, { encoding: "utf8" });
403
+ await fse__namespace.default.ensureDir(path__namespace.default.dirname(pathToFile));
404
+ await fse__namespace.default.writeJson(pathToFile, storedData, { encoding: "utf8" });
370
405
  }
371
406
  async function retrieve({
372
407
  directoryPath
373
408
  } = {}) {
374
409
  const pathToFile = path__namespace.default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
375
- const pathExists = await fse__default.default.pathExists(pathToFile);
410
+ const pathExists = await fse__namespace.default.pathExists(pathToFile);
376
411
  if (!pathExists) {
377
412
  return {};
378
413
  }
379
- return fse__default.default.readJSON(pathToFile, { encoding: "utf8" });
414
+ return fse__namespace.default.readJSON(pathToFile, { encoding: "utf8" });
380
415
  }
381
416
  const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
382
417
  __proto__: null,
@@ -386,7 +421,7 @@ const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defi
386
421
  }, Symbol.toStringTag, { value: "Module" }));
387
422
  let cliConfig;
388
423
  async function tokenServiceFactory({ logger }) {
389
- const cloudApiService = await cloudApiFactory();
424
+ const cloudApiService = await cloudApiFactory({ logger });
390
425
  async function saveToken(str) {
391
426
  const appConfig = await getLocalConfig();
392
427
  if (!appConfig) {
@@ -435,14 +470,17 @@ async function tokenServiceFactory({ logger }) {
435
470
  "There seems to be a problem with your login information. Please try logging in again."
436
471
  );
437
472
  }
473
+ return Promise.reject(new Error("Invalid token"));
438
474
  }
439
475
  return new Promise((resolve, reject) => {
440
476
  jwt__default.default.verify(idToken, getKey, (err) => {
441
477
  if (err) {
442
478
  reject(err);
443
- } else {
444
- resolve();
445
479
  }
480
+ if (decodedToken.payload.exp < Math.floor(Date.now() / 1e3)) {
481
+ reject(new Error("Token is expired"));
482
+ }
483
+ resolve();
446
484
  });
447
485
  });
448
486
  }
@@ -476,15 +514,15 @@ async function tokenServiceFactory({ logger }) {
476
514
  throw e;
477
515
  }
478
516
  }
479
- async function getValidToken() {
480
- const token = await retrieveToken();
481
- if (!token) {
482
- logger.log("No token found. Please login first.");
483
- return null;
484
- }
485
- if (!await isTokenValid(token)) {
486
- logger.log("Unable to proceed: Token is expired or not valid. Please login again.");
487
- return null;
517
+ async function getValidToken(ctx, loginAction2) {
518
+ let token = await retrieveToken();
519
+ while (!token || !await isTokenValid(token)) {
520
+ logger.log(
521
+ 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."
522
+ );
523
+ if (!await loginAction2(ctx))
524
+ return null;
525
+ token = await retrieveToken();
488
526
  }
489
527
  return token;
490
528
  }
@@ -618,17 +656,254 @@ const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePropert
618
656
  local: strapiInfoSave,
619
657
  tokenServiceFactory
620
658
  }, Symbol.toStringTag, { value: "Module" }));
621
- async function handleError(ctx, error) {
659
+ yup__namespace.object({
660
+ name: yup__namespace.string().required(),
661
+ exports: yup__namespace.lazy(
662
+ (value) => yup__namespace.object(
663
+ typeof value === "object" ? Object.entries(value).reduce((acc, [key, value2]) => {
664
+ if (typeof value2 === "object") {
665
+ acc[key] = yup__namespace.object({
666
+ types: yup__namespace.string().optional(),
667
+ source: yup__namespace.string().required(),
668
+ module: yup__namespace.string().optional(),
669
+ import: yup__namespace.string().required(),
670
+ require: yup__namespace.string().required(),
671
+ default: yup__namespace.string().required()
672
+ }).noUnknown(true);
673
+ } else {
674
+ acc[key] = yup__namespace.string().matches(/^\.\/.*\.json$/).required();
675
+ }
676
+ return acc;
677
+ }, {}) : void 0
678
+ ).optional()
679
+ )
680
+ });
681
+ const loadPkg = async ({ cwd, logger }) => {
682
+ const pkgPath = await pkgUp__default.default({ cwd });
683
+ if (!pkgPath) {
684
+ throw new Error("Could not find a package.json in the current directory");
685
+ }
686
+ const buffer = await fse__namespace.readFile(pkgPath);
687
+ const pkg = JSON.parse(buffer.toString());
688
+ logger.debug("Loaded package.json:", os__default.default.EOL, pkg);
689
+ return pkg;
690
+ };
691
+ async function getProjectNameFromPackageJson(ctx) {
692
+ try {
693
+ const packageJson2 = await loadPkg(ctx);
694
+ return packageJson2.name || "my-strapi-project";
695
+ } catch (e) {
696
+ return "my-strapi-project";
697
+ }
698
+ }
699
+ const trackEvent = async (ctx, cloudApiService, eventName, eventData) => {
700
+ try {
701
+ await cloudApiService.track(eventName, eventData);
702
+ } catch (e) {
703
+ ctx.logger.debug(`Failed to track ${eventName}`, e);
704
+ }
705
+ };
706
+ const openModule$1 = import("open");
707
+ async function promptLogin(ctx) {
708
+ const response = await inquirer__default.default.prompt([
709
+ {
710
+ type: "confirm",
711
+ name: "login",
712
+ message: "Would you like to login?"
713
+ }
714
+ ]);
715
+ if (response.login) {
716
+ const loginSuccessful = await loginAction(ctx);
717
+ return loginSuccessful;
718
+ }
719
+ return false;
720
+ }
721
+ async function loginAction(ctx) {
722
+ const { logger } = ctx;
622
723
  const tokenService = await tokenServiceFactory(ctx);
724
+ const existingToken = await tokenService.retrieveToken();
725
+ const cloudApiService = await cloudApiFactory(ctx, existingToken || void 0);
726
+ if (existingToken) {
727
+ const isTokenValid = await tokenService.isTokenValid(existingToken);
728
+ if (isTokenValid) {
729
+ try {
730
+ const userInfo = await cloudApiService.getUserInfo();
731
+ const { email } = userInfo.data.data;
732
+ if (email) {
733
+ logger.log(`You are already logged into your account (${email}).`);
734
+ } else {
735
+ logger.log("You are already logged in.");
736
+ }
737
+ logger.log(
738
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
739
+ );
740
+ logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
741
+ return true;
742
+ } catch (e) {
743
+ logger.debug("Failed to fetch user info", e);
744
+ }
745
+ }
746
+ }
747
+ let cliConfig2;
748
+ try {
749
+ logger.info("🔌 Connecting to the Strapi Cloud API...");
750
+ const config = await cloudApiService.config();
751
+ cliConfig2 = config.data;
752
+ } catch (e) {
753
+ logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
754
+ logger.debug(e);
755
+ return false;
756
+ }
757
+ await trackEvent(ctx, cloudApiService, "willLoginAttempt", {});
758
+ logger.debug("🔐 Creating device authentication request...", {
759
+ client_id: cliConfig2.clientId,
760
+ scope: cliConfig2.scope,
761
+ audience: cliConfig2.audience
762
+ });
763
+ const deviceAuthResponse = await axios__default.default.post(cliConfig2.deviceCodeAuthUrl, {
764
+ client_id: cliConfig2.clientId,
765
+ scope: cliConfig2.scope,
766
+ audience: cliConfig2.audience
767
+ }).catch((e) => {
768
+ logger.error("There was an issue with the authentication process. Please try again.");
769
+ if (e.message) {
770
+ logger.debug(e.message, e);
771
+ } else {
772
+ logger.debug(e);
773
+ }
774
+ });
775
+ openModule$1.then((open) => {
776
+ open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
777
+ logger.error("We encountered an issue opening the browser. Please try again later.");
778
+ logger.debug(e.message, e);
779
+ });
780
+ });
781
+ logger.log("If a browser tab does not open automatically, please follow the next steps:");
782
+ logger.log(
783
+ `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
784
+ );
785
+ logger.log(
786
+ `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
787
+ `
788
+ );
789
+ const tokenPayload = {
790
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
791
+ device_code: deviceAuthResponse.data.device_code,
792
+ client_id: cliConfig2.clientId
793
+ };
794
+ let isAuthenticated = false;
795
+ const authenticate = async () => {
796
+ const spinner = logger.spinner("Waiting for authentication");
797
+ spinner.start();
798
+ const spinnerFail = () => spinner.fail("Authentication failed!");
799
+ while (!isAuthenticated) {
800
+ try {
801
+ const tokenResponse = await axios__default.default.post(cliConfig2.tokenUrl, tokenPayload);
802
+ const authTokenData = tokenResponse.data;
803
+ if (tokenResponse.status === 200) {
804
+ try {
805
+ logger.debug("🔐 Validating token...");
806
+ await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
807
+ logger.debug("🔐 Token validation successful!");
808
+ } catch (e) {
809
+ logger.debug(e);
810
+ spinnerFail();
811
+ throw new Error("Unable to proceed: Token validation failed");
812
+ }
813
+ logger.debug("🔍 Fetching user information...");
814
+ const cloudApiServiceWithToken = await cloudApiFactory(ctx, authTokenData.access_token);
815
+ await cloudApiServiceWithToken.getUserInfo();
816
+ logger.debug("🔍 User information fetched successfully!");
817
+ try {
818
+ logger.debug("📝 Saving login information...");
819
+ await tokenService.saveToken(authTokenData.access_token);
820
+ logger.debug("📝 Login information saved successfully!");
821
+ isAuthenticated = true;
822
+ } catch (e) {
823
+ logger.error(
824
+ "There was a problem saving your login information. Please try logging in again."
825
+ );
826
+ logger.debug(e);
827
+ spinnerFail();
828
+ return false;
829
+ }
830
+ }
831
+ } catch (e) {
832
+ if (e.message === "Unable to proceed: Token validation failed") {
833
+ logger.error(
834
+ "There seems to be a problem with your login information. Please try logging in again."
835
+ );
836
+ spinnerFail();
837
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
838
+ return false;
839
+ }
840
+ if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
841
+ logger.debug(e);
842
+ spinnerFail();
843
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
844
+ return false;
845
+ }
846
+ await new Promise((resolve) => {
847
+ setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
848
+ });
849
+ }
850
+ }
851
+ spinner.succeed("Authentication successful!");
852
+ logger.log("You are now logged into Strapi Cloud.");
853
+ logger.log(
854
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
855
+ );
856
+ logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
857
+ await trackEvent(ctx, cloudApiService, "didLogin", { loginMethod: "cli" });
858
+ };
859
+ await authenticate();
860
+ return isAuthenticated;
861
+ }
862
+ function questionDefaultValuesMapper(questionsMap) {
863
+ return (questions) => {
864
+ return questions.map((question) => {
865
+ const questionName = question.name;
866
+ if (questionName in questionsMap) {
867
+ const questionDefault = questionsMap[questionName];
868
+ if (typeof questionDefault === "function") {
869
+ return {
870
+ ...question,
871
+ default: questionDefault(question)
872
+ };
873
+ }
874
+ return {
875
+ ...question,
876
+ default: questionDefault
877
+ };
878
+ }
879
+ return question;
880
+ });
881
+ };
882
+ }
883
+ function getDefaultsFromQuestions(questions) {
884
+ return questions.reduce((acc, question) => {
885
+ if (question.default && question.name) {
886
+ return { ...acc, [question.name]: question.default };
887
+ }
888
+ return acc;
889
+ }, {});
890
+ }
891
+ function getProjectNodeVersionDefault(question) {
892
+ const currentNodeVersion = process.versions.node.split(".")[0];
893
+ if (question.type === "list" && Array.isArray(question.choices)) {
894
+ const choice = question.choices.find((choice2) => choice2.value === currentNodeVersion);
895
+ if (choice) {
896
+ return choice.value;
897
+ }
898
+ }
899
+ return question.default;
900
+ }
901
+ async function handleError(ctx, error) {
623
902
  const { logger } = ctx;
624
903
  logger.debug(error);
625
904
  if (error instanceof axios.AxiosError) {
626
905
  const errorMessage = typeof error.response?.data === "string" ? error.response.data : null;
627
906
  switch (error.response?.status) {
628
- case 401:
629
- logger.error("Your session has expired. Please log in again.");
630
- await tokenService.eraseToken();
631
- return;
632
907
  case 403:
633
908
  logger.error(
634
909
  errorMessage || "You do not have permission to create a project. Please contact support for assistance."
@@ -654,28 +929,53 @@ async function handleError(ctx, error) {
654
929
  "We encountered an issue while creating your project. Please try again in a moment. If the problem persists, contact support for assistance."
655
930
  );
656
931
  }
657
- const action$3 = async (ctx) => {
932
+ async function createProject$1(ctx, cloudApi, projectInput) {
658
933
  const { logger } = ctx;
659
- const { getValidToken } = await tokenServiceFactory(ctx);
660
- const token = await getValidToken();
934
+ const spinner = logger.spinner("Setting up your project...").start();
935
+ try {
936
+ const { data } = await cloudApi.createProject(projectInput);
937
+ await save({ project: data });
938
+ spinner.succeed("Project created successfully!");
939
+ return data;
940
+ } catch (e) {
941
+ spinner.fail("An error occurred while creating the project on Strapi Cloud.");
942
+ throw e;
943
+ }
944
+ }
945
+ const action$4 = async (ctx) => {
946
+ const { logger } = ctx;
947
+ const { getValidToken, eraseToken } = await tokenServiceFactory(ctx);
948
+ const token = await getValidToken(ctx, promptLogin);
661
949
  if (!token) {
662
950
  return;
663
951
  }
664
- const cloudApi = await cloudApiFactory(token);
952
+ const cloudApi = await cloudApiFactory(ctx, token);
665
953
  const { data: config } = await cloudApi.config();
666
- const { questions, defaults: defaultValues } = config.projectCreation;
954
+ const projectName = await getProjectNameFromPackageJson(ctx);
955
+ const defaultAnswersMapper = questionDefaultValuesMapper({
956
+ name: projectName,
957
+ nodeVersion: getProjectNodeVersionDefault
958
+ });
959
+ const questions = defaultAnswersMapper(config.projectCreation.questions);
960
+ const defaultValues = {
961
+ ...config.projectCreation.defaults,
962
+ ...getDefaultsFromQuestions(questions)
963
+ };
667
964
  const projectAnswersDefaulted = fp.defaults(defaultValues);
668
965
  const projectAnswers = await inquirer__default.default.prompt(questions);
669
966
  const projectInput = projectAnswersDefaulted(projectAnswers);
670
- const spinner = logger.spinner("Setting up your project...").start();
671
967
  try {
672
- const { data } = await cloudApi.createProject(projectInput);
673
- await save({ project: data });
674
- spinner.succeed("Project created successfully!");
675
- return data;
968
+ return await createProject$1(ctx, cloudApi, projectInput);
676
969
  } catch (e) {
677
- spinner.fail("Failed to create project on Strapi Cloud.");
678
- await handleError(ctx, e);
970
+ if (e instanceof axios.AxiosError && e.response?.status === 401) {
971
+ logger.warn("Oops! Your session has expired. Please log in again to retry.");
972
+ await eraseToken();
973
+ if (await promptLogin(ctx)) {
974
+ return await createProject$1(ctx, cloudApi, projectInput);
975
+ }
976
+ } else {
977
+ await handleError(ctx, e);
978
+ }
679
979
  }
680
980
  };
681
981
  function notificationServiceFactory({ logger }) {
@@ -709,38 +1009,6 @@ function notificationServiceFactory({ logger }) {
709
1009
  };
710
1010
  };
711
1011
  }
712
- yup__namespace.object({
713
- name: yup__namespace.string().required(),
714
- exports: yup__namespace.lazy(
715
- (value) => yup__namespace.object(
716
- typeof value === "object" ? Object.entries(value).reduce((acc, [key, value2]) => {
717
- if (typeof value2 === "object") {
718
- acc[key] = yup__namespace.object({
719
- types: yup__namespace.string().optional(),
720
- source: yup__namespace.string().required(),
721
- module: yup__namespace.string().optional(),
722
- import: yup__namespace.string().required(),
723
- require: yup__namespace.string().required(),
724
- default: yup__namespace.string().required()
725
- }).noUnknown(true);
726
- } else {
727
- acc[key] = yup__namespace.string().matches(/^\.\/.*\.json$/).required();
728
- }
729
- return acc;
730
- }, {}) : void 0
731
- ).optional()
732
- )
733
- });
734
- const loadPkg = async ({ cwd, logger }) => {
735
- const pkgPath = await pkgUp__default.default({ cwd });
736
- if (!pkgPath) {
737
- throw new Error("Could not find a package.json in the current directory");
738
- }
739
- const buffer = await fs__default.default.readFile(pkgPath);
740
- const pkg = JSON.parse(buffer.toString());
741
- logger.debug("Loaded package.json:", os__default.default.EOL, pkg);
742
- return pkg;
743
- };
744
1012
  const buildLogsServiceFactory = ({ logger }) => {
745
1013
  return async (url, token, cliConfig2) => {
746
1014
  const CONN_TIMEOUT = Number(cliConfig2.buildLogsConnectionTimeout);
@@ -794,6 +1062,7 @@ const buildLogsServiceFactory = ({ logger }) => {
794
1062
  if (retries > MAX_RETRIES) {
795
1063
  spinner.fail("We were unable to connect to the server to get build logs at this time.");
796
1064
  es.close();
1065
+ clearExistingTimeout();
797
1066
  reject(new Error("Max retries reached"));
798
1067
  }
799
1068
  };
@@ -803,7 +1072,7 @@ const buildLogsServiceFactory = ({ logger }) => {
803
1072
  };
804
1073
  };
805
1074
  async function upload(ctx, project, token, maxProjectFileSize) {
806
- const cloudApi = await cloudApiFactory(token);
1075
+ const cloudApi = await cloudApiFactory(ctx, token);
807
1076
  try {
808
1077
  const storagePath = await getTmpStoragePath();
809
1078
  const projectFolder = path__namespace.default.resolve(process.cwd());
@@ -836,13 +1105,13 @@ async function upload(ctx, project, token, maxProjectFileSize) {
836
1105
  process.exit(1);
837
1106
  }
838
1107
  const tarFilePath = path__namespace.default.resolve(storagePath, compressedFilename);
839
- const fileStats = await fse__default.default.stat(tarFilePath);
1108
+ const fileStats = await fse__namespace.default.stat(tarFilePath);
840
1109
  if (fileStats.size > maxProjectFileSize) {
841
1110
  ctx.logger.log(
842
1111
  "Unable to proceed: Your project is too big to be transferred, please use a git repo instead."
843
1112
  );
844
1113
  try {
845
- await fse__default.default.remove(tarFilePath);
1114
+ await fse__namespace.default.remove(tarFilePath);
846
1115
  } catch (e) {
847
1116
  ctx.logger.log("Unable to remove file: ", tarFilePath);
848
1117
  ctx.logger.debug(e);
@@ -870,8 +1139,8 @@ async function upload(ctx, project, token, maxProjectFileSize) {
870
1139
  progressBar.stop();
871
1140
  if (e instanceof axios.AxiosError && e.response?.data) {
872
1141
  if (e.response.status === 404) {
873
- ctx.logger.error(
874
- `The project does not exist. Remove the ${LOCAL_SAVE_FILENAME} file and try again.`
1142
+ ctx.logger.warn(
1143
+ `The project does not exist. Please link your local project to a Strapi Cloud project using the link command.`
875
1144
  );
876
1145
  } else {
877
1146
  ctx.logger.error(e.response.data);
@@ -881,7 +1150,7 @@ async function upload(ctx, project, token, maxProjectFileSize) {
881
1150
  }
882
1151
  ctx.logger.debug(e);
883
1152
  } finally {
884
- await fse__default.default.remove(tarFilePath);
1153
+ await fse__namespace.default.remove(tarFilePath);
885
1154
  }
886
1155
  process.exit(0);
887
1156
  } catch (e) {
@@ -894,7 +1163,7 @@ async function getProject(ctx) {
894
1163
  const { project } = await retrieve();
895
1164
  if (!project) {
896
1165
  try {
897
- return await action$3(ctx);
1166
+ return await action$4(ctx);
898
1167
  } catch (e) {
899
1168
  ctx.logger.error("An error occurred while deploying the project. Please try again later.");
900
1169
  ctx.logger.debug(e);
@@ -903,10 +1172,21 @@ async function getProject(ctx) {
903
1172
  }
904
1173
  return project;
905
1174
  }
906
- const action$2 = async (ctx) => {
1175
+ async function getConfig({
1176
+ ctx,
1177
+ cloudApiService
1178
+ }) {
1179
+ try {
1180
+ const { data: cliConfig2 } = await cloudApiService.config();
1181
+ return cliConfig2;
1182
+ } catch (e) {
1183
+ ctx.logger.debug("Failed to get cli config", e);
1184
+ return null;
1185
+ }
1186
+ }
1187
+ const action$3 = async (ctx) => {
907
1188
  const { getValidToken } = await tokenServiceFactory(ctx);
908
- const cloudApiService = await cloudApiFactory();
909
- const token = await getValidToken();
1189
+ const token = await getValidToken(ctx, promptLogin);
910
1190
  if (!token) {
911
1191
  return;
912
1192
  }
@@ -914,14 +1194,19 @@ const action$2 = async (ctx) => {
914
1194
  if (!project) {
915
1195
  return;
916
1196
  }
917
- try {
918
- await cloudApiService.track("willDeployWithCLI", { projectInternalName: project.name });
919
- } catch (e) {
920
- ctx.logger.debug("Failed to track willDeploy", e);
921
- }
1197
+ const cloudApiService = await cloudApiFactory(ctx);
1198
+ await trackEvent(ctx, cloudApiService, "willDeployWithCLI", {
1199
+ projectInternalName: project.name
1200
+ });
922
1201
  const notificationService = notificationServiceFactory(ctx);
923
1202
  const buildLogsService = buildLogsServiceFactory(ctx);
924
- const { data: cliConfig2 } = await cloudApiService.config();
1203
+ const cliConfig2 = await getConfig({ ctx, cloudApiService });
1204
+ if (!cliConfig2) {
1205
+ ctx.logger.error(
1206
+ "An error occurred while retrieving data from Strapi Cloud. Please try check your network or again later."
1207
+ );
1208
+ return;
1209
+ }
925
1210
  let maxSize = parseInt(cliConfig2.maxProjectFileSize, 10);
926
1211
  if (Number.isNaN(maxSize)) {
927
1212
  ctx.logger.debug(
@@ -943,10 +1228,11 @@ const action$2 = async (ctx) => {
943
1228
  chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects/${project.name}/deployments`)
944
1229
  );
945
1230
  } catch (e) {
1231
+ ctx.logger.debug(e);
946
1232
  if (e instanceof Error) {
947
1233
  ctx.logger.error(e.message);
948
1234
  } else {
949
- throw e;
1235
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
950
1236
  }
951
1237
  }
952
1238
  };
@@ -977,185 +1263,175 @@ const runAction = (name2, action2) => (...args) => {
977
1263
  process.exit(1);
978
1264
  });
979
1265
  };
980
- const command$3 = ({ command: command2, ctx }) => {
981
- 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));
1266
+ const command$5 = ({ command: command2, ctx }) => {
1267
+ 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));
982
1268
  };
983
1269
  const deployProject = {
984
1270
  name: "deploy-project",
985
1271
  description: "Deploy a Strapi Cloud project",
986
- action: action$2,
987
- command: command$3
1272
+ action: action$3,
1273
+ command: command$5
988
1274
  };
989
- const openModule = import("open");
990
- const action$1 = async (ctx) => {
991
- const { logger } = ctx;
992
- const tokenService = await tokenServiceFactory(ctx);
993
- const existingToken = await tokenService.retrieveToken();
994
- const cloudApiService = await cloudApiFactory(existingToken || void 0);
995
- const trackFailedLogin = async () => {
996
- try {
997
- await cloudApiService.track("didNotLogin", { loginMethod: "cli" });
998
- } catch (e) {
999
- logger.debug("Failed to track failed login", e);
1000
- }
1001
- };
1002
- if (existingToken) {
1003
- const isTokenValid = await tokenService.isTokenValid(existingToken);
1004
- if (isTokenValid) {
1005
- try {
1006
- const userInfo = await cloudApiService.getUserInfo();
1007
- const { email } = userInfo.data.data;
1008
- if (email) {
1009
- logger.log(`You are already logged into your account (${email}).`);
1010
- } else {
1011
- logger.log("You are already logged in.");
1012
- }
1013
- logger.log(
1014
- "To access your dashboard, please copy and paste the following URL into your web browser:"
1015
- );
1016
- logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
1017
- return true;
1018
- } catch (e) {
1019
- logger.debug("Failed to fetch user info", e);
1275
+ const QUIT_OPTION = "Quit";
1276
+ async function getExistingConfig(ctx) {
1277
+ try {
1278
+ return await retrieve();
1279
+ } catch (e) {
1280
+ ctx.logger.debug("Failed to get project config", e);
1281
+ ctx.logger.error("An error occurred while retrieving config data from your local project.");
1282
+ return null;
1283
+ }
1284
+ }
1285
+ async function promptForRelink(ctx, cloudApiService, existingConfig) {
1286
+ if (existingConfig && existingConfig.project) {
1287
+ const { shouldRelink } = await inquirer__default.default.prompt([
1288
+ {
1289
+ type: "confirm",
1290
+ name: "shouldRelink",
1291
+ message: `A project named ${chalk__default.default.cyan(
1292
+ existingConfig.project.displayName ? existingConfig.project.displayName : existingConfig.project.name
1293
+ )} is already linked to this local folder. Do you want to update the link?`,
1294
+ default: false
1020
1295
  }
1296
+ ]);
1297
+ if (!shouldRelink) {
1298
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1299
+ currentProjectName: existingConfig.project?.name
1300
+ });
1301
+ return false;
1021
1302
  }
1022
1303
  }
1023
- let cliConfig2;
1304
+ return true;
1305
+ }
1306
+ async function getProjectsList(ctx, cloudApiService, existingConfig) {
1307
+ const spinner = ctx.logger.spinner("Fetching your projects...\n").start();
1024
1308
  try {
1025
- logger.info("🔌 Connecting to the Strapi Cloud API...");
1026
- const config = await cloudApiService.config();
1027
- cliConfig2 = config.data;
1309
+ const {
1310
+ data: { data: projectList }
1311
+ } = await cloudApiService.listLinkProjects();
1312
+ spinner.succeed();
1313
+ if (!Array.isArray(projectList)) {
1314
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1315
+ return null;
1316
+ }
1317
+ const projects = projectList.filter(
1318
+ (project) => !(project.isMaintainer || project.name === existingConfig?.project?.name)
1319
+ ).map((project) => {
1320
+ return {
1321
+ name: project.displayName,
1322
+ value: { name: project.name, displayName: project.displayName }
1323
+ };
1324
+ });
1325
+ if (projects.length === 0) {
1326
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1327
+ return null;
1328
+ }
1329
+ return projects;
1028
1330
  } catch (e) {
1029
- logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
1030
- logger.debug(e);
1031
- return false;
1331
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1332
+ ctx.logger.debug("Failed to list projects", e);
1333
+ return null;
1032
1334
  }
1335
+ }
1336
+ async function getUserSelection(ctx, projects) {
1337
+ const { logger } = ctx;
1033
1338
  try {
1034
- await cloudApiService.track("willLoginAttempt", {});
1339
+ const answer = await inquirer__default.default.prompt([
1340
+ {
1341
+ type: "list",
1342
+ name: "linkProject",
1343
+ message: "Which project do you want to link?",
1344
+ choices: [...projects, { name: chalk__default.default.grey(`(${QUIT_OPTION})`), value: null }]
1345
+ }
1346
+ ]);
1347
+ if (!answer.linkProject) {
1348
+ return null;
1349
+ }
1350
+ return answer;
1035
1351
  } catch (e) {
1036
- logger.debug("Failed to track login attempt", e);
1352
+ logger.debug("Failed to get user input", e);
1353
+ logger.error("An error occurred while trying to get your input.");
1354
+ return null;
1037
1355
  }
1038
- logger.debug("🔐 Creating device authentication request...", {
1039
- client_id: cliConfig2.clientId,
1040
- scope: cliConfig2.scope,
1041
- audience: cliConfig2.audience
1042
- });
1043
- const deviceAuthResponse = await axios__default.default.post(cliConfig2.deviceCodeAuthUrl, {
1044
- client_id: cliConfig2.clientId,
1045
- scope: cliConfig2.scope,
1046
- audience: cliConfig2.audience
1047
- }).catch((e) => {
1048
- logger.error("There was an issue with the authentication process. Please try again.");
1049
- if (e.message) {
1050
- logger.debug(e.message, e);
1051
- } else {
1052
- logger.debug(e);
1053
- }
1054
- });
1055
- openModule.then((open) => {
1056
- open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
1057
- logger.error("We encountered an issue opening the browser. Please try again later.");
1058
- logger.debug(e.message, e);
1059
- });
1060
- });
1061
- logger.log("If a browser tab does not open automatically, please follow the next steps:");
1062
- logger.log(
1063
- `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
1064
- );
1065
- logger.log(
1066
- `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
1067
- `
1356
+ }
1357
+ const action$2 = async (ctx) => {
1358
+ const { getValidToken } = await tokenServiceFactory(ctx);
1359
+ const token = await getValidToken(ctx, promptLogin);
1360
+ const { logger } = ctx;
1361
+ if (!token) {
1362
+ return;
1363
+ }
1364
+ const cloudApiService = await cloudApiFactory(ctx, token);
1365
+ const existingConfig = await getExistingConfig(ctx);
1366
+ const shouldRelink = await promptForRelink(ctx, cloudApiService, existingConfig);
1367
+ if (!shouldRelink) {
1368
+ return;
1369
+ }
1370
+ await trackEvent(ctx, cloudApiService, "willLinkProject", {});
1371
+ const projects = await getProjectsList(
1372
+ ctx,
1373
+ cloudApiService,
1374
+ existingConfig
1068
1375
  );
1069
- const tokenPayload = {
1070
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1071
- device_code: deviceAuthResponse.data.device_code,
1072
- client_id: cliConfig2.clientId
1073
- };
1074
- let isAuthenticated = false;
1075
- const authenticate = async () => {
1076
- const spinner = logger.spinner("Waiting for authentication");
1077
- spinner.start();
1078
- const spinnerFail = () => spinner.fail("Authentication failed!");
1079
- while (!isAuthenticated) {
1080
- try {
1081
- const tokenResponse = await axios__default.default.post(cliConfig2.tokenUrl, tokenPayload);
1082
- const authTokenData = tokenResponse.data;
1083
- if (tokenResponse.status === 200) {
1084
- try {
1085
- logger.debug("🔐 Validating token...");
1086
- await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
1087
- logger.debug("🔐 Token validation successful!");
1088
- } catch (e) {
1089
- logger.debug(e);
1090
- spinnerFail();
1091
- throw new Error("Unable to proceed: Token validation failed");
1092
- }
1093
- logger.debug("🔍 Fetching user information...");
1094
- const cloudApiServiceWithToken = await cloudApiFactory(authTokenData.access_token);
1095
- await cloudApiServiceWithToken.getUserInfo();
1096
- logger.debug("🔍 User information fetched successfully!");
1097
- try {
1098
- logger.debug("📝 Saving login information...");
1099
- await tokenService.saveToken(authTokenData.access_token);
1100
- logger.debug("📝 Login information saved successfully!");
1101
- isAuthenticated = true;
1102
- } catch (e) {
1103
- logger.error(
1104
- "There was a problem saving your login information. Please try logging in again."
1105
- );
1106
- logger.debug(e);
1107
- spinnerFail();
1108
- return false;
1109
- }
1110
- }
1111
- } catch (e) {
1112
- if (e.message === "Unable to proceed: Token validation failed") {
1113
- logger.error(
1114
- "There seems to be a problem with your login information. Please try logging in again."
1115
- );
1116
- spinnerFail();
1117
- await trackFailedLogin();
1118
- return false;
1119
- }
1120
- if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
1121
- logger.debug(e);
1122
- spinnerFail();
1123
- await trackFailedLogin();
1124
- return false;
1125
- }
1126
- await new Promise((resolve) => {
1127
- setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
1128
- });
1376
+ if (!projects) {
1377
+ return;
1378
+ }
1379
+ const answer = await getUserSelection(ctx, projects);
1380
+ if (!answer) {
1381
+ return;
1382
+ }
1383
+ try {
1384
+ const { confirmAction } = await inquirer__default.default.prompt([
1385
+ {
1386
+ type: "confirm",
1387
+ name: "confirmAction",
1388
+ message: "Warning: Once linked, deploying from CLI will replace the existing project and its data. Confirm to proceed:",
1389
+ default: false
1129
1390
  }
1391
+ ]);
1392
+ if (!confirmAction) {
1393
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1394
+ cancelledProjectName: answer.linkProject.name,
1395
+ currentProjectName: existingConfig ? existingConfig.project?.name : null
1396
+ });
1397
+ return;
1130
1398
  }
1131
- spinner.succeed("Authentication successful!");
1132
- logger.log("You are now logged into Strapi Cloud.");
1133
- logger.log(
1134
- "To access your dashboard, please copy and paste the following URL into your web browser:"
1135
- );
1136
- logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
1137
- try {
1138
- await cloudApiService.track("didLogin", { loginMethod: "cli" });
1139
- } catch (e) {
1140
- logger.debug("Failed to track login", e);
1141
- }
1142
- };
1143
- await authenticate();
1144
- return isAuthenticated;
1399
+ await save({ project: answer.linkProject });
1400
+ logger.log(`Project ${chalk__default.default.cyan(answer.linkProject.displayName)} linked successfully.`);
1401
+ await trackEvent(ctx, cloudApiService, "didLinkProject", {
1402
+ projectInternalName: answer.linkProject
1403
+ });
1404
+ } catch (e) {
1405
+ logger.debug("Failed to link project", e);
1406
+ logger.error("An error occurred while linking the project.");
1407
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1408
+ projectInternalName: answer.linkProject
1409
+ });
1410
+ }
1145
1411
  };
1146
- const command$2 = ({ command: command2, ctx }) => {
1412
+ const command$4 = ({ command: command2, ctx }) => {
1413
+ 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));
1414
+ };
1415
+ const link = {
1416
+ name: "link-project",
1417
+ description: "Link a local directory to a Strapi Cloud project",
1418
+ action: action$2,
1419
+ command: command$4
1420
+ };
1421
+ const command$3 = ({ command: command2, ctx }) => {
1147
1422
  command2.command("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1148
1423
  "after",
1149
1424
  "\nAfter running this command, you will be prompted to enter your authentication information."
1150
- ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", action$1)(ctx));
1425
+ ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", loginAction)(ctx));
1151
1426
  };
1152
1427
  const login = {
1153
1428
  name: "login",
1154
1429
  description: "Strapi Cloud Login",
1155
- action: action$1,
1156
- command: command$2
1430
+ action: loginAction,
1431
+ command: command$3
1157
1432
  };
1158
- const action = async (ctx) => {
1433
+ const openModule = import("open");
1434
+ const action$1 = async (ctx) => {
1159
1435
  const { logger } = ctx;
1160
1436
  const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx);
1161
1437
  const token = await retrieveToken();
@@ -1163,9 +1439,21 @@ const action = async (ctx) => {
1163
1439
  logger.log("You're already logged out.");
1164
1440
  return;
1165
1441
  }
1166
- const cloudApiService = await cloudApiFactory(token);
1442
+ const cloudApiService = await cloudApiFactory(ctx, token);
1443
+ const config = await cloudApiService.config();
1444
+ const cliConfig2 = config.data;
1167
1445
  try {
1168
1446
  await eraseToken();
1447
+ openModule.then((open) => {
1448
+ open.default(
1449
+ `${cliConfig2.baseUrl}/oidc/logout?client_id=${encodeURIComponent(
1450
+ cliConfig2.clientId
1451
+ )}&logout_hint=${encodeURIComponent(token)}
1452
+ `
1453
+ ).catch((e) => {
1454
+ logger.debug(e.message, e);
1455
+ });
1456
+ });
1169
1457
  logger.log(
1170
1458
  "🔌 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."
1171
1459
  );
@@ -1173,37 +1461,64 @@ const action = async (ctx) => {
1173
1461
  logger.error("🥲 Oops! Something went wrong while logging you out. Please try again.");
1174
1462
  logger.debug(e);
1175
1463
  }
1176
- try {
1177
- await cloudApiService.track("didLogout", { loginMethod: "cli" });
1178
- } catch (e) {
1179
- logger.debug("Failed to track logout event", e);
1180
- }
1464
+ await trackEvent(ctx, cloudApiService, "didLogout", { loginMethod: "cli" });
1181
1465
  };
1182
- const command$1 = ({ command: command2, ctx }) => {
1183
- 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));
1466
+ const command$2 = ({ command: command2, ctx }) => {
1467
+ 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));
1184
1468
  };
1185
1469
  const logout = {
1186
1470
  name: "logout",
1187
1471
  description: "Strapi Cloud Logout",
1188
- action,
1189
- command: command$1
1472
+ action: action$1,
1473
+ command: command$2
1190
1474
  };
1191
- const command = ({ command: command2, ctx }) => {
1192
- 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));
1475
+ const command$1 = ({ command: command2, ctx }) => {
1476
+ 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));
1193
1477
  };
1194
1478
  const createProject = {
1195
1479
  name: "create-project",
1196
1480
  description: "Create a new project",
1197
- action: action$3,
1481
+ action: action$4,
1482
+ command: command$1
1483
+ };
1484
+ const action = async (ctx) => {
1485
+ const { getValidToken } = await tokenServiceFactory(ctx);
1486
+ const token = await getValidToken(ctx, promptLogin);
1487
+ const { logger } = ctx;
1488
+ if (!token) {
1489
+ return;
1490
+ }
1491
+ const cloudApiService = await cloudApiFactory(ctx, token);
1492
+ const spinner = logger.spinner("Fetching your projects...").start();
1493
+ try {
1494
+ const {
1495
+ data: { data: projectList }
1496
+ } = await cloudApiService.listProjects();
1497
+ spinner.succeed();
1498
+ logger.log(projectList);
1499
+ } catch (e) {
1500
+ ctx.logger.debug("Failed to list projects", e);
1501
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1502
+ }
1503
+ };
1504
+ const command = ({ command: command2, ctx }) => {
1505
+ 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));
1506
+ };
1507
+ const listProjects = {
1508
+ name: "list-projects",
1509
+ description: "List Strapi Cloud projects",
1510
+ action,
1198
1511
  command
1199
1512
  };
1200
1513
  const cli = {
1201
1514
  deployProject,
1515
+ link,
1202
1516
  login,
1203
1517
  logout,
1204
- createProject
1518
+ createProject,
1519
+ listProjects
1205
1520
  };
1206
- const cloudCommands = [deployProject, login, logout];
1521
+ const cloudCommands = [deployProject, link, login, logout, listProjects];
1207
1522
  async function initCloudCLIConfig() {
1208
1523
  const localConfig = await getLocalConfig();
1209
1524
  if (!localConfig.deviceId) {