Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Use symbolicated stack for composition codemods

Jonny Burgerad2b06e17118
diff --git a/packages/studio-server/src/codemods/apply-codemod-to-file.ts b/packages/studio-server/src/codemods/apply-codemod-to-file.ts
new file mode 100644
index 0000000000..517298218b
--- /dev/null
+++ b/packages/studio-server/src/codemods/apply-codemod-to-file.ts
@@ -0,0 +1,49 @@
+import {existsSync, readFileSync} from 'node:fs';
+import path from 'node:path';
+import type {
+ RecastCodemod,
+ SymbolicatedStackFrame,
+} from '@remotion/studio-shared';
+import {checkIfTypeScriptFile} from '../preview-server/routes/can-update-default-props';
+import {formatOutput, parseAndApplyCodemod} from './duplicate-composition';
+
+export const resolveFilePathFromSymbolicatedStack = (
+ remotionRoot: string,
+ stack: SymbolicatedStackFrame,
+): string => {
+ if (!stack.originalFileName) {
+ throw new Error(
+ 'Could not determine the file where this composition is defined',
+ );
+ }
+
+ const absolutePath = path.resolve(remotionRoot, stack.originalFileName);
+ const fileRelativeToRoot = path.relative(remotionRoot, absolutePath);
+ if (fileRelativeToRoot.startsWith('..')) {
+ throw new Error('Cannot apply codemod to a file outside the project');
+ }
+
+ if (!existsSync(absolutePath)) {
+ throw new Error(`File not found: ${stack.originalFileName}`);
+ }
+
+ return absolutePath;
+};
+
+export const applyCodemodToFile = async ({
+ filePath,
+ codeMod,
+}: {
+ filePath: string;
+ codeMod: RecastCodemod;
+}): Promise<string> => {
+ checkIfTypeScriptFile(filePath);
+
+ const input = readFileSync(filePath, 'utf-8');
+ const {newContents} = parseAndApplyCodemod({
+ codeMod,
+ input,
+ });
+
+ return formatOutput(newContents);
+};
diff --git a/packages/studio-server/src/codemods/duplicate-composition.ts b/packages/studio-server/src/codemods/duplicate-composition.ts
index e3ec6c641f..53bd85fa23 100644
--- a/packages/studio-server/src/codemods/duplicate-composition.ts
+++ b/packages/studio-server/src/codemods/duplicate-composition.ts
@@ -54,7 +54,7 @@ export const parseAndApplyCodemod = ({
if (changesMade.length === 0) {
throw new Error(
- 'Unable to calculate the changes needed for this file. Edit the root file manually.',
+ 'Unable to calculate the changes needed for this file. Edit the file manually.',
);
}
diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts
index e824aa3c37..ce20b57e65 100644
--- a/packages/studio-server/src/index.ts
+++ b/packages/studio-server/src/index.ts
@@ -29,6 +29,7 @@ import {
getCompletedClientRenders,
removeCompletedClientRender,
} from './client-render-queue';
+import {applyCodemodToFile} from './codemods/apply-codemod-to-file';
import {
formatOutput,
parseAndApplyCodemod,
@@ -74,6 +75,7 @@ export const StudioServerInternals = {
AnsiDiff,
formatBytes,
parseAndApplyCodemod,
+ applyCodemodToFile,
formatOutput,
updateDefaultProps,
getInstalledDependencies,
diff --git a/packages/studio-server/src/preview-server/routes/apply-codemod.ts b/packages/studio-server/src/preview-server/routes/apply-codemod.ts
index 9af8d9cd8c..1675d803c3 100644
--- a/packages/studio-server/src/preview-server/routes/apply-codemod.ts
+++ b/packages/studio-server/src/preview-server/routes/apply-codemod.ts
@@ -1,13 +1,14 @@
import {readFileSync} from 'node:fs';
+import path from 'node:path';
import {RenderInternals} from '@remotion/renderer';
import type {
ApplyCodemodRequest,
ApplyCodemodResponse,
} from '@remotion/studio-shared';
import {
- formatOutput,
- parseAndApplyCodemod,
-} from '../../codemods/duplicate-composition';
+ applyCodemodToFile,
+ resolveFilePathFromSymbolicatedStack,
+} from '../../codemods/apply-codemod-to-file';
import {simpleDiff} from '../../codemods/simple-diff';
import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import type {ApiHandler} from '../api-types';
@@ -17,23 +18,30 @@ import {checkIfTypeScriptFile} from './can-update-default-props';
export const applyCodemodHandler: ApiHandler<
ApplyCodemodRequest,
ApplyCodemodResponse
-> = async ({input: {codemod, dryRun}, logLevel, remotionRoot, entryPoint}) => {
+> = async ({
+ input: {codemod, dryRun, symbolicatedStack},
+ logLevel,
+ remotionRoot,
+ entryPoint,
+}) => {
try {
const time = Date.now();
- const projectInfo = await getProjectInfo(remotionRoot, entryPoint);
- if (!projectInfo.rootFile) {
- throw new Error('Cannot find root file in project');
- }
- checkIfTypeScriptFile(projectInfo.rootFile);
+ const filePath = symbolicatedStack
+ ? resolveFilePathFromSymbolicatedStack(remotionRoot, symbolicatedStack)
+ : (await getProjectInfo(remotionRoot, entryPoint)).rootFile;
+
+ if (!filePath) {
+ throw new Error('Cannot find file for composition in project');
+ }
- const input = readFileSync(projectInfo.rootFile, 'utf-8');
+ checkIfTypeScriptFile(filePath);
- const {newContents} = parseAndApplyCodemod({
+ const input = readFileSync(filePath, 'utf-8');
+ const formatted = await applyCodemodToFile({
+ filePath,
codeMod: codemod,
- input,
});
- const formatted = await formatOutput(newContents);
const diff = simpleDiff({
oldLines: input.split('\n'),
@@ -41,15 +49,12 @@ export const applyCodemodHandler: ApiHandler<
});
if (!dryRun) {
- writeFileAndNotifyFileWatchers(
- projectInfo.rootFile,
- formatted,
- undefined,
- );
+ writeFileAndNotifyFileWatchers(filePath, formatted, undefined);
const end = Date.now() - time;
+ const relativePath = path.relative(remotionRoot, filePath);
RenderInternals.Log.info(
{indent: false, logLevel},
- RenderInternals.chalk.blue(`Edited root file in ${end}ms`),
+ RenderInternals.chalk.blue(`Edited ${relativePath} in ${end}ms`),
);
}
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index a3d1f0de01..bdfe9cbd3e 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -25,6 +25,7 @@ import type {RecastCodemod, VisualControlChange} from './codemods';
import type {PackageManager} from './package-manager';
import type {ProjectInfo} from './project-info';
import type {RequiredChromiumOptions} from './render-job';
+import type {SymbolicatedStackFrame} from './stack-types';
import type {EnumPath} from './stringify-default-props';
export type OpenInFileExplorerRequest = {
@@ -163,6 +164,7 @@ export type UpdateDefaultPropsResponse =
export type ApplyCodemodRequest = {
codemod: RecastCodemod;
dryRun: boolean;
+ symbolicatedStack: SymbolicatedStackFrame | null;
};
export type SimpleDiff = {
diff --git a/packages/studio/src/components/NewComposition/CodemodFooter.tsx b/packages/studio/src/components/NewComposition/CodemodFooter.tsx
index 710427ca66..8387b74835 100644
--- a/packages/studio/src/components/NewComposition/CodemodFooter.tsx
+++ b/packages/studio/src/components/NewComposition/CodemodFooter.tsx
@@ -1,18 +1,30 @@
-import type {ProjectInfo, RecastCodemod} from '@remotion/studio-shared';
-import React, {useCallback, useContext, useEffect, useState} from 'react';
+import type {RecastCodemod} from '@remotion/studio-shared';
+import React, {
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useState,
+} from 'react';
import {ShortcutHint} from '../../error-overlay/remotion-overlay/ShortcutHint';
+import {resolvedStackToSymbolicated} from '../../helpers/resolved-stack-to-symbolicated';
import {useKeybinding} from '../../helpers/use-keybinding';
import {ModalsContext} from '../../state/modals';
import {Flex, Row, Spacing} from '../layout';
import {ModalButton} from '../ModalButton';
import {showNotification} from '../Notifications/NotificationCenter';
-import {applyCodemod, getProjectInfo} from '../RenderQueue/actions';
+import {applyCodemod} from '../RenderQueue/actions';
+import {
+ hasResolvedStack,
+ useResolvedStack,
+} from '../Timeline/use-resolved-stack';
import type {CodemodStatus} from './DiffPreview';
import {CodemodDiffPreview} from './DiffPreview';
export const CodemodFooter: React.FC<{
readonly valid: boolean;
readonly codemod: RecastCodemod;
+ readonly stack: string | null;
readonly loadingNotification: React.ReactNode;
readonly successNotification: React.ReactNode;
readonly errorNotification: string;
@@ -21,6 +33,7 @@ export const CodemodFooter: React.FC<{
readonly onSuccess: (() => void) | null;
}> = ({
codemod,
+ stack,
valid,
loadingNotification,
successNotification,
@@ -35,26 +48,13 @@ export const CodemodFooter: React.FC<{
type: 'loading',
});
- const [projectInfo, setProjectInfo] = useState<ProjectInfo | null>(null);
-
- useEffect(() => {
- const controller = new AbortController();
-
- getProjectInfo(controller.signal)
- .then((info) => {
- setProjectInfo(info.projectInfo);
- })
- .catch((err) => {
- showNotification(
- `Could not get project info: ${err.message}. Unable to duplicate composition`,
- 3000,
- );
- });
+ const resolvedLocation = useResolvedStack(stack);
+ const symbolicatedStack = useMemo(
+ () => resolvedStackToSymbolicated(resolvedLocation),
+ [resolvedLocation],
+ );
- return () => {
- controller.abort();
- };
- }, []);
+ const relativeFilePath = symbolicatedStack?.originalFileName ?? null;
const trigger = useCallback(() => {
setSubmitting(true);
@@ -64,6 +64,7 @@ export const CodemodFooter: React.FC<{
applyCodemod({
codemod,
dryRun: false,
+ symbolicatedStack,
signal: new AbortController().signal,
})
.then(() => {
@@ -83,6 +84,7 @@ export const CodemodFooter: React.FC<{
onSuccess,
setSelectedModal,
successNotification,
+ symbolicatedStack,
]);
const getCanApplyCodemod = useCallback(
@@ -90,6 +92,7 @@ export const CodemodFooter: React.FC<{
const res = await applyCodemod({
codemod,
dryRun: true,
+ symbolicatedStack,
signal,
});
@@ -102,10 +105,30 @@ export const CodemodFooter: React.FC<{
});
}
},
- [codemod],
+ [codemod, symbolicatedStack],
);
useEffect(() => {
+ if (!stack) {
+ setCanApplyCodemod({
+ type: 'fail',
+ error: 'Could not determine where this composition is defined',
+ });
+ return;
+ }
+
+ if (!hasResolvedStack(stack)) {
+ return;
+ }
+
+ if (!symbolicatedStack) {
+ setCanApplyCodemod({
+ type: 'fail',
+ error: 'Could not resolve the source location of this composition',
+ });
+ return;
+ }
+
const abortController = new AbortController();
let aborted = false;
getCanApplyCodemod(abortController.signal)
@@ -115,19 +138,19 @@ export const CodemodFooter: React.FC<{
return;
}
- showNotification(`Cannot duplicate composition: ${err.message}`, 3000);
+ showNotification(`${errorNotification}: ${err.message}`, 3000);
});
return () => {
aborted = true;
abortController.abort();
};
- }, [getCanApplyCodemod]);
+ }, [errorNotification, getCanApplyCodemod, stack, symbolicatedStack]);
const disabled =
!valid ||
submitting ||
- projectInfo === null ||
+ symbolicatedStack === null ||
codemodStatus.type !== 'success';
const {registerKeybinding} = useKeybinding();
@@ -159,8 +182,8 @@ export const CodemodFooter: React.FC<{
<Flex />
<Spacing block x={2} />
<ModalButton onClick={trigger} disabled={disabled}>
- {projectInfo && projectInfo.relativeRootFile
- ? submitLabel({relativeRootPath: projectInfo.relativeRootFile})
+ {relativeFilePath
+ ? submitLabel({relativeRootPath: relativeFilePath})
: genericSubmitLabel}
<ShortcutHint keyToPress="↵" cmdOrCtrl />
</ModalButton>
diff --git a/packages/studio/src/components/NewComposition/DeleteComposition.tsx b/packages/studio/src/components/NewComposition/DeleteComposition.tsx
index 75bf6ff9a9..58febad059 100644
--- a/packages/studio/src/components/NewComposition/DeleteComposition.tsx
+++ b/packages/studio/src/components/NewComposition/DeleteComposition.tsx
@@ -26,6 +26,7 @@ const DeleteCompositionLoaded: React.FC<{
}
const {unresolved} = context;
+ const compositionStack = unresolved.stack ?? null;
const codemod: RecastCodemod = useMemo(() => {
return {
@@ -64,6 +65,7 @@ const DeleteCompositionLoaded: React.FC<{
`Delete from ${relativeRootPath}`
}
codemod={codemod}
+ stack={compositionStack}
valid
onSuccess={null}
/>
diff --git a/packages/studio/src/components/NewComposition/DuplicateComposition.tsx b/packages/studio/src/components/NewComposition/DuplicateComposition.tsx
index a59a4e5189..2bad453f55 100644
--- a/packages/studio/src/components/NewComposition/DuplicateComposition.tsx
+++ b/packages/studio/src/components/NewComposition/DuplicateComposition.tsx
@@ -47,6 +47,7 @@ const DuplicateCompositionLoaded: React.FC<{
}
const {resolved, unresolved} = context;
+ const compositionStack = unresolved.stack ?? null;
const [initialCompType] = useState<CompType>(initialType);
@@ -367,6 +368,7 @@ const DuplicateCompositionLoaded: React.FC<{
genericSubmitLabel={'Duplicate'}
submitLabel={({relativeRootPath}) => `Add to ${relativeRootPath}`}
codemod={codemod}
+ stack={compositionStack}
valid={valid}
onSuccess={onDuplicateSuccess}
/>
diff --git a/packages/studio/src/components/NewComposition/RenameComposition.tsx b/packages/studio/src/components/NewComposition/RenameComposition.tsx
index 1aab7dcc00..aad47d42f7 100644
--- a/packages/studio/src/components/NewComposition/RenameComposition.tsx
+++ b/packages/studio/src/components/NewComposition/RenameComposition.tsx
@@ -30,7 +30,8 @@ const RenameCompositionLoaded: React.FC<{}> = () => {
throw new Error('Resolved composition context');
}
- const {resolved} = context;
+ const {resolved, unresolved} = context;
+ const compositionStack = unresolved.stack ?? null;
const {compositions} = useContext(Internals.CompositionManager);
const [newId, setName] = useState(() => {
@@ -103,6 +104,7 @@ const RenameCompositionLoaded: React.FC<{}> = () => {
genericSubmitLabel={'Rename'}
submitLabel={({relativeRootPath}) => `Modify ${relativeRootPath}`}
codemod={codemod}
+ stack={compositionStack}
valid={valid}
onSuccess={null}
/>
diff --git a/packages/studio/src/components/RenderQueue/actions.ts b/packages/studio/src/components/RenderQueue/actions.ts
index 457b857691..45bba2b016 100644
--- a/packages/studio/src/components/RenderQueue/actions.ts
+++ b/packages/studio/src/components/RenderQueue/actions.ts
@@ -339,15 +339,18 @@ export const openInFileExplorer = ({directory}: {directory: string}) => {
export const applyCodemod = ({
codemod,
dryRun,
+ symbolicatedStack,
signal,
}: {
codemod: RecastCodemod;
dryRun: boolean;
+ symbolicatedStack: ApplyCodemodRequest['symbolicatedStack'];
signal: AbortController['signal'];
}) => {
const body: ApplyCodemodRequest = {
codemod,
dryRun,
+ symbolicatedStack,
};
return callApi('/api/apply-codemod', body, signal);
};
diff --git a/packages/studio/src/components/Timeline/use-resolved-stack.ts b/packages/studio/src/components/Timeline/use-resolved-stack.ts
index d492f9c73e..1477f2fc79 100644
--- a/packages/studio/src/components/Timeline/use-resolved-stack.ts
+++ b/packages/studio/src/components/Timeline/use-resolved-stack.ts
@@ -4,6 +4,14 @@ import type {ResolvedStackLocation} from 'remotion';
import {getOriginalLocationFromStack} from './TimelineStack/get-stack';
const resolvedCache = new Map<string, ResolvedStackLocation | null>();
+
+export const hasResolvedStack = (stack: string | null): boolean => {
+ if (!stack) {
+ return true;
+ }
+
+ return resolvedCache.has(stack);
+};
const inFlight = new Set<string>();
const subscribers = new Map<
string,
@@ -54,6 +62,8 @@ export const useResolvedStack = (
.catch((err) => {
// eslint-disable-next-line no-console
console.error('Could not get original location of Sequence', err);
+ resolvedCache.set(stack, null);
+ subs.forEach((fn) => fn(null));
})
.finally(() => {
inFlight.delete(stack);
diff --git a/packages/studio/src/helpers/resolved-stack-to-symbolicated.ts b/packages/studio/src/helpers/resolved-stack-to-symbolicated.ts
new file mode 100644
index 0000000000..778eb214f9
--- /dev/null
+++ b/packages/studio/src/helpers/resolved-stack-to-symbolicated.ts
@@ -0,0 +1,18 @@
+import type {SymbolicatedStackFrame} from '@remotion/studio-shared';
+import type {ResolvedStackLocation} from 'remotion';
+
+export const resolvedStackToSymbolicated = (
+ location: ResolvedStackLocation | null,
+): SymbolicatedStackFrame | null => {
+ if (!location?.source) {
+ return null;
+ }
+
+ return {
+ originalFileName: location.source,
+ originalLineNumber: location.line,
+ originalColumnNumber: location.column,
+ originalFunctionName: null,
+ originalScriptCode: null,
+ };
+};
diff --git a/packages/template-recorder/scripts/server/register-composition.ts b/packages/template-recorder/scripts/server/register-composition.ts
index 6accac9252..233824f1ca 100644
--- a/packages/template-recorder/scripts/server/register-composition.ts
+++ b/packages/template-recorder/scripts/server/register-composition.ts
@@ -1,91 +1,90 @@
-import { existsSync, readFileSync, writeFileSync } from "fs";
-import path from "path";
-import { StudioServerInternals } from "@remotion/studio-server";
+import {existsSync, readFileSync, writeFileSync} from 'fs';
+import path from 'path';
+import {StudioServerInternals} from '@remotion/studio-server';
-const ROOT_RELATIVE_PATH = path.join("remotion", "Root.tsx");
-const TEMPLATE_COMPOSITION_ID = "empty";
+const ROOT_RELATIVE_PATH = path.join('remotion', 'Root.tsx');
+const TEMPLATE_COMPOSITION_ID = 'empty';
const compositionExists = (src: string, compositionId: string) => {
- return (
- src.includes(`id="${compositionId}"`) ||
- src.includes(`id={'${compositionId}'}`) ||
- src.includes(`id={"${compositionId}"}`)
- );
+ return (
+ src.includes(`id="${compositionId}"`) ||
+ src.includes(`id={'${compositionId}'}`) ||
+ src.includes(`id={"${compositionId}"}`)
+ );
};
const getDefaultPropsForNewProject = () => ({
- theme: "light",
- canvasLayout: "square",
- platform: "youtube",
- scenes: [
- {
- type: "videoscene",
- webcamPosition: "bottom-right",
- endOffset: 0,
- transitionToNextScene: false,
- newChapter: "",
- stopChapteringAfterThis: false,
- music: "none",
- startOffset: 0,
- bRolls: [],
- },
- ],
- scenesAndMetadata: [],
+ theme: 'light',
+ canvasLayout: 'square',
+ platform: 'youtube',
+ scenes: [
+ {
+ type: 'videoscene',
+ webcamPosition: 'bottom-right',
+ endOffset: 0,
+ transitionToNextScene: false,
+ newChapter: '',
+ stopChapteringAfterThis: false,
+ music: 'none',
+ startOffset: 0,
+ bRolls: [],
+ },
+ ],
+ scenesAndMetadata: [],
});
export const registerComposition = async ({
- rootDir,
- projectName,
+ rootDir,
+ projectName,
}: {
- rootDir: string;
- projectName: string;
-}): Promise<{ registered: boolean; reason?: string }> => {
- const rootPath = path.join(rootDir, ROOT_RELATIVE_PATH);
+ rootDir: string;
+ projectName: string;
+}): Promise<{registered: boolean; reason?: string}> => {
+ const rootPath = path.join(rootDir, ROOT_RELATIVE_PATH);
- if (!existsSync(rootPath)) {
- return { registered: false, reason: "Root.tsx not found" };
- }
+ if (!existsSync(rootPath)) {
+ return {registered: false, reason: 'Root.tsx not found'};
+ }
- const src = readFileSync(rootPath, "utf-8");
+ const src = readFileSync(rootPath, 'utf-8');
- if (compositionExists(src, projectName)) {
- return { registered: false, reason: "Composition already exists" };
- }
+ if (compositionExists(src, projectName)) {
+ return {registered: false, reason: 'Composition already exists'};
+ }
- try {
- const { newContents: duplicated } =
- StudioServerInternals.parseAndApplyCodemod({
- input: src,
- codeMod: {
- type: "duplicate-composition",
- idToDuplicate: TEMPLATE_COMPOSITION_ID,
- newId: projectName,
- newHeight: null,
- newWidth: null,
- newFps: null,
- newDurationInFrames: null,
- tag: "Composition",
- },
- });
+ try {
+ const duplicated = await StudioServerInternals.applyCodemodToFile({
+ filePath: rootPath,
+ codeMod: {
+ type: 'duplicate-composition',
+ idToDuplicate: TEMPLATE_COMPOSITION_ID,
+ newId: projectName,
+ newHeight: null,
+ newWidth: null,
+ newFps: null,
+ newDurationInFrames: null,
+ tag: 'Composition',
+ },
+ });
- const { output: withDefaultScene } =
- await StudioServerInternals.updateDefaultProps({
- input: duplicated,
- compositionId: projectName,
- newDefaultProps: getDefaultPropsForNewProject(),
- enumPaths: [],
- });
+ const {output: withDefaultScene} =
+ await StudioServerInternals.updateDefaultProps({
+ input: duplicated,
+ compositionId: projectName,
+ newDefaultProps: getDefaultPropsForNewProject(),
+ enumPaths: [],
+ });
- const formatted = await StudioServerInternals.formatOutput(
- withDefaultScene,
- );
+ const formatted = await StudioServerInternals.formatOutput(
+ withDefaultScene,
+ );
- writeFileSync(rootPath, formatted, "utf-8");
- return { registered: true };
- } catch (err) {
- return {
- registered: false,
- reason: err instanceof Error ? err.message : String(err),
- };
- }
+ writeFileSync(rootPath, formatted, 'utf-8');
+ return {registered: true};
+ } catch (err) {
+ return {
+ registered: false,
+ reason: err instanceof Error ? err.message : String(err),
+ };
+ }
};