@strapi/cloud-cli 0.1.0 → 4.24.5

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 (65) hide show
  1. package/LICENSE +1 -1
  2. package/bin/index.js +7 -0
  3. package/dist/bin.js +177 -0
  4. package/dist/bin.js.map +1 -0
  5. package/dist/index.js +1231 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/index.mjs +1171 -0
  8. package/dist/index.mjs.map +1 -0
  9. package/dist/src/bin.d.ts +4 -0
  10. package/dist/src/bin.d.ts.map +1 -0
  11. package/dist/src/config/api.d.ts +5 -0
  12. package/dist/src/config/api.d.ts.map +1 -0
  13. package/dist/src/config/local.d.ts +9 -0
  14. package/dist/src/config/local.d.ts.map +1 -0
  15. package/dist/src/create-project/action.d.ts +4 -0
  16. package/dist/src/create-project/action.d.ts.map +1 -0
  17. package/dist/src/create-project/command.d.ts +7 -0
  18. package/dist/src/create-project/command.d.ts.map +1 -0
  19. package/dist/src/create-project/index.d.ts +7 -0
  20. package/dist/src/create-project/index.d.ts.map +1 -0
  21. package/dist/src/deploy-project/action.d.ts +4 -0
  22. package/dist/src/deploy-project/action.d.ts.map +1 -0
  23. package/dist/src/deploy-project/command.d.ts +7 -0
  24. package/dist/src/deploy-project/command.d.ts.map +1 -0
  25. package/dist/src/deploy-project/index.d.ts +7 -0
  26. package/dist/src/deploy-project/index.d.ts.map +1 -0
  27. package/dist/src/index.d.ts +21 -0
  28. package/dist/src/index.d.ts.map +1 -0
  29. package/dist/src/login/action.d.ts +4 -0
  30. package/dist/src/login/action.d.ts.map +1 -0
  31. package/dist/src/login/command.d.ts +7 -0
  32. package/dist/src/login/command.d.ts.map +1 -0
  33. package/dist/src/login/index.d.ts +7 -0
  34. package/dist/src/login/index.d.ts.map +1 -0
  35. package/dist/src/logout/action.d.ts +4 -0
  36. package/dist/src/logout/action.d.ts.map +1 -0
  37. package/dist/src/logout/command.d.ts +7 -0
  38. package/dist/src/logout/command.d.ts.map +1 -0
  39. package/dist/src/logout/index.d.ts +11 -0
  40. package/dist/src/logout/index.d.ts.map +1 -0
  41. package/dist/src/services/build-logs.d.ts +4 -0
  42. package/dist/src/services/build-logs.d.ts.map +1 -0
  43. package/dist/src/services/cli-api.d.ts +39 -0
  44. package/dist/src/services/cli-api.d.ts.map +1 -0
  45. package/dist/src/services/index.d.ts +5 -0
  46. package/dist/src/services/index.d.ts.map +1 -0
  47. package/dist/src/services/logger.d.ts +22 -0
  48. package/dist/src/services/logger.d.ts.map +1 -0
  49. package/dist/src/services/notification.d.ts +3 -0
  50. package/dist/src/services/notification.d.ts.map +1 -0
  51. package/dist/src/services/strapi-info-save.d.ts +12 -0
  52. package/dist/src/services/strapi-info-save.d.ts.map +1 -0
  53. package/dist/src/services/token.d.ts +12 -0
  54. package/dist/src/services/token.d.ts.map +1 -0
  55. package/dist/src/types.d.ts +44 -0
  56. package/dist/src/types.d.ts.map +1 -0
  57. package/dist/src/utils/compress-files.d.ts +4 -0
  58. package/dist/src/utils/compress-files.d.ts.map +1 -0
  59. package/dist/src/utils/helpers.d.ts +3 -0
  60. package/dist/src/utils/helpers.d.ts.map +1 -0
  61. package/dist/src/utils/pkg.d.ts +121 -0
  62. package/dist/src/utils/pkg.d.ts.map +1 -0
  63. package/dist/src/utils/tests/compress-files.test.d.ts +2 -0
  64. package/dist/src/utils/tests/compress-files.test.d.ts.map +1 -0
  65. package/package.json +55 -8
package/dist/index.mjs ADDED
@@ -0,0 +1,1171 @@
1
+ import crypto$1 from "crypto";
2
+ import fse from "fs-extra";
3
+ import * as path from "path";
4
+ import path__default from "path";
5
+ import chalk from "chalk";
6
+ import axios, { AxiosError } from "axios";
7
+ import * as crypto from "node:crypto";
8
+ import { env } from "@strapi/utils";
9
+ import * as fs from "fs";
10
+ import * as tar from "tar";
11
+ import { minimatch } from "minimatch";
12
+ import inquirer from "inquirer";
13
+ import { defaults, has } from "lodash/fp";
14
+ import os from "os";
15
+ import XDGAppPaths from "xdg-app-paths";
16
+ import jwksClient from "jwks-rsa";
17
+ import jwt from "jsonwebtoken";
18
+ import stringify from "fast-safe-stringify";
19
+ import ora from "ora";
20
+ import * as cliProgress from "cli-progress";
21
+ import EventSource from "eventsource";
22
+ import fs$1 from "fs/promises";
23
+ import pkgUp from "pkg-up";
24
+ import * as yup from "yup";
25
+ const apiConfig = {
26
+ apiBaseUrl: env("STRAPI_CLI_CLOUD_API", "https://cloud-cli-api.strapi.io"),
27
+ dashboardBaseUrl: env("STRAPI_CLI_CLOUD_DASHBOARD", "https://cloud.strapi.io")
28
+ };
29
+ const IGNORED_PATTERNS = [
30
+ "**/.git/**",
31
+ "**/node_modules/**",
32
+ "**/build/**",
33
+ "**/dist/**",
34
+ "**/.cache/**",
35
+ "**/.circleci/**",
36
+ "**/.github/**",
37
+ "**/.gitignore",
38
+ "**/.gitkeep",
39
+ "**/.gitlab-ci.yml",
40
+ "**/.idea/**",
41
+ "**/.vscode/**"
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
+ const isIgnoredFile = (folderPath, file, ignorePatterns) => {
61
+ ignorePatterns.push(...IGNORED_PATTERNS);
62
+ const relativeFilePath = path.join(folderPath, file);
63
+ let isIgnored = false;
64
+ for (const pattern of ignorePatterns) {
65
+ if (pattern.startsWith("!")) {
66
+ if (minimatch(relativeFilePath, pattern.slice(1), { matchBase: true, dot: true })) {
67
+ return false;
68
+ }
69
+ } else if (minimatch(relativeFilePath, pattern, { matchBase: true, dot: true })) {
70
+ if (path.basename(file) !== ".gitkeep") {
71
+ isIgnored = true;
72
+ }
73
+ }
74
+ }
75
+ return isIgnored;
76
+ };
77
+ const readGitignore = (folderPath) => {
78
+ const gitignorePath = path.resolve(folderPath, ".gitignore");
79
+ if (!fs.existsSync(gitignorePath))
80
+ return [];
81
+ const gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
82
+ return gitignoreContent.split(/\r?\n/).filter((line) => Boolean(line.trim()) && !line.startsWith("#"));
83
+ };
84
+ const compressFilesToTar = async (storagePath, folderToCompress, filename) => {
85
+ const ignorePatterns = readGitignore(folderToCompress);
86
+ const filesToCompress = getFiles(folderToCompress, ignorePatterns);
87
+ return tar.c(
88
+ {
89
+ gzip: true,
90
+ file: path.resolve(storagePath, filename)
91
+ },
92
+ filesToCompress
93
+ );
94
+ };
95
+ const APP_FOLDER_NAME = "com.strapi.cli";
96
+ const CONFIG_FILENAME = "config.json";
97
+ async function checkDirectoryExists(directoryPath) {
98
+ try {
99
+ const fsStat = await fse.lstat(directoryPath);
100
+ return fsStat.isDirectory();
101
+ } catch (e) {
102
+ return false;
103
+ }
104
+ }
105
+ async function getTmpStoragePath() {
106
+ const storagePath = path__default.join(os.tmpdir(), APP_FOLDER_NAME);
107
+ await fse.ensureDir(storagePath);
108
+ return storagePath;
109
+ }
110
+ async function getConfigPath() {
111
+ const configDirs = XDGAppPaths(APP_FOLDER_NAME).configDirs();
112
+ const configPath = configDirs.find(checkDirectoryExists);
113
+ if (!configPath) {
114
+ await fse.ensureDir(configDirs[0]);
115
+ return configDirs[0];
116
+ }
117
+ return configPath;
118
+ }
119
+ async function getLocalConfig() {
120
+ const configPath = await getConfigPath();
121
+ const configFilePath = path__default.join(configPath, CONFIG_FILENAME);
122
+ await fse.ensureFile(configFilePath);
123
+ try {
124
+ return await fse.readJSON(configFilePath, { encoding: "utf8", throws: true });
125
+ } catch (e) {
126
+ return {};
127
+ }
128
+ }
129
+ async function saveLocalConfig(data) {
130
+ const configPath = await getConfigPath();
131
+ const configFilePath = path__default.join(configPath, CONFIG_FILENAME);
132
+ await fse.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
133
+ }
134
+ const name = "@strapi/cloud-cli";
135
+ const version = "4.24.5";
136
+ const description = "Commands to interact with the Strapi Cloud";
137
+ const keywords = [
138
+ "strapi",
139
+ "cloud",
140
+ "cli"
141
+ ];
142
+ const homepage = "https://strapi.io";
143
+ const bugs = {
144
+ url: "https://github.com/strapi/strapi/issues"
145
+ };
146
+ const repository = {
147
+ type: "git",
148
+ url: "git://github.com/strapi/strapi.git"
149
+ };
150
+ const license = "SEE LICENSE IN LICENSE";
151
+ const author = {
152
+ name: "Strapi Solutions SAS",
153
+ email: "hi@strapi.io",
154
+ url: "https://strapi.io"
155
+ };
156
+ const maintainers = [
157
+ {
158
+ name: "Strapi Solutions SAS",
159
+ email: "hi@strapi.io",
160
+ url: "https://strapi.io"
161
+ }
162
+ ];
163
+ const main = "./dist/index.js";
164
+ const module = "./dist/index.mjs";
165
+ const source = "./src/index.ts";
166
+ const types = "./dist/src/index.d.ts";
167
+ const bin = "./bin/index.js";
168
+ const files = [
169
+ "./dist",
170
+ "./bin"
171
+ ];
172
+ const scripts = {
173
+ build: "pack-up build",
174
+ clean: "run -T rimraf ./dist",
175
+ lint: "run -T eslint .",
176
+ watch: "pack-up watch"
177
+ };
178
+ const dependencies = {
179
+ "@strapi/utils": "4.24.5",
180
+ axios: "1.6.0",
181
+ chalk: "4.1.2",
182
+ "cli-progress": "3.12.0",
183
+ commander: "8.3.0",
184
+ eventsource: "2.0.2",
185
+ "fast-safe-stringify": "2.1.1",
186
+ "fs-extra": "10.0.0",
187
+ inquirer: "8.2.5",
188
+ jsonwebtoken: "9.0.0",
189
+ "jwks-rsa": "3.1.0",
190
+ lodash: "4.17.21",
191
+ minimatch: "9.0.3",
192
+ open: "8.4.0",
193
+ ora: "5.4.1",
194
+ "pkg-up": "3.1.0",
195
+ tar: "6.1.13",
196
+ "xdg-app-paths": "8.3.0",
197
+ yup: "0.32.9"
198
+ };
199
+ const devDependencies = {
200
+ "@strapi/pack-up": "4.23.0",
201
+ "@types/cli-progress": "3.11.5",
202
+ "@types/eventsource": "1.1.15",
203
+ "@types/lodash": "^4.14.191",
204
+ "eslint-config-custom": "4.24.5",
205
+ tsconfig: "4.24.5"
206
+ };
207
+ const engines = {
208
+ node: ">=18.0.0 <=20.x.x",
209
+ npm: ">=6.0.0"
210
+ };
211
+ const packageJson = {
212
+ name,
213
+ version,
214
+ description,
215
+ keywords,
216
+ homepage,
217
+ bugs,
218
+ repository,
219
+ license,
220
+ author,
221
+ maintainers,
222
+ main,
223
+ module,
224
+ source,
225
+ types,
226
+ bin,
227
+ files,
228
+ scripts,
229
+ dependencies,
230
+ devDependencies,
231
+ engines
232
+ };
233
+ const VERSION = "v1";
234
+ async function cloudApiFactory(token) {
235
+ const localConfig = await getLocalConfig();
236
+ const customHeaders = {
237
+ "x-device-id": localConfig.deviceId,
238
+ "x-app-version": packageJson.version,
239
+ "x-os-name": os.type(),
240
+ "x-os-version": os.version(),
241
+ "x-language": Intl.DateTimeFormat().resolvedOptions().locale,
242
+ "x-node-version": process.versions.node
243
+ };
244
+ const axiosCloudAPI = axios.create({
245
+ baseURL: `${apiConfig.apiBaseUrl}/${VERSION}`,
246
+ headers: {
247
+ "Content-Type": "application/json",
248
+ ...customHeaders
249
+ }
250
+ });
251
+ if (token) {
252
+ axiosCloudAPI.defaults.headers.Authorization = `Bearer ${token}`;
253
+ }
254
+ return {
255
+ deploy({ filePath, project }, { onUploadProgress }) {
256
+ return axiosCloudAPI.post(
257
+ `/deploy/${project.name}`,
258
+ { file: fse.createReadStream(filePath) },
259
+ {
260
+ headers: {
261
+ "Content-Type": "multipart/form-data"
262
+ },
263
+ onUploadProgress
264
+ }
265
+ );
266
+ },
267
+ async createProject({ name: name2, nodeVersion, region, plan }) {
268
+ const response = await axiosCloudAPI.post("/project", {
269
+ projectName: name2,
270
+ region,
271
+ nodeVersion,
272
+ plan
273
+ });
274
+ return {
275
+ data: {
276
+ id: response.data.id,
277
+ name: response.data.name,
278
+ nodeVersion: response.data.nodeVersion,
279
+ region: response.data.region
280
+ },
281
+ status: response.status
282
+ };
283
+ },
284
+ getUserInfo() {
285
+ return axiosCloudAPI.get("/user");
286
+ },
287
+ config() {
288
+ return axiosCloudAPI.get("/config");
289
+ },
290
+ listProjects() {
291
+ return axiosCloudAPI.get("/projects");
292
+ },
293
+ track(event, payload = {}) {
294
+ return axiosCloudAPI.post("/track", {
295
+ event,
296
+ payload
297
+ });
298
+ }
299
+ };
300
+ }
301
+ const LOCAL_SAVE_FILENAME = ".strapi-cloud.json";
302
+ async function save(data, { directoryPath } = {}) {
303
+ const alreadyInFileData = await retrieve({ directoryPath });
304
+ const storedData = { ...alreadyInFileData, ...data };
305
+ 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" });
308
+ }
309
+ async function retrieve({
310
+ directoryPath
311
+ } = {}) {
312
+ const pathToFile = path__default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
313
+ const pathExists = await fse.pathExists(pathToFile);
314
+ if (!pathExists) {
315
+ return {};
316
+ }
317
+ return fse.readJSON(pathToFile, { encoding: "utf8" });
318
+ }
319
+ const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
320
+ __proto__: null,
321
+ LOCAL_SAVE_FILENAME,
322
+ retrieve,
323
+ save
324
+ }, Symbol.toStringTag, { value: "Module" }));
325
+ let cliConfig;
326
+ async function tokenServiceFactory({ logger }) {
327
+ const cloudApiService = await cloudApiFactory();
328
+ async function saveToken(str) {
329
+ const appConfig = await getLocalConfig();
330
+ if (!appConfig) {
331
+ logger.error("There was a problem saving your token. Please try again.");
332
+ return;
333
+ }
334
+ appConfig.token = str;
335
+ try {
336
+ await saveLocalConfig(appConfig);
337
+ } catch (e) {
338
+ logger.debug(e);
339
+ logger.error("There was a problem saving your token. Please try again.");
340
+ }
341
+ }
342
+ async function retrieveToken() {
343
+ const appConfig = await getLocalConfig();
344
+ if (appConfig.token) {
345
+ if (await isTokenValid(appConfig.token)) {
346
+ return appConfig.token;
347
+ }
348
+ }
349
+ return void 0;
350
+ }
351
+ async function validateToken(idToken, jwksUrl) {
352
+ const client = jwksClient({
353
+ jwksUri: jwksUrl
354
+ });
355
+ const getKey = (header, callback) => {
356
+ client.getSigningKey(header.kid, (e, key) => {
357
+ if (e) {
358
+ callback(e);
359
+ } else if (key) {
360
+ const publicKey = "publicKey" in key ? key.publicKey : key.rsaPublicKey;
361
+ callback(null, publicKey);
362
+ } else {
363
+ callback(new Error("Key not found"));
364
+ }
365
+ });
366
+ };
367
+ const decodedToken = jwt.decode(idToken, { complete: true });
368
+ if (!decodedToken) {
369
+ if (typeof idToken === "undefined" || idToken === "") {
370
+ logger.warn("You need to be logged in to use this feature. Please log in and try again.");
371
+ } else {
372
+ logger.error(
373
+ "There seems to be a problem with your login information. Please try logging in again."
374
+ );
375
+ }
376
+ }
377
+ return new Promise((resolve, reject) => {
378
+ jwt.verify(idToken, getKey, (err) => {
379
+ if (err) {
380
+ reject(err);
381
+ } else {
382
+ resolve();
383
+ }
384
+ });
385
+ });
386
+ }
387
+ async function isTokenValid(token) {
388
+ try {
389
+ const config = await cloudApiService.config();
390
+ cliConfig = config.data;
391
+ if (token) {
392
+ await validateToken(token, cliConfig.jwksUrl);
393
+ return true;
394
+ }
395
+ return false;
396
+ } catch (e) {
397
+ logger.debug(e);
398
+ return false;
399
+ }
400
+ }
401
+ async function eraseToken() {
402
+ const appConfig = await getLocalConfig();
403
+ if (!appConfig) {
404
+ return;
405
+ }
406
+ delete appConfig.token;
407
+ try {
408
+ await saveLocalConfig(appConfig);
409
+ } catch (e) {
410
+ logger.debug(e);
411
+ logger.error(
412
+ "There was an issue removing your login information. Please try logging out again."
413
+ );
414
+ throw e;
415
+ }
416
+ }
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;
426
+ }
427
+ return token;
428
+ }
429
+ return {
430
+ saveToken,
431
+ retrieveToken,
432
+ validateToken,
433
+ isTokenValid,
434
+ eraseToken,
435
+ getValidToken
436
+ };
437
+ }
438
+ const stringifyArg = (arg) => {
439
+ return typeof arg === "object" ? stringify(arg) : arg;
440
+ };
441
+ const createLogger = (options = {}) => {
442
+ const { silent = false, debug = false, timestamp = true } = options;
443
+ const state = { errors: 0, warning: 0 };
444
+ return {
445
+ get warnings() {
446
+ return state.warning;
447
+ },
448
+ get errors() {
449
+ return state.errors;
450
+ },
451
+ async debug(...args) {
452
+ if (silent || !debug) {
453
+ return;
454
+ }
455
+ console.log(
456
+ chalk.cyan(`[DEBUG]${timestamp ? ` [${(/* @__PURE__ */ new Date()).toISOString()}]` : ""}`),
457
+ ...args.map(stringifyArg)
458
+ );
459
+ },
460
+ info(...args) {
461
+ if (silent) {
462
+ return;
463
+ }
464
+ console.info(
465
+ chalk.blue(`[INFO]${timestamp ? ` [${(/* @__PURE__ */ new Date()).toISOString()}]` : ""}`),
466
+ ...args.map(stringifyArg)
467
+ );
468
+ },
469
+ log(...args) {
470
+ if (silent) {
471
+ return;
472
+ }
473
+ console.info(
474
+ chalk.blue(`${timestamp ? ` [${(/* @__PURE__ */ new Date()).toISOString()}]` : ""}`),
475
+ ...args.map(stringifyArg)
476
+ );
477
+ },
478
+ success(...args) {
479
+ if (silent) {
480
+ return;
481
+ }
482
+ console.info(
483
+ chalk.green(`[SUCCESS]${timestamp ? ` [${(/* @__PURE__ */ new Date()).toISOString()}]` : ""}`),
484
+ ...args.map(stringifyArg)
485
+ );
486
+ },
487
+ warn(...args) {
488
+ state.warning += 1;
489
+ if (silent) {
490
+ return;
491
+ }
492
+ console.warn(
493
+ chalk.yellow(`[WARN]${timestamp ? ` [${(/* @__PURE__ */ new Date()).toISOString()}]` : ""}`),
494
+ ...args.map(stringifyArg)
495
+ );
496
+ },
497
+ error(...args) {
498
+ state.errors += 1;
499
+ if (silent) {
500
+ return;
501
+ }
502
+ console.error(
503
+ chalk.red(`[ERROR]${timestamp ? ` [${(/* @__PURE__ */ new Date()).toISOString()}]` : ""}`),
504
+ ...args.map(stringifyArg)
505
+ );
506
+ },
507
+ // @ts-expect-error – returning a subpart of ora is fine because the types tell us what is what.
508
+ spinner(text) {
509
+ if (silent) {
510
+ return {
511
+ succeed() {
512
+ return this;
513
+ },
514
+ fail() {
515
+ return this;
516
+ },
517
+ start() {
518
+ return this;
519
+ },
520
+ text: "",
521
+ isSpinning: false
522
+ };
523
+ }
524
+ return ora(text);
525
+ },
526
+ progressBar(totalSize, text) {
527
+ if (silent) {
528
+ return {
529
+ start() {
530
+ return this;
531
+ },
532
+ stop() {
533
+ return this;
534
+ },
535
+ update() {
536
+ return this;
537
+ }
538
+ };
539
+ }
540
+ const progressBar = new cliProgress.SingleBar({
541
+ format: `${text ? `${text} |` : ""}${chalk.green("{bar}")}| {percentage}%`,
542
+ barCompleteChar: "█",
543
+ barIncompleteChar: "░",
544
+ hideCursor: true,
545
+ forceRedraw: true
546
+ });
547
+ progressBar.start(totalSize, 0);
548
+ return progressBar;
549
+ }
550
+ };
551
+ };
552
+ const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
553
+ __proto__: null,
554
+ cloudApiFactory,
555
+ createLogger,
556
+ local: strapiInfoSave,
557
+ tokenServiceFactory
558
+ }, Symbol.toStringTag, { value: "Module" }));
559
+ async function handleError(ctx, error) {
560
+ const tokenService = await tokenServiceFactory(ctx);
561
+ const { logger } = ctx;
562
+ logger.debug(error);
563
+ if (error instanceof AxiosError) {
564
+ const errorMessage = typeof error.response?.data === "string" ? error.response.data : null;
565
+ 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
+ case 403:
571
+ logger.error(
572
+ errorMessage || "You do not have permission to create a project. Please contact support for assistance."
573
+ );
574
+ return;
575
+ case 400:
576
+ logger.error(errorMessage || "Invalid input. Please check your inputs and try again.");
577
+ return;
578
+ case 503:
579
+ logger.error(
580
+ "Strapi Cloud project creation is currently unavailable. Please try again later."
581
+ );
582
+ return;
583
+ default:
584
+ if (errorMessage) {
585
+ logger.error(errorMessage);
586
+ return;
587
+ }
588
+ break;
589
+ }
590
+ }
591
+ logger.error(
592
+ "We encountered an issue while creating your project. Please try again in a moment. If the problem persists, contact support for assistance."
593
+ );
594
+ }
595
+ const action$3 = async (ctx) => {
596
+ const { logger } = ctx;
597
+ const { getValidToken } = await tokenServiceFactory(ctx);
598
+ const token = await getValidToken();
599
+ if (!token) {
600
+ return;
601
+ }
602
+ const cloudApi = await cloudApiFactory(token);
603
+ const { data: config } = await cloudApi.config();
604
+ const { questions, defaults: defaultValues } = config.projectCreation;
605
+ const projectAnswersDefaulted = defaults(defaultValues);
606
+ const projectAnswers = await inquirer.prompt(questions);
607
+ const projectInput = projectAnswersDefaulted(projectAnswers);
608
+ const spinner = logger.spinner("Setting up your project...").start();
609
+ try {
610
+ const { data } = await cloudApi.createProject(projectInput);
611
+ await save({ project: data });
612
+ spinner.succeed("Project created successfully!");
613
+ return data;
614
+ } catch (e) {
615
+ spinner.fail("Failed to create project on Strapi Cloud.");
616
+ await handleError(ctx, e);
617
+ }
618
+ };
619
+ function notificationServiceFactory({ logger }) {
620
+ return (url, token, cliConfig2) => {
621
+ const CONN_TIMEOUT = Number(cliConfig2.notificationsConnectionTimeout);
622
+ const es = new EventSource(url, {
623
+ headers: {
624
+ Authorization: `Bearer ${token}`
625
+ }
626
+ });
627
+ let timeoutId;
628
+ const resetTimeout = () => {
629
+ clearTimeout(timeoutId);
630
+ timeoutId = setTimeout(() => {
631
+ logger.log(
632
+ "We were unable to connect to the server at this time. This could be due to a temporary issue. Please try again in a moment."
633
+ );
634
+ es.close();
635
+ }, CONN_TIMEOUT);
636
+ };
637
+ es.onopen = resetTimeout;
638
+ es.onmessage = (event) => {
639
+ resetTimeout();
640
+ const data = JSON.parse(event.data);
641
+ if (data.message) {
642
+ logger.log(data.message);
643
+ }
644
+ if (data.event === "deploymentFinished" || data.event === "deploymentFailed") {
645
+ es.close();
646
+ }
647
+ };
648
+ };
649
+ }
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
+ const buildLogsServiceFactory = ({ logger }) => {
683
+ return async (url, token, cliConfig2) => {
684
+ const CONN_TIMEOUT = Number(cliConfig2.buildLogsConnectionTimeout);
685
+ const MAX_RETRIES = Number(cliConfig2.buildLogsMaxRetries);
686
+ return new Promise((resolve, reject) => {
687
+ let timeoutId = null;
688
+ let retries = 0;
689
+ const connect = (url2) => {
690
+ const spinner = logger.spinner("Connecting to server to get build logs");
691
+ spinner.start();
692
+ const es = new EventSource(`${url2}`, {
693
+ headers: {
694
+ Authorization: `Bearer ${token}`
695
+ }
696
+ });
697
+ const clearExistingTimeout = () => {
698
+ if (timeoutId) {
699
+ clearTimeout(timeoutId);
700
+ }
701
+ };
702
+ const resetTimeout = () => {
703
+ clearExistingTimeout();
704
+ timeoutId = setTimeout(() => {
705
+ if (spinner.isSpinning) {
706
+ spinner.fail(
707
+ "We were unable to connect to the server to get build logs at this time. This could be due to a temporary issue."
708
+ );
709
+ }
710
+ es.close();
711
+ reject(new Error("Connection timed out"));
712
+ }, CONN_TIMEOUT);
713
+ };
714
+ es.onopen = resetTimeout;
715
+ es.addEventListener("finished", (event) => {
716
+ const data = JSON.parse(event.data);
717
+ logger.log(data.msg);
718
+ es.close();
719
+ clearExistingTimeout();
720
+ resolve(null);
721
+ });
722
+ es.addEventListener("log", (event) => {
723
+ if (spinner.isSpinning) {
724
+ spinner.succeed();
725
+ }
726
+ resetTimeout();
727
+ const data = JSON.parse(event.data);
728
+ logger.log(data.msg);
729
+ });
730
+ es.onerror = async () => {
731
+ retries += 1;
732
+ if (retries > MAX_RETRIES) {
733
+ spinner.fail("We were unable to connect to the server to get build logs at this time.");
734
+ es.close();
735
+ reject(new Error("Max retries reached"));
736
+ }
737
+ };
738
+ };
739
+ connect(url);
740
+ });
741
+ };
742
+ };
743
+ async function upload(ctx, project, token, maxProjectFileSize) {
744
+ const cloudApi = await cloudApiFactory(token);
745
+ try {
746
+ const storagePath = await getTmpStoragePath();
747
+ const projectFolder = path__default.resolve(process.cwd());
748
+ const packageJson2 = await loadPkg(ctx);
749
+ if (!packageJson2) {
750
+ ctx.logger.error(
751
+ "Unable to deploy the project. Please make sure the package.json file is correctly formatted."
752
+ );
753
+ return;
754
+ }
755
+ ctx.logger.log("📦 Compressing project...");
756
+ const hashname = crypto.createHash("sha512").update(packageJson2.name).digest("hex");
757
+ const compressedFilename = `${hashname}.tar.gz`;
758
+ try {
759
+ ctx.logger.debug(
760
+ "Compression parameters\n",
761
+ `Storage path: ${storagePath}
762
+ `,
763
+ `Project folder: ${projectFolder}
764
+ `,
765
+ `Compressed filename: ${compressedFilename}`
766
+ );
767
+ await compressFilesToTar(storagePath, projectFolder, compressedFilename);
768
+ ctx.logger.log("📦 Project compressed successfully!");
769
+ } catch (e) {
770
+ ctx.logger.error(
771
+ "⚠️ Project compression failed. Try again later or check for large/incompatible files."
772
+ );
773
+ ctx.logger.debug(e);
774
+ process.exit(1);
775
+ }
776
+ const tarFilePath = path__default.resolve(storagePath, compressedFilename);
777
+ const fileStats = await fse.stat(tarFilePath);
778
+ if (fileStats.size > maxProjectFileSize) {
779
+ ctx.logger.log(
780
+ "Unable to proceed: Your project is too big to be transferred, please use a git repo instead."
781
+ );
782
+ try {
783
+ await fse.remove(tarFilePath);
784
+ } catch (e) {
785
+ ctx.logger.log("Unable to remove file: ", tarFilePath);
786
+ ctx.logger.debug(e);
787
+ }
788
+ return;
789
+ }
790
+ ctx.logger.info("🚀 Uploading project...");
791
+ const progressBar = ctx.logger.progressBar(100, "Upload Progress");
792
+ try {
793
+ const { data } = await cloudApi.deploy(
794
+ { filePath: tarFilePath, project },
795
+ {
796
+ onUploadProgress(progressEvent) {
797
+ const total = progressEvent.total || fileStats.size;
798
+ const percentage = Math.round(progressEvent.loaded * 100 / total);
799
+ progressBar.update(percentage);
800
+ }
801
+ }
802
+ );
803
+ progressBar.update(100);
804
+ progressBar.stop();
805
+ ctx.logger.success("✨ Upload finished!");
806
+ return data.build_id;
807
+ } catch (e) {
808
+ progressBar.stop();
809
+ if (e instanceof AxiosError && e.response?.data) {
810
+ if (e.response.status === 404) {
811
+ ctx.logger.error(
812
+ `The project does not exist. Remove the ${LOCAL_SAVE_FILENAME} file and try again.`
813
+ );
814
+ } else {
815
+ ctx.logger.error(e.response.data);
816
+ }
817
+ } else {
818
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
819
+ }
820
+ ctx.logger.debug(e);
821
+ } finally {
822
+ await fse.remove(tarFilePath);
823
+ }
824
+ process.exit(0);
825
+ } catch (e) {
826
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
827
+ ctx.logger.debug(e);
828
+ process.exit(1);
829
+ }
830
+ }
831
+ async function getProject(ctx) {
832
+ const { project } = await retrieve();
833
+ if (!project) {
834
+ try {
835
+ return await action$3(ctx);
836
+ } catch (e) {
837
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
838
+ ctx.logger.debug(e);
839
+ process.exit(1);
840
+ }
841
+ }
842
+ return project;
843
+ }
844
+ const action$2 = async (ctx) => {
845
+ const { getValidToken } = await tokenServiceFactory(ctx);
846
+ const cloudApiService = await cloudApiFactory();
847
+ const token = await getValidToken();
848
+ if (!token) {
849
+ return;
850
+ }
851
+ const project = await getProject(ctx);
852
+ if (!project) {
853
+ return;
854
+ }
855
+ try {
856
+ await cloudApiService.track("willDeployWithCLI", { projectInternalName: project.name });
857
+ } catch (e) {
858
+ ctx.logger.debug("Failed to track willDeploy", e);
859
+ }
860
+ const notificationService = notificationServiceFactory(ctx);
861
+ const buildLogsService = buildLogsServiceFactory(ctx);
862
+ const { data: cliConfig2 } = await cloudApiService.config();
863
+ let maxSize = parseInt(cliConfig2.maxProjectFileSize, 10);
864
+ if (Number.isNaN(maxSize)) {
865
+ ctx.logger.debug(
866
+ "An error occurred while parsing the maxProjectFileSize. Using default value."
867
+ );
868
+ maxSize = 1e8;
869
+ }
870
+ const buildId = await upload(ctx, project, token, maxSize);
871
+ if (!buildId) {
872
+ return;
873
+ }
874
+ try {
875
+ notificationService(`${apiConfig.apiBaseUrl}/notifications`, token, cliConfig2);
876
+ await buildLogsService(`${apiConfig.apiBaseUrl}/v1/logs/${buildId}`, token, cliConfig2);
877
+ ctx.logger.log(
878
+ "Visit the following URL for deployment logs. Your deployment will be available here shortly."
879
+ );
880
+ ctx.logger.log(
881
+ chalk.underline(`${apiConfig.dashboardBaseUrl}/projects/${project.name}/deployments`)
882
+ );
883
+ } catch (e) {
884
+ if (e instanceof Error) {
885
+ ctx.logger.error(e.message);
886
+ } else {
887
+ throw e;
888
+ }
889
+ }
890
+ };
891
+ const assertCwdContainsStrapiProject = (name2) => {
892
+ const logErrorAndExit = () => {
893
+ console.log(
894
+ `You need to run ${chalk.yellow(
895
+ `strapi ${name2}`
896
+ )} in a Strapi project. Make sure you are in the right directory.`
897
+ );
898
+ process.exit(1);
899
+ };
900
+ try {
901
+ const pkgJSON = require(`${process.cwd()}/package.json`);
902
+ if (!has("dependencies.@strapi/strapi", pkgJSON) && !has("devDependencies.@strapi/strapi", pkgJSON)) {
903
+ logErrorAndExit();
904
+ }
905
+ } catch (err) {
906
+ logErrorAndExit();
907
+ }
908
+ };
909
+ const runAction = (name2, action2) => (...args) => {
910
+ assertCwdContainsStrapiProject(name2);
911
+ Promise.resolve().then(() => {
912
+ return action2(...args);
913
+ }).catch((error) => {
914
+ console.error(error);
915
+ process.exit(1);
916
+ });
917
+ };
918
+ const command$3 = ({ command: command2, ctx }) => {
919
+ command2.command("cloud:deploy").alias("deploy").description("Deploy a Strapi Cloud project").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("deploy", action$2)(ctx));
920
+ };
921
+ const deployProject = {
922
+ name: "deploy-project",
923
+ description: "Deploy a Strapi Cloud project",
924
+ action: action$2,
925
+ command: command$3
926
+ };
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;
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;
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;
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 }) => {
1085
+ command2.command("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1086
+ "after",
1087
+ "\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));
1089
+ };
1090
+ const login = {
1091
+ name: "login",
1092
+ description: "Strapi Cloud Login",
1093
+ action: action$1,
1094
+ command: command$2
1095
+ };
1096
+ const action = async (ctx) => {
1097
+ const { logger } = ctx;
1098
+ const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx);
1099
+ const token = await retrieveToken();
1100
+ if (!token) {
1101
+ logger.log("You're already logged out.");
1102
+ return;
1103
+ }
1104
+ const cloudApiService = await cloudApiFactory(token);
1105
+ try {
1106
+ await eraseToken();
1107
+ logger.log(
1108
+ "🔌 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
+ );
1110
+ } catch (e) {
1111
+ logger.error("🥲 Oops! Something went wrong while logging you out. Please try again.");
1112
+ logger.debug(e);
1113
+ }
1114
+ try {
1115
+ await cloudApiService.track("didLogout", { loginMethod: "cli" });
1116
+ } catch (e) {
1117
+ logger.debug("Failed to track logout event", e);
1118
+ }
1119
+ };
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));
1122
+ };
1123
+ const logout = {
1124
+ name: "logout",
1125
+ description: "Strapi Cloud Logout",
1126
+ action,
1127
+ command: command$1
1128
+ };
1129
+ const command = ({ command: command2, ctx }) => {
1130
+ command2.command("cloud:create-project").description("Create a Strapi Cloud project").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("cloud:create-project", action$3)(ctx));
1131
+ };
1132
+ const createProject = {
1133
+ name: "create-project",
1134
+ description: "Create a new project",
1135
+ action: action$3,
1136
+ command
1137
+ };
1138
+ const cli = {
1139
+ deployProject,
1140
+ login,
1141
+ logout,
1142
+ createProject
1143
+ };
1144
+ const cloudCommands = [deployProject, login, logout];
1145
+ async function initCloudCLIConfig() {
1146
+ const localConfig = await getLocalConfig();
1147
+ if (!localConfig.deviceId) {
1148
+ localConfig.deviceId = crypto$1.randomUUID();
1149
+ }
1150
+ await saveLocalConfig(localConfig);
1151
+ }
1152
+ async function buildStrapiCloudCommands({
1153
+ command: command2,
1154
+ ctx,
1155
+ argv
1156
+ }) {
1157
+ await initCloudCLIConfig();
1158
+ for (const cloudCommand of cloudCommands) {
1159
+ try {
1160
+ await cloudCommand.command({ command: command2, ctx, argv });
1161
+ } catch (e) {
1162
+ console.error(`Failed to load command ${cloudCommand.name}`, e);
1163
+ }
1164
+ }
1165
+ }
1166
+ export {
1167
+ buildStrapiCloudCommands,
1168
+ cli,
1169
+ index as services
1170
+ };
1171
+ //# sourceMappingURL=index.mjs.map