Merge branch 'develop' into v5/main (#20566)

* Merge branch 'develop' into v5/main

* fix: missing dependency

* fix: yarn lock

* fix: prettier

* fix(cloud-cli): update types and structure for v5 (#20567)

* chore: skip cloud deployment until ready

* fix: webhook tests

* chore: revert schema changes

* fix: versions

---------

Co-authored-by: Nathan Pichon <nathan.pichon@strapi.io>
This commit is contained in:
Marc Roig 2024-06-21 13:38:56 +02:00 committed by GitHub
parent b8b91d16eb
commit 099cbbec8e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
62 changed files with 3153 additions and 68 deletions

2
.gitignore vendored
View File

@ -156,4 +156,4 @@ tests/cli/.env
# Strapi
############################
examples/**/types/generated
.nx/cache
.nx/cache

View File

@ -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",

View File

@ -0,0 +1,4 @@
node_modules/
.eslintrc.js
dist/
bin/

View File

@ -0,0 +1,4 @@
module.exports = {
root: true,
extends: ['custom/back/typescript'],
};

View File

@ -0,0 +1,22 @@
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 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.

View File

@ -0,0 +1,3 @@
# Cloud CLI
This package includes the `cloud` CLI to manage Strapi projects on the cloud.

View File

@ -0,0 +1,7 @@
#!/usr/bin/env node
'use strict';
const { runStrapiCloudCommand } = require('../dist/bin');
runStrapiCloudCommand(process.argv);

View File

@ -0,0 +1,79 @@
{
"name": "@strapi/cloud-cli",
"version": "5.0.0-beta.14",
"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-beta.14",
"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-beta.14",
"tsconfig": "5.0.0-beta.14"
},
"engines": {
"node": ">=18.0.0 <=20.x.x",
"npm": ">=6.0.0"
}
}

View File

@ -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',
});

View File

@ -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 };

View File

@ -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'),
};

View File

@ -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<LocalConfig> {
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 });
}

View File

@ -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<ProjectAnswers>(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);
}
};

View File

@ -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;

View File

@ -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;

View File

@ -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;
}
}
};

View File

@ -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;

View File

@ -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;

View File

@ -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';

View File

@ -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<boolean> => {
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;
};

View File

@ -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;

View File

@ -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;

View File

@ -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);
}
};

View File

@ -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;

View File

@ -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,
};

View File

@ -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 };

View File

@ -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<ProjectInfos, 'id'>;
export type DeployResponse = {
build_id: string;
image: string;
};
export type TrackPayload = Record<string, unknown>;
export interface CloudApiService {
deploy(
deployInput: {
filePath: string;
project: { name: string };
},
{
onUploadProgress,
}: {
onUploadProgress: (progressEvent: { loaded: number; total?: number }) => void;
}
): Promise<AxiosResponse<DeployResponse>>;
createProject(projectInput: ProjectInput): Promise<{
data: ProjectInfos;
status: number;
}>;
getUserInfo(): Promise<AxiosResponse>;
config(): Promise<AxiosResponse<CloudCliConfig>>;
listProjects(): Promise<AxiosResponse<ProjectInfos[]>>;
track(event: string, payload?: TrackPayload): Promise<AxiosResponse<void>>;
}
export async function cloudApiFactory(token?: string): Promise<CloudApiService> {
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<AxiosResponse<CloudCliConfig>> {
return axiosCloudAPI.get('/config');
},
listProjects() {
return axiosCloudAPI.get<ProjectInfos[]>('/projects');
},
track(event, payload = {}) {
return axiosCloudAPI.post<void>('/track', {
event,
payload,
});
},
};
}

View File

@ -0,0 +1,4 @@
export { cloudApiFactory } from './cli-api';
export * as local from './strapi-info-save';
export { tokenServiceFactory } from './token';
export { createLogger } from './logger';

View File

@ -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<ora.Ora, 'succeed' | 'fail' | 'start' | 'text' | 'isSpinning'>;
progressBar: (
totalSize: number,
text: string
) => Pick<cliProgress.SingleBar, 'start' | 'stop' | 'update'>;
}
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 };

View File

@ -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();
}
};
};
}

View File

@ -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<LocalSave> {
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' });
}

View File

@ -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<void> {
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<void>((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,
};
}

View File

@ -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<DistinctQuestion<ProjectAnswers>>;
defaults: Partial<ProjectAnswers>;
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<Command | void>;
export type StrapiCloudCommandInfo = {
name: string;
description: string;
command: StrapiCloudCommand;
action: (ctx: CLIContext) => Promise<unknown>;
};
export type * from './services/cli-api';

View File

@ -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<void> => {
const ignorePatterns = readGitignore(folderToCompress);
const filesToCompress = getFiles(folderToCompress, ignorePatterns);
return tar.c(
{
gzip: true,
file: path.resolve(storagePath, filename),
},
filesToCompress
);
};
export { compressFilesToTar, isIgnoredFile };

View File

@ -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<unknown>) =>
(...args: unknown[]) => {
assertCwdContainsStrapiProject(name);
Promise.resolve()
.then(() => {
return action(...args);
})
.catch((error) => {
console.error(error);
process.exit(1);
});
};
export { runAction };

View File

@ -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<string, yup.SchemaOf<string> | yup.SchemaOf<Export>>
)
: undefined
)
.optional()
),
});
type PackageJson = yup.Asserts<typeof packageJsonSchema>;
/**
* @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<PackageJson> => {
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<PackageJson> => {
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 };

View File

@ -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'),
]);
});
});

View File

@ -0,0 +1,8 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "dist"
},
"include": ["src"],
"exclude": ["node_modules", "**/__tests__/**"]
}

View File

@ -0,0 +1,3 @@
{
"extends": "./tsconfig.json"
}

View File

@ -0,0 +1,5 @@
{
"extends": "tsconfig/base.json",
"include": ["src", "packup.config.ts"],
"exclude": ["node_modules"]
}

View File

@ -43,7 +43,9 @@
"watch": "pack-up watch"
},
"dependencies": {
"@strapi/cloud-cli": "5.0.0-beta.14",
"@strapi/generate-new": "5.0.0-beta.14",
"chalk": "4.1.2",
"commander": "8.3.0",
"inquirer": "8.2.5"
},

View File

@ -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<void> {
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);
}
}
}
}

View File

@ -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 <dbclient>', 'Database client')
.option('--dbhost <dbhost>', 'Database host')
.option('--dbport <dbport>', 'Database port')
@ -56,6 +60,12 @@ 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,

View File

@ -5,6 +5,7 @@ export interface Options {
quickstart?: boolean;
run?: boolean;
dbclient?: DBClient;
skipCloud?: boolean;
dbhost?: string;
dbport?: string;
dbname?: string;

View File

@ -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;
}

View File

@ -59,9 +59,9 @@ const FieldWrapper = styled(Field.Root)`
const delays = {
postResponse: 90 * 24 * 60 * 60 * 1000, // 90 days in ms
postFirstDismissal: 7 * 24 * 60 * 60 * 1000, // 7 days in ms
postFirstDismissal: 14 * 24 * 60 * 60 * 1000, // 14 days in ms
postSubsequentDismissal: 90 * 24 * 60 * 60 * 1000, // 90 days in ms
display: 5 * 60 * 1000, // 5 minutes in ms
display: 30 * 60 * 1000, // 30 minutes in ms
};
const ratingArray = [...Array(11).keys()];

View File

@ -239,8 +239,8 @@ describe('NPS survey', () => {
it('respects the delay after first user dismissal', async () => {
const initialDate = new Date('2020-01-01');
const withinDelay = new Date('2020-01-04');
const beyondDelay = new Date('2020-01-08');
const withinDelay = new Date('2020-01-08');
const beyondDelay = new Date('2020-01-15');
localStorageMock.getItem.mockImplementation((key) => {
if (key === NPS_KEY) {

View File

@ -45,6 +45,13 @@ const EditPage = () => {
_unstableFormatAPIError: formatAPIError,
_unstableFormatValidationErrors: formatValidationErrors,
} = useAPIErrorHandler();
/**
* Prevents the notifications from showing up twice because the function identity
* coming from the helper plugin is not stable
*/
// eslint-disable-next-line react-hooks/exhaustive-deps
const stableFormatAPIError = React.useCallback(formatAPIError, []);
const [isTriggering, setIsTriggering] = React.useState(false);
const [triggerResponse, setTriggerResponse] = React.useState<TriggerWebhook.Response['data']>();
@ -59,10 +66,10 @@ const EditPage = () => {
if (error) {
toggleNotification({
type: 'danger',
message: formatAPIError(error),
message: stableFormatAPIError(error),
});
}
}, [error, toggleNotification, formatAPIError]);
}, [error, toggleNotification, stableFormatAPIError]);
const handleTriggerWebhook = async () => {
try {

View File

@ -15,15 +15,16 @@ const useWebhooks = (
queryArgs?: Parameters<typeof useGetWebhooksQuery>[1]
) => {
const { data: webhooks, isLoading, error } = useGetWebhooksQuery(args, queryArgs);
const [createWebhook] = useCreateWebhookMutation();
const [updateWebhook] = useUpdateWebhookMutation();
const [createWebhook, { error: createError }] = useCreateWebhookMutation();
const [updateWebhook, { error: updateError }] = useUpdateWebhookMutation();
const [triggerWebhook] = useTriggerWebhookMutation();
const [deleteManyWebhooks] = useDeleteManyWebhooksMutation();
return {
webhooks: webhooks as GetWebhooks.Response['data'] | undefined,
isLoading: isLoading as boolean,
error: error as BaseQueryError | SerializedError,
error: (error || createError || updateError) as BaseQueryError | SerializedError,
createWebhook,
updateWebhook,
triggerWebhook,

View File

@ -104,6 +104,7 @@
"immer": "9.0.21",
"inquirer": "8.2.5",
"invariant": "^2.2.4",
"is-localhost-ip": "2.0.0",
"jsonwebtoken": "9.0.0",
"koa": "2.15.2",
"koa-compose": "4.1.0",
@ -117,6 +118,7 @@
"p-map": "4.0.0",
"passport-local": "1.0.0",
"pluralize": "8.0.0",
"punycode": "2.3.1",
"qs": "6.11.1",
"react-dnd": "16.0.1",
"react-dnd-html5-backend": "16.0.1",
@ -152,6 +154,7 @@
"@types/markdown-it-footnote": "3.0.3",
"@types/passport-local": "1.0.36",
"@types/pluralize": "0.0.32",
"@types/punycode": "2.1.4",
"@types/react-window": "1.8.8",
"@types/sanitize-html": "2.11.0",
"@vitejs/plugin-react-swc": "3.6.0",

View File

@ -1,6 +1,10 @@
import isLocalhostIp from 'is-localhost-ip';
// Regular import references a deprecated node module,
// See https://www.npmjs.com/package/punycode.js#installation
import punycode from 'punycode/';
import type { Context } from 'koa';
import _ from 'lodash';
import { yup, validateYupSchema } from '@strapi/utils';
import type { Modules } from '@strapi/types';
@ -21,7 +25,27 @@ const urlRegex =
const webhookValidator = yup
.object({
name: yup.string().required(),
url: yup.string().matches(urlRegex, 'url must be a valid URL').required(),
url: yup
.string()
.matches(urlRegex, 'url must be a valid URL')
.required()
.test(
'is-public-url',
"Url is not supported because it isn't reachable over the public internet",
async (url) => {
if (process.env.NODE_ENV !== 'production') {
return true;
}
try {
const parsedUrl = new URL(punycode.toASCII(url!));
const isLocalUrl = await isLocalhostIp(parsedUrl.hostname);
return !isLocalUrl;
} catch {
return false;
}
}
),
headers: yup.lazy((data) => {
if (typeof data !== 'object') {
return yup.object().required();

View File

@ -110,6 +110,7 @@
"dependencies": {
"@pmmmwh/react-refresh-webpack-plugin": "0.5.11",
"@strapi/admin": "5.0.0-beta.14",
"@strapi/cloud-cli": "5.0.0-beta.14",
"@strapi/content-manager": "5.0.0-beta.14",
"@strapi/content-releases": "5.0.0-beta.14",
"@strapi/content-type-builder": "5.0.0-beta.14",
@ -135,6 +136,8 @@
"browserslist-to-esbuild": "1.2.0",
"chalk": "4.1.2",
"chokidar": "3.5.3",
"ci-info": "3.8.0",
"cli-progress": "3.12.0",
"cli-table3": "0.6.2",
"commander": "8.3.0",
"concurrently": "8.2.2",

View File

@ -1,3 +1,5 @@
// import { buildStrapiCloudCommands as cloudCommands } from '@strapi/cloud-cli';
import { command as createAdminUser } from './admin/create-user';
import { command as resetAdminUserPassword } from './admin/reset-user-password';
import { command as listComponents } from './components/list';
@ -54,4 +56,9 @@ export const commands: StrapiCommand[] = [
exportCommand,
importCommand,
transferCommand,
/**
* Cloud
*/
// TODO V5: Uncomment when cloud-cli is ready
// cloudCommands,
];

View File

@ -41,9 +41,9 @@ const createCLI = async (argv: string[], command = new Command()) => {
} satisfies CLIContext;
// Load all commands
strapiCommands.forEach((commandFactory) => {
for (const commandFactory of strapiCommands) {
try {
const subCommand = commandFactory({ command, argv, ctx });
const subCommand = await commandFactory({ command, argv, ctx });
// Add this command to the Commander command object
if (subCommand) {
@ -52,7 +52,7 @@ const createCLI = async (argv: string[], command = new Command()) => {
} catch (e) {
console.error(`Failed to load command`, e);
}
});
}
// TODO v6: remove these deprecation notices
const deprecatedCommands = [

View File

@ -12,4 +12,4 @@ export type StrapiCommand = (params: {
command: Command;
argv: string[];
ctx: CLIContext;
}) => void | Command;
}) => void | Command | Promise<void | Command>;

View File

@ -1,5 +1,6 @@
import chalk from 'chalk';
import ora from 'ora';
import ora, { Ora } from 'ora';
import * as cliProgress from 'cli-progress';
export interface LoggerOptions {
silent?: boolean;
@ -12,12 +13,43 @@ export interface Logger {
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<ora.Ora, 'succeed' | 'fail' | 'start' | 'text'>;
spinner: (text: string) => Pick<ora.Ora, 'succeed' | 'fail' | 'start' | 'text' | 'isSpinning'>;
progressBar: (
totalSize: number,
text: string
) => Pick<cliProgress.SingleBar, 'start' | 'stop' | 'update'>;
}
const silentSpinner = {
succeed() {
return this;
},
fail() {
return this;
},
start() {
return this;
},
text: '',
isSpinning: false,
} as Ora;
const silentProgressBar = {
start() {
return this;
},
stop() {
return this;
},
update() {
return this;
},
} as unknown as cliProgress.SingleBar;
const createLogger = (options: LoggerOptions = {}): Logger => {
const { silent = false, debug = false, timestamp = true } = options;
@ -62,6 +94,17 @@ const createLogger = (options: LoggerOptions = {}): Logger => {
console.info(chalk.blue(`${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args);
},
success(...args) {
if (silent) {
return;
}
console.info(
chalk.green(`[SUCCESS]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`),
...args
);
},
warn(...args) {
state.warning += 1;
@ -88,25 +131,31 @@ const createLogger = (options: LoggerOptions = {}): Logger => {
);
},
// @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: '',
};
return silentSpinner;
}
return ora(text);
},
progressBar(totalSize: number, text: string) {
if (silent) {
return silentProgressBar;
}
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;
},
};
};

View File

@ -172,6 +172,9 @@ export default async function createProject(scope: Scope) {
console.log(` ${cmd} build`);
console.log(' Build Strapi admin panel.');
console.log();
console.log(` ${cmd} deploy`);
console.log(' Deploy Strapi project.');
console.log();
console.log(` ${cmd} strapi`);
console.log(` Display all available commands.`);
console.log();

View File

@ -14,6 +14,8 @@ import createProject from './create-project';
import { addDatabaseDependencies } from './utils/database';
export type { Options };
export { default as checkInstallPath } from './utils/check-install-path';
export { default as checkRequirements } from './utils/check-requirements';
const packageJson = JSON.parse(readFileSync(resolve(__dirname, '../package.json'), 'utf8'));
@ -32,7 +34,7 @@ export const generateNewApp = async (options: Options) => {
database: options.database,
runApp: options.runApp ?? false,
isQuickstart: options.isQuickstart,
// use pacakge version as strapiVersion (all packages have the same version);
// use package version as strapiVersion (all packages have the same version);
strapiVersion: packageJson.version,
template: options.template,
packageJsonStrapi: {

View File

@ -128,3 +128,4 @@ exports
dist
build
.strapi-updater.json
.strapi-cloud.json

View File

@ -16,6 +16,7 @@ export default async (scope: Scope) => {
start: 'strapi start',
build: 'strapi build',
strapi: 'strapi',
deploy: 'strapi deploy',
},
devDependencies: scope.devDependencies,
dependencies: scope.dependencies,

View File

@ -0,0 +1,139 @@
import { omit } from 'lodash';
import type { Webhook, LoadedStrapi } from '@strapi/types';
import { createStrapiInstance } from 'api-tests/strapi';
import { createAuthRequest } from 'api-tests/request';
let rq;
let strapi: LoadedStrapi;
const defaultWebhook = {
name: 'test',
url: 'https://example.com',
headers: {},
events: [],
} satisfies Omit<Webhook, 'id' | 'isEnabled'>;
const createWebhook = async (webhook: Partial<Webhook>) => {
const res = await rq({
url: '/admin/webhooks',
method: 'POST',
body: {
...defaultWebhook,
...webhook,
},
});
return {
status: res.statusCode,
webhook: res.body.data,
};
};
const updateWebhook = async (id: string, webhook: Partial<Webhook>) => {
const res = await rq({
url: `/admin/webhooks/${id}`,
method: 'PUT',
body: {
...defaultWebhook,
...webhook,
},
});
return {
status: res.statusCode,
webhook: res.body.data,
};
};
const deleteWebhook = async (id: string) => {
const res = await rq({
url: `/admin/webhooks/${id}`,
method: 'DELETE',
});
return {
status: res.statusCode,
webhook: res.body.data,
};
};
describe('Admin API Webhooks', () => {
// Initialization Actions
beforeAll(async () => {
strapi = await createStrapiInstance();
rq = await createAuthRequest({ strapi });
});
// Cleanup actions
afterAll(async () => {
await strapi.destroy();
});
test('Can create a webhook', async () => {
const { webhook, status } = await createWebhook({
url: 'https://example.com',
});
expect(status).toBe(201);
expect(webhook).toMatchObject({
id: expect.anything(),
...defaultWebhook,
url: 'https://example.com',
});
});
test('Can not create a webhook with a local url on production', async () => {
// change NODE_ENV to 'production' to test this
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'production';
const { status } = await createWebhook({ url: 'http://localhost:1337' });
const { status: statusInt } = await createWebhook({ url: '私の.家' });
process.env.NODE_ENV = originalNodeEnv;
expect(status).toBe(400);
expect(statusInt).toBe(400);
});
test('Can not create a webhook with an invalid url', async () => {
const { status } = await createWebhook({
url: 'invalid-url',
});
expect(status).toBe(400);
});
test('Can update a webhook', async () => {
const { webhook: createdWebhook } = await createWebhook({
url: 'https://example.com',
});
const { webhook, status } = await updateWebhook(createdWebhook.id, {
url: 'https://example.com/updated',
});
expect(status).toBe(200);
expect(webhook).toMatchObject({
id: createdWebhook.id,
...defaultWebhook,
url: 'https://example.com/updated',
});
});
test('Can delete a webhook', async () => {
const { webhook: createdWebhook } = await createWebhook({
url: 'https://example.com',
});
const { webhook, status } = await deleteWebhook(createdWebhook.id);
expect(status).toBe(200);
expect(webhook).toMatchObject({
id: createdWebhook.id,
url: 'https://example.com',
...defaultWebhook,
});
});
});

905
yarn.lock

File diff suppressed because it is too large Load Diff