diff --git a/.github/actions/check-pr-status/package.json b/.github/actions/check-pr-status/package.json index 78e5f5723f..1badfc620b 100644 --- a/.github/actions/check-pr-status/package.json +++ b/.github/actions/check-pr-status/package.json @@ -1,6 +1,6 @@ { "name": "check-pr-status", - "version": "5.0.0-beta.12", + "version": "5.0.0-rc.1", "private": true, "license": "MIT", "main": "dist/index.js", diff --git a/.gitignore b/.gitignore index c3fbe1ae7d..a59af4f94f 100644 --- a/.gitignore +++ b/.gitignore @@ -156,4 +156,4 @@ tests/cli/.env # Strapi ############################ examples/**/types/generated -.nx/cache \ No newline at end of file +.nx/cache diff --git a/examples/experimental-dev/package.json b/examples/experimental-dev/package.json index 82476e93a3..587a8a3a0b 100644 --- a/examples/experimental-dev/package.json +++ b/examples/experimental-dev/package.json @@ -1,6 +1,6 @@ { "name": "experimental-dev", - "version": "5.0.0-beta.12", + "version": "5.0.0-rc.1", "private": true, "description": "A Strapi application", "license": "MIT", @@ -14,8 +14,8 @@ "strapi": "strapi" }, "dependencies": { - "@strapi/plugin-users-permissions": "5.0.0-beta.12", - "@strapi/strapi": "5.0.0-beta.12", + "@strapi/plugin-users-permissions": "5.0.0-rc.1", + "@strapi/strapi": "5.0.0-rc.1", "better-sqlite3": "9.4.3", "react": "rc", "react-dom": "rc", diff --git a/examples/getstarted/package.json b/examples/getstarted/package.json index 349f4157c8..aa71e3f084 100644 --- a/examples/getstarted/package.json +++ b/examples/getstarted/package.json @@ -1,6 +1,6 @@ { "name": "getstarted", - "version": "5.0.0-beta.12", + "version": "5.0.0-rc.1", "private": true, "description": "A Strapi application.", "license": "SEE LICENSE IN LICENSE", @@ -14,15 +14,15 @@ }, "dependencies": { "@strapi/icons": "2.0.0-beta.6", - "@strapi/plugin-color-picker": "5.0.0-beta.12", - "@strapi/plugin-documentation": "5.0.0-beta.12", - "@strapi/plugin-graphql": "5.0.0-beta.12", - "@strapi/plugin-sentry": "5.0.0-beta.12", - "@strapi/plugin-users-permissions": "5.0.0-beta.12", - "@strapi/provider-email-mailgun": "5.0.0-beta.12", - "@strapi/provider-upload-aws-s3": "5.0.0-beta.12", - "@strapi/provider-upload-cloudinary": "5.0.0-beta.12", - "@strapi/strapi": "5.0.0-beta.12", + "@strapi/plugin-color-picker": "5.0.0-rc.1", + "@strapi/plugin-documentation": "5.0.0-rc.1", + "@strapi/plugin-graphql": "5.0.0-rc.1", + "@strapi/plugin-sentry": "5.0.0-rc.1", + "@strapi/plugin-users-permissions": "5.0.0-rc.1", + "@strapi/provider-email-mailgun": "5.0.0-rc.1", + "@strapi/provider-upload-aws-s3": "5.0.0-rc.1", + "@strapi/provider-upload-cloudinary": "5.0.0-rc.1", + "@strapi/strapi": "5.0.0-rc.1", "better-sqlite3": "9.4.3", "lodash": "4.17.21", "mysql2": "3.9.4", diff --git a/examples/getstarted/src/admin/app.jsx b/examples/getstarted/src/admin/app.jsx index 884f9b6e5c..0e45ed5b61 100644 --- a/examples/getstarted/src/admin/app.jsx +++ b/examples/getstarted/src/admin/app.jsx @@ -5,8 +5,6 @@ const config = { locales: ['it', 'es', 'en'], }; const bootstrap = (app) => { - console.log('I AM BOOTSTRAPPED'); - app.getPlugin('content-manager').injectComponent('editView', 'right-links', { name: 'PreviewButton', Component: () => ( diff --git a/examples/kitchensink-ts/package.json b/examples/kitchensink-ts/package.json index e2a94f6d00..ad35265eaf 100644 --- a/examples/kitchensink-ts/package.json +++ b/examples/kitchensink-ts/package.json @@ -1,6 +1,6 @@ { "name": "kitchensink-ts", - "version": "5.0.0-beta.12", + "version": "5.0.0-rc.1", "private": true, "description": "A Strapi application", "license": "MIT", @@ -14,8 +14,8 @@ "strapi": "strapi" }, "dependencies": { - "@strapi/plugin-users-permissions": "5.0.0-beta.12", - "@strapi/strapi": "5.0.0-beta.12", + "@strapi/plugin-users-permissions": "5.0.0-rc.1", + "@strapi/strapi": "5.0.0-rc.1", "better-sqlite3": "9.4.3", "react": "18.3.1", "react-dom": "18.3.1", diff --git a/examples/kitchensink/package.json b/examples/kitchensink/package.json index 89cb1560d9..6a3f86f38c 100644 --- a/examples/kitchensink/package.json +++ b/examples/kitchensink/package.json @@ -1,6 +1,6 @@ { "name": "kitchensink", - "version": "5.0.0-beta.12", + "version": "5.0.0-rc.1", "private": true, "description": "A Strapi application.", "license": "SEE LICENSE IN LICENSE", @@ -13,10 +13,10 @@ "strapi": "strapi" }, "dependencies": { - "@strapi/provider-email-mailgun": "5.0.0-beta.12", - "@strapi/provider-upload-aws-s3": "5.0.0-beta.12", - "@strapi/provider-upload-cloudinary": "5.0.0-beta.12", - "@strapi/strapi": "5.0.0-beta.12", + "@strapi/provider-email-mailgun": "5.0.0-rc.1", + "@strapi/provider-upload-aws-s3": "5.0.0-rc.1", + "@strapi/provider-upload-cloudinary": "5.0.0-rc.1", + "@strapi/strapi": "5.0.0-rc.1", "better-sqlite3": "9.4.3", "lodash": "4.17.21", "mysql2": "3.9.4", diff --git a/examples/plugins/workspace-plugin/package.json b/examples/plugins/workspace-plugin/package.json index e281bab7cb..1c7d1cfdc5 100644 --- a/examples/plugins/workspace-plugin/package.json +++ b/examples/plugins/workspace-plugin/package.json @@ -1,6 +1,6 @@ { "name": "strapi-plugin-workspace-plugin", - "version": "5.0.0-beta.12", + "version": "5.0.0-rc.1", "private": true, "description": "This is the description of my plugin.", "exports": { diff --git a/lerna.json b/lerna.json index 4a4bef8264..d49b8aca7e 100644 --- a/lerna.json +++ b/lerna.json @@ -1,4 +1,4 @@ { - "version": "5.0.0-beta.12", + "version": "5.0.0-rc.1", "npmClient": "yarn" } diff --git a/package.json b/package.json index 3f08ef031c..efcf583f30 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,8 @@ "prettier:write": "prettier --write \"**/*.{js,ts,jsx,tsx,json,md,mdx,css,scss,yaml,yml}\"", "setup": "yarn && yarn clean && yarn build --skip-nx-cache", "test:api": "node tests/scripts/run-api-tests.js", - "test:clean": "rimraf ./coverage", + "test:api:clean": "rimraf ./coverage", + "test:clean": "yarn test:api:clean && yarn test:e2e:clean", "test:cli": "node tests/scripts/run-cli-tests.js", "test:cli:clean": "node tests/scripts/run-cli-tests.js clean", "test:cli:debug": "node tests/scripts/run-cli-tests.js --debug", diff --git a/packages/admin-test-utils/LICENSE b/packages/admin-test-utils/LICENSE index db018546b5..d82875fe30 100644 --- a/packages/admin-test-utils/LICENSE +++ b/packages/admin-test-utils/LICENSE @@ -2,7 +2,21 @@ Copyright (c) 2015-present Strapi Solutions SAS Portions of the Strapi software are licensed as follows: -* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined in "ee/LICENSE". +* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined below. + +Enterprise License + +If you or the company you represent has entered into a written agreement referencing the Enterprise Edition of the Strapi source code available at +https://github.com/strapi/strapi, then such agreement applies to your use of the Enterprise Edition of the Strapi Software. If you or the company you +represent is using the Enterprise Edition of the Strapi Software in connection with a subscription to our cloud offering, then the agreement you have +agreed to with respect to our cloud offering and the licenses included in such agreement apply to your use of the Enterprise Edition of the Strapi Software. +Otherwise, the Strapi Enterprise Software License Agreement (found here https://strapi.io/enterprise-terms) applies to your use of the Enterprise Edition of the Strapi Software. + +BY ACCESSING OR USING THE ENTERPRISE EDITION OF THE STRAPI SOFTWARE, YOU ARE AGREEING TO BE BOUND BY THE RELEVANT REFERENCED AGREEMENT. +IF YOU ARE NOT AUTHORIZED TO ACCEPT THESE TERMS ON BEHALF OF THE COMPANY YOU REPRESENT OR IF YOU DO NOT AGREE TO ALL OF THE RELEVANT TERMS AND CONDITIONS REFERENCED AND YOU +HAVE NOT OTHERWISE EXECUTED A WRITTEN AGREEMENT WITH STRAPI, YOU ARE NOT AUTHORIZED TO ACCESS OR USE OR ALLOW ANY USER TO ACCESS OR USE ANY PART OF +THE ENTERPRISE EDITION OF THE STRAPI SOFTWARE. YOUR ACCESS RIGHTS ARE CONDITIONAL ON YOUR CONSENT TO THE RELEVANT REFERENCED TERMS TO THE EXCLUSION OF ALL OTHER TERMS; +IF THE RELEVANT REFERENCED TERMS ARE CONSIDERED AN OFFER BY YOU, ACCEPTANCE IS EXPRESSLY LIMITED TO THE RELEVANT REFERENCED TERMS. * All software outside of the above-mentioned directories or restrictions above is available under the "MIT Expat" license as set forth below. @@ -18,5 +32,6 @@ furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/admin-test-utils/package.json b/packages/admin-test-utils/package.json index eabb60d8a5..ac566dc81f 100644 --- a/packages/admin-test-utils/package.json +++ b/packages/admin-test-utils/package.json @@ -1,6 +1,6 @@ { "name": "@strapi/admin-test-utils", - "version": "5.0.0-beta.12", + "version": "5.0.0-rc.1", "private": true, "description": "Test utilities for the Strapi administration panel", "license": "MIT", @@ -81,9 +81,9 @@ "@reduxjs/toolkit": "1.9.7", "@strapi/pack-up": "5.0.0", "@testing-library/jest-dom": "6.4.5", - "eslint-config-custom": "5.0.0-beta.12", + "eslint-config-custom": "5.0.0-rc.1", "jest-environment-jsdom": "29.6.1", - "tsconfig": "5.0.0-beta.12" + "tsconfig": "5.0.0-rc.1" }, "peerDependencies": { "@reduxjs/toolkit": "^1.9.7", diff --git a/packages/cli/cloud/.eslintignore b/packages/cli/cloud/.eslintignore new file mode 100644 index 0000000000..3933753720 --- /dev/null +++ b/packages/cli/cloud/.eslintignore @@ -0,0 +1,4 @@ +node_modules/ +.eslintrc.js +dist/ +bin/ diff --git a/packages/cli/cloud/.eslintrc.js b/packages/cli/cloud/.eslintrc.js new file mode 100644 index 0000000000..a165f57061 --- /dev/null +++ b/packages/cli/cloud/.eslintrc.js @@ -0,0 +1,4 @@ +module.exports = { + root: true, + extends: ['custom/back/typescript'], +}; diff --git a/packages/cli/cloud/LICENSE b/packages/cli/cloud/LICENSE new file mode 100644 index 0000000000..d82875fe30 --- /dev/null +++ b/packages/cli/cloud/LICENSE @@ -0,0 +1,37 @@ +Copyright (c) 2015-present Strapi Solutions SAS + +Portions of the Strapi software are licensed as follows: + +* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined below. + +Enterprise License + +If you or the company you represent has entered into a written agreement referencing the Enterprise Edition of the Strapi source code available at +https://github.com/strapi/strapi, then such agreement applies to your use of the Enterprise Edition of the Strapi Software. If you or the company you +represent is using the Enterprise Edition of the Strapi Software in connection with a subscription to our cloud offering, then the agreement you have +agreed to with respect to our cloud offering and the licenses included in such agreement apply to your use of the Enterprise Edition of the Strapi Software. +Otherwise, the Strapi Enterprise Software License Agreement (found here https://strapi.io/enterprise-terms) applies to your use of the Enterprise Edition of the Strapi Software. + +BY ACCESSING OR USING THE ENTERPRISE EDITION OF THE STRAPI SOFTWARE, YOU ARE AGREEING TO BE BOUND BY THE RELEVANT REFERENCED AGREEMENT. +IF YOU ARE NOT AUTHORIZED TO ACCEPT THESE TERMS ON BEHALF OF THE COMPANY YOU REPRESENT OR IF YOU DO NOT AGREE TO ALL OF THE RELEVANT TERMS AND CONDITIONS REFERENCED AND YOU +HAVE NOT OTHERWISE EXECUTED A WRITTEN AGREEMENT WITH STRAPI, YOU ARE NOT AUTHORIZED TO ACCESS OR USE OR ALLOW ANY USER TO ACCESS OR USE ANY PART OF +THE ENTERPRISE EDITION OF THE STRAPI SOFTWARE. YOUR ACCESS RIGHTS ARE CONDITIONAL ON YOUR CONSENT TO THE RELEVANT REFERENCED TERMS TO THE EXCLUSION OF ALL OTHER TERMS; +IF THE RELEVANT REFERENCED TERMS ARE CONSIDERED AN OFFER BY YOU, ACCEPTANCE IS EXPRESSLY LIMITED TO THE RELEVANT REFERENCED TERMS. + +* All software outside of the above-mentioned directories or restrictions above is available under the "MIT Expat" license as set forth below. + +MIT Expat License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/cli/cloud/README.md b/packages/cli/cloud/README.md new file mode 100644 index 0000000000..7175098087 --- /dev/null +++ b/packages/cli/cloud/README.md @@ -0,0 +1,3 @@ +# Cloud CLI + +This package includes the `cloud` CLI to manage Strapi projects on the cloud. diff --git a/packages/cli/cloud/bin/index.js b/packages/cli/cloud/bin/index.js new file mode 100755 index 0000000000..a88ceaa195 --- /dev/null +++ b/packages/cli/cloud/bin/index.js @@ -0,0 +1,7 @@ +#!/usr/bin/env node + +'use strict'; + +const { runStrapiCloudCommand } = require('../dist/bin'); + +runStrapiCloudCommand(process.argv); diff --git a/packages/cli/cloud/package.json b/packages/cli/cloud/package.json new file mode 100644 index 0000000000..5f1b9c2bd2 --- /dev/null +++ b/packages/cli/cloud/package.json @@ -0,0 +1,79 @@ +{ + "name": "@strapi/cloud-cli", + "version": "5.0.0-rc.1", + "description": "Commands to interact with the Strapi Cloud", + "keywords": [ + "strapi", + "cloud", + "cli" + ], + "homepage": "https://strapi.io", + "bugs": { + "url": "https://github.com/strapi/strapi/issues" + }, + "repository": { + "type": "git", + "url": "git://github.com/strapi/strapi.git" + }, + "license": "SEE LICENSE IN LICENSE", + "author": { + "name": "Strapi Solutions SAS", + "email": "hi@strapi.io", + "url": "https://strapi.io" + }, + "maintainers": [ + { + "name": "Strapi Solutions SAS", + "email": "hi@strapi.io", + "url": "https://strapi.io" + } + ], + "main": "./dist/index.js", + "module": "./dist/index.mjs", + "source": "./src/index.ts", + "types": "./dist/src/index.d.ts", + "bin": "./bin/index.js", + "files": [ + "./dist", + "./bin" + ], + "scripts": { + "build": "pack-up build", + "clean": "run -T rimraf ./dist", + "lint": "run -T eslint .", + "watch": "pack-up watch" + }, + "dependencies": { + "@strapi/utils": "5.0.0-rc.1", + "axios": "1.6.0", + "chalk": "4.1.2", + "cli-progress": "3.12.0", + "commander": "8.3.0", + "eventsource": "2.0.2", + "fast-safe-stringify": "2.1.1", + "fs-extra": "10.0.0", + "inquirer": "8.2.5", + "jsonwebtoken": "9.0.0", + "jwks-rsa": "3.1.0", + "lodash": "4.17.21", + "minimatch": "9.0.3", + "open": "8.4.0", + "ora": "5.4.1", + "pkg-up": "3.1.0", + "tar": "6.1.13", + "xdg-app-paths": "8.3.0", + "yup": "0.32.9" + }, + "devDependencies": { + "@strapi/pack-up": "4.23.0", + "@types/cli-progress": "3.11.5", + "@types/eventsource": "1.1.15", + "@types/lodash": "^4.14.191", + "eslint-config-custom": "5.0.0-rc.1", + "tsconfig": "5.0.0-rc.1" + }, + "engines": { + "node": ">=18.0.0 <=20.x.x", + "npm": ">=6.0.0" + } +} diff --git a/packages/cli/cloud/packup.config.ts b/packages/cli/cloud/packup.config.ts new file mode 100644 index 0000000000..d676ac372c --- /dev/null +++ b/packages/cli/cloud/packup.config.ts @@ -0,0 +1,20 @@ +// eslint-disable-next-line import/no-extraneous-dependencies +import { defineConfig } from '@strapi/pack-up'; + +export default defineConfig({ + bundles: [ + { + source: './src/index.ts', + import: './dist/index.js', + require: './dist/index.js', + types: './dist/index.d.ts', + runtime: 'node', + }, + { + source: './src/bin.ts', + require: './dist/bin.js', + runtime: 'node', + }, + ], + dist: './dist', +}); diff --git a/packages/cli/cloud/src/bin.ts b/packages/cli/cloud/src/bin.ts new file mode 100644 index 0000000000..d064fe48d9 --- /dev/null +++ b/packages/cli/cloud/src/bin.ts @@ -0,0 +1,34 @@ +import { Command } from 'commander'; +import { createLogger } from './services'; +import { CLIContext } from './types'; +import { buildStrapiCloudCommands } from './index'; + +function loadStrapiCloudCommand(argv = process.argv, command = new Command()) { + // Initial program setup + command.storeOptionsAsProperties(false).allowUnknownOption(true); + + // Help command + command.helpOption('-h, --help', 'Display help for command'); + command.addHelpCommand('help [command]', 'Display help for command'); + + const cwd = process.cwd(); + + const hasDebug = argv.includes('--debug'); + const hasSilent = argv.includes('--silent'); + + const logger = createLogger({ debug: hasDebug, silent: hasSilent, timestamp: false }); + + const ctx = { + cwd, + logger, + } satisfies CLIContext; + + buildStrapiCloudCommands({ command, ctx, argv }); +} + +function runStrapiCloudCommand(argv = process.argv, command = new Command()) { + loadStrapiCloudCommand(argv, command); + command.parse(argv); +} + +export { runStrapiCloudCommand }; diff --git a/packages/cli/cloud/src/config/api.ts b/packages/cli/cloud/src/config/api.ts new file mode 100644 index 0000000000..018ca578d1 --- /dev/null +++ b/packages/cli/cloud/src/config/api.ts @@ -0,0 +1,6 @@ +import { env } from '@strapi/utils'; + +export const apiConfig = { + apiBaseUrl: env('STRAPI_CLI_CLOUD_API', 'https://cloud-cli-api.strapi.io'), + dashboardBaseUrl: env('STRAPI_CLI_CLOUD_DASHBOARD', 'https://cloud.strapi.io'), +}; diff --git a/packages/cli/cloud/src/config/local.ts b/packages/cli/cloud/src/config/local.ts new file mode 100644 index 0000000000..5ccb524210 --- /dev/null +++ b/packages/cli/cloud/src/config/local.ts @@ -0,0 +1,57 @@ +import path from 'path'; +import os from 'os'; +import fse from 'fs-extra'; +import XDGAppPaths from 'xdg-app-paths'; + +const APP_FOLDER_NAME = 'com.strapi.cli'; + +export const CONFIG_FILENAME = 'config.json'; + +export type LocalConfig = { + token?: string; + deviceId?: string; +}; + +async function checkDirectoryExists(directoryPath: string) { + try { + const fsStat = await fse.lstat(directoryPath); + return fsStat.isDirectory(); + } catch (e) { + return false; + } +} + +// Determine storage path based on the operating system +export async function getTmpStoragePath() { + const storagePath = path.join(os.tmpdir(), APP_FOLDER_NAME); + await fse.ensureDir(storagePath); + return storagePath; +} + +async function getConfigPath() { + const configDirs = XDGAppPaths(APP_FOLDER_NAME).configDirs(); + const configPath = configDirs.find(checkDirectoryExists); + + if (!configPath) { + await fse.ensureDir(configDirs[0]); + return configDirs[0]; + } + return configPath; +} + +export async function getLocalConfig(): Promise { + const configPath = await getConfigPath(); + const configFilePath = path.join(configPath, CONFIG_FILENAME); + await fse.ensureFile(configFilePath); + try { + return await fse.readJSON(configFilePath, { encoding: 'utf8', throws: true }); + } catch (e) { + return {}; + } +} + +export async function saveLocalConfig(data: LocalConfig) { + const configPath = await getConfigPath(); + const configFilePath = path.join(configPath, CONFIG_FILENAME); + await fse.writeJson(configFilePath, data, { encoding: 'utf8', spaces: 2, mode: 0o600 }); +} diff --git a/packages/cli/cloud/src/create-project/action.ts b/packages/cli/cloud/src/create-project/action.ts new file mode 100644 index 0000000000..61253b13a0 --- /dev/null +++ b/packages/cli/cloud/src/create-project/action.ts @@ -0,0 +1,73 @@ +import inquirer from 'inquirer'; +import { AxiosError } from 'axios'; +import { defaults } from 'lodash/fp'; +import type { CLIContext, ProjectAnswers, ProjectInput } from '../types'; +import { tokenServiceFactory, cloudApiFactory, local } from '../services'; + +async function handleError(ctx: CLIContext, error: Error) { + const tokenService = await tokenServiceFactory(ctx); + const { logger } = ctx; + + logger.debug(error); + if (error instanceof AxiosError) { + const errorMessage = typeof error.response?.data === 'string' ? error.response.data : null; + switch (error.response?.status) { + case 401: + logger.error('Your session has expired. Please log in again.'); + await tokenService.eraseToken(); + return; + case 403: + logger.error( + errorMessage || + 'You do not have permission to create a project. Please contact support for assistance.' + ); + return; + case 400: + logger.error(errorMessage || 'Invalid input. Please check your inputs and try again.'); + return; + case 503: + logger.error( + 'Strapi Cloud project creation is currently unavailable. Please try again later.' + ); + return; + default: + if (errorMessage) { + logger.error(errorMessage); + return; + } + break; + } + } + logger.error( + 'We encountered an issue while creating your project. Please try again in a moment. If the problem persists, contact support for assistance.' + ); +} + +export default async (ctx: CLIContext) => { + const { logger } = ctx; + const { getValidToken } = await tokenServiceFactory(ctx); + + const token = await getValidToken(); + if (!token) { + return; + } + const cloudApi = await cloudApiFactory(token); + const { data: config } = await cloudApi.config(); + const { questions, defaults: defaultValues } = config.projectCreation; + + const projectAnswersDefaulted = defaults(defaultValues); + const projectAnswers = await inquirer.prompt(questions); + + const projectInput: ProjectInput = projectAnswersDefaulted(projectAnswers); + + const spinner = logger.spinner('Setting up your project...').start(); + try { + const { data } = await cloudApi.createProject(projectInput); + await local.save({ project: data }); + spinner.succeed('Project created successfully!'); + return data; + } catch (e: Error | unknown) { + spinner.fail('Failed to create project on Strapi Cloud.'); + await handleError(ctx, e as Error); + } +}; diff --git a/packages/cli/cloud/src/create-project/command.ts b/packages/cli/cloud/src/create-project/command.ts new file mode 100644 index 0000000000..e084eb971c --- /dev/null +++ b/packages/cli/cloud/src/create-project/command.ts @@ -0,0 +1,17 @@ +import { createCommand } from 'commander'; +import { type StrapiCloudCommand } from '../types'; +import { runAction } from '../utils/helpers'; +import action from './action'; + +/** + * `$ create project in Strapi cloud` + */ +const command: StrapiCloudCommand = ({ ctx }) => { + return 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)(ctx)); +}; + +export default command; diff --git a/packages/cli/cloud/src/create-project/index.ts b/packages/cli/cloud/src/create-project/index.ts new file mode 100644 index 0000000000..4b8e5bc83b --- /dev/null +++ b/packages/cli/cloud/src/create-project/index.ts @@ -0,0 +1,12 @@ +import action from './action'; +import command from './command'; +import type { StrapiCloudCommandInfo } from '../types'; + +export { action, command }; + +export default { + name: 'create-project', + description: 'Create a new project', + action, + command, +} as StrapiCloudCommandInfo; diff --git a/packages/cli/cloud/src/deploy-project/action.ts b/packages/cli/cloud/src/deploy-project/action.ts new file mode 100644 index 0000000000..5bbe48cadf --- /dev/null +++ b/packages/cli/cloud/src/deploy-project/action.ts @@ -0,0 +1,196 @@ +import fse from 'fs-extra'; +import path from 'path'; +import chalk from 'chalk'; +import { AxiosError } from 'axios'; +import * as crypto from 'node:crypto'; +import { apiConfig } from '../config/api'; +import { compressFilesToTar } from '../utils/compress-files'; +import createProjectAction from '../create-project/action'; +import type { CLIContext, ProjectInfos } from '../types'; +import { getTmpStoragePath } from '../config/local'; +import { cloudApiFactory, tokenServiceFactory, local } from '../services'; +import { notificationServiceFactory } from '../services/notification'; +import { loadPkg } from '../utils/pkg'; +import { buildLogsServiceFactory } from '../services/build-logs'; + +type PackageJson = { + name: string; + strapi?: { + uuid: string; + }; +}; + +async function upload( + ctx: CLIContext, + project: ProjectInfos, + token: string, + maxProjectFileSize: number +) { + const cloudApi = await cloudApiFactory(token); + // * Upload project + try { + const storagePath = await getTmpStoragePath(); + const projectFolder = path.resolve(process.cwd()); + const packageJson = (await loadPkg(ctx)) as PackageJson; + + if (!packageJson) { + ctx.logger.error( + 'Unable to deploy the project. Please make sure the package.json file is correctly formatted.' + ); + return; + } + + ctx.logger.log('📦 Compressing project...'); + // hash packageJson.name to avoid conflicts + const hashname = crypto.createHash('sha512').update(packageJson.name).digest('hex'); + const compressedFilename = `${hashname}.tar.gz`; + try { + ctx.logger.debug( + 'Compression parameters\n', + `Storage path: ${storagePath}\n`, + `Project folder: ${projectFolder}\n`, + `Compressed filename: ${compressedFilename}` + ); + await compressFilesToTar(storagePath, projectFolder, compressedFilename); + ctx.logger.log('📦 Project compressed successfully!'); + } catch (e: unknown) { + ctx.logger.error( + '⚠️ Project compression failed. Try again later or check for large/incompatible files.' + ); + ctx.logger.debug(e); + process.exit(1); + } + + const tarFilePath = path.resolve(storagePath, compressedFilename); + const fileStats = await fse.stat(tarFilePath); + + if (fileStats.size > maxProjectFileSize) { + ctx.logger.log( + 'Unable to proceed: Your project is too big to be transferred, please use a git repo instead.' + ); + try { + await fse.remove(tarFilePath); + } catch (e: any) { + ctx.logger.log('Unable to remove file: ', tarFilePath); + ctx.logger.debug(e); + } + return; + } + + ctx.logger.info('🚀 Uploading project...'); + const progressBar = ctx.logger.progressBar(100, 'Upload Progress'); + + try { + const { data } = await cloudApi.deploy( + { filePath: tarFilePath, project }, + { + onUploadProgress(progressEvent) { + const total = progressEvent.total || fileStats.size; + const percentage = Math.round((progressEvent.loaded * 100) / total); + progressBar.update(percentage); + }, + } + ); + + progressBar.update(100); + progressBar.stop(); + ctx.logger.success('✨ Upload finished!'); + return data.build_id; + } catch (e: any) { + progressBar.stop(); + if (e instanceof AxiosError && e.response?.data) { + if (e.response.status === 404) { + ctx.logger.error( + `The project does not exist. Remove the ${local.LOCAL_SAVE_FILENAME} file and try again.` + ); + } else { + ctx.logger.error(e.response.data); + } + } else { + ctx.logger.error('An error occurred while deploying the project. Please try again later.'); + } + + ctx.logger.debug(e); + } finally { + await fse.remove(tarFilePath); + } + process.exit(0); + } catch (e: any) { + ctx.logger.error('An error occurred while deploying the project. Please try again later.'); + ctx.logger.debug(e); + process.exit(1); + } +} + +async function getProject(ctx: CLIContext) { + const { project } = await local.retrieve(); + if (!project) { + try { + return await createProjectAction(ctx); + } catch (e: any) { + ctx.logger.error('An error occurred while deploying the project. Please try again later.'); + ctx.logger.debug(e); + process.exit(1); + } + } + return project; +} + +export default async (ctx: CLIContext) => { + const { getValidToken } = await tokenServiceFactory(ctx); + const cloudApiService = await cloudApiFactory(); + const token = await getValidToken(); + + if (!token) { + return; + } + + const project = await getProject(ctx); + + if (!project) { + return; + } + + try { + await cloudApiService.track('willDeployWithCLI', { projectInternalName: project.name }); + } catch (e) { + ctx.logger.debug('Failed to track willDeploy', e); + } + + const notificationService = notificationServiceFactory(ctx); + const buildLogsService = buildLogsServiceFactory(ctx); + + const { data: cliConfig } = await cloudApiService.config(); + + let maxSize: number = parseInt(cliConfig.maxProjectFileSize, 10); + if (Number.isNaN(maxSize)) { + ctx.logger.debug( + 'An error occurred while parsing the maxProjectFileSize. Using default value.' + ); + maxSize = 100000000; + } + + const buildId = await upload(ctx, project, token, maxSize); + + if (!buildId) { + return; + } + + try { + notificationService(`${apiConfig.apiBaseUrl}/notifications`, token, cliConfig); + await buildLogsService(`${apiConfig.apiBaseUrl}/v1/logs/${buildId}`, token, cliConfig); + + ctx.logger.log( + 'Visit the following URL for deployment logs. Your deployment will be available here shortly.' + ); + ctx.logger.log( + chalk.underline(`${apiConfig.dashboardBaseUrl}/projects/${project.name}/deployments`) + ); + } catch (e: Error | unknown) { + if (e instanceof Error) { + ctx.logger.error(e.message); + } else { + throw e; + } + } +}; diff --git a/packages/cli/cloud/src/deploy-project/command.ts b/packages/cli/cloud/src/deploy-project/command.ts new file mode 100644 index 0000000000..ee767593dc --- /dev/null +++ b/packages/cli/cloud/src/deploy-project/command.ts @@ -0,0 +1,18 @@ +import { createCommand } from 'commander'; +import { type StrapiCloudCommand } from '../types'; +import { runAction } from '../utils/helpers'; +import action from './action'; + +/** + * `$ deploy project to the cloud` + */ +const command: StrapiCloudCommand = ({ ctx }) => { + return 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)(ctx)); +}; + +export default command; diff --git a/packages/cli/cloud/src/deploy-project/index.ts b/packages/cli/cloud/src/deploy-project/index.ts new file mode 100644 index 0000000000..91df9ab4ae --- /dev/null +++ b/packages/cli/cloud/src/deploy-project/index.ts @@ -0,0 +1,12 @@ +import action from './action'; +import command from './command'; +import type { StrapiCloudCommandInfo } from '../types'; + +export { action, command }; + +export default { + name: 'deploy-project', + description: 'Deploy a Strapi Cloud project', + action, + command, +} as StrapiCloudCommandInfo; diff --git a/packages/cli/cloud/src/index.ts b/packages/cli/cloud/src/index.ts new file mode 100644 index 0000000000..06e12a9d6b --- /dev/null +++ b/packages/cli/cloud/src/index.ts @@ -0,0 +1,56 @@ +import { Command } from 'commander'; +import crypto from 'crypto'; +import deployProject from './deploy-project'; +import login from './login'; +import logout from './logout'; +import createProject from './create-project'; +import { CLIContext } from './types'; +import { getLocalConfig, saveLocalConfig } from './config/local'; + +export const cli = { + deployProject, + login, + logout, + createProject, +}; + +const cloudCommands = [deployProject, login, logout]; + +async function initCloudCLIConfig() { + const localConfig = await getLocalConfig(); + + if (!localConfig.deviceId) { + localConfig.deviceId = crypto.randomUUID(); + } + + await saveLocalConfig(localConfig); +} + +export async function buildStrapiCloudCommands({ + command, + ctx, + argv, +}: { + command: Command; + ctx: CLIContext; + argv: string[]; +}) { + await initCloudCLIConfig(); + // Load all commands + for (const cloudCommand of cloudCommands) { + try { + // Add this command to the Commander command object + const subCommand = await cloudCommand.command({ command, ctx, argv }); + + if (subCommand) { + command.addCommand(subCommand); + } + } catch (e) { + console.error(`Failed to load command ${cloudCommand.name}`, e); + } + } +} + +export * as services from './services'; + +export * from './types'; diff --git a/packages/cli/cloud/src/login/action.ts b/packages/cli/cloud/src/login/action.ts new file mode 100644 index 0000000000..dcc5555f73 --- /dev/null +++ b/packages/cli/cloud/src/login/action.ts @@ -0,0 +1,187 @@ +import axios, { AxiosResponse, AxiosError } from 'axios'; +import chalk from 'chalk'; +import { tokenServiceFactory, cloudApiFactory } from '../services'; +import type { CloudCliConfig, CLIContext } from '../types'; +import { apiConfig } from '../config/api'; + +const openModule = import('open'); + +export default async (ctx: CLIContext): Promise => { + const { logger } = ctx; + const tokenService = await tokenServiceFactory(ctx); + const existingToken = await tokenService.retrieveToken(); + const cloudApiService = await cloudApiFactory(existingToken || undefined); + + const trackFailedLogin = async () => { + try { + await cloudApiService.track('didNotLogin', { loginMethod: 'cli' }); + } catch (e) { + logger.debug('Failed to track failed login', e); + } + }; + + if (existingToken) { + const isTokenValid = await tokenService.isTokenValid(existingToken); + if (isTokenValid) { + try { + const userInfo = await cloudApiService.getUserInfo(); + const { email } = userInfo.data.data; + if (email) { + logger.log(`You are already logged into your account (${email}).`); + } else { + logger.log('You are already logged in.'); + } + logger.log( + 'To access your dashboard, please copy and paste the following URL into your web browser:' + ); + logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`)); + return true; + } catch (e) { + logger.debug('Failed to fetch user info', e); + // If the token is invalid and request failed, we should proceed with the login process + } + } + } + + let cliConfig: CloudCliConfig; + try { + logger.info('🔌 Connecting to the Strapi Cloud API...'); + const config = await cloudApiService.config(); + cliConfig = config.data; + } catch (e: unknown) { + logger.error('🥲 Oops! Something went wrong while logging you in. Please try again.'); + logger.debug(e); + return false; + } + + try { + await cloudApiService.track('willLoginAttempt', {}); + } catch (e) { + logger.debug('Failed to track login attempt', e); + } + + logger.debug('🔐 Creating device authentication request...', { + client_id: cliConfig.clientId, + scope: cliConfig.scope, + audience: cliConfig.audience, + }); + const deviceAuthResponse = (await axios + .post(cliConfig.deviceCodeAuthUrl, { + client_id: cliConfig.clientId, + scope: cliConfig.scope, + audience: cliConfig.audience, + }) + .catch((e: AxiosError) => { + logger.error('There was an issue with the authentication process. Please try again.'); + if (e.message) { + logger.debug(e.message, e); + } else { + logger.debug(e); + } + })) as AxiosResponse; + + openModule.then((open) => { + open.default(deviceAuthResponse.data.verification_uri_complete).catch((e: Error) => { + logger.error('We encountered an issue opening the browser. Please try again later.'); + logger.debug(e.message, e); + }); + }); + + logger.log('If a browser tab does not open automatically, please follow the next steps:'); + logger.log( + `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}` + ); + logger.log( + `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.\n` + ); + + const tokenPayload = { + grant_type: 'urn:ietf:params:oauth:grant-type:device_code', + device_code: deviceAuthResponse.data.device_code, + client_id: cliConfig.clientId, + }; + + let isAuthenticated = false; + + const authenticate = async () => { + const spinner = logger.spinner('Waiting for authentication'); + spinner.start(); + const spinnerFail = () => spinner.fail('Authentication failed!'); + + while (!isAuthenticated) { + try { + const tokenResponse = await axios.post(cliConfig.tokenUrl, tokenPayload); + const authTokenData = tokenResponse.data; + + if (tokenResponse.status === 200) { + // Token validation + try { + logger.debug('🔐 Validating token...'); + await tokenService.validateToken(authTokenData.id_token, cliConfig.jwksUrl); + logger.debug('🔐 Token validation successful!'); + } catch (e: any) { + logger.debug(e); + spinnerFail(); + throw new Error('Unable to proceed: Token validation failed'); + } + + logger.debug('🔍 Fetching user information...'); + const cloudApiServiceWithToken = await cloudApiFactory(authTokenData.access_token); + // Call to get user info to create the user in DB if not exists + await cloudApiServiceWithToken.getUserInfo(); + logger.debug('🔍 User information fetched successfully!'); + + try { + logger.debug('📝 Saving login information...'); + await tokenService.saveToken(authTokenData.access_token); + logger.debug('📝 Login information saved successfully!'); + isAuthenticated = true; + } catch (e) { + logger.error( + 'There was a problem saving your login information. Please try logging in again.' + ); + logger.debug(e); + spinnerFail(); + return false; + } + } + } catch (e: any) { + if (e.message === 'Unable to proceed: Token validation failed') { + logger.error( + 'There seems to be a problem with your login information. Please try logging in again.' + ); + spinnerFail(); + await trackFailedLogin(); + return false; + } + if ( + e.response?.data.error && + !['authorization_pending', 'slow_down'].includes(e!.response.data.error) + ) { + logger.debug(e); + spinnerFail(); + await trackFailedLogin(); + return false; + } + // Await interval before retrying + await new Promise((resolve) => { + setTimeout(resolve, deviceAuthResponse.data.interval * 1000); + }); + } + } + spinner.succeed('Authentication successful!'); + logger.log('You are now logged into Strapi Cloud.'); + logger.log( + 'To access your dashboard, please copy and paste the following URL into your web browser:' + ); + logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`)); + try { + await cloudApiService.track('didLogin', { loginMethod: 'cli' }); + } catch (e) { + logger.debug('Failed to track login', e); + } + }; + + await authenticate(); + return isAuthenticated; +}; diff --git a/packages/cli/cloud/src/login/command.ts b/packages/cli/cloud/src/login/command.ts new file mode 100644 index 0000000000..fab1a54fd3 --- /dev/null +++ b/packages/cli/cloud/src/login/command.ts @@ -0,0 +1,22 @@ +import { createCommand } from 'commander'; +import type { StrapiCloudCommand } from '../types'; +import { runAction } from '../utils/helpers'; +import action from './action'; + +/** + * `$ cloud device flow login` + */ +const command: StrapiCloudCommand = ({ ctx }) => { + return createCommand('cloud:login') + .alias('login') + .description('Strapi Cloud Login') + .addHelpText( + 'after', + '\nAfter running this command, you will be prompted to enter your authentication information.' + ) + .option('-d, --debug', 'Enable debugging mode with verbose logs') + .option('-s, --silent', "Don't log anything") + .action(() => runAction('login', action)(ctx)); +}; + +export default command; diff --git a/packages/cli/cloud/src/login/index.ts b/packages/cli/cloud/src/login/index.ts new file mode 100644 index 0000000000..ee2c46650a --- /dev/null +++ b/packages/cli/cloud/src/login/index.ts @@ -0,0 +1,12 @@ +import action from './action'; +import command from './command'; +import type { StrapiCloudCommandInfo } from '../types'; + +export { action, command }; + +export default { + name: 'login', + description: 'Strapi Cloud Login', + action, + command, +} as StrapiCloudCommandInfo; diff --git a/packages/cli/cloud/src/logout/action.ts b/packages/cli/cloud/src/logout/action.ts new file mode 100644 index 0000000000..b387e0ca0c --- /dev/null +++ b/packages/cli/cloud/src/logout/action.ts @@ -0,0 +1,29 @@ +import type { CLIContext } from '../types'; +import { tokenServiceFactory, cloudApiFactory } from '../services'; + +export default async (ctx: CLIContext) => { + const { logger } = ctx; + const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx); + + const token = await retrieveToken(); + if (!token) { + logger.log("You're already logged out."); + return; + } + const cloudApiService = await cloudApiFactory(token); + try { + // we might want also to perform extra actions like logging out from the auth0 tenant + await eraseToken(); + logger.log( + '🔌 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.' + ); + } catch (e) { + logger.error('🥲 Oops! Something went wrong while logging you out. Please try again.'); + logger.debug(e); + } + try { + await cloudApiService.track('didLogout', { loginMethod: 'cli' }); + } catch (e) { + logger.debug('Failed to track logout event', e); + } +}; diff --git a/packages/cli/cloud/src/logout/command.ts b/packages/cli/cloud/src/logout/command.ts new file mode 100644 index 0000000000..33576fc80c --- /dev/null +++ b/packages/cli/cloud/src/logout/command.ts @@ -0,0 +1,18 @@ +import { createCommand } from 'commander'; +import type { StrapiCloudCommand } from '../types'; +import { runAction } from '../utils/helpers'; +import action from './action'; + +/** + * `$ cloud device flow logout` + */ +const command: StrapiCloudCommand = ({ ctx }) => { + return 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)(ctx)); +}; + +export default command; diff --git a/packages/cli/cloud/src/logout/index.ts b/packages/cli/cloud/src/logout/index.ts new file mode 100644 index 0000000000..70308703aa --- /dev/null +++ b/packages/cli/cloud/src/logout/index.ts @@ -0,0 +1,11 @@ +import action from './action'; +import command from './command'; + +export { action, command }; + +export default { + name: 'logout', + description: 'Strapi Cloud Logout', + action, + command, +}; diff --git a/packages/cli/cloud/src/services/build-logs.ts b/packages/cli/cloud/src/services/build-logs.ts new file mode 100644 index 0000000000..922e54127c --- /dev/null +++ b/packages/cli/cloud/src/services/build-logs.ts @@ -0,0 +1,75 @@ +import EventSource from 'eventsource'; +import { CLIContext, type CloudCliConfig } from '../types'; + +const buildLogsServiceFactory = ({ logger }: CLIContext) => { + return async (url: string, token: string, cliConfig: CloudCliConfig) => { + const CONN_TIMEOUT = Number(cliConfig.buildLogsConnectionTimeout); + const MAX_RETRIES = Number(cliConfig.buildLogsMaxRetries); + + return new Promise((resolve, reject) => { + let timeoutId: NodeJS.Timeout | null = null; + let retries = 0; + + const connect = (url: string) => { + const spinner = logger.spinner('Connecting to server to get build logs'); + spinner.start(); + const es = new EventSource(`${url}`, { + headers: { + Authorization: `Bearer ${token}`, + }, + }); + + const clearExistingTimeout = () => { + if (timeoutId) { + clearTimeout(timeoutId); + } + }; + + const resetTimeout = () => { + clearExistingTimeout(); + timeoutId = setTimeout(() => { + if (spinner.isSpinning) { + spinner.fail( + 'We were unable to connect to the server to get build logs at this time. This could be due to a temporary issue.' + ); + } + es.close(); + reject(new Error('Connection timed out')); + }, CONN_TIMEOUT); + }; + + es.onopen = resetTimeout; + + es.addEventListener('finished', (event) => { + const data = JSON.parse(event.data); + logger.log(data.msg); + es.close(); + clearExistingTimeout(); + resolve(null); + }); + + es.addEventListener('log', (event) => { + if (spinner.isSpinning) { + spinner.succeed(); + } + resetTimeout(); + const data = JSON.parse(event.data); + logger.log(data.msg); + }); + + es.onerror = async () => { + retries += 1; + if (retries > MAX_RETRIES) { + spinner.fail('We were unable to connect to the server to get build logs at this time.'); + es.close(); + reject(new Error('Max retries reached')); + } + }; + }; + + connect(url); + }); + }; +}; + +export { buildLogsServiceFactory }; diff --git a/packages/cli/cloud/src/services/cli-api.ts b/packages/cli/cloud/src/services/cli-api.ts new file mode 100644 index 0000000000..68e6e5c308 --- /dev/null +++ b/packages/cli/cloud/src/services/cli-api.ts @@ -0,0 +1,129 @@ +import axios, { type AxiosResponse } from 'axios'; +import fse from 'fs-extra'; +import os from 'os'; +import { apiConfig } from '../config/api'; +import type { CloudCliConfig } from '../types'; +import { getLocalConfig } from '../config/local'; + +import packageJson from '../../package.json'; + +export const VERSION = 'v1'; + +export type ProjectInfos = { + name: string; + nodeVersion: string; + region: string; + plan?: string; + url?: string; +}; +export type ProjectInput = Omit; + +export type DeployResponse = { + build_id: string; + image: string; +}; + +export type TrackPayload = Record; + +export interface CloudApiService { + deploy( + deployInput: { + filePath: string; + project: { name: string }; + }, + { + onUploadProgress, + }: { + onUploadProgress: (progressEvent: { loaded: number; total?: number }) => void; + } + ): Promise>; + + createProject(projectInput: ProjectInput): Promise<{ + data: ProjectInfos; + status: number; + }>; + + getUserInfo(): Promise; + + config(): Promise>; + + listProjects(): Promise>; + + track(event: string, payload?: TrackPayload): Promise>; +} + +export async function cloudApiFactory(token?: string): Promise { + const localConfig = await getLocalConfig(); + const customHeaders = { + 'x-device-id': localConfig.deviceId, + 'x-app-version': packageJson.version, + 'x-os-name': os.type(), + 'x-os-version': os.version(), + 'x-language': Intl.DateTimeFormat().resolvedOptions().locale, + 'x-node-version': process.versions.node, + }; + const axiosCloudAPI = axios.create({ + baseURL: `${apiConfig.apiBaseUrl}/${VERSION}`, + headers: { + 'Content-Type': 'application/json', + ...customHeaders, + }, + }); + + if (token) { + axiosCloudAPI.defaults.headers.Authorization = `Bearer ${token}`; + } + + return { + deploy({ filePath, project }, { onUploadProgress }) { + return axiosCloudAPI.post( + `/deploy/${project.name}`, + { file: fse.createReadStream(filePath) }, + { + headers: { + 'Content-Type': 'multipart/form-data', + }, + onUploadProgress, + } + ); + }, + + async createProject({ name, nodeVersion, region, plan }) { + const response = await axiosCloudAPI.post('/project', { + projectName: name, + region, + nodeVersion, + plan, + }); + + return { + data: { + id: response.data.id, + name: response.data.name, + nodeVersion: response.data.nodeVersion, + region: response.data.region, + }, + status: response.status, + }; + }, + + getUserInfo() { + return axiosCloudAPI.get('/user'); + }, + + config(): Promise> { + return axiosCloudAPI.get('/config'); + }, + + listProjects() { + return axiosCloudAPI.get('/projects'); + }, + + track(event, payload = {}) { + return axiosCloudAPI.post('/track', { + event, + payload, + }); + }, + }; +} diff --git a/packages/cli/cloud/src/services/index.ts b/packages/cli/cloud/src/services/index.ts new file mode 100644 index 0000000000..24e9edc020 --- /dev/null +++ b/packages/cli/cloud/src/services/index.ts @@ -0,0 +1,4 @@ +export { cloudApiFactory } from './cli-api'; +export * as local from './strapi-info-save'; +export { tokenServiceFactory } from './token'; +export { createLogger } from './logger'; diff --git a/packages/cli/cloud/src/services/logger.ts b/packages/cli/cloud/src/services/logger.ts new file mode 100644 index 0000000000..25d459ca63 --- /dev/null +++ b/packages/cli/cloud/src/services/logger.ts @@ -0,0 +1,168 @@ +import chalk from 'chalk'; +import stringify from 'fast-safe-stringify'; + +import ora from 'ora'; +import * as cliProgress from 'cli-progress'; + +export interface LoggerOptions { + silent?: boolean; + debug?: boolean; + timestamp?: boolean; +} + +export interface Logger { + warnings: number; + errors: number; + debug: (...args: unknown[]) => void; + info: (...args: unknown[]) => void; + success: (...args: unknown[]) => void; + warn: (...args: unknown[]) => void; + error: (...args: unknown[]) => void; + log: (...args: unknown[]) => void; + spinner: (text: string) => Pick; + progressBar: ( + totalSize: number, + text: string + ) => Pick; +} + +const stringifyArg = (arg: unknown) => { + return typeof arg === 'object' ? stringify(arg) : arg; +}; + +const createLogger = (options: LoggerOptions = {}): Logger => { + const { silent = false, debug = false, timestamp = true } = options; + + const state = { errors: 0, warning: 0 }; + + return { + get warnings() { + return state.warning; + }, + + get errors() { + return state.errors; + }, + + async debug(...args) { + if (silent || !debug) { + return; + } + + console.log( + chalk.cyan(`[DEBUG]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), + ...args.map(stringifyArg) + ); + }, + + info(...args) { + if (silent) { + return; + } + + console.info( + chalk.blue(`[INFO]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), + ...args.map(stringifyArg) + ); + }, + + log(...args) { + if (silent) { + return; + } + + console.info( + chalk.blue(`${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), + ...args.map(stringifyArg) + ); + }, + + success(...args) { + if (silent) { + return; + } + + console.info( + chalk.green(`[SUCCESS]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), + ...args.map(stringifyArg) + ); + }, + + warn(...args) { + state.warning += 1; + + if (silent) { + return; + } + + console.warn( + chalk.yellow(`[WARN]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), + ...args.map(stringifyArg) + ); + }, + + error(...args) { + state.errors += 1; + + if (silent) { + return; + } + + console.error( + chalk.red(`[ERROR]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), + ...args.map(stringifyArg) + ); + }, + + // @ts-expect-error – returning a subpart of ora is fine because the types tell us what is what. + spinner(text: string) { + if (silent) { + return { + succeed() { + return this; + }, + fail() { + return this; + }, + start() { + return this; + }, + text: '', + isSpinning: false, + }; + } + + return ora(text); + }, + + progressBar(totalSize: number, text: string) { + if (silent) { + return { + start() { + return this; + }, + stop() { + return this; + }, + update() { + return this; + }, + }; + } + + const progressBar = new cliProgress.SingleBar({ + format: `${text ? `${text} |` : ''}${chalk.green('{bar}')}| {percentage}%`, + barCompleteChar: '\u2588', + barIncompleteChar: '\u2591', + hideCursor: true, + forceRedraw: true, + }); + + progressBar.start(totalSize, 0); + + return progressBar; + }, + }; +}; + +export { createLogger }; diff --git a/packages/cli/cloud/src/services/notification.ts b/packages/cli/cloud/src/services/notification.ts new file mode 100644 index 0000000000..6567f06049 --- /dev/null +++ b/packages/cli/cloud/src/services/notification.ts @@ -0,0 +1,47 @@ +import EventSource from 'eventsource'; +import type { CLIContext, CloudCliConfig } from '../types'; + +type Event = { + type: string; + data: string; + lastEventId: string; + origin: string; +}; + +export function notificationServiceFactory({ logger }: CLIContext) { + return (url: string, token: string, cliConfig: CloudCliConfig) => { + const CONN_TIMEOUT = Number(cliConfig.notificationsConnectionTimeout); + + const es = new EventSource(url, { + headers: { + Authorization: `Bearer ${token}`, + }, + }); + let timeoutId: NodeJS.Timeout; + + const resetTimeout = () => { + clearTimeout(timeoutId); + timeoutId = setTimeout(() => { + logger.log( + '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.' + ); + es.close(); + }, CONN_TIMEOUT); // 5 minutes + }; + + es.onopen = resetTimeout; + es.onmessage = (event: Event) => { + resetTimeout(); + const data = JSON.parse(event.data); + + if (data.message) { + logger.log(data.message); + } + + // Close connection when a specific event is received + if (data.event === 'deploymentFinished' || data.event === 'deploymentFailed') { + es.close(); + } + }; + }; +} diff --git a/packages/cli/cloud/src/services/strapi-info-save.ts b/packages/cli/cloud/src/services/strapi-info-save.ts new file mode 100644 index 0000000000..253fdaf7d2 --- /dev/null +++ b/packages/cli/cloud/src/services/strapi-info-save.ts @@ -0,0 +1,30 @@ +import fse from 'fs-extra'; +import path from 'path'; +import type { ProjectInfos } from './cli-api'; + +export const LOCAL_SAVE_FILENAME = '.strapi-cloud.json'; + +export type LocalSave = { + project?: ProjectInfos; +}; + +export async function save(data: LocalSave, { directoryPath }: { directoryPath?: string } = {}) { + const alreadyInFileData = await retrieve({ directoryPath }); + const storedData = { ...alreadyInFileData, ...data }; + const pathToFile = path.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME); + // Ensure the directory exists + await fse.ensureDir(path.dirname(pathToFile)); + await fse.writeJson(pathToFile, storedData, { encoding: 'utf8' }); +} + +export async function retrieve({ + directoryPath, +}: { directoryPath?: string } = {}): Promise { + const pathToFile = path.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME); + const pathExists = await fse.pathExists(pathToFile); + if (!pathExists) { + return {}; + } + + return fse.readJSON(pathToFile, { encoding: 'utf8' }); +} diff --git a/packages/cli/cloud/src/services/token.ts b/packages/cli/cloud/src/services/token.ts new file mode 100644 index 0000000000..54447676f3 --- /dev/null +++ b/packages/cli/cloud/src/services/token.ts @@ -0,0 +1,146 @@ +import jwksClient, { type JwksClient, type SigningKey } from 'jwks-rsa'; +import type { JwtHeader, VerifyErrors } from 'jsonwebtoken'; +import jwt from 'jsonwebtoken'; +import { getLocalConfig, saveLocalConfig } from '../config/local'; +import type { CloudCliConfig, CLIContext } from '../types'; +import { cloudApiFactory } from './cli-api'; + +let cliConfig: CloudCliConfig; + +interface DecodedToken { + [key: string]: any; +} + +export async function tokenServiceFactory({ logger }: { logger: CLIContext['logger'] }) { + const cloudApiService = await cloudApiFactory(); + + async function saveToken(str: string) { + const appConfig = await getLocalConfig(); + + if (!appConfig) { + logger.error('There was a problem saving your token. Please try again.'); + return; + } + + appConfig.token = str; + + try { + await saveLocalConfig(appConfig); + } catch (e: Error | unknown) { + logger.debug(e); + logger.error('There was a problem saving your token. Please try again.'); + } + } + + async function retrieveToken() { + const appConfig = await getLocalConfig(); + if (appConfig.token) { + // check if token is still valid + if (await isTokenValid(appConfig.token)) { + return appConfig.token; + } + } + return undefined; + } + + async function validateToken(idToken: string, jwksUrl: string): Promise { + const client: JwksClient = jwksClient({ + jwksUri: jwksUrl, + }); + + // Get the Key from the JWKS using the token header's Key ID (kid) + const getKey = (header: JwtHeader, callback: (e: Error | null, key?: string) => void) => { + client.getSigningKey(header.kid, (e: Error | null, key?: SigningKey) => { + if (e) { + callback(e); + } else if (key) { + const publicKey = 'publicKey' in key ? key.publicKey : key.rsaPublicKey; + callback(null, publicKey); + } else { + callback(new Error('Key not found')); + } + }); + }; + + // Decode the JWT token to get the header and payload + const decodedToken = jwt.decode(idToken, { complete: true }) as DecodedToken; + if (!decodedToken) { + if (typeof idToken === 'undefined' || idToken === '') { + logger.warn('You need to be logged in to use this feature. Please log in and try again.'); + } else { + logger.error( + 'There seems to be a problem with your login information. Please try logging in again.' + ); + } + } + + // Verify the JWT token signature using the JWKS Key + return new Promise((resolve, reject) => { + jwt.verify(idToken, getKey, (err: VerifyErrors | null) => { + if (err) { + reject(err); + } else { + resolve(); + } + }); + }); + } + + async function isTokenValid(token: string) { + try { + const config = await cloudApiService.config(); + + cliConfig = config.data; + if (token) { + await validateToken(token, cliConfig.jwksUrl); + return true; + } + return false; + } catch (e) { + logger.debug(e); + return false; + } + } + + async function eraseToken() { + const appConfig = await getLocalConfig(); + if (!appConfig) { + return; + } + + delete appConfig.token; + + try { + await saveLocalConfig(appConfig); + } catch (e: Error | unknown) { + logger.debug(e); + logger.error( + 'There was an issue removing your login information. Please try logging out again.' + ); + throw e; + } + } + + async function getValidToken() { + const token = await retrieveToken(); + if (!token) { + logger.log('No token found. Please login first.'); + return null; + } + + if (!(await isTokenValid(token))) { + logger.log('Unable to proceed: Token is expired or not valid. Please login again.'); + return null; + } + return token; + } + + return { + saveToken, + retrieveToken, + validateToken, + isTokenValid, + eraseToken, + getValidToken, + }; +} diff --git a/packages/cli/cloud/src/types.ts b/packages/cli/cloud/src/types.ts new file mode 100644 index 0000000000..0e61489eb6 --- /dev/null +++ b/packages/cli/cloud/src/types.ts @@ -0,0 +1,49 @@ +import type { Command } from 'commander'; +import type { DistinctQuestion } from 'inquirer'; +import { Logger } from './services/logger'; + +export type ProjectAnswers = { + name: string; + nodeVersion: string; + region: string; + plan: string; +}; + +export type CloudCliConfig = { + clientId: string; + baseUrl: string; + deviceCodeAuthUrl: string; + audience: string; + scope: string; + tokenUrl: string; + jwksUrl: string; + projectCreation: { + questions: ReadonlyArray>; + defaults: Partial; + introText: string; + }; + buildLogsConnectionTimeout: string; + buildLogsMaxRetries: string; + notificationsConnectionTimeout: string; + maxProjectFileSize: string; +}; + +export interface CLIContext { + cwd: string; + logger: Logger; +} + +export type StrapiCloudCommand = (params: { + command: Command; + argv: string[]; + ctx: CLIContext; +}) => void | Command | Promise; + +export type StrapiCloudCommandInfo = { + name: string; + description: string; + command: StrapiCloudCommand; + action: (ctx: CLIContext) => Promise; +}; + +export type * from './services/cli-api'; diff --git a/packages/cli/cloud/src/utils/compress-files.ts b/packages/cli/cloud/src/utils/compress-files.ts new file mode 100644 index 0000000000..a08592951e --- /dev/null +++ b/packages/cli/cloud/src/utils/compress-files.ts @@ -0,0 +1,89 @@ +// TODO Migrate to fs-extra +import * as fs from 'fs'; +import * as tar from 'tar'; +import * as path from 'path'; +import { minimatch } from 'minimatch'; + +const IGNORED_PATTERNS = [ + '**/.git/**', + '**/node_modules/**', + '**/build/**', + '**/dist/**', + '**/.cache/**', + '**/.circleci/**', + '**/.github/**', + '**/.gitignore', + '**/.gitkeep', + '**/.gitlab-ci.yml', + '**/.idea/**', + '**/.vscode/**', +]; + +const getFiles = ( + dirPath: string, + ignorePatterns: string[] = [], + arrayOfFiles: string[] = [], + subfolder: string = '' +): string[] => { + const entries = fs.readdirSync(path.join(dirPath, subfolder)); + entries.forEach((entry) => { + const entryPathFromRoot = path.join(subfolder, entry); + const entryPath = path.relative(dirPath, entryPathFromRoot); + const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns); + if (isIgnored) { + return; + } + if (fs.statSync(entryPath).isDirectory()) { + getFiles(dirPath, ignorePatterns, arrayOfFiles, entryPathFromRoot); + } else { + arrayOfFiles.push(entryPath); + } + }); + return arrayOfFiles; +}; + +const isIgnoredFile = (folderPath: string, file: string, ignorePatterns: string[]): boolean => { + ignorePatterns.push(...IGNORED_PATTERNS); + const relativeFilePath = path.join(folderPath, file); + let isIgnored = false; + for (const pattern of ignorePatterns) { + if (pattern.startsWith('!')) { + if (minimatch(relativeFilePath, pattern.slice(1), { matchBase: true, dot: true })) { + return false; + } + } else if (minimatch(relativeFilePath, pattern, { matchBase: true, dot: true })) { + if (path.basename(file) !== '.gitkeep') { + isIgnored = true; + } + } + } + return isIgnored; +}; + +const readGitignore = (folderPath: string): string[] => { + const gitignorePath = path.resolve(folderPath, '.gitignore'); + if (!fs.existsSync(gitignorePath)) return []; + const gitignoreContent = fs.readFileSync(gitignorePath, 'utf8'); + return gitignoreContent + .split(/\r?\n/) + .filter((line) => Boolean(line.trim()) && !line.startsWith('#')); +}; + +const compressFilesToTar = async ( + storagePath: string, + folderToCompress: string, + filename: string +): Promise => { + const ignorePatterns = readGitignore(folderToCompress); + const filesToCompress = getFiles(folderToCompress, ignorePatterns); + + return tar.c( + { + gzip: true, + file: path.resolve(storagePath, filename), + }, + filesToCompress + ); +}; + +export { compressFilesToTar, isIgnoredFile }; diff --git a/packages/cli/cloud/src/utils/helpers.ts b/packages/cli/cloud/src/utils/helpers.ts new file mode 100644 index 0000000000..2fb4042599 --- /dev/null +++ b/packages/cli/cloud/src/utils/helpers.ts @@ -0,0 +1,45 @@ +import chalk from 'chalk'; +import { has } from 'lodash/fp'; + +// TODO: Remove duplicated code by extracting to a shared package + +const assertCwdContainsStrapiProject = (name: string) => { + const logErrorAndExit = () => { + console.log( + `You need to run ${chalk.yellow( + `strapi ${name}` + )} in a Strapi project. Make sure you are in the right directory.` + ); + process.exit(1); + }; + + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const pkgJSON = require(`${process.cwd()}/package.json`); + if ( + !has('dependencies.@strapi/strapi', pkgJSON) && + !has('devDependencies.@strapi/strapi', pkgJSON) + ) { + logErrorAndExit(); + } + } catch (err) { + logErrorAndExit(); + } +}; + +const runAction = + (name: string, action: (...args: any[]) => Promise) => + (...args: unknown[]) => { + assertCwdContainsStrapiProject(name); + + Promise.resolve() + .then(() => { + return action(...args); + }) + .catch((error) => { + console.error(error); + process.exit(1); + }); + }; + +export { runAction }; diff --git a/packages/cli/cloud/src/utils/pkg.ts b/packages/cli/cloud/src/utils/pkg.ts new file mode 100644 index 0000000000..5deb2308e5 --- /dev/null +++ b/packages/cli/cloud/src/utils/pkg.ts @@ -0,0 +1,131 @@ +// TODO Migrate to fs-extra +import fs from 'fs/promises'; +import os from 'os'; +import pkgUp from 'pkg-up'; +import * as yup from 'yup'; +import chalk from 'chalk'; +import { Logger } from '../services/logger'; + +interface Export { + types?: string; + source: string; + module?: string; + import?: string; + require?: string; + default: string; +} + +const packageJsonSchema = yup.object({ + name: yup.string().required(), + exports: yup.lazy((value) => + yup + .object( + typeof value === 'object' + ? Object.entries(value).reduce( + (acc, [key, value]) => { + if (typeof value === 'object') { + acc[key] = yup + .object({ + types: yup.string().optional(), + source: yup.string().required(), + module: yup.string().optional(), + import: yup.string().required(), + require: yup.string().required(), + default: yup.string().required(), + }) + .noUnknown(true); + } else { + acc[key] = yup + .string() + .matches(/^\.\/.*\.json$/) + .required(); + } + + return acc; + }, + {} as Record | yup.SchemaOf> + ) + : undefined + ) + .optional() + ), +}); + +type PackageJson = yup.Asserts; + +/** + * @description being a task to load the package.json starting from the current working directory + * using a shallow find for the package.json and `fs` to read the file. If no package.json is found, + * the process will throw with an appropriate error message. + */ +const loadPkg = async ({ cwd, logger }: { cwd: string; logger: Logger }): Promise => { + const pkgPath = await pkgUp({ cwd }); + + if (!pkgPath) { + throw new Error('Could not find a package.json in the current directory'); + } + + const buffer = await fs.readFile(pkgPath); + + const pkg = JSON.parse(buffer.toString()); + + logger.debug('Loaded package.json:', os.EOL, pkg); + + return pkg; +}; + +/** + * @description validate the package.json against a standardised schema using `yup`. + * If the validation fails, the process will throw with an appropriate error message. + */ +const validatePkg = async ({ pkg }: { pkg: object }): Promise => { + try { + const validatedPkg = await packageJsonSchema.validate(pkg, { + strict: true, + }); + + return validatedPkg; + } catch (err) { + if (err instanceof yup.ValidationError) { + switch (err.type) { + case 'required': + if (err.path) { + throw new Error( + `'${err.path}' in 'package.json' is required as type '${chalk.magenta( + yup.reach(packageJsonSchema, err.path).type + )}'` + ); + } + break; + /** + * This will only be thrown if there are keys in the export map + * that we don't expect so we can therefore make some assumptions + */ + case 'noUnknown': + if (err.path && err.params && 'unknown' in err.params) { + throw new Error( + `'${err.path}' in 'package.json' contains the unknown key ${chalk.magenta( + err.params.unknown + )}, for compatability only the following keys are allowed: ${chalk.magenta( + "['types', 'source', 'import', 'require', 'default']" + )}` + ); + } + break; + default: + if (err.path && err.params && 'type' in err.params && 'value' in err.params) { + throw new Error( + `'${err.path}' in 'package.json' must be of type '${chalk.magenta( + err.params.type + )}' (recieved '${chalk.magenta(typeof err.params.value)}')` + ); + } + } + } + + throw err; + } +}; + +export type { PackageJson, Export }; +export { loadPkg, validatePkg }; diff --git a/packages/cli/cloud/src/utils/tests/compress-files.test.ts b/packages/cli/cloud/src/utils/tests/compress-files.test.ts new file mode 100644 index 0000000000..3023e72131 --- /dev/null +++ b/packages/cli/cloud/src/utils/tests/compress-files.test.ts @@ -0,0 +1,37 @@ +import path from 'path'; +import os from 'os'; +import { isIgnoredFile } from '../compress-files'; + +describe('isIgnoredFile', () => { + const folderPath = os.tmpdir(); // We are using the system's directory path for simulating a real path + it('should correctly handle various ignore patterns', () => { + const allFiles = [ + path.join(folderPath, 'file1.txt'), + path.join(folderPath, 'file2.txt'), + path.join(folderPath, 'node_modules', 'file3.js'), + path.join(folderPath, '.git', 'file4.js'), + path.join(folderPath, 'dist', 'file5.js'), + path.join(folderPath, 'public', 'uploads', '.gitkeep'), + path.join(folderPath, 'src', 'secret', 'file6.js'), + path.join(folderPath, 'src', 'secret', 'keep.me'), + path.join(folderPath, 'test', 'file7.test.ts'), + ]; + const ignorePatterns = [ + '**/node_modules/**', + '**/.git/**', + '**/dist/**', + '!public/uploads/.gitkeep', + '!**/*.test.ts', + '**/src/secret/**', + '!**/src/secret/keep.me', + ]; + const result = allFiles.filter((file) => !isIgnoredFile(folderPath, file, ignorePatterns)); + expect(result).toEqual([ + path.join(folderPath, 'file1.txt'), + path.join(folderPath, 'file2.txt'), + path.join(folderPath, 'public', 'uploads', '.gitkeep'), + path.join(folderPath, 'src', 'secret', 'keep.me'), + path.join(folderPath, 'test', 'file7.test.ts'), + ]); + }); +}); diff --git a/packages/cli/cloud/tsconfig.build.json b/packages/cli/cloud/tsconfig.build.json new file mode 100644 index 0000000000..c80c96eb9b --- /dev/null +++ b/packages/cli/cloud/tsconfig.build.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "dist" + }, + "include": ["src"], + "exclude": ["node_modules", "**/__tests__/**"] +} diff --git a/packages/cli/cloud/tsconfig.eslint.json b/packages/cli/cloud/tsconfig.eslint.json new file mode 100644 index 0000000000..fc8520e737 --- /dev/null +++ b/packages/cli/cloud/tsconfig.eslint.json @@ -0,0 +1,3 @@ +{ + "extends": "./tsconfig.json" +} diff --git a/packages/cli/cloud/tsconfig.json b/packages/cli/cloud/tsconfig.json new file mode 100644 index 0000000000..327ffb9a92 --- /dev/null +++ b/packages/cli/cloud/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "tsconfig/base.json", + "include": ["src", "packup.config.ts"], + "exclude": ["node_modules"] +} diff --git a/packages/cli/create-strapi-app/LICENSE b/packages/cli/create-strapi-app/LICENSE index db018546b5..d82875fe30 100644 --- a/packages/cli/create-strapi-app/LICENSE +++ b/packages/cli/create-strapi-app/LICENSE @@ -2,7 +2,21 @@ Copyright (c) 2015-present Strapi Solutions SAS Portions of the Strapi software are licensed as follows: -* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined in "ee/LICENSE". +* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined below. + +Enterprise License + +If you or the company you represent has entered into a written agreement referencing the Enterprise Edition of the Strapi source code available at +https://github.com/strapi/strapi, then such agreement applies to your use of the Enterprise Edition of the Strapi Software. If you or the company you +represent is using the Enterprise Edition of the Strapi Software in connection with a subscription to our cloud offering, then the agreement you have +agreed to with respect to our cloud offering and the licenses included in such agreement apply to your use of the Enterprise Edition of the Strapi Software. +Otherwise, the Strapi Enterprise Software License Agreement (found here https://strapi.io/enterprise-terms) applies to your use of the Enterprise Edition of the Strapi Software. + +BY ACCESSING OR USING THE ENTERPRISE EDITION OF THE STRAPI SOFTWARE, YOU ARE AGREEING TO BE BOUND BY THE RELEVANT REFERENCED AGREEMENT. +IF YOU ARE NOT AUTHORIZED TO ACCEPT THESE TERMS ON BEHALF OF THE COMPANY YOU REPRESENT OR IF YOU DO NOT AGREE TO ALL OF THE RELEVANT TERMS AND CONDITIONS REFERENCED AND YOU +HAVE NOT OTHERWISE EXECUTED A WRITTEN AGREEMENT WITH STRAPI, YOU ARE NOT AUTHORIZED TO ACCESS OR USE OR ALLOW ANY USER TO ACCESS OR USE ANY PART OF +THE ENTERPRISE EDITION OF THE STRAPI SOFTWARE. YOUR ACCESS RIGHTS ARE CONDITIONAL ON YOUR CONSENT TO THE RELEVANT REFERENCED TERMS TO THE EXCLUSION OF ALL OTHER TERMS; +IF THE RELEVANT REFERENCED TERMS ARE CONSIDERED AN OFFER BY YOU, ACCEPTANCE IS EXPRESSLY LIMITED TO THE RELEVANT REFERENCED TERMS. * All software outside of the above-mentioned directories or restrictions above is available under the "MIT Expat" license as set forth below. @@ -18,5 +32,6 @@ furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/cli/create-strapi-app/package.json b/packages/cli/create-strapi-app/package.json index c462530bfb..6d63519590 100644 --- a/packages/cli/create-strapi-app/package.json +++ b/packages/cli/create-strapi-app/package.json @@ -1,6 +1,6 @@ { "name": "create-strapi-app", - "version": "5.0.0-beta.12", + "version": "5.0.0-rc.1", "description": "Generate a new Strapi application.", "keywords": [ "create-strapi-app", @@ -43,15 +43,17 @@ "watch": "pack-up watch" }, "dependencies": { - "@strapi/generate-new": "5.0.0-beta.12", + "@strapi/cloud-cli": "5.0.0-rc.1", + "@strapi/generate-new": "5.0.0-rc.1", + "chalk": "4.1.2", "commander": "8.3.0", "inquirer": "8.2.5" }, "devDependencies": { "@strapi/pack-up": "5.0.0", "@types/inquirer": "8.2.5", - "eslint-config-custom": "5.0.0-beta.12", - "tsconfig": "5.0.0-beta.12" + "eslint-config-custom": "5.0.0-rc.1", + "tsconfig": "5.0.0-rc.1" }, "engines": { "node": ">=18.0.0 <=20.x.x", diff --git a/packages/cli/create-strapi-app/src/cloud.ts b/packages/cli/create-strapi-app/src/cloud.ts new file mode 100644 index 0000000000..287f3446e6 --- /dev/null +++ b/packages/cli/create-strapi-app/src/cloud.ts @@ -0,0 +1,107 @@ +import inquirer from 'inquirer'; +import { resolve } from 'node:path'; +import { cli as cloudCli, services as cloudServices } from '@strapi/cloud-cli'; +import parseToChalk from './utils/parse-to-chalk'; + +interface CloudError { + response: { + status: number; + data: string | object; + }; +} + +function assertCloudError(e: unknown): asserts e is CloudError { + if ((e as CloudError).response === undefined) { + throw Error('Expected CloudError'); + } +} + +export async function handleCloudProject(projectName: string): Promise { + const logger = cloudServices.createLogger({ + silent: false, + debug: process.argv.includes('--debug'), + timestamp: false, + }); + let cloudApiService = await cloudServices.cloudApiFactory(); + const defaultErrorMessage = + 'An error occurred while trying to interact with Strapi Cloud. Use strapi deploy command once the project is generated.'; + + try { + const { data: config } = await cloudApiService.config(); + logger.log(parseToChalk(config.projectCreation.introText)); + } catch (e: unknown) { + logger.debug(e); + logger.error(defaultErrorMessage); + return; + } + const { userChoice } = await inquirer.prompt<{ userChoice: string }>([ + { + type: 'list', + name: 'userChoice', + message: `Please log in or sign up.`, + choices: ['Login/Sign up', 'Skip'], + }, + ]); + + if (userChoice !== 'Skip') { + const cliContext = { + logger, + cwd: process.cwd(), + }; + const projectCreationSpinner = logger.spinner('Creating project on Strapi Cloud'); + + try { + const tokenService = await cloudServices.tokenServiceFactory(cliContext); + const loginSuccess = await cloudCli.login.action(cliContext); + if (!loginSuccess) { + return; + } + logger.debug('Retrieving token'); + const token = await tokenService.retrieveToken(); + + cloudApiService = await cloudServices.cloudApiFactory(token); + + logger.debug('Retrieving config'); + const { data: config } = await cloudApiService.config(); + logger.debug('config', config); + const defaultProjectValues = config.projectCreation?.defaults || {}; + logger.debug('default project values', defaultProjectValues); + projectCreationSpinner.start(); + const { data: project } = await cloudApiService.createProject({ + nodeVersion: process.versions?.node?.slice(1, 3) || '20', + region: 'NYC', + plan: 'trial', + ...defaultProjectValues, + name: projectName, + }); + projectCreationSpinner.succeed('Project created on Strapi Cloud'); + const projectPath = resolve(projectName); + logger.debug(project, projectPath); + await cloudServices.local.save({ project }, { directoryPath: projectPath }); + } catch (e: Error | CloudError | unknown) { + logger.debug(e); + try { + assertCloudError(e); + if (e.response.status === 403) { + const message = + typeof e.response.data === 'string' + ? e.response.data + : 'We are sorry, but we are not able to create a Strapi Cloud project for you at the moment.'; + if (projectCreationSpinner.isSpinning) { + projectCreationSpinner.fail(message); + } else { + logger.warn(message); + } + return; + } + } catch (e) { + /* empty */ + } + if (projectCreationSpinner.isSpinning) { + projectCreationSpinner.fail(defaultErrorMessage); + } else { + logger.error(defaultErrorMessage); + } + } + } +} diff --git a/packages/cli/create-strapi-app/src/create-strapi-app.ts b/packages/cli/create-strapi-app/src/create-strapi-app.ts index 3a6e580f67..f90f938bb1 100644 --- a/packages/cli/create-strapi-app/src/create-strapi-app.ts +++ b/packages/cli/create-strapi-app/src/create-strapi-app.ts @@ -1,12 +1,14 @@ import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; import commander from 'commander'; + import { generateNewApp, type Options as GenerateNewAppOptions } from '@strapi/generate-new'; import * as prompts from './prompts'; import type { Options } from './types'; import { detectPackageManager } from './package-manager'; import * as database from './database'; +// import { handleCloudProject } from './cloud'; const packageJson = JSON.parse(readFileSync(resolve(__dirname, '../package.json'), 'utf8')); @@ -29,6 +31,8 @@ command .option('--use-pnpm', 'Use pnpm as the project package manager') // Database options + // TODO V5: Uncomment when cloud-cli is ready + // .option('--skip-cloud', 'Skip cloud login and project creation') .option('--dbclient ', 'Database client') .option('--dbhost ', 'Database host') .option('--dbport ', 'Database port') @@ -39,7 +43,7 @@ command .option('--dbfile ', 'Database file path for sqlite') // templates - .option('--template ', 'Specify a Strapi template') + // .option('--template ', 'Specify a Strapi template') .description('create a new application') .action((directory, options) => { createStrapiApp(directory, options); @@ -56,11 +60,17 @@ async function createStrapiApp(directory: string | undefined, options: Options) const appDirectory = directory || (await prompts.directory()); + // TODO V5: Uncomment when cloud-cli is ready + // if (!options.skipCloud) { + // checkRequirements(); + // await handleCloudProject(projectName); + // } + const appOptions = { directory: appDirectory, useTypescript: true, packageManager: 'npm', - template: options.template, + // template: options.template, isQuickstart: options.quickstart, } as GenerateNewAppOptions; @@ -101,16 +111,16 @@ async function createStrapiApp(directory: string | undefined, options: Options) } async function validateOptions(options: Options) { - const programFlags = command - .createHelp() - .visibleOptions(command) - .reduce>((acc, { short, long }) => [...acc, short, long], []) - .filter(Boolean); + // const programFlags = command + // .createHelp() + // .visibleOptions(command) + // .reduce>((acc, { short, long }) => [...acc, short, long], []) + // .filter(Boolean); - if (options.template && programFlags.includes(options.template)) { - console.error(`${options.template} is not a valid template`); - process.exit(1); - } + // if (options.template && programFlags.includes(options.template)) { + // console.error(`${options.template} is not a valid template`); + // process.exit(1); + // } if (options.javascript === true && options.typescript === true) { console.error('You cannot use both --typescript (--ts) and --javascript (--js) flags together'); diff --git a/packages/cli/create-strapi-app/src/types.ts b/packages/cli/create-strapi-app/src/types.ts index 9da23b0959..aa4acf889d 100644 --- a/packages/cli/create-strapi-app/src/types.ts +++ b/packages/cli/create-strapi-app/src/types.ts @@ -5,6 +5,7 @@ export interface Options { quickstart?: boolean; run?: boolean; dbclient?: DBClient; + skipCloud?: boolean; dbhost?: string; dbport?: string; dbname?: string; @@ -12,7 +13,7 @@ export interface Options { dbpassword?: string; dbssl?: string; dbfile?: string; - template?: string; + // template?: string; typescript?: boolean; javascript?: boolean; } diff --git a/packages/cli/create-strapi-app/src/utils/parse-to-chalk.ts b/packages/cli/create-strapi-app/src/utils/parse-to-chalk.ts new file mode 100644 index 0000000000..a785ca93f0 --- /dev/null +++ b/packages/cli/create-strapi-app/src/utils/parse-to-chalk.ts @@ -0,0 +1,24 @@ +import chalk from 'chalk'; + +// TODO: move styles to API + +const supportedStyles = { + magentaBright: chalk.magentaBright, + blueBright: chalk.blueBright, + yellowBright: chalk.yellowBright, + green: chalk.green, + red: chalk.red, + bold: chalk.bold, + italic: chalk.italic, +}; + +export default function parseToChalk(template: string) { + let result = template; + + for (const [color, chalkFunction] of Object.entries(supportedStyles)) { + const regex = new RegExp(`{${color}}(.*?){/${color}}`, 'g'); + result = result.replace(regex, (_, p1) => chalkFunction(p1.trim())); + } + + return result; +} diff --git a/packages/cli/create-strapi/LICENSE b/packages/cli/create-strapi/LICENSE index db018546b5..d82875fe30 100644 --- a/packages/cli/create-strapi/LICENSE +++ b/packages/cli/create-strapi/LICENSE @@ -2,7 +2,21 @@ Copyright (c) 2015-present Strapi Solutions SAS Portions of the Strapi software are licensed as follows: -* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined in "ee/LICENSE". +* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined below. + +Enterprise License + +If you or the company you represent has entered into a written agreement referencing the Enterprise Edition of the Strapi source code available at +https://github.com/strapi/strapi, then such agreement applies to your use of the Enterprise Edition of the Strapi Software. If you or the company you +represent is using the Enterprise Edition of the Strapi Software in connection with a subscription to our cloud offering, then the agreement you have +agreed to with respect to our cloud offering and the licenses included in such agreement apply to your use of the Enterprise Edition of the Strapi Software. +Otherwise, the Strapi Enterprise Software License Agreement (found here https://strapi.io/enterprise-terms) applies to your use of the Enterprise Edition of the Strapi Software. + +BY ACCESSING OR USING THE ENTERPRISE EDITION OF THE STRAPI SOFTWARE, YOU ARE AGREEING TO BE BOUND BY THE RELEVANT REFERENCED AGREEMENT. +IF YOU ARE NOT AUTHORIZED TO ACCEPT THESE TERMS ON BEHALF OF THE COMPANY YOU REPRESENT OR IF YOU DO NOT AGREE TO ALL OF THE RELEVANT TERMS AND CONDITIONS REFERENCED AND YOU +HAVE NOT OTHERWISE EXECUTED A WRITTEN AGREEMENT WITH STRAPI, YOU ARE NOT AUTHORIZED TO ACCESS OR USE OR ALLOW ANY USER TO ACCESS OR USE ANY PART OF +THE ENTERPRISE EDITION OF THE STRAPI SOFTWARE. YOUR ACCESS RIGHTS ARE CONDITIONAL ON YOUR CONSENT TO THE RELEVANT REFERENCED TERMS TO THE EXCLUSION OF ALL OTHER TERMS; +IF THE RELEVANT REFERENCED TERMS ARE CONSIDERED AN OFFER BY YOU, ACCEPTANCE IS EXPRESSLY LIMITED TO THE RELEVANT REFERENCED TERMS. * All software outside of the above-mentioned directories or restrictions above is available under the "MIT Expat" license as set forth below. @@ -18,5 +32,6 @@ furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/cli/create-strapi/package.json b/packages/cli/create-strapi/package.json index 30c0afd693..8efef5bb75 100644 --- a/packages/cli/create-strapi/package.json +++ b/packages/cli/create-strapi/package.json @@ -1,6 +1,6 @@ { "name": "create-strapi", - "version": "5.0.0-beta.12", + "version": "5.0.0-rc.1", "description": "Generate a new Strapi application.", "keywords": [ "create-strapi", @@ -36,7 +36,7 @@ "bin/" ], "dependencies": { - "create-strapi-app": "5.0.0-beta.12" + "create-strapi-app": "5.0.0-rc.1" }, "engines": { "node": ">=18.0.0 <=20.x.x", diff --git a/packages/core/admin/LICENSE b/packages/core/admin/LICENSE index 638baf882b..d82875fe30 100644 --- a/packages/core/admin/LICENSE +++ b/packages/core/admin/LICENSE @@ -2,7 +2,21 @@ Copyright (c) 2015-present Strapi Solutions SAS Portions of the Strapi software are licensed as follows: -* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined in "ee/LICENSE". +* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined below. + +Enterprise License + +If you or the company you represent has entered into a written agreement referencing the Enterprise Edition of the Strapi source code available at +https://github.com/strapi/strapi, then such agreement applies to your use of the Enterprise Edition of the Strapi Software. If you or the company you +represent is using the Enterprise Edition of the Strapi Software in connection with a subscription to our cloud offering, then the agreement you have +agreed to with respect to our cloud offering and the licenses included in such agreement apply to your use of the Enterprise Edition of the Strapi Software. +Otherwise, the Strapi Enterprise Software License Agreement (found here https://strapi.io/enterprise-terms) applies to your use of the Enterprise Edition of the Strapi Software. + +BY ACCESSING OR USING THE ENTERPRISE EDITION OF THE STRAPI SOFTWARE, YOU ARE AGREEING TO BE BOUND BY THE RELEVANT REFERENCED AGREEMENT. +IF YOU ARE NOT AUTHORIZED TO ACCEPT THESE TERMS ON BEHALF OF THE COMPANY YOU REPRESENT OR IF YOU DO NOT AGREE TO ALL OF THE RELEVANT TERMS AND CONDITIONS REFERENCED AND YOU +HAVE NOT OTHERWISE EXECUTED A WRITTEN AGREEMENT WITH STRAPI, YOU ARE NOT AUTHORIZED TO ACCESS OR USE OR ALLOW ANY USER TO ACCESS OR USE ANY PART OF +THE ENTERPRISE EDITION OF THE STRAPI SOFTWARE. YOUR ACCESS RIGHTS ARE CONDITIONAL ON YOUR CONSENT TO THE RELEVANT REFERENCED TERMS TO THE EXCLUSION OF ALL OTHER TERMS; +IF THE RELEVANT REFERENCED TERMS ARE CONSIDERED AN OFFER BY YOU, ACCEPTANCE IS EXPRESSLY LIMITED TO THE RELEVANT REFERENCED TERMS. * All software outside of the above-mentioned directories or restrictions above is available under the "MIT Expat" license as set forth below. @@ -18,5 +32,6 @@ furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/core/admin/admin/src/StrapiApp.tsx b/packages/core/admin/admin/src/StrapiApp.tsx index 3313d6a2e0..4a234fd714 100644 --- a/packages/core/admin/admin/src/StrapiApp.tsx +++ b/packages/core/admin/admin/src/StrapiApp.tsx @@ -19,7 +19,12 @@ import { Router, StrapiAppSetting, UnloadedSettingsLink } from './core/apis/rout import { RootState, Store, configureStore } from './core/store/configure'; import { getBasename } from './core/utils/basename'; import { Handler, createHook } from './core/utils/createHook'; -import { THEME_LOCAL_STORAGE_KEY, LANGUAGE_LOCAL_STORAGE_KEY, ThemeName } from './reducer'; +import { + THEME_LOCAL_STORAGE_KEY, + LANGUAGE_LOCAL_STORAGE_KEY, + ThemeName, + getStoredToken, +} from './reducer'; import { getInitialRoutes } from './router'; import { languageNativeNames } from './translations/languageNativeNames'; @@ -439,6 +444,7 @@ class StrapiApp { locale: localeNames[locale] ? locale : 'en', localeNames, }, + token: getStoredToken(), }, }, this.middlewares, diff --git a/packages/core/admin/admin/src/components/ConfirmDialog.tsx b/packages/core/admin/admin/src/components/ConfirmDialog.tsx index c80d47fbd2..3545907835 100644 --- a/packages/core/admin/admin/src/components/ConfirmDialog.tsx +++ b/packages/core/admin/admin/src/components/ConfirmDialog.tsx @@ -3,12 +3,13 @@ import * as React from 'react'; import { Button, ButtonProps, Dialog } from '@strapi/design-system'; import { WarningCircle } from '@strapi/icons'; import { useIntl } from 'react-intl'; +import { styled } from 'styled-components'; /* ------------------------------------------------------------------------------------------------- * ConfirmDialog * -----------------------------------------------------------------------------------------------*/ interface ConfirmDialogProps extends Pick, Pick { - onConfirm?: () => Promise | void; + onConfirm?: (e?: React.MouseEvent) => Promise | void; children?: React.ReactNode; endAction?: React.ReactNode; startAction?: React.ReactNode; @@ -49,7 +50,7 @@ interface ConfirmDialogProps extends Pick, Pick, + icon = , onConfirm, variant = 'danger-light', startAction, @@ -66,14 +67,14 @@ const ConfirmDialog = ({ defaultMessage: 'Are you sure?', }); - const handleConfirm = async () => { + const handleConfirm = async (e: React.MouseEvent) => { if (!onConfirm) { return; } try { setIsConfirming(true); - await onConfirm(); + await onConfirm(e); } finally { setIsConfirming(false); } @@ -92,7 +93,13 @@ const ConfirmDialog = ({ {startAction || ( - diff --git a/packages/core/admin/admin/src/pages/Settings/pages/ApplicationInfo/components/LogoInput.tsx b/packages/core/admin/admin/src/pages/Settings/pages/ApplicationInfo/components/LogoInput.tsx index a54bd752ba..8e3598e010 100644 --- a/packages/core/admin/admin/src/pages/Settings/pages/ApplicationInfo/components/LogoInput.tsx +++ b/packages/core/admin/admin/src/pages/Settings/pages/ApplicationInfo/components/LogoInput.tsx @@ -81,7 +81,14 @@ const LogoInput = ({ }; return ( - + { + if (state === false) { + handleClose(); + } + }} + > { const { setLocalImage, goToStep, onClose } = useLogoInputContext('ComputerForm'); - const handleDragEnter = () => setDragOver(true); - const handleDragLeave = () => setDragOver(false); + const handleDragEnter = () => { + setDragOver(true); + }; + const handleDragLeave = () => { + setDragOver(false); + }; const handleClick: ButtonProps['onClick'] = (e) => { e.preventDefault(); @@ -367,15 +378,17 @@ const ComputerForm = () => { })} - + + + - + - + ) : null + } + title={formatMessage({ + id: 'content-releases.pages.Settings.releases.title', + defaultMessage: 'Releases', + })} + subtitle={formatMessage({ + id: 'content-releases.pages.Settings.releases.description', + defaultMessage: 'Create and manage content updates', + })} + /> + + + + {formatMessage({ + id: 'content-releases.pages.Settings.releases.preferences.title', + defaultMessage: 'Preferences', + })} + + + + + + + + + + ); + }} + + + + ); +}; + +const TimezoneDropdown = () => { + const permissions = useTypedSelector( + (state) => state.admin_app.permissions['settings']?.['releases'] + ); + const { + allowedActions: { canUpdate }, + } = useRBAC(permissions); + const { formatMessage } = useIntl(); + const { timezoneList } = getTimezones(new Date()); + const field = useField('defaultTimezone'); + return ( + + + {formatMessage({ + id: 'content-releases.pages.Settings.releases.timezone.label', + defaultMessage: 'Default timezone', + })} + + field.onChange('defaultTimezone', value)} + onTextValueChange={(value) => field.onChange('defaultTimezone', value)} + onClear={() => field.onChange('defaultTimezone', '')} + value={field.value} + disabled={!canUpdate} + > + {timezoneList.map((timezone) => ( + + {timezone.value.replace(/&/, ' ')} + + ))} + + + + + ); +}; + +/* ------------------------------------------------------------------------------------------------- + * ProtectedSettingsPage + * -----------------------------------------------------------------------------------------------*/ + +export const ProtectedReleasesSettingsPage = () => { + const permissions = useTypedSelector( + (state) => state.admin_app.permissions['settings']?.['releases']?.read + ); + + return ( + + + + ); +}; diff --git a/packages/core/content-releases/admin/src/pages/SettingsPage.tsx b/packages/core/content-releases/admin/src/pages/SettingsPage.tsx deleted file mode 100644 index 438c7f59c0..0000000000 --- a/packages/core/content-releases/admin/src/pages/SettingsPage.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { Form, Layouts, Page } from '@strapi/admin/strapi-admin'; -import { Button } from '@strapi/design-system'; -import { Check } from '@strapi/icons'; -import { useIntl } from 'react-intl'; - -export const SettingsPage = () => { - const { formatMessage } = useIntl(); - return ( - - - {formatMessage( - { id: 'Settings.PageTitle', defaultMessage: 'Settings - {name}' }, - { - name: 'Releases', - } - )} - - -
- } type="submit" size="L"> - {formatMessage({ - id: 'global.save', - defaultMessage: 'Save', - })} - - } - title={formatMessage({ - id: 'content-releases.pages.Settings.releases.title', - defaultMessage: 'Releases', - })} - subtitle={formatMessage({ - id: 'content-releases.pages.Settings.releases.description', - defaultMessage: 'Create and manage content updates', - })} - /> - -
TODO: define the Settings page content (not part of this US)
-
- -
-
- ); -}; diff --git a/packages/core/content-releases/admin/src/pages/tests/ReleasesSettingsPage.test.tsx b/packages/core/content-releases/admin/src/pages/tests/ReleasesSettingsPage.test.tsx new file mode 100644 index 0000000000..ff4d38e5ff --- /dev/null +++ b/packages/core/content-releases/admin/src/pages/tests/ReleasesSettingsPage.test.tsx @@ -0,0 +1,106 @@ +import { useRBAC } from '@strapi/admin/strapi-admin'; +import { render, server, screen } from '@tests/utils'; +import { rest } from 'msw'; + +import { useTypedSelector } from '../../modules/hooks'; +import { ProtectedReleasesSettingsPage } from '../ReleasesSettingsPage'; + +jest.mock('@strapi/admin/strapi-admin', () => ({ + ...jest.requireActual('@strapi/admin/strapi-admin'), + useRBAC: jest.fn(() => ({ + isLoading: false, + allowedActions: { canRead: false, canUpdate: false }, + })), +})); + +jest.mock('../../modules/hooks', () => ({ + ...jest.requireActual('../../modules/hooks'), + useTypedSelector: jest.fn(() => []), +})); + +describe('Releases Settings page', () => { + afterEach(() => { + jest.clearAllMocks(); + }); + + it('renders the no permissions content if you do not have read permission', async () => { + // @ts-expect-error – mocking + useRBAC.mockImplementation(() => ({ + isLoading: false, + allowedActions: { canRead: false, canUpdate: false }, + })); + + render(); + + expect( + screen.getByText("You don't have the permissions to access that content") + ).toBeInTheDocument(); + }); + + it('renders the settings page with read permission', async () => { + // @ts-expect-error – mocking + useRBAC.mockImplementation(() => ({ + isLoading: false, + allowedActions: { canRead: true, canUpdate: false }, + })); + // @ts-expect-error – mocking + useTypedSelector.mockImplementation(() => [ + { + action: 'plugin::content-releases.settings.read', + subject: null, + }, + ]); + server.use( + rest.get('/content-releases/settings', (req, res, ctx) => + res( + ctx.json({ + data: { + defaultTimezone: null, + }, + }) + ) + ) + ); + + render(); + + const title = await screen.findByRole('heading', { name: 'Releases' }); + expect(title).toBeInTheDocument(); + + const saveButton = screen.queryByRole('button', { name: 'Save' }); + expect(saveButton).not.toBeInTheDocument(); + + const defaultTimezoneCombobox = screen.getByRole('combobox', { name: 'Default timezone' }); + expect(defaultTimezoneCombobox).toBeDisabled(); + }); + + it('renders the settings page with read and update permissions', async () => { + // @ts-expect-error – mocking + useRBAC.mockImplementation(() => ({ + isLoading: false, + allowedActions: { canRead: true, canUpdate: true }, + })); + server.use( + rest.get('/content-releases/settings', (req, res, ctx) => + res( + ctx.json({ + data: { + defaultTimezone: '', + }, + }) + ) + ) + ); + + render(); + + const title = await screen.findByRole('heading', { name: 'Releases' }); + expect(title).toBeInTheDocument(); + + const saveButton = screen.getByRole('button', { name: 'Save' }); + expect(saveButton).toBeInTheDocument(); + + const defaultTimezoneCombobox = screen.getByRole('combobox', { name: 'Default timezone' }); + expect(defaultTimezoneCombobox).toBeEnabled(); + }); +}); diff --git a/packages/core/content-releases/admin/src/services/release.ts b/packages/core/content-releases/admin/src/services/release.ts index bb54484a3d..a3139342a1 100644 --- a/packages/core/content-releases/admin/src/services/release.ts +++ b/packages/core/content-releases/admin/src/services/release.ts @@ -21,6 +21,7 @@ import type { PublishRelease, MapEntriesToReleases, } from '../../../shared/contracts/releases'; +import type { GetSettings, UpdateSettings } from '../../../shared/contracts/settings'; import type { EndpointDefinition } from '@reduxjs/toolkit/query'; export interface GetReleasesQueryParams { @@ -78,7 +79,7 @@ const extendInvalidatesTags = ( const releaseApi = adminApi .enhanceEndpoints({ - addTagTypes: ['Release', 'ReleaseAction', 'EntriesInRelease'], + addTagTypes: ['Release', 'ReleaseAction', 'EntriesInRelease', 'ReleaseSettings'], endpoints: { updateDocument(endpoint: AnyEndpointDefinition) { extendInvalidatesTags(endpoint, [ @@ -355,6 +356,20 @@ const releaseApi = adminApi }, providesTags: [{ type: 'EntriesInRelease' }], }), + getReleaseSettings: build.query({ + query: () => '/content-releases/settings', + providesTags: [{ type: 'ReleaseSettings' }], + }), + updateReleaseSettings: build.mutation({ + query(data) { + return { + url: '/content-releases/settings', + method: 'PUT', + data, + }; + }, + invalidatesTags: (result, error, arg) => [{ type: 'ReleaseSettings' }], + }), }; }, }); @@ -373,6 +388,8 @@ const { useDeleteReleaseActionMutation, useDeleteReleaseMutation, useGetMappedEntriesInReleasesQuery, + useGetReleaseSettingsQuery, + useUpdateReleaseSettingsMutation, } = releaseApi; export { @@ -389,5 +406,7 @@ export { useDeleteReleaseActionMutation, useDeleteReleaseMutation, useGetMappedEntriesInReleasesQuery, + useGetReleaseSettingsQuery, + useUpdateReleaseSettingsMutation, releaseApi, }; diff --git a/packages/core/content-releases/admin/src/translations/en.json b/packages/core/content-releases/admin/src/translations/en.json index 08b7644bff..ecd795558e 100644 --- a/packages/core/content-releases/admin/src/translations/en.json +++ b/packages/core/content-releases/admin/src/translations/en.json @@ -79,5 +79,9 @@ "pages.ReleaseDetails.groupBy.option.content-type": "Content-Types", "pages.ReleaseDetails.groupBy.option.locales": "Locales", "pages.ReleaseDetails.groupBy.option.actions": "Actions", - "pages.ReleaseDetails.header-subtitle.scheduled": "Scheduled for {date} at {time} ({offset})" + "pages.ReleaseDetails.header-subtitle.scheduled": "Scheduled for {date} at {time} ({offset})", + "pages.Settings.releases.title": "Releases", + "pages.Settings.releases.description": "Create and manage content updates", + "pages.Settings.releases.timezone.label": "Default timezone", + "pages.Settings.releases.setting.default-timezone-notification-success": "Default timezone updated." } diff --git a/packages/core/content-releases/admin/src/utils/time.ts b/packages/core/content-releases/admin/src/utils/time.ts index 59bf4e586a..7fc62983d1 100644 --- a/packages/core/content-releases/admin/src/utils/time.ts +++ b/packages/core/content-releases/admin/src/utils/time.ts @@ -23,3 +23,25 @@ export const getTimezoneOffset = (timezone: string, date: Date) => { return ''; } }; + +interface ITimezoneOption { + offset: string; + value: string; +} + +export const getTimezones = (selectedDate: Date) => { + const timezoneList: ITimezoneOption[] = Intl.supportedValuesOf('timeZone').map((timezone) => { + // Timezone will be in the format GMT${OFFSET} where offset could be nothing, + // a four digit string e.g. +05:00 or -08:00 + const utcOffset = getTimezoneOffset(timezone, selectedDate); + + // Offset and timezone are concatenated with '&', so to split and save the required timezone in DB + return { offset: utcOffset, value: `${utcOffset}&${timezone}` } satisfies ITimezoneOption; + }); + + const systemTimezone = timezoneList.find( + (timezone) => timezone.value.split('&')[1] === Intl.DateTimeFormat().resolvedOptions().timeZone + ); + + return { timezoneList, systemTimezone }; +}; diff --git a/packages/core/content-releases/admin/tests/utils.tsx b/packages/core/content-releases/admin/tests/utils.tsx index 94844ee1d0..a7fb619ddf 100644 --- a/packages/core/content-releases/admin/tests/utils.tsx +++ b/packages/core/content-releases/admin/tests/utils.tsx @@ -10,7 +10,7 @@ import { type RenderOptions, } from '@strapi/admin/strapi-admin/test'; -import { PERMISSIONS } from '../src/constants'; +import { PERMISSIONS, PERMISSIONS_SETTINGS } from '../src/constants'; const render = ( ui: React.ReactElement, @@ -18,7 +18,9 @@ const render = ( ): ReturnType => renderAdmin(ui, { ...options, - providerOptions: { permissions: Object.values(PERMISSIONS).flat() }, + providerOptions: { + permissions: Object.values({ ...PERMISSIONS, ...PERMISSIONS_SETTINGS }).flat(), + }, }); export { render, waitFor, act, screen, server }; diff --git a/packages/core/content-releases/package.json b/packages/core/content-releases/package.json index 50fcfaf779..c0f5a9b9bc 100644 --- a/packages/core/content-releases/package.json +++ b/packages/core/content-releases/package.json @@ -1,6 +1,6 @@ { "name": "@strapi/content-releases", - "version": "5.0.0-beta.12", + "version": "5.0.0-rc.1", "description": "Strapi plugin for organizing and releasing content", "repository": { "type": "git", @@ -55,11 +55,11 @@ }, "dependencies": { "@reduxjs/toolkit": "1.9.7", - "@strapi/database": "5.0.0-beta.12", + "@strapi/database": "5.0.0-rc.1", "@strapi/design-system": "2.0.0-beta.6", "@strapi/icons": "2.0.0-beta.6", "@strapi/types": "workspace:*", - "@strapi/utils": "5.0.0-beta.12", + "@strapi/utils": "5.0.0-rc.1", "date-fns": "2.30.0", "date-fns-tz": "2.0.1", "formik": "2.4.5", @@ -70,9 +70,9 @@ "yup": "0.32.9" }, "devDependencies": { - "@strapi/admin": "5.0.0-beta.12", - "@strapi/admin-test-utils": "5.0.0-beta.12", - "@strapi/content-manager": "5.0.0-beta.12", + "@strapi/admin": "5.0.0-rc.1", + "@strapi/admin-test-utils": "5.0.0-rc.1", + "@strapi/content-manager": "5.0.0-rc.1", "@strapi/pack-up": "5.0.0", "@testing-library/react": "15.0.7", "@testing-library/user-event": "14.5.2", diff --git a/packages/core/content-releases/shared/contracts/settings.ts b/packages/core/content-releases/shared/contracts/settings.ts index 04025763aa..f11662c566 100644 --- a/packages/core/content-releases/shared/contracts/settings.ts +++ b/packages/core/content-releases/shared/contracts/settings.ts @@ -7,7 +7,7 @@ import { errors } from '@strapi/utils'; import { Utils } from '@strapi/types'; export interface Settings { - defaultTimezone: string | null; + defaultTimezone: string | null | undefined; } /** diff --git a/packages/core/content-type-builder/LICENSE b/packages/core/content-type-builder/LICENSE index 638baf882b..d82875fe30 100644 --- a/packages/core/content-type-builder/LICENSE +++ b/packages/core/content-type-builder/LICENSE @@ -2,7 +2,21 @@ Copyright (c) 2015-present Strapi Solutions SAS Portions of the Strapi software are licensed as follows: -* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined in "ee/LICENSE". +* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined below. + +Enterprise License + +If you or the company you represent has entered into a written agreement referencing the Enterprise Edition of the Strapi source code available at +https://github.com/strapi/strapi, then such agreement applies to your use of the Enterprise Edition of the Strapi Software. If you or the company you +represent is using the Enterprise Edition of the Strapi Software in connection with a subscription to our cloud offering, then the agreement you have +agreed to with respect to our cloud offering and the licenses included in such agreement apply to your use of the Enterprise Edition of the Strapi Software. +Otherwise, the Strapi Enterprise Software License Agreement (found here https://strapi.io/enterprise-terms) applies to your use of the Enterprise Edition of the Strapi Software. + +BY ACCESSING OR USING THE ENTERPRISE EDITION OF THE STRAPI SOFTWARE, YOU ARE AGREEING TO BE BOUND BY THE RELEVANT REFERENCED AGREEMENT. +IF YOU ARE NOT AUTHORIZED TO ACCEPT THESE TERMS ON BEHALF OF THE COMPANY YOU REPRESENT OR IF YOU DO NOT AGREE TO ALL OF THE RELEVANT TERMS AND CONDITIONS REFERENCED AND YOU +HAVE NOT OTHERWISE EXECUTED A WRITTEN AGREEMENT WITH STRAPI, YOU ARE NOT AUTHORIZED TO ACCESS OR USE OR ALLOW ANY USER TO ACCESS OR USE ANY PART OF +THE ENTERPRISE EDITION OF THE STRAPI SOFTWARE. YOUR ACCESS RIGHTS ARE CONDITIONAL ON YOUR CONSENT TO THE RELEVANT REFERENCED TERMS TO THE EXCLUSION OF ALL OTHER TERMS; +IF THE RELEVANT REFERENCED TERMS ARE CONSIDERED AN OFFER BY YOU, ACCEPTANCE IS EXPRESSLY LIMITED TO THE RELEVANT REFERENCED TERMS. * All software outside of the above-mentioned directories or restrictions above is available under the "MIT Expat" license as set forth below. @@ -18,5 +32,6 @@ furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/core/content-type-builder/admin/src/components/AutoReloadOverlayBlocker.tsx b/packages/core/content-type-builder/admin/src/components/AutoReloadOverlayBlocker.tsx index 81e41e3fcb..6562a4d0e9 100644 --- a/packages/core/content-type-builder/admin/src/components/AutoReloadOverlayBlocker.tsx +++ b/packages/core/content-type-builder/admin/src/components/AutoReloadOverlayBlocker.tsx @@ -77,7 +77,7 @@ const AutoReloadOverlayBlockerProvider = ({ children }: AutoReloadOverlayBlocker let description = { id: config?.description || 'components.OverlayBlocker.description', defaultMessage: - "You're using a feature that needs the server to restart. Please wait until the server is up.", + "You're using a feature that needs the server to restart. The page will reload automatically.", }; let title = { diff --git a/packages/core/content-type-builder/admin/src/components/CheckboxWithNumberField.tsx b/packages/core/content-type-builder/admin/src/components/CheckboxWithNumberField.tsx index 428a89373e..e2615171b9 100644 --- a/packages/core/content-type-builder/admin/src/components/CheckboxWithNumberField.tsx +++ b/packages/core/content-type-builder/admin/src/components/CheckboxWithNumberField.tsx @@ -1,5 +1,3 @@ -import { useState } from 'react'; - import { Box, Checkbox, Field, Flex, NumberInput, TextInput } from '@strapi/design-system'; import { useIntl } from 'react-intl'; @@ -23,7 +21,6 @@ export const CheckboxWithNumberField = ({ value = null, }: CheckboxWithNumberFieldProps) => { const { formatMessage } = useIntl(); - const [showInput, setShowInput] = useState(!!value || value === 0); const label = intlLabel.id ? formatMessage( { id: intlLabel.id, defaultMessage: intlLabel.defaultMessage }, @@ -46,13 +43,12 @@ export const CheckboxWithNumberField = ({ const nextValue = value ? initValue : null; onChange({ target: { name, value: nextValue } }); - setShowInput((prev) => !prev); }} - checked={showInput} + checked={value !== null} > {label} - {showInput && ( + {value !== null && ( {type === 'text' ? ( @@ -70,7 +66,7 @@ export const CheckboxWithNumberField = ({ aria-label={label} disabled={disabled} onValueChange={(value: any) => { - onChange({ target: { name, value, type } }); + onChange({ target: { name, value: value ?? 0, type } }); }} value={value || 0} /> diff --git a/packages/core/content-type-builder/admin/src/components/ContentTypeBuilderNav/ContentTypeBuilderNav.tsx b/packages/core/content-type-builder/admin/src/components/ContentTypeBuilderNav/ContentTypeBuilderNav.tsx index 1f6cdd6206..4b433c5dc6 100644 --- a/packages/core/content-type-builder/admin/src/components/ContentTypeBuilderNav/ContentTypeBuilderNav.tsx +++ b/packages/core/content-type-builder/admin/src/components/ContentTypeBuilderNav/ContentTypeBuilderNav.tsx @@ -23,22 +23,19 @@ export const ContentTypeBuilderNav = () => { const { menu, searchValue, onSearchChange } = useContentTypeBuilderMenu(); const { formatMessage } = useIntl(); + const pluginName = formatMessage({ + id: getTrad('plugin.name'), + defaultMessage: 'Content-Type Builder', + }); + return ( - + onSearchChange('')} onChange={(e) => onSearchChange(e.target.value)} - label={formatMessage({ - id: `${getTrad('plugin.name')}`, - defaultMessage: 'Content-Types Builder', - })} + label={pluginName} searchLabel={formatMessage({ id: 'global.search', defaultMessage: 'Search', @@ -53,7 +50,7 @@ export const ContentTypeBuilderNav = () => { defaultMessage: section.title.defaultMessage, })} collapsable - badgeLabel={section.links.length.toString()} + badgeLabel={section.linksCount.toString()} > {section.links.map((link) => { if (link.links) { diff --git a/packages/core/content-type-builder/admin/src/components/ContentTypeBuilderNav/tests/__snapshots__/index.test.tsx.snap b/packages/core/content-type-builder/admin/src/components/ContentTypeBuilderNav/tests/__snapshots__/index.test.tsx.snap index a324d050d1..992b6076bf 100644 --- a/packages/core/content-type-builder/admin/src/components/ContentTypeBuilderNav/tests/__snapshots__/index.test.tsx.snap +++ b/packages/core/content-type-builder/admin/src/components/ContentTypeBuilderNav/tests/__snapshots__/index.test.tsx.snap @@ -405,7 +405,7 @@ exports[` renders and matches the snapshot 1`] = ` class="c0" >