🎥 Make videos programmatically with React
Visual Mode: Handle gracefully if Prettier is not available
Jonny Burger14eac760782c
diff --git a/packages/studio-server/src/codemods/duplicate-composition.ts b/packages/studio-server/src/codemods/duplicate-composition.tsindex e3ec6c641f..6f9eccdbfe 100644--- a/packages/studio-server/src/codemods/duplicate-composition.ts+++ b/packages/studio-server/src/codemods/duplicate-composition.ts@@ -3,31 +3,29 @@ import {parseAst, serializeAst} from './parse-ast';import type {Change} from './recast-mods';import {applyCodemod} from './recast-mods';-const getPrettier = async () => {+export const formatOutput = async (+ tsContent: string,+): Promise<{output: string; formatted: boolean}> => {+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports+ type PrettierType = typeof import('prettier');+ let prettier: PrettierType | null = null;+try {- return await import('prettier');+ prettier = await import('prettier');} catch {- throw new Error('Prettier cannot be found in the current project.');+ return {output: tsContent, formatted: false};}-};-export const formatOutput = async (tsContent: string) => {- const prettier = await getPrettier();-- const {format, resolveConfig, resolveConfigFile} = prettier;+ const {format, resolveConfig, resolveConfigFile} = prettier as PrettierType;const configFilePath = await resolveConfigFile();if (!configFilePath) {- throw new Error(- 'The Prettier config file was not found. For this feature, the "prettier" package must be installed and a .prettierrc file must exist.',- );+ return {output: tsContent, formatted: false};}const prettierConfig = await resolveConfig(configFilePath);if (!prettierConfig) {- throw new Error(- `The Prettier config at ${configFilePath} could not be read`,- );+ return {output: tsContent, formatted: false};}const newContents = await format(tsContent, {@@ -35,7 +33,7 @@ export const formatOutput = async (tsContent: string) => {filepath: 'test.tsx',});- return newContents;+ return {output: newContents, formatted: true};};export const parseAndApplyCodemod = ({diff --git a/packages/studio-server/src/codemods/update-default-props.ts b/packages/studio-server/src/codemods/update-default-props.tsindex 9830da0caa..df48e6e88e 100644--- a/packages/studio-server/src/codemods/update-default-props.ts+++ b/packages/studio-server/src/codemods/update-default-props.ts@@ -12,7 +12,7 @@ export const updateDefaultProps = async ({compositionId: string;newDefaultProps: Record<string, unknown>;enumPaths: EnumPath[];-}): Promise<Promise<Promise<Promise<string>>>> => {+}): Promise<{output: string; formatted: boolean}> => {const ast = parseAst(input);recast.types.visit(ast, {@@ -121,6 +121,8 @@ export const updateDefaultProps = async ({},});+ const finalFile = serializeAst(ast);+// 5: finally, format the file// eslint-disable-next-line @typescript-eslint/consistent-type-importstype PrettierType = typeof import('prettier');@@ -129,30 +131,26 @@ export const updateDefaultProps = async ({try {prettier = await import('prettier');} catch {- throw new Error('Prettier cannot be found in the current project.');+ return {output: finalFile, formatted: false};}const {format, resolveConfig, resolveConfigFile} = prettier as PrettierType;const configFilePath = await resolveConfigFile();if (!configFilePath) {- throw new Error('The Prettier config file was not found');+ return {output: finalFile, formatted: false};}const prettierConfig = await resolveConfig(configFilePath);if (!prettierConfig) {- throw new Error(- 'The Prettier config file was not found. For this feature, the "prettier" package must be installed and a .prettierrc file must exist.',- );+ return {output: finalFile, formatted: false};}- const finalfile = serializeAst(ast);-- const prettified = await format(finalfile, {+ const prettified = await format(finalFile, {...prettierConfig,filepath: 'test.tsx',plugins: [],endOfLine: 'auto',});- return prettified;+ return {output: prettified, formatted: true};};diff --git a/packages/studio-server/src/codemods/update-sequence-props.ts b/packages/studio-server/src/codemods/update-sequence-props.tsindex e5a12d2406..d07a7cad4f 100644--- a/packages/studio-server/src/codemods/update-sequence-props.ts+++ b/packages/studio-server/src/codemods/update-sequence-props.ts@@ -19,7 +19,7 @@ export const updateSequenceProps = async ({value: unknown;enumPaths: EnumPath[];defaultValue: unknown | null;-}): Promise<{output: string; oldValueString: string}> => {+}): Promise<{output: string; oldValueString: string; formatted: boolean}> => {const ast = parseAst(input);let found = false;let oldValueString = '';@@ -123,6 +123,8 @@ export const updateSequenceProps = async ({);}+ const finalFile = serializeAst(ast);+// eslint-disable-next-line @typescript-eslint/consistent-type-importstype PrettierType = typeof import('prettier');let prettier: PrettierType | null = null;@@ -130,30 +132,26 @@ export const updateSequenceProps = async ({try {prettier = await import('prettier');} catch {- throw new Error('Prettier cannot be found in the current project.');+ return {output: finalFile, oldValueString, formatted: false};}const {format, resolveConfig, resolveConfigFile} = prettier as PrettierType;const configFilePath = await resolveConfigFile();if (!configFilePath) {- throw new Error('The Prettier config file was not found');+ return {output: finalFile, oldValueString, formatted: false};}const prettierConfig = await resolveConfig(configFilePath);if (!prettierConfig) {- throw new Error(- 'The Prettier config file was not found. For this feature, the "prettier" package must be installed and a .prettierrc file must exist.',- );+ return {output: finalFile, oldValueString, formatted: false};}- const finalFile = serializeAst(ast);-const prettified = await format(finalFile, {...prettierConfig,filepath: 'test.tsx',plugins: [],endOfLine: 'auto',});- return {output: prettified, oldValueString};+ return {output: prettified, oldValueString, formatted: true};};diff --git a/packages/studio-server/src/preview-server/routes/apply-codemod.ts b/packages/studio-server/src/preview-server/routes/apply-codemod.tsindex 0d69761aa1..7dba75decb 100644--- a/packages/studio-server/src/preview-server/routes/apply-codemod.ts+++ b/packages/studio-server/src/preview-server/routes/apply-codemod.ts@@ -13,6 +13,8 @@ import type {ApiHandler} from '../api-types';import {getProjectInfo} from '../project-info';import {checkIfTypeScriptFile} from './can-update-default-props';+let warnedAboutPrettier = false;+export const applyCodemodHandler: ApiHandler<ApplyCodemodRequest,ApplyCodemodResponse@@ -32,20 +34,29 @@ export const applyCodemodHandler: ApiHandler<codeMod: codemod,input,});- const formatted = await formatOutput(newContents);+ const {output, formatted} = await formatOutput(newContents);const diff = simpleDiff({oldLines: input.split('\n'),- newLines: formatted.split('\n'),+ newLines: output.split('\n'),});if (!dryRun) {- writeFileSync(projectInfo.rootFile, formatted);+ writeFileSync(projectInfo.rootFile, output);const end = Date.now() - time;RenderInternals.Log.info({indent: false, logLevel},RenderInternals.chalk.blue(`Edited root file in ${end}ms`),);+ if (!formatted && !warnedAboutPrettier) {+ warnedAboutPrettier = true;+ RenderInternals.Log.warn(+ {indent: false, logLevel},+ RenderInternals.chalk.yellow(+ 'Could not format the file using Prettier. Install "prettier" and add a config file to enable automatic formatting.',+ ),+ );+ }}return {diff --git a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts b/packages/studio-server/src/preview-server/routes/save-sequence-props.tsindex 8c18644379..19b106f6bf 100644--- a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts+++ b/packages/studio-server/src/preview-server/routes/save-sequence-props.ts@@ -10,6 +10,8 @@ import {makeHyperlink} from '../../hyperlinks/make-link';import type {ApiHandler} from '../api-types';import {suppressHmrForFile} from '../hmr-suppression';+let warnedAboutPrettier = false;+export const saveSequencePropsHandler: ApiHandler<SaveSequencePropsRequest,SaveSequencePropsResponse@@ -27,7 +29,7 @@ export const saveSequencePropsHandler: ApiHandler<const fileContents = readFileSync(absolutePath, 'utf-8');- const {output, oldValueString} = await updateSequenceProps({+ const {output, oldValueString, formatted} = await updateSequenceProps({input: fileContents,targetLine: line,key,@@ -52,6 +54,15 @@ export const saveSequencePropsHandler: ApiHandler<`${fileLink} updated: ${key} ${oldValueString} \u2192 ${newValueString}`,),);+ if (!formatted && !warnedAboutPrettier) {+ warnedAboutPrettier = true;+ RenderInternals.Log.warn(+ {indent: false, logLevel},+ RenderInternals.chalk.yellow(+ 'Could not format the file using Prettier. Install "prettier" and add a config file to enable automatic formatting.',+ ),+ );+ }return {success: true,diff --git a/packages/studio-server/src/preview-server/routes/update-default-props.ts b/packages/studio-server/src/preview-server/routes/update-default-props.tsindex 8f76ce74f3..b752761618 100644--- a/packages/studio-server/src/preview-server/routes/update-default-props.ts+++ b/packages/studio-server/src/preview-server/routes/update-default-props.ts@@ -1,4 +1,5 @@import {readFileSync, writeFileSync} from 'node:fs';+import {RenderInternals} from '@remotion/renderer';import type {UpdateDefaultPropsRequest,UpdateDefaultPropsResponse,@@ -8,6 +9,8 @@ import type {ApiHandler} from '../api-types';import {getProjectInfo} from '../project-info';import {checkIfTypeScriptFile} from './can-update-default-props';+let warnedAboutPrettier = false;+export const updateDefaultPropsHandler: ApiHandler<UpdateDefaultPropsRequest,UpdateDefaultPropsResponse@@ -15,6 +18,7 @@ export const updateDefaultPropsHandler: ApiHandler<input: {compositionId, defaultProps, enumPaths},remotionRoot,entryPoint,+ logLevel,}) => {try {const projectInfo = await getProjectInfo(remotionRoot, entryPoint);@@ -24,14 +28,24 @@ export const updateDefaultPropsHandler: ApiHandler<checkIfTypeScriptFile(projectInfo.rootFile);- const updated = await updateDefaultProps({+ const {output, formatted} = await updateDefaultProps({compositionId,input: readFileSync(projectInfo.rootFile, 'utf-8'),newDefaultProps: JSON.parse(defaultProps),enumPaths,});- writeFileSync(projectInfo.rootFile, updated);+ writeFileSync(projectInfo.rootFile, output);+ if (!formatted && !warnedAboutPrettier) {+ warnedAboutPrettier = true;+ RenderInternals.Log.warn(+ {indent: false, logLevel},+ RenderInternals.chalk.yellow(+ 'Could not format the file using Prettier. Install "prettier" and add a config file to enable automatic formatting.',+ ),+ );+ }+return {success: true,};diff --git a/packages/studio-server/src/test/update-default-props.test.ts b/packages/studio-server/src/test/update-default-props.test.tsindex 02291e0de5..d83cb28e32 100644--- a/packages/studio-server/src/test/update-default-props.test.ts+++ b/packages/studio-server/src/test/update-default-props.test.ts@@ -20,7 +20,7 @@ test('Should be able to update default props', async () => {enumPaths: [],});- expect(update).toBe(expected);+ expect(update.output).toBe(expected);});test('Should be able to update default props', async () => {@@ -40,5 +40,5 @@ test('Should be able to update default props', async () => {enumPaths: [],});- expect(update).toBe(expected);+ expect(update.output).toBe(expected);});