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

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 (47) hide show
  1. package/LICENSE +18 -3
  2. package/dist/index.js +664 -306
  3. package/dist/index.js.map +1 -1
  4. package/dist/index.mjs +664 -303
  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/command.d.ts.map +1 -1
  9. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts +3 -0
  10. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts.map +1 -0
  11. package/dist/src/create-project/utils/project-questions.utils.d.ts +20 -0
  12. package/dist/src/create-project/utils/project-questions.utils.d.ts.map +1 -0
  13. package/dist/src/deploy-project/action.d.ts.map +1 -1
  14. package/dist/src/deploy-project/command.d.ts.map +1 -1
  15. package/dist/src/index.d.ts +2 -0
  16. package/dist/src/index.d.ts.map +1 -1
  17. package/dist/src/link/action.d.ts +4 -0
  18. package/dist/src/link/action.d.ts.map +1 -0
  19. package/dist/src/link/command.d.ts +7 -0
  20. package/dist/src/link/command.d.ts.map +1 -0
  21. package/dist/src/link/index.d.ts +7 -0
  22. package/dist/src/link/index.d.ts.map +1 -0
  23. package/dist/src/list-projects/action.d.ts +4 -0
  24. package/dist/src/list-projects/action.d.ts.map +1 -0
  25. package/dist/src/list-projects/command.d.ts +7 -0
  26. package/dist/src/list-projects/command.d.ts.map +1 -0
  27. package/dist/src/list-projects/index.d.ts +7 -0
  28. package/dist/src/list-projects/index.d.ts.map +1 -0
  29. package/dist/src/login/action.d.ts +2 -2
  30. package/dist/src/login/action.d.ts.map +1 -1
  31. package/dist/src/login/command.d.ts.map +1 -1
  32. package/dist/src/logout/action.d.ts.map +1 -1
  33. package/dist/src/logout/command.d.ts.map +1 -1
  34. package/dist/src/services/build-logs.d.ts.map +1 -1
  35. package/dist/src/services/cli-api.d.ts +38 -8
  36. package/dist/src/services/cli-api.d.ts.map +1 -1
  37. package/dist/src/services/strapi-info-save.d.ts +1 -1
  38. package/dist/src/services/strapi-info-save.d.ts.map +1 -1
  39. package/dist/src/services/token.d.ts +1 -1
  40. package/dist/src/services/token.d.ts.map +1 -1
  41. package/dist/src/types.d.ts +2 -1
  42. package/dist/src/types.d.ts.map +1 -1
  43. package/dist/src/utils/analytics.d.ts +4 -0
  44. package/dist/src/utils/analytics.d.ts.map +1 -0
  45. package/dist/src/utils/compress-files.d.ts.map +1 -1
  46. package/dist/src/utils/pkg.d.ts.map +1 -1
  47. package/package.json +9 -8
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,10 @@ 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");
46
+ const commander = require("commander");
48
47
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
49
48
  function _interopNamespace(e) {
50
49
  if (e && e.__esModule)
@@ -65,12 +64,11 @@ function _interopNamespace(e) {
65
64
  return Object.freeze(n);
66
65
  }
67
66
  const crypto__default = /* @__PURE__ */ _interopDefault(crypto$1);
68
- const fse__default = /* @__PURE__ */ _interopDefault(fse);
67
+ const fse__namespace = /* @__PURE__ */ _interopNamespace(fse);
69
68
  const path__namespace = /* @__PURE__ */ _interopNamespace(path);
70
69
  const chalk__default = /* @__PURE__ */ _interopDefault(chalk);
71
70
  const axios__default = /* @__PURE__ */ _interopDefault(axios);
72
71
  const crypto__namespace = /* @__PURE__ */ _interopNamespace(crypto);
73
- const fs__namespace = /* @__PURE__ */ _interopNamespace(fs);
74
72
  const tar__namespace = /* @__PURE__ */ _interopNamespace(tar);
75
73
  const inquirer__default = /* @__PURE__ */ _interopDefault(inquirer);
76
74
  const os__default = /* @__PURE__ */ _interopDefault(os);
@@ -80,10 +78,9 @@ const jwt__default = /* @__PURE__ */ _interopDefault(jwt);
80
78
  const stringify__default = /* @__PURE__ */ _interopDefault(stringify);
81
79
  const ora__default = /* @__PURE__ */ _interopDefault(ora);
82
80
  const cliProgress__namespace = /* @__PURE__ */ _interopNamespace(cliProgress);
83
- const EventSource__default = /* @__PURE__ */ _interopDefault(EventSource);
84
- const fs__default = /* @__PURE__ */ _interopDefault(fs$1);
85
81
  const pkgUp__default = /* @__PURE__ */ _interopDefault(pkgUp);
86
82
  const yup__namespace = /* @__PURE__ */ _interopNamespace(yup);
83
+ const EventSource__default = /* @__PURE__ */ _interopDefault(EventSource);
87
84
  const apiConfig = {
88
85
  apiBaseUrl: utils.env("STRAPI_CLI_CLOUD_API", "https://cloud-cli-api.strapi.io"),
89
86
  dashboardBaseUrl: utils.env("STRAPI_CLI_CLOUD_DASHBOARD", "https://cloud.strapi.io")
@@ -102,23 +99,6 @@ const IGNORED_PATTERNS = [
102
99
  "**/.idea/**",
103
100
  "**/.vscode/**"
104
101
  ];
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
102
  const isIgnoredFile = (folderPath, file, ignorePatterns) => {
123
103
  ignorePatterns.push(...IGNORED_PATTERNS);
124
104
  const relativeFilePath = path__namespace.join(folderPath, file);
@@ -136,16 +116,35 @@ const isIgnoredFile = (folderPath, file, ignorePatterns) => {
136
116
  }
137
117
  return isIgnored;
138
118
  };
139
- const readGitignore = (folderPath) => {
119
+ const getFiles = async (dirPath, ignorePatterns = [], subfolder = "") => {
120
+ const arrayOfFiles = [];
121
+ const entries = await fse__namespace.readdir(path__namespace.join(dirPath, subfolder));
122
+ for (const entry of entries) {
123
+ const entryPathFromRoot = path__namespace.join(subfolder, entry);
124
+ const entryPath = path__namespace.relative(dirPath, entryPathFromRoot);
125
+ const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
126
+ if (!isIgnored) {
127
+ if (fse__namespace.statSync(entryPath).isDirectory()) {
128
+ const subFiles = await getFiles(dirPath, ignorePatterns, entryPathFromRoot);
129
+ arrayOfFiles.push(...subFiles);
130
+ } else {
131
+ arrayOfFiles.push(entryPath);
132
+ }
133
+ }
134
+ }
135
+ return arrayOfFiles;
136
+ };
137
+ const readGitignore = async (folderPath) => {
140
138
  const gitignorePath = path__namespace.resolve(folderPath, ".gitignore");
141
- if (!fs__namespace.existsSync(gitignorePath))
139
+ const pathExist = await fse__namespace.pathExists(gitignorePath);
140
+ if (!pathExist)
142
141
  return [];
143
- const gitignoreContent = fs__namespace.readFileSync(gitignorePath, "utf8");
142
+ const gitignoreContent = await fse__namespace.readFile(gitignorePath, "utf8");
144
143
  return gitignoreContent.split(/\r?\n/).filter((line) => Boolean(line.trim()) && !line.startsWith("#"));
145
144
  };
146
145
  const compressFilesToTar = async (storagePath, folderToCompress, filename) => {
147
- const ignorePatterns = readGitignore(folderToCompress);
148
- const filesToCompress = getFiles(folderToCompress, ignorePatterns);
146
+ const ignorePatterns = await readGitignore(folderToCompress);
147
+ const filesToCompress = await getFiles(folderToCompress, ignorePatterns);
149
148
  return tar__namespace.c(
150
149
  {
151
150
  gzip: true,
@@ -158,7 +157,7 @@ const APP_FOLDER_NAME = "com.strapi.cli";
158
157
  const CONFIG_FILENAME = "config.json";
159
158
  async function checkDirectoryExists(directoryPath) {
160
159
  try {
161
- const fsStat = await fse__default.default.lstat(directoryPath);
160
+ const fsStat = await fse__namespace.default.lstat(directoryPath);
162
161
  return fsStat.isDirectory();
163
162
  } catch (e) {
164
163
  return false;
@@ -166,14 +165,14 @@ async function checkDirectoryExists(directoryPath) {
166
165
  }
167
166
  async function getTmpStoragePath() {
168
167
  const storagePath = path__namespace.default.join(os__default.default.tmpdir(), APP_FOLDER_NAME);
169
- await fse__default.default.ensureDir(storagePath);
168
+ await fse__namespace.default.ensureDir(storagePath);
170
169
  return storagePath;
171
170
  }
172
171
  async function getConfigPath() {
173
172
  const configDirs = XDGAppPaths__default.default(APP_FOLDER_NAME).configDirs();
174
173
  const configPath = configDirs.find(checkDirectoryExists);
175
174
  if (!configPath) {
176
- await fse__default.default.ensureDir(configDirs[0]);
175
+ await fse__namespace.default.ensureDir(configDirs[0]);
177
176
  return configDirs[0];
178
177
  }
179
178
  return configPath;
@@ -181,9 +180,9 @@ async function getConfigPath() {
181
180
  async function getLocalConfig() {
182
181
  const configPath = await getConfigPath();
183
182
  const configFilePath = path__namespace.default.join(configPath, CONFIG_FILENAME);
184
- await fse__default.default.ensureFile(configFilePath);
183
+ await fse__namespace.default.ensureFile(configFilePath);
185
184
  try {
186
- return await fse__default.default.readJSON(configFilePath, { encoding: "utf8", throws: true });
185
+ return await fse__namespace.default.readJSON(configFilePath, { encoding: "utf8", throws: true });
187
186
  } catch (e) {
188
187
  return {};
189
188
  }
@@ -191,10 +190,10 @@ async function getLocalConfig() {
191
190
  async function saveLocalConfig(data) {
192
191
  const configPath = await getConfigPath();
193
192
  const configFilePath = path__namespace.default.join(configPath, CONFIG_FILENAME);
194
- await fse__default.default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
193
+ await fse__namespace.default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
195
194
  }
196
195
  const name = "@strapi/cloud-cli";
197
- const version = "4.25.0";
196
+ const version = "5.0.2";
198
197
  const description = "Commands to interact with the Strapi Cloud";
199
198
  const keywords = [
200
199
  "strapi",
@@ -235,17 +234,18 @@ const scripts = {
235
234
  build: "pack-up build",
236
235
  clean: "run -T rimraf ./dist",
237
236
  lint: "run -T eslint .",
237
+ "test:unit": "run -T jest",
238
238
  watch: "pack-up watch"
239
239
  };
240
240
  const dependencies = {
241
- "@strapi/utils": "4.25.0",
242
- axios: "1.6.0",
241
+ "@strapi/utils": "workspace:*",
242
+ axios: "1.7.4",
243
243
  chalk: "4.1.2",
244
244
  "cli-progress": "3.12.0",
245
245
  commander: "8.3.0",
246
246
  eventsource: "2.0.2",
247
247
  "fast-safe-stringify": "2.1.1",
248
- "fs-extra": "10.0.0",
248
+ "fs-extra": "11.2.0",
249
249
  inquirer: "8.2.5",
250
250
  jsonwebtoken: "9.0.0",
251
251
  "jwks-rsa": "3.1.0",
@@ -254,7 +254,7 @@ const dependencies = {
254
254
  open: "8.4.0",
255
255
  ora: "5.4.1",
256
256
  "pkg-up": "3.1.0",
257
- tar: "6.1.13",
257
+ tar: "6.2.1",
258
258
  "xdg-app-paths": "8.3.0",
259
259
  yup: "0.32.9"
260
260
  };
@@ -263,8 +263,8 @@ const devDependencies = {
263
263
  "@types/cli-progress": "3.11.5",
264
264
  "@types/eventsource": "1.1.15",
265
265
  "@types/lodash": "^4.14.191",
266
- "eslint-config-custom": "4.25.0",
267
- tsconfig: "4.25.0"
266
+ "eslint-config-custom": "workspace:*",
267
+ tsconfig: "workspace:*"
268
268
  };
269
269
  const engines = {
270
270
  node: ">=18.0.0 <=20.x.x",
@@ -293,7 +293,7 @@ const packageJson = {
293
293
  engines
294
294
  };
295
295
  const VERSION = "v1";
296
- async function cloudApiFactory(token) {
296
+ async function cloudApiFactory({ logger }, token) {
297
297
  const localConfig = await getLocalConfig();
298
298
  const customHeaders = {
299
299
  "x-device-id": localConfig.deviceId,
@@ -317,7 +317,7 @@ async function cloudApiFactory(token) {
317
317
  deploy({ filePath, project }, { onUploadProgress }) {
318
318
  return axiosCloudAPI.post(
319
319
  `/deploy/${project.name}`,
320
- { file: fse__default.default.createReadStream(filePath) },
320
+ { file: fse__namespace.default.createReadStream(filePath) },
321
321
  {
322
322
  headers: {
323
323
  "Content-Type": "multipart/form-data"
@@ -346,11 +346,61 @@ async function cloudApiFactory(token) {
346
346
  getUserInfo() {
347
347
  return axiosCloudAPI.get("/user");
348
348
  },
349
- config() {
350
- return axiosCloudAPI.get("/config");
349
+ async config() {
350
+ try {
351
+ const response = await axiosCloudAPI.get("/config");
352
+ if (response.status !== 200) {
353
+ throw new Error("Error fetching cloud CLI config from the server.");
354
+ }
355
+ return response;
356
+ } catch (error) {
357
+ logger.debug(
358
+ "🥲 Oops! Couldn't retrieve the cloud CLI config from the server. Please try again."
359
+ );
360
+ throw error;
361
+ }
362
+ },
363
+ async listProjects() {
364
+ try {
365
+ const response = await axiosCloudAPI.get("/projects");
366
+ if (response.status !== 200) {
367
+ throw new Error("Error fetching cloud projects from the server.");
368
+ }
369
+ return response;
370
+ } catch (error) {
371
+ logger.debug(
372
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
373
+ );
374
+ throw error;
375
+ }
376
+ },
377
+ async listLinkProjects() {
378
+ try {
379
+ const response = await axiosCloudAPI.get("/projects-linkable");
380
+ if (response.status !== 200) {
381
+ throw new Error("Error fetching cloud projects from the server.");
382
+ }
383
+ return response;
384
+ } catch (error) {
385
+ logger.debug(
386
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
387
+ );
388
+ throw error;
389
+ }
351
390
  },
352
- listProjects() {
353
- return axiosCloudAPI.get("/projects");
391
+ async getProject({ name: name2 }) {
392
+ try {
393
+ const response = await axiosCloudAPI.get(`/projects/${name2}`);
394
+ if (response.status !== 200) {
395
+ throw new Error("Error fetching project's details.");
396
+ }
397
+ return response;
398
+ } catch (error) {
399
+ logger.debug(
400
+ "🥲 Oops! There was a problem retrieving your project's details. Please try again."
401
+ );
402
+ throw error;
403
+ }
354
404
  },
355
405
  track(event, payload = {}) {
356
406
  return axiosCloudAPI.post("/track", {
@@ -365,18 +415,18 @@ async function save(data, { directoryPath } = {}) {
365
415
  const alreadyInFileData = await retrieve({ directoryPath });
366
416
  const storedData = { ...alreadyInFileData, ...data };
367
417
  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" });
418
+ await fse__namespace.default.ensureDir(path__namespace.default.dirname(pathToFile));
419
+ await fse__namespace.default.writeJson(pathToFile, storedData, { encoding: "utf8" });
370
420
  }
371
421
  async function retrieve({
372
422
  directoryPath
373
423
  } = {}) {
374
424
  const pathToFile = path__namespace.default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
375
- const pathExists = await fse__default.default.pathExists(pathToFile);
425
+ const pathExists = await fse__namespace.default.pathExists(pathToFile);
376
426
  if (!pathExists) {
377
427
  return {};
378
428
  }
379
- return fse__default.default.readJSON(pathToFile, { encoding: "utf8" });
429
+ return fse__namespace.default.readJSON(pathToFile, { encoding: "utf8" });
380
430
  }
381
431
  const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
382
432
  __proto__: null,
@@ -386,7 +436,7 @@ const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defi
386
436
  }, Symbol.toStringTag, { value: "Module" }));
387
437
  let cliConfig;
388
438
  async function tokenServiceFactory({ logger }) {
389
- const cloudApiService = await cloudApiFactory();
439
+ const cloudApiService = await cloudApiFactory({ logger });
390
440
  async function saveToken(str) {
391
441
  const appConfig = await getLocalConfig();
392
442
  if (!appConfig) {
@@ -435,14 +485,17 @@ async function tokenServiceFactory({ logger }) {
435
485
  "There seems to be a problem with your login information. Please try logging in again."
436
486
  );
437
487
  }
488
+ return Promise.reject(new Error("Invalid token"));
438
489
  }
439
490
  return new Promise((resolve, reject) => {
440
491
  jwt__default.default.verify(idToken, getKey, (err) => {
441
492
  if (err) {
442
493
  reject(err);
443
- } else {
444
- resolve();
445
494
  }
495
+ if (decodedToken.payload.exp < Math.floor(Date.now() / 1e3)) {
496
+ reject(new Error("Token is expired"));
497
+ }
498
+ resolve();
446
499
  });
447
500
  });
448
501
  }
@@ -476,15 +529,15 @@ async function tokenServiceFactory({ logger }) {
476
529
  throw e;
477
530
  }
478
531
  }
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;
532
+ async function getValidToken(ctx, loginAction2) {
533
+ let token = await retrieveToken();
534
+ while (!token || !await isTokenValid(token)) {
535
+ logger.log(
536
+ 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."
537
+ );
538
+ if (!await loginAction2(ctx))
539
+ return null;
540
+ token = await retrieveToken();
488
541
  }
489
542
  return token;
490
543
  }
@@ -618,17 +671,257 @@ const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePropert
618
671
  local: strapiInfoSave,
619
672
  tokenServiceFactory
620
673
  }, Symbol.toStringTag, { value: "Module" }));
621
- async function handleError(ctx, error) {
674
+ yup__namespace.object({
675
+ name: yup__namespace.string().required(),
676
+ exports: yup__namespace.lazy(
677
+ (value) => yup__namespace.object(
678
+ typeof value === "object" ? Object.entries(value).reduce(
679
+ (acc, [key, value2]) => {
680
+ if (typeof value2 === "object") {
681
+ acc[key] = yup__namespace.object({
682
+ types: yup__namespace.string().optional(),
683
+ source: yup__namespace.string().required(),
684
+ module: yup__namespace.string().optional(),
685
+ import: yup__namespace.string().required(),
686
+ require: yup__namespace.string().required(),
687
+ default: yup__namespace.string().required()
688
+ }).noUnknown(true);
689
+ } else {
690
+ acc[key] = yup__namespace.string().matches(/^\.\/.*\.json$/).required();
691
+ }
692
+ return acc;
693
+ },
694
+ {}
695
+ ) : void 0
696
+ ).optional()
697
+ )
698
+ });
699
+ const loadPkg = async ({ cwd, logger }) => {
700
+ const pkgPath = await pkgUp__default.default({ cwd });
701
+ if (!pkgPath) {
702
+ throw new Error("Could not find a package.json in the current directory");
703
+ }
704
+ const buffer = await fse__namespace.readFile(pkgPath);
705
+ const pkg = JSON.parse(buffer.toString());
706
+ logger.debug("Loaded package.json:", os__default.default.EOL, pkg);
707
+ return pkg;
708
+ };
709
+ async function getProjectNameFromPackageJson(ctx) {
710
+ try {
711
+ const packageJson2 = await loadPkg(ctx);
712
+ return packageJson2.name || "my-strapi-project";
713
+ } catch (e) {
714
+ return "my-strapi-project";
715
+ }
716
+ }
717
+ const trackEvent = async (ctx, cloudApiService, eventName, eventData) => {
718
+ try {
719
+ await cloudApiService.track(eventName, eventData);
720
+ } catch (e) {
721
+ ctx.logger.debug(`Failed to track ${eventName}`, e);
722
+ }
723
+ };
724
+ const openModule$1 = import("open");
725
+ async function promptLogin(ctx) {
726
+ const response = await inquirer__default.default.prompt([
727
+ {
728
+ type: "confirm",
729
+ name: "login",
730
+ message: "Would you like to login?"
731
+ }
732
+ ]);
733
+ if (response.login) {
734
+ const loginSuccessful = await loginAction(ctx);
735
+ return loginSuccessful;
736
+ }
737
+ return false;
738
+ }
739
+ async function loginAction(ctx) {
740
+ const { logger } = ctx;
622
741
  const tokenService = await tokenServiceFactory(ctx);
742
+ const existingToken = await tokenService.retrieveToken();
743
+ const cloudApiService = await cloudApiFactory(ctx, existingToken || void 0);
744
+ if (existingToken) {
745
+ const isTokenValid = await tokenService.isTokenValid(existingToken);
746
+ if (isTokenValid) {
747
+ try {
748
+ const userInfo = await cloudApiService.getUserInfo();
749
+ const { email } = userInfo.data.data;
750
+ if (email) {
751
+ logger.log(`You are already logged into your account (${email}).`);
752
+ } else {
753
+ logger.log("You are already logged in.");
754
+ }
755
+ logger.log(
756
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
757
+ );
758
+ logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
759
+ return true;
760
+ } catch (e) {
761
+ logger.debug("Failed to fetch user info", e);
762
+ }
763
+ }
764
+ }
765
+ let cliConfig2;
766
+ try {
767
+ logger.info("🔌 Connecting to the Strapi Cloud API...");
768
+ const config = await cloudApiService.config();
769
+ cliConfig2 = config.data;
770
+ } catch (e) {
771
+ logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
772
+ logger.debug(e);
773
+ return false;
774
+ }
775
+ await trackEvent(ctx, cloudApiService, "willLoginAttempt", {});
776
+ logger.debug("🔐 Creating device authentication request...", {
777
+ client_id: cliConfig2.clientId,
778
+ scope: cliConfig2.scope,
779
+ audience: cliConfig2.audience
780
+ });
781
+ const deviceAuthResponse = await axios__default.default.post(cliConfig2.deviceCodeAuthUrl, {
782
+ client_id: cliConfig2.clientId,
783
+ scope: cliConfig2.scope,
784
+ audience: cliConfig2.audience
785
+ }).catch((e) => {
786
+ logger.error("There was an issue with the authentication process. Please try again.");
787
+ if (e.message) {
788
+ logger.debug(e.message, e);
789
+ } else {
790
+ logger.debug(e);
791
+ }
792
+ });
793
+ openModule$1.then((open) => {
794
+ open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
795
+ logger.error("We encountered an issue opening the browser. Please try again later.");
796
+ logger.debug(e.message, e);
797
+ });
798
+ });
799
+ logger.log("If a browser tab does not open automatically, please follow the next steps:");
800
+ logger.log(
801
+ `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
802
+ );
803
+ logger.log(
804
+ `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
805
+ `
806
+ );
807
+ const tokenPayload = {
808
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
809
+ device_code: deviceAuthResponse.data.device_code,
810
+ client_id: cliConfig2.clientId
811
+ };
812
+ let isAuthenticated = false;
813
+ const authenticate = async () => {
814
+ const spinner = logger.spinner("Waiting for authentication");
815
+ spinner.start();
816
+ const spinnerFail = () => spinner.fail("Authentication failed!");
817
+ while (!isAuthenticated) {
818
+ try {
819
+ const tokenResponse = await axios__default.default.post(cliConfig2.tokenUrl, tokenPayload);
820
+ const authTokenData = tokenResponse.data;
821
+ if (tokenResponse.status === 200) {
822
+ try {
823
+ logger.debug("🔐 Validating token...");
824
+ await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
825
+ logger.debug("🔐 Token validation successful!");
826
+ } catch (e) {
827
+ logger.debug(e);
828
+ spinnerFail();
829
+ throw new Error("Unable to proceed: Token validation failed");
830
+ }
831
+ logger.debug("🔍 Fetching user information...");
832
+ const cloudApiServiceWithToken = await cloudApiFactory(ctx, authTokenData.access_token);
833
+ await cloudApiServiceWithToken.getUserInfo();
834
+ logger.debug("🔍 User information fetched successfully!");
835
+ try {
836
+ logger.debug("📝 Saving login information...");
837
+ await tokenService.saveToken(authTokenData.access_token);
838
+ logger.debug("📝 Login information saved successfully!");
839
+ isAuthenticated = true;
840
+ } catch (e) {
841
+ logger.error(
842
+ "There was a problem saving your login information. Please try logging in again."
843
+ );
844
+ logger.debug(e);
845
+ spinnerFail();
846
+ return false;
847
+ }
848
+ }
849
+ } catch (e) {
850
+ if (e.message === "Unable to proceed: Token validation failed") {
851
+ logger.error(
852
+ "There seems to be a problem with your login information. Please try logging in again."
853
+ );
854
+ spinnerFail();
855
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
856
+ return false;
857
+ }
858
+ if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
859
+ logger.debug(e);
860
+ spinnerFail();
861
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
862
+ return false;
863
+ }
864
+ await new Promise((resolve) => {
865
+ setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
866
+ });
867
+ }
868
+ }
869
+ spinner.succeed("Authentication successful!");
870
+ logger.log("You are now logged into Strapi Cloud.");
871
+ logger.log(
872
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
873
+ );
874
+ logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
875
+ await trackEvent(ctx, cloudApiService, "didLogin", { loginMethod: "cli" });
876
+ };
877
+ await authenticate();
878
+ return isAuthenticated;
879
+ }
880
+ function questionDefaultValuesMapper(questionsMap) {
881
+ return (questions) => {
882
+ return questions.map((question) => {
883
+ const questionName = question.name;
884
+ if (questionName in questionsMap) {
885
+ const questionDefault = questionsMap[questionName];
886
+ if (typeof questionDefault === "function") {
887
+ return {
888
+ ...question,
889
+ default: questionDefault(question)
890
+ };
891
+ }
892
+ return {
893
+ ...question,
894
+ default: questionDefault
895
+ };
896
+ }
897
+ return question;
898
+ });
899
+ };
900
+ }
901
+ function getDefaultsFromQuestions(questions) {
902
+ return questions.reduce((acc, question) => {
903
+ if (question.default && question.name) {
904
+ return { ...acc, [question.name]: question.default };
905
+ }
906
+ return acc;
907
+ }, {});
908
+ }
909
+ function getProjectNodeVersionDefault(question) {
910
+ const currentNodeVersion = process.versions.node.split(".")[0];
911
+ if (question.type === "list" && Array.isArray(question.choices)) {
912
+ const choice = question.choices.find((choice2) => choice2.value === currentNodeVersion);
913
+ if (choice) {
914
+ return choice.value;
915
+ }
916
+ }
917
+ return question.default;
918
+ }
919
+ async function handleError(ctx, error) {
623
920
  const { logger } = ctx;
624
921
  logger.debug(error);
625
922
  if (error instanceof axios.AxiosError) {
626
923
  const errorMessage = typeof error.response?.data === "string" ? error.response.data : null;
627
924
  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
925
  case 403:
633
926
  logger.error(
634
927
  errorMessage || "You do not have permission to create a project. Please contact support for assistance."
@@ -654,28 +947,53 @@ async function handleError(ctx, error) {
654
947
  "We encountered an issue while creating your project. Please try again in a moment. If the problem persists, contact support for assistance."
655
948
  );
656
949
  }
657
- const action$3 = async (ctx) => {
950
+ async function createProject$1(ctx, cloudApi, projectInput) {
658
951
  const { logger } = ctx;
659
- const { getValidToken } = await tokenServiceFactory(ctx);
660
- const token = await getValidToken();
952
+ const spinner = logger.spinner("Setting up your project...").start();
953
+ try {
954
+ const { data } = await cloudApi.createProject(projectInput);
955
+ await save({ project: data });
956
+ spinner.succeed("Project created successfully!");
957
+ return data;
958
+ } catch (e) {
959
+ spinner.fail("An error occurred while creating the project on Strapi Cloud.");
960
+ throw e;
961
+ }
962
+ }
963
+ const action$4 = async (ctx) => {
964
+ const { logger } = ctx;
965
+ const { getValidToken, eraseToken } = await tokenServiceFactory(ctx);
966
+ const token = await getValidToken(ctx, promptLogin);
661
967
  if (!token) {
662
968
  return;
663
969
  }
664
- const cloudApi = await cloudApiFactory(token);
970
+ const cloudApi = await cloudApiFactory(ctx, token);
665
971
  const { data: config } = await cloudApi.config();
666
- const { questions, defaults: defaultValues } = config.projectCreation;
972
+ const projectName = await getProjectNameFromPackageJson(ctx);
973
+ const defaultAnswersMapper = questionDefaultValuesMapper({
974
+ name: projectName,
975
+ nodeVersion: getProjectNodeVersionDefault
976
+ });
977
+ const questions = defaultAnswersMapper(config.projectCreation.questions);
978
+ const defaultValues = {
979
+ ...config.projectCreation.defaults,
980
+ ...getDefaultsFromQuestions(questions)
981
+ };
667
982
  const projectAnswersDefaulted = fp.defaults(defaultValues);
668
983
  const projectAnswers = await inquirer__default.default.prompt(questions);
669
984
  const projectInput = projectAnswersDefaulted(projectAnswers);
670
- const spinner = logger.spinner("Setting up your project...").start();
671
985
  try {
672
- const { data } = await cloudApi.createProject(projectInput);
673
- await save({ project: data });
674
- spinner.succeed("Project created successfully!");
675
- return data;
986
+ return await createProject$1(ctx, cloudApi, projectInput);
676
987
  } catch (e) {
677
- spinner.fail("Failed to create project on Strapi Cloud.");
678
- await handleError(ctx, e);
988
+ if (e instanceof axios.AxiosError && e.response?.status === 401) {
989
+ logger.warn("Oops! Your session has expired. Please log in again to retry.");
990
+ await eraseToken();
991
+ if (await promptLogin(ctx)) {
992
+ return await createProject$1(ctx, cloudApi, projectInput);
993
+ }
994
+ } else {
995
+ await handleError(ctx, e);
996
+ }
679
997
  }
680
998
  };
681
999
  function notificationServiceFactory({ logger }) {
@@ -709,38 +1027,6 @@ function notificationServiceFactory({ logger }) {
709
1027
  };
710
1028
  };
711
1029
  }
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
1030
  const buildLogsServiceFactory = ({ logger }) => {
745
1031
  return async (url, token, cliConfig2) => {
746
1032
  const CONN_TIMEOUT = Number(cliConfig2.buildLogsConnectionTimeout);
@@ -794,6 +1080,7 @@ const buildLogsServiceFactory = ({ logger }) => {
794
1080
  if (retries > MAX_RETRIES) {
795
1081
  spinner.fail("We were unable to connect to the server to get build logs at this time.");
796
1082
  es.close();
1083
+ clearExistingTimeout();
797
1084
  reject(new Error("Max retries reached"));
798
1085
  }
799
1086
  };
@@ -803,7 +1090,7 @@ const buildLogsServiceFactory = ({ logger }) => {
803
1090
  };
804
1091
  };
805
1092
  async function upload(ctx, project, token, maxProjectFileSize) {
806
- const cloudApi = await cloudApiFactory(token);
1093
+ const cloudApi = await cloudApiFactory(ctx, token);
807
1094
  try {
808
1095
  const storagePath = await getTmpStoragePath();
809
1096
  const projectFolder = path__namespace.default.resolve(process.cwd());
@@ -836,13 +1123,13 @@ async function upload(ctx, project, token, maxProjectFileSize) {
836
1123
  process.exit(1);
837
1124
  }
838
1125
  const tarFilePath = path__namespace.default.resolve(storagePath, compressedFilename);
839
- const fileStats = await fse__default.default.stat(tarFilePath);
1126
+ const fileStats = await fse__namespace.default.stat(tarFilePath);
840
1127
  if (fileStats.size > maxProjectFileSize) {
841
1128
  ctx.logger.log(
842
1129
  "Unable to proceed: Your project is too big to be transferred, please use a git repo instead."
843
1130
  );
844
1131
  try {
845
- await fse__default.default.remove(tarFilePath);
1132
+ await fse__namespace.default.remove(tarFilePath);
846
1133
  } catch (e) {
847
1134
  ctx.logger.log("Unable to remove file: ", tarFilePath);
848
1135
  ctx.logger.debug(e);
@@ -868,20 +1155,10 @@ async function upload(ctx, project, token, maxProjectFileSize) {
868
1155
  return data.build_id;
869
1156
  } catch (e) {
870
1157
  progressBar.stop();
871
- if (e instanceof axios.AxiosError && e.response?.data) {
872
- if (e.response.status === 404) {
873
- ctx.logger.error(
874
- `The project does not exist. Remove the ${LOCAL_SAVE_FILENAME} file and try again.`
875
- );
876
- } else {
877
- ctx.logger.error(e.response.data);
878
- }
879
- } else {
880
- ctx.logger.error("An error occurred while deploying the project. Please try again later.");
881
- }
1158
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
882
1159
  ctx.logger.debug(e);
883
1160
  } finally {
884
- await fse__default.default.remove(tarFilePath);
1161
+ await fse__namespace.default.remove(tarFilePath);
885
1162
  }
886
1163
  process.exit(0);
887
1164
  } catch (e) {
@@ -894,7 +1171,7 @@ async function getProject(ctx) {
894
1171
  const { project } = await retrieve();
895
1172
  if (!project) {
896
1173
  try {
897
- return await action$3(ctx);
1174
+ return await action$4(ctx);
898
1175
  } catch (e) {
899
1176
  ctx.logger.error("An error occurred while deploying the project. Please try again later.");
900
1177
  ctx.logger.debug(e);
@@ -903,10 +1180,21 @@ async function getProject(ctx) {
903
1180
  }
904
1181
  return project;
905
1182
  }
906
- const action$2 = async (ctx) => {
1183
+ async function getConfig({
1184
+ ctx,
1185
+ cloudApiService
1186
+ }) {
1187
+ try {
1188
+ const { data: cliConfig2 } = await cloudApiService.config();
1189
+ return cliConfig2;
1190
+ } catch (e) {
1191
+ ctx.logger.debug("Failed to get cli config", e);
1192
+ return null;
1193
+ }
1194
+ }
1195
+ const action$3 = async (ctx) => {
907
1196
  const { getValidToken } = await tokenServiceFactory(ctx);
908
- const cloudApiService = await cloudApiFactory();
909
- const token = await getValidToken();
1197
+ const token = await getValidToken(ctx, promptLogin);
910
1198
  if (!token) {
911
1199
  return;
912
1200
  }
@@ -914,14 +1202,51 @@ const action$2 = async (ctx) => {
914
1202
  if (!project) {
915
1203
  return;
916
1204
  }
1205
+ const cloudApiService = await cloudApiFactory(ctx, token);
917
1206
  try {
918
- await cloudApiService.track("willDeployWithCLI", { projectInternalName: project.name });
1207
+ const {
1208
+ data: { data: projectData, metadata }
1209
+ } = await cloudApiService.getProject({ name: project.name });
1210
+ const isProjectSuspended = projectData.suspendedAt;
1211
+ if (isProjectSuspended) {
1212
+ ctx.logger.log(
1213
+ "\n Oops! This project has been suspended. \n\n Please reactivate it from the dashboard to continue deploying: "
1214
+ );
1215
+ ctx.logger.log(chalk__default.default.underline(`${metadata.dashboardUrls.project}`));
1216
+ return;
1217
+ }
919
1218
  } catch (e) {
920
- ctx.logger.debug("Failed to track willDeploy", e);
1219
+ if (e instanceof axios.AxiosError && e.response?.data) {
1220
+ if (e.response.status === 404) {
1221
+ ctx.logger.warn(
1222
+ `The project associated with this folder does not exist in Strapi Cloud.
1223
+ Please link your local project to an existing Strapi Cloud project using the ${chalk__default.default.cyan(
1224
+ "link"
1225
+ )} command before deploying.`
1226
+ );
1227
+ } else {
1228
+ ctx.logger.error(e.response.data);
1229
+ }
1230
+ } else {
1231
+ ctx.logger.error(
1232
+ "An error occurred while retrieving the project's information. Please try again later."
1233
+ );
1234
+ }
1235
+ ctx.logger.debug(e);
1236
+ return;
921
1237
  }
1238
+ await trackEvent(ctx, cloudApiService, "willDeployWithCLI", {
1239
+ projectInternalName: project.name
1240
+ });
922
1241
  const notificationService = notificationServiceFactory(ctx);
923
1242
  const buildLogsService = buildLogsServiceFactory(ctx);
924
- const { data: cliConfig2 } = await cloudApiService.config();
1243
+ const cliConfig2 = await getConfig({ ctx, cloudApiService });
1244
+ if (!cliConfig2) {
1245
+ ctx.logger.error(
1246
+ "An error occurred while retrieving data from Strapi Cloud. Please check your network or try again later."
1247
+ );
1248
+ return;
1249
+ }
925
1250
  let maxSize = parseInt(cliConfig2.maxProjectFileSize, 10);
926
1251
  if (Number.isNaN(maxSize)) {
927
1252
  ctx.logger.debug(
@@ -943,10 +1268,11 @@ const action$2 = async (ctx) => {
943
1268
  chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects/${project.name}/deployments`)
944
1269
  );
945
1270
  } catch (e) {
1271
+ ctx.logger.debug(e);
946
1272
  if (e instanceof Error) {
947
1273
  ctx.logger.error(e.message);
948
1274
  } else {
949
- throw e;
1275
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
950
1276
  }
951
1277
  }
952
1278
  };
@@ -977,185 +1303,175 @@ const runAction = (name2, action2) => (...args) => {
977
1303
  process.exit(1);
978
1304
  });
979
1305
  };
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));
1306
+ const command$5 = ({ ctx }) => {
1307
+ return commander.createCommand("cloud:deploy").alias("deploy").description("Deploy a Strapi Cloud project").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("deploy", action$3)(ctx));
982
1308
  };
983
1309
  const deployProject = {
984
1310
  name: "deploy-project",
985
1311
  description: "Deploy a Strapi Cloud project",
986
- action: action$2,
987
- command: command$3
1312
+ action: action$3,
1313
+ command: command$5
988
1314
  };
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);
1315
+ const QUIT_OPTION = "Quit";
1316
+ async function getExistingConfig(ctx) {
1317
+ try {
1318
+ return await retrieve();
1319
+ } catch (e) {
1320
+ ctx.logger.debug("Failed to get project config", e);
1321
+ ctx.logger.error("An error occurred while retrieving config data from your local project.");
1322
+ return null;
1323
+ }
1324
+ }
1325
+ async function promptForRelink(ctx, cloudApiService, existingConfig) {
1326
+ if (existingConfig && existingConfig.project) {
1327
+ const { shouldRelink } = await inquirer__default.default.prompt([
1328
+ {
1329
+ type: "confirm",
1330
+ name: "shouldRelink",
1331
+ message: `A project named ${chalk__default.default.cyan(
1332
+ existingConfig.project.displayName ? existingConfig.project.displayName : existingConfig.project.name
1333
+ )} is already linked to this local folder. Do you want to update the link?`,
1334
+ default: false
1020
1335
  }
1336
+ ]);
1337
+ if (!shouldRelink) {
1338
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1339
+ currentProjectName: existingConfig.project?.name
1340
+ });
1341
+ return false;
1021
1342
  }
1022
1343
  }
1023
- let cliConfig2;
1344
+ return true;
1345
+ }
1346
+ async function getProjectsList(ctx, cloudApiService, existingConfig) {
1347
+ const spinner = ctx.logger.spinner("Fetching your projects...\n").start();
1024
1348
  try {
1025
- logger.info("🔌 Connecting to the Strapi Cloud API...");
1026
- const config = await cloudApiService.config();
1027
- cliConfig2 = config.data;
1349
+ const {
1350
+ data: { data: projectList }
1351
+ } = await cloudApiService.listLinkProjects();
1352
+ spinner.succeed();
1353
+ if (!Array.isArray(projectList)) {
1354
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1355
+ return null;
1356
+ }
1357
+ const projects = projectList.filter(
1358
+ (project) => !(project.isMaintainer || project.name === existingConfig?.project?.name)
1359
+ ).map((project) => {
1360
+ return {
1361
+ name: project.displayName,
1362
+ value: { name: project.name, displayName: project.displayName }
1363
+ };
1364
+ });
1365
+ if (projects.length === 0) {
1366
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1367
+ return null;
1368
+ }
1369
+ return projects;
1028
1370
  } catch (e) {
1029
- logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
1030
- logger.debug(e);
1031
- return false;
1371
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1372
+ ctx.logger.debug("Failed to list projects", e);
1373
+ return null;
1032
1374
  }
1375
+ }
1376
+ async function getUserSelection(ctx, projects) {
1377
+ const { logger } = ctx;
1033
1378
  try {
1034
- await cloudApiService.track("willLoginAttempt", {});
1379
+ const answer = await inquirer__default.default.prompt([
1380
+ {
1381
+ type: "list",
1382
+ name: "linkProject",
1383
+ message: "Which project do you want to link?",
1384
+ choices: [...projects, { name: chalk__default.default.grey(`(${QUIT_OPTION})`), value: null }]
1385
+ }
1386
+ ]);
1387
+ if (!answer.linkProject) {
1388
+ return null;
1389
+ }
1390
+ return answer;
1035
1391
  } catch (e) {
1036
- logger.debug("Failed to track login attempt", e);
1392
+ logger.debug("Failed to get user input", e);
1393
+ logger.error("An error occurred while trying to get your input.");
1394
+ return null;
1037
1395
  }
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
- `
1396
+ }
1397
+ const action$2 = async (ctx) => {
1398
+ const { getValidToken } = await tokenServiceFactory(ctx);
1399
+ const token = await getValidToken(ctx, promptLogin);
1400
+ const { logger } = ctx;
1401
+ if (!token) {
1402
+ return;
1403
+ }
1404
+ const cloudApiService = await cloudApiFactory(ctx, token);
1405
+ const existingConfig = await getExistingConfig(ctx);
1406
+ const shouldRelink = await promptForRelink(ctx, cloudApiService, existingConfig);
1407
+ if (!shouldRelink) {
1408
+ return;
1409
+ }
1410
+ await trackEvent(ctx, cloudApiService, "willLinkProject", {});
1411
+ const projects = await getProjectsList(
1412
+ ctx,
1413
+ cloudApiService,
1414
+ existingConfig
1068
1415
  );
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
- });
1416
+ if (!projects) {
1417
+ return;
1418
+ }
1419
+ const answer = await getUserSelection(ctx, projects);
1420
+ if (!answer) {
1421
+ return;
1422
+ }
1423
+ try {
1424
+ const { confirmAction } = await inquirer__default.default.prompt([
1425
+ {
1426
+ type: "confirm",
1427
+ name: "confirmAction",
1428
+ message: "Warning: Once linked, deploying from CLI will replace the existing project and its data. Confirm to proceed:",
1429
+ default: false
1129
1430
  }
1431
+ ]);
1432
+ if (!confirmAction) {
1433
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1434
+ cancelledProjectName: answer.linkProject.name,
1435
+ currentProjectName: existingConfig ? existingConfig.project?.name : null
1436
+ });
1437
+ return;
1130
1438
  }
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;
1439
+ await save({ project: answer.linkProject });
1440
+ logger.log(`Project ${chalk__default.default.cyan(answer.linkProject.displayName)} linked successfully.`);
1441
+ await trackEvent(ctx, cloudApiService, "didLinkProject", {
1442
+ projectInternalName: answer.linkProject
1443
+ });
1444
+ } catch (e) {
1445
+ logger.debug("Failed to link project", e);
1446
+ logger.error("An error occurred while linking the project.");
1447
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1448
+ projectInternalName: answer.linkProject
1449
+ });
1450
+ }
1451
+ };
1452
+ const command$4 = ({ command: command2, ctx }) => {
1453
+ 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));
1145
1454
  };
1146
- const command$2 = ({ command: command2, ctx }) => {
1147
- command2.command("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1455
+ const link = {
1456
+ name: "link-project",
1457
+ description: "Link a local directory to a Strapi Cloud project",
1458
+ action: action$2,
1459
+ command: command$4
1460
+ };
1461
+ const command$3 = ({ ctx }) => {
1462
+ return commander.createCommand("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1148
1463
  "after",
1149
1464
  "\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));
1465
+ ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", loginAction)(ctx));
1151
1466
  };
1152
1467
  const login = {
1153
1468
  name: "login",
1154
1469
  description: "Strapi Cloud Login",
1155
- action: action$1,
1156
- command: command$2
1470
+ action: loginAction,
1471
+ command: command$3
1157
1472
  };
1158
- const action = async (ctx) => {
1473
+ const openModule = import("open");
1474
+ const action$1 = async (ctx) => {
1159
1475
  const { logger } = ctx;
1160
1476
  const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx);
1161
1477
  const token = await retrieveToken();
@@ -1163,9 +1479,21 @@ const action = async (ctx) => {
1163
1479
  logger.log("You're already logged out.");
1164
1480
  return;
1165
1481
  }
1166
- const cloudApiService = await cloudApiFactory(token);
1482
+ const cloudApiService = await cloudApiFactory(ctx, token);
1483
+ const config = await cloudApiService.config();
1484
+ const cliConfig2 = config.data;
1167
1485
  try {
1168
1486
  await eraseToken();
1487
+ openModule.then((open) => {
1488
+ open.default(
1489
+ `${cliConfig2.baseUrl}/oidc/logout?client_id=${encodeURIComponent(
1490
+ cliConfig2.clientId
1491
+ )}&logout_hint=${encodeURIComponent(token)}
1492
+ `
1493
+ ).catch((e) => {
1494
+ logger.debug(e.message, e);
1495
+ });
1496
+ });
1169
1497
  logger.log(
1170
1498
  "🔌 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
1499
  );
@@ -1173,37 +1501,64 @@ const action = async (ctx) => {
1173
1501
  logger.error("🥲 Oops! Something went wrong while logging you out. Please try again.");
1174
1502
  logger.debug(e);
1175
1503
  }
1176
- try {
1177
- await cloudApiService.track("didLogout", { loginMethod: "cli" });
1178
- } catch (e) {
1179
- logger.debug("Failed to track logout event", e);
1180
- }
1504
+ await trackEvent(ctx, cloudApiService, "didLogout", { loginMethod: "cli" });
1181
1505
  };
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));
1506
+ const command$2 = ({ ctx }) => {
1507
+ return commander.createCommand("cloud:logout").alias("logout").description("Strapi Cloud Logout").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("logout", action$1)(ctx));
1184
1508
  };
1185
1509
  const logout = {
1186
1510
  name: "logout",
1187
1511
  description: "Strapi Cloud Logout",
1188
- action,
1189
- command: command$1
1512
+ action: action$1,
1513
+ command: command$2
1190
1514
  };
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));
1515
+ const command$1 = ({ ctx }) => {
1516
+ return commander.createCommand("cloud:create-project").description("Create a Strapi Cloud project").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("cloud:create-project", action$4)(ctx));
1193
1517
  };
1194
1518
  const createProject = {
1195
1519
  name: "create-project",
1196
1520
  description: "Create a new project",
1197
- action: action$3,
1521
+ action: action$4,
1522
+ command: command$1
1523
+ };
1524
+ const action = async (ctx) => {
1525
+ const { getValidToken } = await tokenServiceFactory(ctx);
1526
+ const token = await getValidToken(ctx, promptLogin);
1527
+ const { logger } = ctx;
1528
+ if (!token) {
1529
+ return;
1530
+ }
1531
+ const cloudApiService = await cloudApiFactory(ctx, token);
1532
+ const spinner = logger.spinner("Fetching your projects...").start();
1533
+ try {
1534
+ const {
1535
+ data: { data: projectList }
1536
+ } = await cloudApiService.listProjects();
1537
+ spinner.succeed();
1538
+ logger.log(projectList);
1539
+ } catch (e) {
1540
+ ctx.logger.debug("Failed to list projects", e);
1541
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1542
+ }
1543
+ };
1544
+ const command = ({ command: command2, ctx }) => {
1545
+ 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));
1546
+ };
1547
+ const listProjects = {
1548
+ name: "list-projects",
1549
+ description: "List Strapi Cloud projects",
1550
+ action,
1198
1551
  command
1199
1552
  };
1200
1553
  const cli = {
1201
1554
  deployProject,
1555
+ link,
1202
1556
  login,
1203
1557
  logout,
1204
- createProject
1558
+ createProject,
1559
+ listProjects
1205
1560
  };
1206
- const cloudCommands = [deployProject, login, logout];
1561
+ const cloudCommands = [deployProject, link, login, logout, listProjects];
1207
1562
  async function initCloudCLIConfig() {
1208
1563
  const localConfig = await getLocalConfig();
1209
1564
  if (!localConfig.deviceId) {
@@ -1219,7 +1574,10 @@ async function buildStrapiCloudCommands({
1219
1574
  await initCloudCLIConfig();
1220
1575
  for (const cloudCommand of cloudCommands) {
1221
1576
  try {
1222
- await cloudCommand.command({ command: command2, ctx, argv });
1577
+ const subCommand = await cloudCommand.command({ command: command2, ctx, argv });
1578
+ if (subCommand) {
1579
+ command2.addCommand(subCommand);
1580
+ }
1223
1581
  } catch (e) {
1224
1582
  console.error(`Failed to load command ${cloudCommand.name}`, e);
1225
1583
  }