@strapi/cloud-cli 0.0.0-next.a64ced5364618f917adb31b8684b4e3c01c58862 → 0.0.0-next.ae38a9dcdeddea4b4c0978686fb024413e5c54f5

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 (32) hide show
  1. package/LICENSE +18 -3
  2. package/dist/index.js +405 -287
  3. package/dist/index.js.map +1 -1
  4. package/dist/index.mjs +404 -284
  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/apply-default-name.d.ts +7 -0
  9. package/dist/src/create-project/utils/apply-default-name.d.ts.map +1 -0
  10. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts +3 -0
  11. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts.map +1 -0
  12. package/dist/src/deploy-project/action.d.ts.map +1 -1
  13. package/dist/src/index.d.ts +1 -0
  14. package/dist/src/index.d.ts.map +1 -1
  15. package/dist/src/list-projects/action.d.ts +4 -0
  16. package/dist/src/list-projects/action.d.ts.map +1 -0
  17. package/dist/src/list-projects/command.d.ts +7 -0
  18. package/dist/src/list-projects/command.d.ts.map +1 -0
  19. package/dist/src/list-projects/index.d.ts +7 -0
  20. package/dist/src/list-projects/index.d.ts.map +1 -0
  21. package/dist/src/login/action.d.ts +2 -2
  22. package/dist/src/login/action.d.ts.map +1 -1
  23. package/dist/src/logout/action.d.ts.map +1 -1
  24. package/dist/src/services/cli-api.d.ts +10 -3
  25. package/dist/src/services/cli-api.d.ts.map +1 -1
  26. package/dist/src/services/token.d.ts +1 -1
  27. package/dist/src/services/token.d.ts.map +1 -1
  28. package/dist/src/utils/compress-files.d.ts.map +1 -1
  29. package/dist/src/utils/pkg.d.ts.map +1 -1
  30. package/package.json +6 -5
  31. package/dist/src/utils/tests/compress-files.test.d.ts +0 -2
  32. package/dist/src/utils/tests/compress-files.test.d.ts.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,12 +1,12 @@
1
1
  import crypto$1 from "crypto";
2
- import fse from "fs-extra";
2
+ import * as fse from "fs-extra";
3
+ import fse__default from "fs-extra";
3
4
  import * as path from "path";
4
5
  import path__default from "path";
5
6
  import chalk from "chalk";
6
7
  import axios, { AxiosError } from "axios";
7
8
  import * as crypto from "node:crypto";
8
9
  import { env } from "@strapi/utils";
9
- import * as fs from "fs";
10
10
  import * as tar from "tar";
11
11
  import { minimatch } from "minimatch";
12
12
  import inquirer from "inquirer";
@@ -18,10 +18,10 @@ import jwt from "jsonwebtoken";
18
18
  import stringify from "fast-safe-stringify";
19
19
  import ora from "ora";
20
20
  import * as cliProgress from "cli-progress";
21
- import EventSource from "eventsource";
22
- import fs$1 from "fs/promises";
23
21
  import pkgUp from "pkg-up";
24
22
  import * as yup from "yup";
23
+ import _ from "lodash";
24
+ import EventSource from "eventsource";
25
25
  const apiConfig = {
26
26
  apiBaseUrl: env("STRAPI_CLI_CLOUD_API", "https://cloud-cli-api.strapi.io"),
27
27
  dashboardBaseUrl: env("STRAPI_CLI_CLOUD_DASHBOARD", "https://cloud.strapi.io")
@@ -40,23 +40,6 @@ const IGNORED_PATTERNS = [
40
40
  "**/.idea/**",
41
41
  "**/.vscode/**"
42
42
  ];
43
- const getFiles = (dirPath, ignorePatterns = [], arrayOfFiles = [], subfolder = "") => {
44
- const entries = fs.readdirSync(path.join(dirPath, subfolder));
45
- entries.forEach((entry) => {
46
- const entryPathFromRoot = path.join(subfolder, entry);
47
- const entryPath = path.relative(dirPath, entryPathFromRoot);
48
- const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
49
- if (isIgnored) {
50
- return;
51
- }
52
- if (fs.statSync(entryPath).isDirectory()) {
53
- getFiles(dirPath, ignorePatterns, arrayOfFiles, entryPathFromRoot);
54
- } else {
55
- arrayOfFiles.push(entryPath);
56
- }
57
- });
58
- return arrayOfFiles;
59
- };
60
43
  const isIgnoredFile = (folderPath, file, ignorePatterns) => {
61
44
  ignorePatterns.push(...IGNORED_PATTERNS);
62
45
  const relativeFilePath = path.join(folderPath, file);
@@ -74,16 +57,35 @@ const isIgnoredFile = (folderPath, file, ignorePatterns) => {
74
57
  }
75
58
  return isIgnored;
76
59
  };
77
- const readGitignore = (folderPath) => {
60
+ const getFiles = async (dirPath, ignorePatterns = [], subfolder = "") => {
61
+ const arrayOfFiles = [];
62
+ const entries = await fse.readdir(path.join(dirPath, subfolder));
63
+ for (const entry of entries) {
64
+ const entryPathFromRoot = path.join(subfolder, entry);
65
+ const entryPath = path.relative(dirPath, entryPathFromRoot);
66
+ const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
67
+ if (!isIgnored) {
68
+ if (fse.statSync(entryPath).isDirectory()) {
69
+ const subFiles = await getFiles(dirPath, ignorePatterns, entryPathFromRoot);
70
+ arrayOfFiles.push(...subFiles);
71
+ } else {
72
+ arrayOfFiles.push(entryPath);
73
+ }
74
+ }
75
+ }
76
+ return arrayOfFiles;
77
+ };
78
+ const readGitignore = async (folderPath) => {
78
79
  const gitignorePath = path.resolve(folderPath, ".gitignore");
79
- if (!fs.existsSync(gitignorePath))
80
+ const pathExist = await fse.pathExists(gitignorePath);
81
+ if (!pathExist)
80
82
  return [];
81
- const gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
83
+ const gitignoreContent = await fse.readFile(gitignorePath, "utf8");
82
84
  return gitignoreContent.split(/\r?\n/).filter((line) => Boolean(line.trim()) && !line.startsWith("#"));
83
85
  };
84
86
  const compressFilesToTar = async (storagePath, folderToCompress, filename) => {
85
- const ignorePatterns = readGitignore(folderToCompress);
86
- const filesToCompress = getFiles(folderToCompress, ignorePatterns);
87
+ const ignorePatterns = await readGitignore(folderToCompress);
88
+ const filesToCompress = await getFiles(folderToCompress, ignorePatterns);
87
89
  return tar.c(
88
90
  {
89
91
  gzip: true,
@@ -96,7 +98,7 @@ const APP_FOLDER_NAME = "com.strapi.cli";
96
98
  const CONFIG_FILENAME = "config.json";
97
99
  async function checkDirectoryExists(directoryPath) {
98
100
  try {
99
- const fsStat = await fse.lstat(directoryPath);
101
+ const fsStat = await fse__default.lstat(directoryPath);
100
102
  return fsStat.isDirectory();
101
103
  } catch (e) {
102
104
  return false;
@@ -104,14 +106,14 @@ async function checkDirectoryExists(directoryPath) {
104
106
  }
105
107
  async function getTmpStoragePath() {
106
108
  const storagePath = path__default.join(os.tmpdir(), APP_FOLDER_NAME);
107
- await fse.ensureDir(storagePath);
109
+ await fse__default.ensureDir(storagePath);
108
110
  return storagePath;
109
111
  }
110
112
  async function getConfigPath() {
111
113
  const configDirs = XDGAppPaths(APP_FOLDER_NAME).configDirs();
112
114
  const configPath = configDirs.find(checkDirectoryExists);
113
115
  if (!configPath) {
114
- await fse.ensureDir(configDirs[0]);
116
+ await fse__default.ensureDir(configDirs[0]);
115
117
  return configDirs[0];
116
118
  }
117
119
  return configPath;
@@ -119,9 +121,9 @@ async function getConfigPath() {
119
121
  async function getLocalConfig() {
120
122
  const configPath = await getConfigPath();
121
123
  const configFilePath = path__default.join(configPath, CONFIG_FILENAME);
122
- await fse.ensureFile(configFilePath);
124
+ await fse__default.ensureFile(configFilePath);
123
125
  try {
124
- return await fse.readJSON(configFilePath, { encoding: "utf8", throws: true });
126
+ return await fse__default.readJSON(configFilePath, { encoding: "utf8", throws: true });
125
127
  } catch (e) {
126
128
  return {};
127
129
  }
@@ -129,10 +131,10 @@ async function getLocalConfig() {
129
131
  async function saveLocalConfig(data) {
130
132
  const configPath = await getConfigPath();
131
133
  const configFilePath = path__default.join(configPath, CONFIG_FILENAME);
132
- await fse.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
134
+ await fse__default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
133
135
  }
134
136
  const name = "@strapi/cloud-cli";
135
- const version = "4.25.0";
137
+ const version = "4.25.4";
136
138
  const description = "Commands to interact with the Strapi Cloud";
137
139
  const keywords = [
138
140
  "strapi",
@@ -173,10 +175,11 @@ const scripts = {
173
175
  build: "pack-up build",
174
176
  clean: "run -T rimraf ./dist",
175
177
  lint: "run -T eslint .",
178
+ "test:unit": "run -T jest",
176
179
  watch: "pack-up watch"
177
180
  };
178
181
  const dependencies = {
179
- "@strapi/utils": "4.25.0",
182
+ "@strapi/utils": "4.25.4",
180
183
  axios: "1.6.0",
181
184
  chalk: "4.1.2",
182
185
  "cli-progress": "3.12.0",
@@ -201,8 +204,8 @@ const devDependencies = {
201
204
  "@types/cli-progress": "3.11.5",
202
205
  "@types/eventsource": "1.1.15",
203
206
  "@types/lodash": "^4.14.191",
204
- "eslint-config-custom": "4.25.0",
205
- tsconfig: "4.25.0"
207
+ "eslint-config-custom": "4.25.4",
208
+ tsconfig: "4.25.4"
206
209
  };
207
210
  const engines = {
208
211
  node: ">=18.0.0 <=20.x.x",
@@ -231,7 +234,7 @@ const packageJson = {
231
234
  engines
232
235
  };
233
236
  const VERSION = "v1";
234
- async function cloudApiFactory(token) {
237
+ async function cloudApiFactory({ logger }, token) {
235
238
  const localConfig = await getLocalConfig();
236
239
  const customHeaders = {
237
240
  "x-device-id": localConfig.deviceId,
@@ -255,7 +258,7 @@ async function cloudApiFactory(token) {
255
258
  deploy({ filePath, project }, { onUploadProgress }) {
256
259
  return axiosCloudAPI.post(
257
260
  `/deploy/${project.name}`,
258
- { file: fse.createReadStream(filePath) },
261
+ { file: fse__default.createReadStream(filePath) },
259
262
  {
260
263
  headers: {
261
264
  "Content-Type": "multipart/form-data"
@@ -284,11 +287,33 @@ async function cloudApiFactory(token) {
284
287
  getUserInfo() {
285
288
  return axiosCloudAPI.get("/user");
286
289
  },
287
- config() {
288
- return axiosCloudAPI.get("/config");
290
+ async config() {
291
+ try {
292
+ const response = await axiosCloudAPI.get("/config");
293
+ if (response.status !== 200) {
294
+ throw new Error("Error fetching cloud CLI config from the server.");
295
+ }
296
+ return response;
297
+ } catch (error) {
298
+ logger.debug(
299
+ "🥲 Oops! Couldn't retrieve the cloud CLI config from the server. Please try again."
300
+ );
301
+ throw error;
302
+ }
289
303
  },
290
- listProjects() {
291
- return axiosCloudAPI.get("/projects");
304
+ async listProjects() {
305
+ try {
306
+ const response = await axiosCloudAPI.get("/projects");
307
+ if (response.status !== 200) {
308
+ throw new Error("Error fetching cloud projects from the server.");
309
+ }
310
+ return response;
311
+ } catch (error) {
312
+ logger.debug(
313
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
314
+ );
315
+ throw error;
316
+ }
292
317
  },
293
318
  track(event, payload = {}) {
294
319
  return axiosCloudAPI.post("/track", {
@@ -303,18 +328,18 @@ async function save(data, { directoryPath } = {}) {
303
328
  const alreadyInFileData = await retrieve({ directoryPath });
304
329
  const storedData = { ...alreadyInFileData, ...data };
305
330
  const pathToFile = path__default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
306
- await fse.ensureDir(path__default.dirname(pathToFile));
307
- await fse.writeJson(pathToFile, storedData, { encoding: "utf8" });
331
+ await fse__default.ensureDir(path__default.dirname(pathToFile));
332
+ await fse__default.writeJson(pathToFile, storedData, { encoding: "utf8" });
308
333
  }
309
334
  async function retrieve({
310
335
  directoryPath
311
336
  } = {}) {
312
337
  const pathToFile = path__default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
313
- const pathExists = await fse.pathExists(pathToFile);
338
+ const pathExists = await fse__default.pathExists(pathToFile);
314
339
  if (!pathExists) {
315
340
  return {};
316
341
  }
317
- return fse.readJSON(pathToFile, { encoding: "utf8" });
342
+ return fse__default.readJSON(pathToFile, { encoding: "utf8" });
318
343
  }
319
344
  const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
320
345
  __proto__: null,
@@ -324,7 +349,7 @@ const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defi
324
349
  }, Symbol.toStringTag, { value: "Module" }));
325
350
  let cliConfig;
326
351
  async function tokenServiceFactory({ logger }) {
327
- const cloudApiService = await cloudApiFactory();
352
+ const cloudApiService = await cloudApiFactory({ logger });
328
353
  async function saveToken(str) {
329
354
  const appConfig = await getLocalConfig();
330
355
  if (!appConfig) {
@@ -373,14 +398,17 @@ async function tokenServiceFactory({ logger }) {
373
398
  "There seems to be a problem with your login information. Please try logging in again."
374
399
  );
375
400
  }
401
+ return Promise.reject(new Error("Invalid token"));
376
402
  }
377
403
  return new Promise((resolve, reject) => {
378
404
  jwt.verify(idToken, getKey, (err) => {
379
405
  if (err) {
380
406
  reject(err);
381
- } else {
382
- resolve();
383
407
  }
408
+ if (decodedToken.payload.exp < Math.floor(Date.now() / 1e3)) {
409
+ reject(new Error("Token is expired"));
410
+ }
411
+ resolve();
384
412
  });
385
413
  });
386
414
  }
@@ -414,15 +442,15 @@ async function tokenServiceFactory({ logger }) {
414
442
  throw e;
415
443
  }
416
444
  }
417
- async function getValidToken() {
418
- const token = await retrieveToken();
419
- if (!token) {
420
- logger.log("No token found. Please login first.");
421
- return null;
422
- }
423
- if (!await isTokenValid(token)) {
424
- logger.log("Unable to proceed: Token is expired or not valid. Please login again.");
425
- return null;
445
+ async function getValidToken(ctx, loginAction2) {
446
+ let token = await retrieveToken();
447
+ while (!token || !await isTokenValid(token)) {
448
+ logger.log(
449
+ 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."
450
+ );
451
+ if (!await loginAction2(ctx))
452
+ return null;
453
+ token = await retrieveToken();
426
454
  }
427
455
  return token;
428
456
  }
@@ -556,17 +584,235 @@ const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePropert
556
584
  local: strapiInfoSave,
557
585
  tokenServiceFactory
558
586
  }, Symbol.toStringTag, { value: "Module" }));
559
- async function handleError(ctx, error) {
587
+ yup.object({
588
+ name: yup.string().required(),
589
+ exports: yup.lazy(
590
+ (value) => yup.object(
591
+ typeof value === "object" ? Object.entries(value).reduce((acc, [key, value2]) => {
592
+ if (typeof value2 === "object") {
593
+ acc[key] = yup.object({
594
+ types: yup.string().optional(),
595
+ source: yup.string().required(),
596
+ module: yup.string().optional(),
597
+ import: yup.string().required(),
598
+ require: yup.string().required(),
599
+ default: yup.string().required()
600
+ }).noUnknown(true);
601
+ } else {
602
+ acc[key] = yup.string().matches(/^\.\/.*\.json$/).required();
603
+ }
604
+ return acc;
605
+ }, {}) : void 0
606
+ ).optional()
607
+ )
608
+ });
609
+ const loadPkg = async ({ cwd, logger }) => {
610
+ const pkgPath = await pkgUp({ cwd });
611
+ if (!pkgPath) {
612
+ throw new Error("Could not find a package.json in the current directory");
613
+ }
614
+ const buffer = await fse.readFile(pkgPath);
615
+ const pkg = JSON.parse(buffer.toString());
616
+ logger.debug("Loaded package.json:", os.EOL, pkg);
617
+ return pkg;
618
+ };
619
+ async function getProjectNameFromPackageJson(ctx) {
620
+ try {
621
+ const packageJson2 = await loadPkg(ctx);
622
+ return packageJson2.name || "my-strapi-project";
623
+ } catch (e) {
624
+ return "my-strapi-project";
625
+ }
626
+ }
627
+ function applyDefaultName(newDefaultName, questions, defaultValues) {
628
+ const newDefaultValues = _.cloneDeep(defaultValues);
629
+ newDefaultValues.name = newDefaultName;
630
+ const newQuestions = questions.map((question) => {
631
+ const questionCopy = _.cloneDeep(question);
632
+ if (questionCopy.name === "name") {
633
+ questionCopy.default = newDefaultName;
634
+ }
635
+ return questionCopy;
636
+ });
637
+ return { newQuestions, newDefaultValues };
638
+ }
639
+ const openModule$1 = import("open");
640
+ async function promptLogin(ctx) {
641
+ const response = await inquirer.prompt([
642
+ {
643
+ type: "confirm",
644
+ name: "login",
645
+ message: "Would you like to login?"
646
+ }
647
+ ]);
648
+ if (response.login) {
649
+ const loginSuccessful = await loginAction(ctx);
650
+ return loginSuccessful;
651
+ }
652
+ return false;
653
+ }
654
+ async function loginAction(ctx) {
655
+ const { logger } = ctx;
560
656
  const tokenService = await tokenServiceFactory(ctx);
657
+ const existingToken = await tokenService.retrieveToken();
658
+ const cloudApiService = await cloudApiFactory(ctx, existingToken || void 0);
659
+ const trackFailedLogin = async () => {
660
+ try {
661
+ await cloudApiService.track("didNotLogin", { loginMethod: "cli" });
662
+ } catch (e) {
663
+ logger.debug("Failed to track failed login", e);
664
+ }
665
+ };
666
+ if (existingToken) {
667
+ const isTokenValid = await tokenService.isTokenValid(existingToken);
668
+ if (isTokenValid) {
669
+ try {
670
+ const userInfo = await cloudApiService.getUserInfo();
671
+ const { email } = userInfo.data.data;
672
+ if (email) {
673
+ logger.log(`You are already logged into your account (${email}).`);
674
+ } else {
675
+ logger.log("You are already logged in.");
676
+ }
677
+ logger.log(
678
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
679
+ );
680
+ logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
681
+ return true;
682
+ } catch (e) {
683
+ logger.debug("Failed to fetch user info", e);
684
+ }
685
+ }
686
+ }
687
+ let cliConfig2;
688
+ try {
689
+ logger.info("🔌 Connecting to the Strapi Cloud API...");
690
+ const config = await cloudApiService.config();
691
+ cliConfig2 = config.data;
692
+ } catch (e) {
693
+ logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
694
+ logger.debug(e);
695
+ return false;
696
+ }
697
+ try {
698
+ await cloudApiService.track("willLoginAttempt", {});
699
+ } catch (e) {
700
+ logger.debug("Failed to track login attempt", e);
701
+ }
702
+ logger.debug("🔐 Creating device authentication request...", {
703
+ client_id: cliConfig2.clientId,
704
+ scope: cliConfig2.scope,
705
+ audience: cliConfig2.audience
706
+ });
707
+ const deviceAuthResponse = await axios.post(cliConfig2.deviceCodeAuthUrl, {
708
+ client_id: cliConfig2.clientId,
709
+ scope: cliConfig2.scope,
710
+ audience: cliConfig2.audience
711
+ }).catch((e) => {
712
+ logger.error("There was an issue with the authentication process. Please try again.");
713
+ if (e.message) {
714
+ logger.debug(e.message, e);
715
+ } else {
716
+ logger.debug(e);
717
+ }
718
+ });
719
+ openModule$1.then((open) => {
720
+ open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
721
+ logger.error("We encountered an issue opening the browser. Please try again later.");
722
+ logger.debug(e.message, e);
723
+ });
724
+ });
725
+ logger.log("If a browser tab does not open automatically, please follow the next steps:");
726
+ logger.log(
727
+ `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
728
+ );
729
+ logger.log(
730
+ `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
731
+ `
732
+ );
733
+ const tokenPayload = {
734
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
735
+ device_code: deviceAuthResponse.data.device_code,
736
+ client_id: cliConfig2.clientId
737
+ };
738
+ let isAuthenticated = false;
739
+ const authenticate = async () => {
740
+ const spinner = logger.spinner("Waiting for authentication");
741
+ spinner.start();
742
+ const spinnerFail = () => spinner.fail("Authentication failed!");
743
+ while (!isAuthenticated) {
744
+ try {
745
+ const tokenResponse = await axios.post(cliConfig2.tokenUrl, tokenPayload);
746
+ const authTokenData = tokenResponse.data;
747
+ if (tokenResponse.status === 200) {
748
+ try {
749
+ logger.debug("🔐 Validating token...");
750
+ await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
751
+ logger.debug("🔐 Token validation successful!");
752
+ } catch (e) {
753
+ logger.debug(e);
754
+ spinnerFail();
755
+ throw new Error("Unable to proceed: Token validation failed");
756
+ }
757
+ logger.debug("🔍 Fetching user information...");
758
+ const cloudApiServiceWithToken = await cloudApiFactory(ctx, authTokenData.access_token);
759
+ await cloudApiServiceWithToken.getUserInfo();
760
+ logger.debug("🔍 User information fetched successfully!");
761
+ try {
762
+ logger.debug("📝 Saving login information...");
763
+ await tokenService.saveToken(authTokenData.access_token);
764
+ logger.debug("📝 Login information saved successfully!");
765
+ isAuthenticated = true;
766
+ } catch (e) {
767
+ logger.error(
768
+ "There was a problem saving your login information. Please try logging in again."
769
+ );
770
+ logger.debug(e);
771
+ spinnerFail();
772
+ return false;
773
+ }
774
+ }
775
+ } catch (e) {
776
+ if (e.message === "Unable to proceed: Token validation failed") {
777
+ logger.error(
778
+ "There seems to be a problem with your login information. Please try logging in again."
779
+ );
780
+ spinnerFail();
781
+ await trackFailedLogin();
782
+ return false;
783
+ }
784
+ if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
785
+ logger.debug(e);
786
+ spinnerFail();
787
+ await trackFailedLogin();
788
+ return false;
789
+ }
790
+ await new Promise((resolve) => {
791
+ setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
792
+ });
793
+ }
794
+ }
795
+ spinner.succeed("Authentication successful!");
796
+ logger.log("You are now logged into Strapi Cloud.");
797
+ logger.log(
798
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
799
+ );
800
+ logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
801
+ try {
802
+ await cloudApiService.track("didLogin", { loginMethod: "cli" });
803
+ } catch (e) {
804
+ logger.debug("Failed to track login", e);
805
+ }
806
+ };
807
+ await authenticate();
808
+ return isAuthenticated;
809
+ }
810
+ async function handleError(ctx, error) {
561
811
  const { logger } = ctx;
562
812
  logger.debug(error);
563
813
  if (error instanceof AxiosError) {
564
814
  const errorMessage = typeof error.response?.data === "string" ? error.response.data : null;
565
815
  switch (error.response?.status) {
566
- case 401:
567
- logger.error("Your session has expired. Please log in again.");
568
- await tokenService.eraseToken();
569
- return;
570
816
  case 403:
571
817
  logger.error(
572
818
  errorMessage || "You do not have permission to create a project. Please contact support for assistance."
@@ -592,28 +838,48 @@ async function handleError(ctx, error) {
592
838
  "We encountered an issue while creating your project. Please try again in a moment. If the problem persists, contact support for assistance."
593
839
  );
594
840
  }
841
+ async function createProject$1(ctx, cloudApi, projectInput) {
842
+ const { logger } = ctx;
843
+ const spinner = logger.spinner("Setting up your project...").start();
844
+ try {
845
+ const { data } = await cloudApi.createProject(projectInput);
846
+ await save({ project: data });
847
+ spinner.succeed("Project created successfully!");
848
+ return data;
849
+ } catch (e) {
850
+ spinner.fail("An error occurred while creating the project on Strapi Cloud.");
851
+ throw e;
852
+ }
853
+ }
595
854
  const action$3 = async (ctx) => {
596
855
  const { logger } = ctx;
597
- const { getValidToken } = await tokenServiceFactory(ctx);
598
- const token = await getValidToken();
856
+ const { getValidToken, eraseToken } = await tokenServiceFactory(ctx);
857
+ const token = await getValidToken(ctx, promptLogin);
599
858
  if (!token) {
600
859
  return;
601
860
  }
602
- const cloudApi = await cloudApiFactory(token);
861
+ const cloudApi = await cloudApiFactory(ctx, token);
603
862
  const { data: config } = await cloudApi.config();
604
- const { questions, defaults: defaultValues } = config.projectCreation;
863
+ const { newQuestions: questions, newDefaultValues: defaultValues } = applyDefaultName(
864
+ await getProjectNameFromPackageJson(ctx),
865
+ config.projectCreation.questions,
866
+ config.projectCreation.defaults
867
+ );
605
868
  const projectAnswersDefaulted = defaults(defaultValues);
606
869
  const projectAnswers = await inquirer.prompt(questions);
607
870
  const projectInput = projectAnswersDefaulted(projectAnswers);
608
- const spinner = logger.spinner("Setting up your project...").start();
609
871
  try {
610
- const { data } = await cloudApi.createProject(projectInput);
611
- await save({ project: data });
612
- spinner.succeed("Project created successfully!");
613
- return data;
872
+ return await createProject$1(ctx, cloudApi, projectInput);
614
873
  } catch (e) {
615
- spinner.fail("Failed to create project on Strapi Cloud.");
616
- await handleError(ctx, e);
874
+ if (e instanceof AxiosError && e.response?.status === 401) {
875
+ logger.warn("Oops! Your session has expired. Please log in again to retry.");
876
+ await eraseToken();
877
+ if (await promptLogin(ctx)) {
878
+ return await createProject$1(ctx, cloudApi, projectInput);
879
+ }
880
+ } else {
881
+ await handleError(ctx, e);
882
+ }
617
883
  }
618
884
  };
619
885
  function notificationServiceFactory({ logger }) {
@@ -647,38 +913,6 @@ function notificationServiceFactory({ logger }) {
647
913
  };
648
914
  };
649
915
  }
650
- yup.object({
651
- name: yup.string().required(),
652
- exports: yup.lazy(
653
- (value) => yup.object(
654
- typeof value === "object" ? Object.entries(value).reduce((acc, [key, value2]) => {
655
- if (typeof value2 === "object") {
656
- acc[key] = yup.object({
657
- types: yup.string().optional(),
658
- source: yup.string().required(),
659
- module: yup.string().optional(),
660
- import: yup.string().required(),
661
- require: yup.string().required(),
662
- default: yup.string().required()
663
- }).noUnknown(true);
664
- } else {
665
- acc[key] = yup.string().matches(/^\.\/.*\.json$/).required();
666
- }
667
- return acc;
668
- }, {}) : void 0
669
- ).optional()
670
- )
671
- });
672
- const loadPkg = async ({ cwd, logger }) => {
673
- const pkgPath = await pkgUp({ cwd });
674
- if (!pkgPath) {
675
- throw new Error("Could not find a package.json in the current directory");
676
- }
677
- const buffer = await fs$1.readFile(pkgPath);
678
- const pkg = JSON.parse(buffer.toString());
679
- logger.debug("Loaded package.json:", os.EOL, pkg);
680
- return pkg;
681
- };
682
916
  const buildLogsServiceFactory = ({ logger }) => {
683
917
  return async (url, token, cliConfig2) => {
684
918
  const CONN_TIMEOUT = Number(cliConfig2.buildLogsConnectionTimeout);
@@ -741,7 +975,7 @@ const buildLogsServiceFactory = ({ logger }) => {
741
975
  };
742
976
  };
743
977
  async function upload(ctx, project, token, maxProjectFileSize) {
744
- const cloudApi = await cloudApiFactory(token);
978
+ const cloudApi = await cloudApiFactory(ctx, token);
745
979
  try {
746
980
  const storagePath = await getTmpStoragePath();
747
981
  const projectFolder = path__default.resolve(process.cwd());
@@ -774,13 +1008,13 @@ async function upload(ctx, project, token, maxProjectFileSize) {
774
1008
  process.exit(1);
775
1009
  }
776
1010
  const tarFilePath = path__default.resolve(storagePath, compressedFilename);
777
- const fileStats = await fse.stat(tarFilePath);
1011
+ const fileStats = await fse__default.stat(tarFilePath);
778
1012
  if (fileStats.size > maxProjectFileSize) {
779
1013
  ctx.logger.log(
780
1014
  "Unable to proceed: Your project is too big to be transferred, please use a git repo instead."
781
1015
  );
782
1016
  try {
783
- await fse.remove(tarFilePath);
1017
+ await fse__default.remove(tarFilePath);
784
1018
  } catch (e) {
785
1019
  ctx.logger.log("Unable to remove file: ", tarFilePath);
786
1020
  ctx.logger.debug(e);
@@ -819,7 +1053,7 @@ async function upload(ctx, project, token, maxProjectFileSize) {
819
1053
  }
820
1054
  ctx.logger.debug(e);
821
1055
  } finally {
822
- await fse.remove(tarFilePath);
1056
+ await fse__default.remove(tarFilePath);
823
1057
  }
824
1058
  process.exit(0);
825
1059
  } catch (e) {
@@ -843,8 +1077,7 @@ async function getProject(ctx) {
843
1077
  }
844
1078
  const action$2 = async (ctx) => {
845
1079
  const { getValidToken } = await tokenServiceFactory(ctx);
846
- const cloudApiService = await cloudApiFactory();
847
- const token = await getValidToken();
1080
+ const token = await getValidToken(ctx, promptLogin);
848
1081
  if (!token) {
849
1082
  return;
850
1083
  }
@@ -852,6 +1085,7 @@ const action$2 = async (ctx) => {
852
1085
  if (!project) {
853
1086
  return;
854
1087
  }
1088
+ const cloudApiService = await cloudApiFactory(ctx);
855
1089
  try {
856
1090
  await cloudApiService.track("willDeployWithCLI", { projectInternalName: project.name });
857
1091
  } catch (e) {
@@ -915,185 +1149,29 @@ const runAction = (name2, action2) => (...args) => {
915
1149
  process.exit(1);
916
1150
  });
917
1151
  };
918
- const command$3 = ({ command: command2, ctx }) => {
1152
+ const command$4 = ({ command: command2, ctx }) => {
919
1153
  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));
920
1154
  };
921
1155
  const deployProject = {
922
1156
  name: "deploy-project",
923
1157
  description: "Deploy a Strapi Cloud project",
924
1158
  action: action$2,
925
- command: command$3
1159
+ command: command$4
926
1160
  };
927
- const openModule = import("open");
928
- const action$1 = async (ctx) => {
929
- const { logger } = ctx;
930
- const tokenService = await tokenServiceFactory(ctx);
931
- const existingToken = await tokenService.retrieveToken();
932
- const cloudApiService = await cloudApiFactory(existingToken || void 0);
933
- const trackFailedLogin = async () => {
934
- try {
935
- await cloudApiService.track("didNotLogin", { loginMethod: "cli" });
936
- } catch (e) {
937
- logger.debug("Failed to track failed login", e);
938
- }
939
- };
940
- if (existingToken) {
941
- const isTokenValid = await tokenService.isTokenValid(existingToken);
942
- if (isTokenValid) {
943
- try {
944
- const userInfo = await cloudApiService.getUserInfo();
945
- const { email } = userInfo.data.data;
946
- if (email) {
947
- logger.log(`You are already logged into your account (${email}).`);
948
- } else {
949
- logger.log("You are already logged in.");
950
- }
951
- logger.log(
952
- "To access your dashboard, please copy and paste the following URL into your web browser:"
953
- );
954
- logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
955
- return true;
956
- } catch (e) {
957
- logger.debug("Failed to fetch user info", e);
958
- }
959
- }
960
- }
961
- let cliConfig2;
962
- try {
963
- logger.info("🔌 Connecting to the Strapi Cloud API...");
964
- const config = await cloudApiService.config();
965
- cliConfig2 = config.data;
966
- } catch (e) {
967
- logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
968
- logger.debug(e);
969
- return false;
970
- }
971
- try {
972
- await cloudApiService.track("willLoginAttempt", {});
973
- } catch (e) {
974
- logger.debug("Failed to track login attempt", e);
975
- }
976
- logger.debug("🔐 Creating device authentication request...", {
977
- client_id: cliConfig2.clientId,
978
- scope: cliConfig2.scope,
979
- audience: cliConfig2.audience
980
- });
981
- const deviceAuthResponse = await axios.post(cliConfig2.deviceCodeAuthUrl, {
982
- client_id: cliConfig2.clientId,
983
- scope: cliConfig2.scope,
984
- audience: cliConfig2.audience
985
- }).catch((e) => {
986
- logger.error("There was an issue with the authentication process. Please try again.");
987
- if (e.message) {
988
- logger.debug(e.message, e);
989
- } else {
990
- logger.debug(e);
991
- }
992
- });
993
- openModule.then((open) => {
994
- open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
995
- logger.error("We encountered an issue opening the browser. Please try again later.");
996
- logger.debug(e.message, e);
997
- });
998
- });
999
- logger.log("If a browser tab does not open automatically, please follow the next steps:");
1000
- logger.log(
1001
- `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
1002
- );
1003
- logger.log(
1004
- `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
1005
- `
1006
- );
1007
- const tokenPayload = {
1008
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1009
- device_code: deviceAuthResponse.data.device_code,
1010
- client_id: cliConfig2.clientId
1011
- };
1012
- let isAuthenticated = false;
1013
- const authenticate = async () => {
1014
- const spinner = logger.spinner("Waiting for authentication");
1015
- spinner.start();
1016
- const spinnerFail = () => spinner.fail("Authentication failed!");
1017
- while (!isAuthenticated) {
1018
- try {
1019
- const tokenResponse = await axios.post(cliConfig2.tokenUrl, tokenPayload);
1020
- const authTokenData = tokenResponse.data;
1021
- if (tokenResponse.status === 200) {
1022
- try {
1023
- logger.debug("🔐 Validating token...");
1024
- await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
1025
- logger.debug("🔐 Token validation successful!");
1026
- } catch (e) {
1027
- logger.debug(e);
1028
- spinnerFail();
1029
- throw new Error("Unable to proceed: Token validation failed");
1030
- }
1031
- logger.debug("🔍 Fetching user information...");
1032
- const cloudApiServiceWithToken = await cloudApiFactory(authTokenData.access_token);
1033
- await cloudApiServiceWithToken.getUserInfo();
1034
- logger.debug("🔍 User information fetched successfully!");
1035
- try {
1036
- logger.debug("📝 Saving login information...");
1037
- await tokenService.saveToken(authTokenData.access_token);
1038
- logger.debug("📝 Login information saved successfully!");
1039
- isAuthenticated = true;
1040
- } catch (e) {
1041
- logger.error(
1042
- "There was a problem saving your login information. Please try logging in again."
1043
- );
1044
- logger.debug(e);
1045
- spinnerFail();
1046
- return false;
1047
- }
1048
- }
1049
- } catch (e) {
1050
- if (e.message === "Unable to proceed: Token validation failed") {
1051
- logger.error(
1052
- "There seems to be a problem with your login information. Please try logging in again."
1053
- );
1054
- spinnerFail();
1055
- await trackFailedLogin();
1056
- return false;
1057
- }
1058
- if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
1059
- logger.debug(e);
1060
- spinnerFail();
1061
- await trackFailedLogin();
1062
- return false;
1063
- }
1064
- await new Promise((resolve) => {
1065
- setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
1066
- });
1067
- }
1068
- }
1069
- spinner.succeed("Authentication successful!");
1070
- logger.log("You are now logged into Strapi Cloud.");
1071
- logger.log(
1072
- "To access your dashboard, please copy and paste the following URL into your web browser:"
1073
- );
1074
- logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
1075
- try {
1076
- await cloudApiService.track("didLogin", { loginMethod: "cli" });
1077
- } catch (e) {
1078
- logger.debug("Failed to track login", e);
1079
- }
1080
- };
1081
- await authenticate();
1082
- return isAuthenticated;
1083
- };
1084
- const command$2 = ({ command: command2, ctx }) => {
1161
+ const command$3 = ({ command: command2, ctx }) => {
1085
1162
  command2.command("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1086
1163
  "after",
1087
1164
  "\nAfter running this command, you will be prompted to enter your authentication information."
1088
- ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", action$1)(ctx));
1165
+ ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", loginAction)(ctx));
1089
1166
  };
1090
1167
  const login = {
1091
1168
  name: "login",
1092
1169
  description: "Strapi Cloud Login",
1093
- action: action$1,
1094
- command: command$2
1170
+ action: loginAction,
1171
+ command: command$3
1095
1172
  };
1096
- const action = async (ctx) => {
1173
+ const openModule = import("open");
1174
+ const action$1 = async (ctx) => {
1097
1175
  const { logger } = ctx;
1098
1176
  const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx);
1099
1177
  const token = await retrieveToken();
@@ -1101,9 +1179,21 @@ const action = async (ctx) => {
1101
1179
  logger.log("You're already logged out.");
1102
1180
  return;
1103
1181
  }
1104
- const cloudApiService = await cloudApiFactory(token);
1182
+ const cloudApiService = await cloudApiFactory(ctx, token);
1183
+ const config = await cloudApiService.config();
1184
+ const cliConfig2 = config.data;
1105
1185
  try {
1106
1186
  await eraseToken();
1187
+ openModule.then((open) => {
1188
+ open.default(
1189
+ `${cliConfig2.baseUrl}/oidc/logout?client_id=${encodeURIComponent(
1190
+ cliConfig2.clientId
1191
+ )}&logout_hint=${encodeURIComponent(token)}
1192
+ `
1193
+ ).catch((e) => {
1194
+ logger.debug(e.message, e);
1195
+ });
1196
+ });
1107
1197
  logger.log(
1108
1198
  "🔌 You have been logged out from the CLI. If you are on a shared computer, please make sure to log out from the Strapi Cloud Dashboard as well."
1109
1199
  );
@@ -1117,31 +1207,61 @@ const action = async (ctx) => {
1117
1207
  logger.debug("Failed to track logout event", e);
1118
1208
  }
1119
1209
  };
1120
- const command$1 = ({ command: command2, ctx }) => {
1121
- command2.command("cloud:logout").alias("logout").description("Strapi Cloud Logout").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("logout", action)(ctx));
1210
+ const command$2 = ({ command: command2, ctx }) => {
1211
+ command2.command("cloud:logout").alias("logout").description("Strapi Cloud Logout").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("logout", action$1)(ctx));
1122
1212
  };
1123
1213
  const logout = {
1124
1214
  name: "logout",
1125
1215
  description: "Strapi Cloud Logout",
1126
- action,
1127
- command: command$1
1216
+ action: action$1,
1217
+ command: command$2
1128
1218
  };
1129
- const command = ({ command: command2, ctx }) => {
1219
+ const command$1 = ({ command: command2, ctx }) => {
1130
1220
  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));
1131
1221
  };
1132
1222
  const createProject = {
1133
1223
  name: "create-project",
1134
1224
  description: "Create a new project",
1135
1225
  action: action$3,
1226
+ command: command$1
1227
+ };
1228
+ const action = async (ctx) => {
1229
+ const { getValidToken } = await tokenServiceFactory(ctx);
1230
+ const token = await getValidToken(ctx, promptLogin);
1231
+ const { logger } = ctx;
1232
+ if (!token) {
1233
+ return;
1234
+ }
1235
+ const cloudApiService = await cloudApiFactory(ctx, token);
1236
+ const spinner = logger.spinner("Fetching your projects...").start();
1237
+ try {
1238
+ const {
1239
+ data: { data: projectList }
1240
+ } = await cloudApiService.listProjects();
1241
+ spinner.succeed();
1242
+ logger.log(projectList);
1243
+ } catch (e) {
1244
+ ctx.logger.debug("Failed to list projects", e);
1245
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1246
+ }
1247
+ };
1248
+ const command = ({ command: command2, ctx }) => {
1249
+ 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("listProjects", action)(ctx));
1250
+ };
1251
+ const listProjects = {
1252
+ name: "list-projects",
1253
+ description: "List Strapi Cloud projects",
1254
+ action,
1136
1255
  command
1137
1256
  };
1138
1257
  const cli = {
1139
1258
  deployProject,
1140
1259
  login,
1141
1260
  logout,
1142
- createProject
1261
+ createProject,
1262
+ listProjects
1143
1263
  };
1144
- const cloudCommands = [deployProject, login, logout];
1264
+ const cloudCommands = [deployProject, login, logout, listProjects];
1145
1265
  async function initCloudCLIConfig() {
1146
1266
  const localConfig = await getLocalConfig();
1147
1267
  if (!localConfig.deviceId) {