🎥 Make videos programmatically with React
Refactor codemods to return file changes
Jonny Burgerf88c7b3bf955
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.tsindex f186db2103..7bbf8f6617 100644--- a/packages/browser-studio/src/browser-studio-operations.ts+++ b/packages/browser-studio/src/browser-studio-operations.ts@@ -1,5 +1,6 @@import {CodemodsInternals,+ applyCodemodChanges,addComposition,addCanvasCaptureComposition,addEffect as addEffectCodemod,@@ -29,6 +30,7 @@ import {updateJsxNodeKeyframes,updateJsxNodeProps,type CodemodNodeResult,+ type CodemodResult,type CompositionDestination,type EffectKeyframeUpdate,type SequenceKeyframeUpdate,@@ -115,7 +117,7 @@ const formatCodemodFile = async ({contents}: {contents: string}) => ({}),});-const getNodePathMutationFiles = (result: CodemodNodeResult<VirtualProject>) =>+const getNodePathMutationFiles = (result: CodemodNodeResult) =>[...new Set([...result.changes.map(({filePath}) => filePath),@@ -331,6 +333,8 @@ const applyCompositionCodemod = ({codemod: RecastCodemod;}): VirtualProject => {const target = {project, compositionFile};+ const apply = (result: CodemodResult) =>+ applyCodemodChanges(project, result.changes);switch (codemod.type) {case 'new-composition': {const componentFilePath = `${dirname(compositionFile)}/${codemod.componentName}.tsx`;@@ -360,90 +364,110 @@ const applyCompositionCodemod = ({: {name: codemod.folderName, parentName: codemod.parentName},};if (codemod.canvasCapture !== null) {- return addCanvasCaptureComposition({- ...composition,- capture: codemod.canvasCapture,- }).project;+ return apply(+ addCanvasCaptureComposition({+ ...composition,+ capture: codemod.canvasCapture,+ }),+ );}- const result = addComposition(composition).project;- return {- ...result,- files: {- ...result.files,- [componentFilePath]: emptyCompositionComponent(codemod.componentName),+ const result = addComposition(composition);+ return applyCodemodChanges(project, [+ ...result.changes,+ {+ filePath: componentFilePath,+ previousContents: null,+ nextContents: emptyCompositionComponent(codemod.componentName),},- };+ ]);}case 'duplicate-composition':- return duplicateCompositionCodemod({- ...target,- compositionId: codemod.idToDuplicate,- newId: codemod.newId,- tag: codemod.tag,- metadata: {- width: codemod.newWidth ?? undefined,- height: codemod.newHeight ?? undefined,- fps:- codemod.tag === 'Still' ? undefined : (codemod.newFps ?? undefined),- durationInFrames:- codemod.tag === 'Still'- ? undefined- : (codemod.newDurationInFrames ?? undefined),- },- }).project;+ return apply(+ duplicateCompositionCodemod({+ ...target,+ compositionId: codemod.idToDuplicate,+ newId: codemod.newId,+ tag: codemod.tag,+ metadata: {+ width: codemod.newWidth ?? undefined,+ height: codemod.newHeight ?? undefined,+ fps:+ codemod.tag === 'Still'+ ? undefined+ : (codemod.newFps ?? undefined),+ durationInFrames:+ codemod.tag === 'Still'+ ? undefined+ : (codemod.newDurationInFrames ?? undefined),+ },+ }),+ );case 'rename-composition':- return renameComposition({- ...target,- compositionId: codemod.idToRename,- newId: codemod.newId,- }).project;+ return apply(+ renameComposition({+ ...target,+ compositionId: codemod.idToRename,+ newId: codemod.newId,+ }),+ );case 'delete-composition':- return deleteComposition({...target, compositionId: codemod.idToDelete})- .project;+ return apply(+ deleteComposition({...target, compositionId: codemod.idToDelete}),+ );case 'update-composition-metadata':- return updateCompositionMetadata({- ...target,- compositionId: codemod.idToUpdate,- metadata: {- width: codemod.newWidth ?? undefined,- height: codemod.newHeight ?? undefined,- fps: codemod.newFps ?? undefined,- durationInFrames: codemod.newDurationInFrames ?? undefined,- },- }).project;+ return apply(+ updateCompositionMetadata({+ ...target,+ compositionId: codemod.idToUpdate,+ metadata: {+ width: codemod.newWidth ?? undefined,+ height: codemod.newHeight ?? undefined,+ fps: codemod.newFps ?? undefined,+ durationInFrames: codemod.newDurationInFrames ?? undefined,+ },+ }),+ );case 'new-folder':- return addFolder({- ...target,- folder: {name: codemod.folderName, parentName: codemod.parentName},- }).project;+ return apply(+ addFolder({+ ...target,+ folder: {name: codemod.folderName, parentName: codemod.parentName},+ }),+ );case 'rename-folder':- return renameFolder({- ...target,- folder: {name: codemod.folderName, parentName: codemod.parentName},- newName: codemod.newName,- }).project;+ return apply(+ renameFolder({+ ...target,+ folder: {name: codemod.folderName, parentName: codemod.parentName},+ newName: codemod.newName,+ }),+ );case 'delete-folder':- return unwrapFolder({- ...target,- folder: {name: codemod.folderName, parentName: codemod.parentName},- }).project;+ return apply(+ unwrapFolder({+ ...target,+ folder: {name: codemod.folderName, parentName: codemod.parentName},+ }),+ );case 'move-composition-to-folder':- return moveComposition({- ...target,- compositionId: codemod.idToMove,- destination:- codemod.folderName === null- ? {type: 'root'}- : {- type: 'folder',- folder: {- name: codemod.folderName,- parentName: codemod.parentName,+ return apply(+ moveComposition({+ ...target,+ compositionId: codemod.idToMove,+ destination:+ codemod.folderName === null+ ? {type: 'root'}+ : {+ type: 'folder',+ folder: {+ name: codemod.folderName,+ parentName: codemod.parentName,+ },},- },- }).project;+ }),+ );case 'move-composition-or-folder': {const destination: CompositionDestination =codemod.destination.type === 'folder'@@ -467,20 +491,22 @@ const applyCompositionCodemod = ({parentName: codemod.destination.target.parentName,},};- return codemod.source.type === 'composition'- ? moveComposition({- ...target,- compositionId: codemod.source.compositionId,- destination,- }).project- : moveFolder({- ...target,- folder: {- name: codemod.source.folderName,- parentName: codemod.source.parentName,- },- destination,- }).project;+ return apply(+ codemod.source.type === 'composition'+ ? moveComposition({+ ...target,+ compositionId: codemod.source.compositionId,+ destination,+ })+ : moveFolder({+ ...target,+ folder: {+ name: codemod.source.folderName,+ parentName: codemod.source.parentName,+ },+ destination,+ }),+ );}case 'apply-visual-control':@@ -763,7 +789,7 @@ export const createBrowserStudioOperations = ({schema: mutation.schema,videoConfig: mutation.nodePath.videoConfigValues ?? undefined,});- nextProject = result.project;+ nextProject = applyCodemodChanges(nextProject, result.changes);appliedSequenceMutations.push({...mutation,absolutePath,@@ -787,7 +813,7 @@ export const createBrowserStudioOperations = ({schema: mutation.schema,videoConfig: mutation.sequenceNodePath.videoConfigValues ?? undefined,});- nextProject = result.project;+ nextProject = applyCodemodChanges(nextProject, result.changes);appliedEffectMutations.push({...mutation,absolutePath,@@ -1086,7 +1112,11 @@ export const createBrowserStudioOperations = ({timelineSelection: null,fileName: absolutePath,nodePathMutationFiles: null,- mutate: () => result.project,+ mutate: (current) =>+ applyCodemodChanges(+ addDependenciesToProject({dependencies, project: current}),+ result.changes,+ ),});return {success: true};} catch (error) {@@ -1114,7 +1144,7 @@ export const createBrowserStudioOperations = ({timelineSelection: null,fileName: result.changes.map(({filePath}) => filePath).join(', '),nodePathMutationFiles: null,- mutate: () => result.project,+ mutate: (current) => applyCodemodChanges(current, result.changes),});return {success: true};} catch (error) {@@ -1141,7 +1171,7 @@ export const createBrowserStudioOperations = ({timelineSelection: null,fileName: result.changes.map(({filePath}) => filePath).join(', '),nodePathMutationFiles: null,- mutate: () => result.project,+ mutate: (current) => applyCodemodChanges(current, result.changes),});return {success: true};} catch (error) {@@ -1212,7 +1242,7 @@ export const createBrowserStudioOperations = ({timelineSelection: null,fileName: absolutePath,nodePathMutationFiles: null,- mutate: () => result.project,+ mutate: (current) => applyCodemodChanges(current, result.changes),});return {success: true};} catch (error) {@@ -1253,7 +1283,7 @@ export const createBrowserStudioOperations = ({},],});- const nextProject = result.project;+ const nextProject = applyCodemodChanges(project, result.changes);controller.applyMutation({undoRedoNavigation: null,timelineSelection: null,@@ -1309,7 +1339,7 @@ export const createBrowserStudioOperations = ({},],});- nextProject = result.project;+ nextProject = applyCodemodChanges(nextProject, result.changes);}controller.applyMutation({@@ -1396,7 +1426,7 @@ export const createBrowserStudioOperations = ({undoRedoNavigation: null,timelineSelection: null,fileName: result.changes.map(({filePath}) => filePath).join(', '),- mutate: () => result.project,+ mutate: (current) => applyCodemodChanges(current, result.changes),nodePathMutationFiles: getNodePathMutationFiles(result),});if (nodePathMutation === null) {@@ -1433,7 +1463,7 @@ export const createBrowserStudioOperations = ({undoRedoNavigation: null,timelineSelection: null,fileName: result.changes.map(({filePath}) => filePath).join(', '),- mutate: () => result.project,+ mutate: (current) => applyCodemodChanges(current, result.changes),nodePathMutationFiles: getNodePathMutationFiles(result),});if (nodePathMutation === null) {@@ -1467,7 +1497,7 @@ export const createBrowserStudioOperations = ({undoRedoNavigation: null,timelineSelection: null,fileName: result.changes.map(({filePath}) => filePath).join(', '),- mutate: () => result.project,+ mutate: (current) => applyCodemodChanges(current, result.changes),nodePathMutationFiles: getNodePathMutationFiles(result),});if (nodePathMutation === null) {@@ -1568,7 +1598,7 @@ export const createBrowserStudioOperations = ({undoRedoNavigation: null,timelineSelection: null,fileName: absolutePath,- mutate: () => result.project,+ mutate: (current) => applyCodemodChanges(current, result.changes),nodePathMutationFiles: getNodePathMutationFiles(result),});if (nodePathMutation === null) {@@ -1910,7 +1940,7 @@ export const createBrowserStudioOperations = ({timelineSelection: null,fileName: absolutePath,nodePathMutationFiles: null,- mutate: () => result.project,+ mutate: (current) => applyCodemodChanges(current, result.changes),});return {success: true};@@ -1936,7 +1966,7 @@ export const createBrowserStudioOperations = ({undoRedoNavigation: null,timelineSelection: null,fileName: absolutePath,- mutate: () => result.project,+ mutate: (current) => applyCodemodChanges(current, result.changes),nodePathMutationFiles: getNodePathMutationFiles(result),});if (nodePathMutation === null) {@@ -2031,7 +2061,7 @@ export const createBrowserStudioOperations = ({undoRedoNavigation: null,timelineSelection: null,fileName: absolutePath,- mutate: () => result.project,+ mutate: (current) => applyCodemodChanges(current, result.changes),nodePathMutationFiles: getNodePathMutationFiles(result),});if (nodePathMutation === null) {@@ -2079,7 +2109,7 @@ export const createBrowserStudioOperations = ({: null;const result = insertion? {- project: insertion.project,+ changes: insertion.changes,filePath: insertion.insertedNode.filePath,insertedNodePath: insertion.insertedNode.nodePath,nodePathRemappings: insertion.nodePathRemappings.map(@@ -2092,6 +2122,16 @@ export const createBrowserStudioOperations = ({svgMarkupToJsx,wrapInSequence: null,});+ const changes =+ 'changes' in result+ ? result.changes+ : [+ {+ filePath: result.filePath,+ previousContents: project.files[result.filePath] ?? null,+ nextContents: result.output,+ },+ ];const nodePathMutation = controller.applyMutation({undoRedoNavigation: null,timelineSelection:@@ -2103,7 +2143,14 @@ export const createBrowserStudioOperations = ({nodePath: result.insertedNodePath,},fileName: result.filePath,- mutate: () => result.project,+ mutate: (current) =>+ applyCodemodChanges(+ addDependenciesToProject({+ dependencies: installedDependencies,+ project: current,+ }),+ changes,+ ),nodePathMutationFiles: [{absolutePath: result.filePath,@@ -2393,13 +2440,18 @@ export const createBrowserStudioOperations = ({position: request.position,},});- const projectWithElement = {- ...insertion.project,- files: {- ...insertion.project.files,- [plan.elementFilePath]: element.sourceCode,+ const projectWithElement = applyCodemodChanges(project, [+ {+ filePath: insertion.filePath,+ previousContents: project.files[insertion.filePath] ?? null,+ nextContents: insertion.output,},- };+ {+ filePath: plan.elementFilePath,+ previousContents: project.files[plan.elementFilePath] ?? null,+ nextContents: element.sourceCode,+ },+ ]);const nextProject = addDependenciesToProject({dependencies: installedDependencies,project: {diff --git a/packages/browser-studio/src/save-sequence-props.ts b/packages/browser-studio/src/save-sequence-props.tsindex 4a6a9a08e4..752df2e009 100644--- a/packages/browser-studio/src/save-sequence-props.ts+++ b/packages/browser-studio/src/save-sequence-props.ts@@ -1,5 +1,6 @@import {CodemodsInternals,+ applyCodemodChanges,getJsxNodeProps,updateMultipleJsxNodeProps,} from '@remotion/codemods';@@ -82,7 +83,9 @@ export const saveSequencePropsInProject = ({})),}): null;- const nextFiles = {...(updateResult?.project.files ?? project.files)};+ const nextFiles = {+ ...applyCodemodChanges(project, updateResult?.changes ?? []).files,+ };const updatedNodePaths = new Map<string, SequenceNodePath>();for (const [index, node] of (updateResult?.updatedNodes ?? []).entries()) {updatedNodePaths.set(diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.tsindex d6841283f5..d7cd4deafe 100644--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts@@ -1,5 +1,9 @@import {expect, test} from 'bun:test';-import {addSolid, CodemodsInternals} from '@remotion/codemods';+import {+ addSolid,+ applyCodemodChanges,+ CodemodsInternals,+} from '@remotion/codemods';import {createElementPayload} from '@remotion/studio-protocol';import type {EventSourceEvent} from '@remotion/studio-shared';import type {InteractivitySchema} from 'remotion';@@ -14,13 +18,16 @@ const insertSolid = (project: VirtualProject,compositionFile = '/project/src/Composition.tsx',) => {- return addSolid({+ return applyCodemodChanges(project,- compositionFile,- compositionId: 'MyComp',- width: 1280,- height: 720,- }).project;+ addSolid({+ project,+ compositionFile,+ compositionId: 'MyComp',+ width: 1280,+ height: 720,+ }).changes,+ );};test('consumes an initial Element payload only once', () => {@@ -80,15 +87,18 @@ test('adds multiple Solids without duplicating the import', () => {test('adds a Solid at a timeline frame', () => {const project = createBlankTemplateProject();- const updated = addSolid({+ const updated = applyCodemodChanges(project,- compositionFile: '/project/src/Composition.tsx',- compositionId: 'MyComp',- from: 42,- width: 1280,- height: 720,- position: {x: 100, y: 50},- }).project;+ addSolid({+ project,+ compositionFile: '/project/src/Composition.tsx',+ compositionId: 'MyComp',+ from: 42,+ width: 1280,+ height: 720,+ position: {x: 100, y: 50},+ }).changes,+ );const composition = updated.files['/project/src/Composition.tsx'];expect(composition).toContain('<Sequence from={42}');@@ -185,13 +195,15 @@ registerRoot(Root);`,},};- const {project: updated, nodePathRemappings} = addSolid({+ const result = addSolid({project,compositionFile: '/project/src/index.tsx',compositionId: 'MyComp',width: 1280,height: 720,});+ const updated = applyCodemodChanges(project, result.changes);+ const {nodePathRemappings} = result;const output = updated.files['/project/src/index.tsx'];expect(output).toContain(diff --git a/packages/codemods/src/add-canvas-capture-composition.ts b/packages/codemods/src/add-canvas-capture-composition.tsindex 572f361cd1..1f84843692 100644--- a/packages/codemods/src/add-canvas-capture-composition.ts+++ b/packages/codemods/src/add-canvas-capture-composition.ts@@ -47,7 +47,7 @@ export const addCanvasCaptureComposition = <Project extends CodemodProject>({metadata,folder,capture,-}: AddCanvasCaptureCompositionOptions<Project>): CodemodResult<Project> => {+}: AddCanvasCaptureCompositionOptions<Project>): CodemodResult => {assertNewCompositionId({project, compositionFile, compositionId});validateMetadata(metadata);if (!/^[A-Z_$][\w$]*$/.test(component.importName)) {@@ -115,13 +115,9 @@ export const addCanvasCaptureComposition = <Project extends CodemodProject>({parseAst(componentSource);return getCodemodResult({project,- nextProject: {- ...project,- files: {- ...project.files,- [filePath]: output,- [component.filePath]: componentSource,- },- },+ edits: [+ {filePath, nextContents: output},+ {filePath: component.filePath, nextContents: componentSource},+ ],});};diff --git a/packages/codemods/src/add-component.ts b/packages/codemods/src/add-component.tsindex ff7c62e84f..504d9a0fe2 100644--- a/packages/codemods/src/add-component.ts+++ b/packages/codemods/src/add-component.ts@@ -15,7 +15,7 @@ export const addComponent = <Project extends CodemodProject>({importPath,props = {},...options-}: AddComponentOptions<Project>): Promise<CodemodInsertionResult<Project>> => {+}: AddComponentOptions<Project>): Promise<CodemodInsertionResult> => {if (!/^[A-Z_$][\w$]*$/.test(importName) || importName === 'default') {throw new Error('importName must be a named component export beginning with an uppercase letter, _ or $',diff --git a/packages/codemods/src/add-composition.ts b/packages/codemods/src/add-composition.tsindex c2b1efdb34..c8f1e4e5e5 100644--- a/packages/codemods/src/add-composition.ts+++ b/packages/codemods/src/add-composition.ts@@ -34,7 +34,7 @@ export const addComposition = <Project extends CodemodProject>({component,metadata,folder,-}: AddCompositionOptions<Project>): CodemodResult<Project> => {+}: AddCompositionOptions<Project>): CodemodResult => {assertNewCompositionId({project, compositionFile, compositionId});validateMetadata(metadata);if (!/^[A-Z_$][\w$]*$/.test(component.importName)) {@@ -102,6 +102,6 @@ export const addComposition = <Project extends CodemodProject>({parseAst(output);return getCodemodResult({project,- nextProject: {...project, files: {...project.files, [filePath]: output}},+ edits: [{filePath, nextContents: output}],});};diff --git a/packages/codemods/src/add-effect.ts b/packages/codemods/src/add-effect.tsindex 2431a6d8b8..a12a4100ea 100644--- a/packages/codemods/src/add-effect.ts+++ b/packages/codemods/src/add-effect.ts@@ -47,7 +47,7 @@ export const addEffect = async <Project extends CodemodProject>({...result,editDetails: [{filePath, formatted, effectLabel, nodeLabel, logLine}],insertedEffect: {- ...getUpdatedNodeReference({...result, node}),+ ...getUpdatedNodeReference({project, ...result, node}),effectIndex: length,},};diff --git a/packages/codemods/src/add-folder.ts b/packages/codemods/src/add-folder.tsindex 5c0c946436..0b2a330d14 100644--- a/packages/codemods/src/add-folder.ts+++ b/packages/codemods/src/add-folder.ts@@ -95,9 +95,6 @@ export const addFolder = <Project extends CodemodProject>({parseAst(nextContents);return getCodemodResult({project,- nextProject: {- ...project,- files: {...project.files, [filePath]: nextContents},- },+ edits: [{filePath, nextContents}],});};diff --git a/packages/codemods/src/add-media.ts b/packages/codemods/src/add-media.tsindex 364bce70bc..12ddaf6510 100644--- a/packages/codemods/src/add-media.ts+++ b/packages/codemods/src/add-media.ts@@ -16,7 +16,7 @@ export const addMedia = <Project extends CodemodProject>({srcType,dimensions,...options-}: AddMediaOptions<Project>): Promise<CodemodInsertionResult<Project>> => {+}: AddMediaOptions<Project>): Promise<CodemodInsertionResult> => {if (dimensions &&(!Number.isFinite(dimensions.width) ||diff --git a/packages/codemods/src/add-solid.ts b/packages/codemods/src/add-solid.tsindex 78eab62af4..597705a90b 100644--- a/packages/codemods/src/add-solid.ts+++ b/packages/codemods/src/add-solid.ts@@ -13,8 +13,7 @@ export type AddSolidOptions<Project extends CodemodProject> = {position?: {x: number; y: number};};-export type AddSolidResult<Project extends CodemodProject> =- CodemodInsertionResult<Project>;+export type AddSolidResult = CodemodInsertionResult;export const addSolid = <Project extends CodemodProject>({project,@@ -24,7 +23,7 @@ export const addSolid = <Project extends CodemodProject>({height,from,position,-}: AddSolidOptions<Project>): AddSolidResult<Project> => {+}: AddSolidOptions<Project>): AddSolidResult => {const insertion = insertSolidIntoProjectWithNodePathRemappings({project,request: {@@ -47,7 +46,12 @@ export const addSolid = <Project extends CodemodProject>({}return {- ...getCodemodResult({nextProject: insertion.project, project}),+ ...getCodemodResult({+ project,+ edits: [+ {filePath: insertion.filePath, nextContents: insertion.nextSource},+ ],+ }),nodePathRemappings: insertion.nodePathRemappings.map((remapping) => ({filePath: insertion.filePath,...remapping,diff --git a/packages/codemods/src/codemod-project.ts b/packages/codemods/src/codemod-project.tsindex 7aff311c44..f0b9cd4eda 100644--- a/packages/codemods/src/codemod-project.ts+++ b/packages/codemods/src/codemod-project.ts@@ -9,29 +9,63 @@ export type CodemodFileChange = {nextContents: string | null;};-export type CodemodResult<Project extends CodemodProject> = {- project: Project;+export type CodemodResult = {changes: CodemodFileChange[];};-export const getCodemodResult = <Project extends CodemodProject>({+export const getCodemodResult = ({project,- nextProject,+ edits,}: {- project: Project;- nextProject: Project;-}): CodemodResult<Project> => {- const filePaths = new Set([- ...Object.keys(project.files),- ...Object.keys(nextProject.files),- ]);- const changes = [...filePaths].flatMap((filePath): CodemodFileChange[] => {- const previousContents = project.files[filePath] ?? null;- const nextContents = nextProject.files[filePath] ?? null;- return previousContents === nextContents- ? []- : [{filePath, previousContents, nextContents}];- });-- return {changes, project: nextProject};+ project: CodemodProject;+ edits: {filePath: string; nextContents: string | null}[];+}): CodemodResult => {+ const seen = new Set<string>();+ const changes = edits.flatMap(+ ({filePath, nextContents}): CodemodFileChange[] => {+ if (seen.has(filePath)) {+ throw new Error(`Multiple edits for ${filePath}`);+ }++ seen.add(filePath);+ const previousContents = project.files[filePath] ?? null;+ return previousContents === nextContents+ ? []+ : [{filePath, previousContents, nextContents}];+ },+ );++ return {changes};+};++export const applyCodemodChanges = <Project extends CodemodProject>(+ project: Project,+ changes: readonly CodemodFileChange[],+): Project => {+ if (changes.length === 0) {+ return project;+ }++ const seen = new Set<string>();+ for (const {filePath, previousContents} of changes) {+ if (seen.has(filePath)) {+ throw new Error(`Multiple changes for ${filePath}`);+ }++ seen.add(filePath);+ if ((project.files[filePath] ?? null) !== previousContents) {+ throw new Error(`Source changed before applying codemod: ${filePath}`);+ }+ }++ const files = {...project.files};+ for (const {filePath, nextContents} of changes) {+ if (nextContents === null) {+ delete files[filePath];+ } else {+ files[filePath] = nextContents;+ }+ }++ return {...project, files};};diff --git a/packages/codemods/src/delete-composition.ts b/packages/codemods/src/delete-composition.tsindex d63aedebbb..86c2edcaf2 100644--- a/packages/codemods/src/delete-composition.ts+++ b/packages/codemods/src/delete-composition.ts@@ -18,7 +18,7 @@ export const deleteComposition = <Project extends CodemodProject>({project,compositionFile,compositionId,-}: DeleteCompositionOptions<Project>): CodemodResult<Project> => {+}: DeleteCompositionOptions<Project>): CodemodResult => {const node = requireComposition({project, compositionFile, compositionId});const input = project.files[node.filePath];const ast = parseAst(input);@@ -33,9 +33,6 @@ export const deleteComposition = <Project extends CodemodProject>({});return getCodemodResult({project,- nextProject: {- ...project,- files: {...project.files, [node.filePath]: output},- },+ edits: [{filePath: node.filePath, nextContents: output}],});};diff --git a/packages/codemods/src/delete-jsx-nodes.ts b/packages/codemods/src/delete-jsx-nodes.tsindex 14038a2d8e..f803c4761e 100644--- a/packages/codemods/src/delete-jsx-nodes.ts+++ b/packages/codemods/src/delete-jsx-nodes.ts@@ -16,7 +16,7 @@ export const deleteJsxNodes = async <Project extends CodemodProject>({project,nodes,}: DeleteJsxNodesOptions<Project>): Promise<- CodemodNodeResult<Project> & {+ CodemodNodeResult & {editDetails: {filePath: string;formatted: boolean;diff --git a/packages/codemods/src/detach-audio.ts b/packages/codemods/src/detach-audio.tsindex 4e52c1962e..791289cc4e 100644--- a/packages/codemods/src/detach-audio.ts+++ b/packages/codemods/src/detach-audio.ts@@ -53,6 +53,6 @@ export const detachAudio = async <Project extends CodemodProject>({},],insertedNode: {filePath, nodePath},- updatedNode: getUpdatedNodeReference({...result, node}),+ updatedNode: getUpdatedNodeReference({project, ...result, node}),};};diff --git a/packages/codemods/src/duplicate-composition.ts b/packages/codemods/src/duplicate-composition.tsindex 0d347cc06a..7de484b7dd 100644--- a/packages/codemods/src/duplicate-composition.ts+++ b/packages/codemods/src/duplicate-composition.ts@@ -25,7 +25,7 @@ export const duplicateComposition = <Project extends CodemodProject>({newId,tag,metadata = {},-}: DuplicateCompositionOptions<Project>): CodemodResult<Project> => {+}: DuplicateCompositionOptions<Project>): CodemodResult => {const node = requireComposition({project, compositionFile, compositionId});assertNewCompositionId({project, compositionFile, compositionId: newId});validateMetadata(metadata);@@ -47,9 +47,6 @@ export const duplicateComposition = <Project extends CodemodProject>({parseAst(output);return getCodemodResult({project,- nextProject: {- ...project,- files: {...project.files, [node.filePath]: output},- },+ edits: [{filePath: node.filePath, nextContents: output}],});};diff --git a/packages/codemods/src/duplicate-effects.ts b/packages/codemods/src/duplicate-effects.tsindex 38d22617b0..e0c7e11052 100644--- a/packages/codemods/src/duplicate-effects.ts+++ b/packages/codemods/src/duplicate-effects.ts@@ -50,7 +50,7 @@ export const duplicateEffects = async <Project extends CodemodProject>({})),insertedEffects: [...groups.values()].flatMap((group) =>group.map((effect) => ({- ...getUpdatedNodeReference({...result, node: effect}),+ ...getUpdatedNodeReference({project, ...result, node: effect}),effectIndex:effect.effectIndex +1 +diff --git a/packages/codemods/src/duplicate-jsx-nodes.ts b/packages/codemods/src/duplicate-jsx-nodes.tsindex 539ed62de6..29ccbdb0c6 100644--- a/packages/codemods/src/duplicate-jsx-nodes.ts+++ b/packages/codemods/src/duplicate-jsx-nodes.ts@@ -13,18 +13,15 @@ export type DuplicateJsxNodesOptions<Project extends CodemodProject> = {nodes: JsxNodeReference[];};-export type DuplicateJsxNodesResult<Project extends CodemodProject> =- CodemodNodeResult<Project> & {- insertedNodes: JsxNodeReference[];- editDetails: {filePath: string; nodeLabels: string[]; logLines: number[]}[];- };+export type DuplicateJsxNodesResult = CodemodNodeResult & {+ insertedNodes: JsxNodeReference[];+ editDetails: {filePath: string; nodeLabels: string[]; logLines: number[]}[];+};export const duplicateJsxNodes = async <Project extends CodemodProject>({project,nodes,-}: DuplicateJsxNodesOptions<Project>): Promise<- DuplicateJsxNodesResult<Project>-> => {+}: DuplicateJsxNodesOptions<Project>): Promise<DuplicateJsxNodesResult> => {const groups = groupNodeReferencesByFile({project, nodes});const edits = await Promise.all([...groups].map(async ([filePath, nodePaths]) => ({diff --git a/packages/codemods/src/folder-editing.ts b/packages/codemods/src/folder-editing.tsindex 9dab3c2ad6..54abf4675b 100644--- a/packages/codemods/src/folder-editing.ts+++ b/packages/codemods/src/folder-editing.ts@@ -148,7 +148,7 @@ export const moveTreeItem = <Project extends CodemodProject>({((destination.type === 'folder' || destination.type === 'root') &&entry.parentName === destinationParentName)) {- return getCodemodResult({project, nextProject: project});+ return {changes: []};}if (!entry.directJsxChild)@@ -171,9 +171,6 @@ export const moveTreeItem = <Project extends CodemodProject>({parseAst(nextContents);return getCodemodResult({project,- nextProject: {- ...project,- files: {...project.files, [filePath]: nextContents},- },+ edits: [{filePath, nextContents}],});};diff --git a/packages/codemods/src/index.ts b/packages/codemods/src/index.tsindex 1b756abb67..1bbfd933a4 100644--- a/packages/codemods/src/index.ts+++ b/packages/codemods/src/index.ts@@ -127,6 +127,7 @@ export type {CodemodProject,CodemodResult,} from './codemod-project';+export {applyCodemodChanges} from './codemod-project';export {deleteJsxNodes, type DeleteJsxNodesOptions} from './delete-jsx-nodes';export type {EffectArrayElement,diff --git a/packages/codemods/src/insert-content.ts b/packages/codemods/src/insert-content.tsindex 7cdfd9c75a..fa18305aeb 100644--- a/packages/codemods/src/insert-content.ts+++ b/packages/codemods/src/insert-content.ts@@ -26,7 +26,7 @@ export const insertContent = async <Project extends CodemodProject>({element,}: AddContentOptions<Project> & {element: InsertableCompositionElement;-}): Promise<CodemodInsertionResult<Project>> => {+}): Promise<CodemodInsertionResult> => {if (from !== undefined && (!Number.isInteger(from) || from < 0)) {throw new Error('from must be a non-negative integer');}@@ -78,7 +78,7 @@ export const insertContent = async <Project extends CodemodProject>({edits: [{filePath,- output: insertion.project.files[insertion.filePath],+ output: insertion.output,nodePathRemappings: insertion.nodePathRemappings,},],diff --git a/packages/codemods/src/insert-jsx-element.ts b/packages/codemods/src/insert-jsx-element.tsindex c121c47f56..44ec16a1c1 100644--- a/packages/codemods/src/insert-jsx-element.ts+++ b/packages/codemods/src/insert-jsx-element.ts@@ -2966,15 +2966,13 @@ export const insertJsxElementIntoComposition = async ({};};-export const insertJsxElementIntoProjectWithNodePathRemappings = async <- Project extends {files: Record<string, string>; rootDir: string},->({+export const insertJsxElementIntoProjectWithNodePathRemappings = async ({project,request,svgMarkupToJsx,wrapInSequence,}: {- project: Project;+ project: {files: Record<string, string>; rootDir: string};request: InsertJsxElementRequest;svgMarkupToJsx: InsertJsxElementCodemodEnvironment['svgMarkupToJsx'];wrapInSequence: {@@ -2988,7 +2986,7 @@ export const insertJsxElementIntoProjectWithNodePathRemappings = async <filePath: string;insertedNodePath: SequenceNodePath | null;nodePathRemappings: SequenceNodePathRemapping[];- project: Project;+ output: string;}> => {const result = await insertJsxElementIntoComposition({compositionFile: request.compositionFile,@@ -3007,9 +3005,6 @@ export const insertJsxElementIntoProjectWithNodePathRemappings = async <filePath: result.fileName,insertedNodePath: result.insertedNodePath,nodePathRemappings: result.nodePathRemappings,- project: {- ...project,- files: {...project.files, [result.fileName]: result.output},- },+ output: result.output,};};diff --git a/packages/codemods/src/internals.ts b/packages/codemods/src/internals.tsindex fa169ae35b..a59c13d711 100644--- a/packages/codemods/src/internals.ts+++ b/packages/codemods/src/internals.ts@@ -902,16 +902,13 @@ const getNodePathRemappings = ({return remappings;};-const insertSolidIntoProjectWithoutNodePathRemappings = <- Project extends CodemodProject,->({+const insertSolidIntoProjectWithoutNodePathRemappings = ({project,request,}: {- project: Project;+ project: CodemodProject;request: InsertJsxElementRequest;}): {- project: Project;filePath: string;previousSource: string;nextSource: string;@@ -960,27 +957,18 @@ const insertSolidIntoProjectWithoutNodePathRemappings = <filePath: resolved.filePath,nextSource: output,previousSource: resolved.source,- project: {- ...project,- files: {- ...project.files,- [resolved.filePath]: output,- },- },};};-export const insertSolidIntoProjectWithNodePathRemappings = <- Project extends CodemodProject,->({+export const insertSolidIntoProjectWithNodePathRemappings = ({project,request,}: {- project: Project;+ project: CodemodProject;request: InsertJsxElementRequest;}): {- project: Project;filePath: string;+ nextSource: string;nodePathRemappings: SequenceNodePathRemapping[];} => {const result = insertSolidIntoProjectWithoutNodePathRemappings({@@ -990,11 +978,11 @@ export const insertSolidIntoProjectWithNodePathRemappings = <return {filePath: result.filePath,+ nextSource: result.nextSource,nodePathRemappings: getNodePathRemappings({afterSource: result.nextSource,beforeSource: result.previousSource,}),- project: result.project,};};diff --git a/packages/codemods/src/node-references.ts b/packages/codemods/src/node-references.tsindex a8b25e4ae8..6590a52ae8 100644--- a/packages/codemods/src/node-references.ts+++ b/packages/codemods/src/node-references.ts@@ -16,11 +16,13 @@ export type JsxNodePathRemapping = {newNodePath: SequenceNodePath | null;};-export type CodemodNodeResult<Project extends CodemodProject> =- CodemodResult<Project> & {nodePathRemappings: JsxNodePathRemapping[]};+export type CodemodNodeResult = CodemodResult & {+ nodePathRemappings: JsxNodePathRemapping[];+};-export type CodemodInsertionResult<Project extends CodemodProject> =- CodemodNodeResult<Project> & {insertedNode: JsxNodeReference};+export type CodemodInsertionResult = CodemodNodeResult & {+ insertedNode: JsxNodeReference;+};export type NodeSourceEdit = {filePath: string;@@ -52,25 +54,20 @@ export const getInsertedNodeReferences = ();};-export const getNodeEditResult = <Project extends CodemodProject>({+export const getNodeEditResult = ({project,edits,}: {- project: Project;+ project: CodemodProject;edits: NodeSourceEdit[];-}): CodemodNodeResult<Project> => {+}): CodemodNodeResult => {return {...getCodemodResult({project,- nextProject: {- ...project,- files: {- ...project.files,- ...Object.fromEntries(- edits.map(({filePath, output}) => [filePath, output]),- ),- },- },+ edits: edits.map(({filePath, output}) => ({+ filePath,+ nextContents: output,+ })),}),nodePathRemappings: edits.flatMap(({filePath, nodePathRemappings}) =>nodePathRemappings.map((remapping) => ({filePath, ...remapping})),diff --git a/packages/codemods/src/rename-composition.ts b/packages/codemods/src/rename-composition.tsindex b8b98b6950..2bbd33dc95 100644--- a/packages/codemods/src/rename-composition.ts+++ b/packages/codemods/src/rename-composition.ts@@ -21,10 +21,10 @@ export const renameComposition = <Project extends CodemodProject>({compositionFile,compositionId,newId,-}: RenameCompositionOptions<Project>): CodemodResult<Project> => {+}: RenameCompositionOptions<Project>): CodemodResult => {const node = requireComposition({project, compositionFile, compositionId});if (newId === compositionId) {- return getCodemodResult({project, nextProject: project});+ return {changes: []};}assertNewCompositionId({project, compositionFile, compositionId: newId});@@ -51,9 +51,6 @@ export const renameComposition = <Project extends CodemodProject>({});return getCodemodResult({project,- nextProject: {- ...project,- files: {...project.files, [node.filePath]: output},- },+ edits: [{filePath: node.filePath, nextContents: output}],});};diff --git a/packages/codemods/src/rename-folder.ts b/packages/codemods/src/rename-folder.tsindex 5a72ab51e4..7fd67ce7d9 100644--- a/packages/codemods/src/rename-folder.ts+++ b/packages/codemods/src/rename-folder.ts@@ -23,7 +23,7 @@ export const renameFolder = <Project extends CodemodProject>({const entries = getTreeEntries({ast: parseAst(input)});const located = requireTreeItem(entries, {type: 'folder', ...folder});if (newName === folder.name) {- return getCodemodResult({project, nextProject: project});+ return {changes: []};}if (!newName || newName.includes('/')) {@@ -62,9 +62,6 @@ export const renameFolder = <Project extends CodemodProject>({parseAst(nextContents);return getCodemodResult({project,- nextProject: {- ...project,- files: {...project.files, [filePath]: nextContents},- },+ edits: [{filePath, nextContents}],});};diff --git a/packages/codemods/src/reorder-effect.ts b/packages/codemods/src/reorder-effect.tsindex a1e4a8080b..96279da2ca 100644--- a/packages/codemods/src/reorder-effect.ts+++ b/packages/codemods/src/reorder-effect.ts@@ -50,7 +50,7 @@ export const reorderEffect = async <Project extends CodemodProject>({...result,editDetails: [{filePath, formatted, effectLabel, logLine}],updatedEffect: {- ...getUpdatedNodeReference({...result, node: effect}),+ ...getUpdatedNodeReference({project, ...result, node: effect}),effectIndex: toIndex,},};diff --git a/packages/codemods/src/reorder-jsx-node.ts b/packages/codemods/src/reorder-jsx-node.tsindex bddc9d7772..a68d994d03 100644--- a/packages/codemods/src/reorder-jsx-node.ts+++ b/packages/codemods/src/reorder-jsx-node.ts@@ -44,6 +44,6 @@ export const reorderJsxNode = async <Project extends CodemodProject>({logLine: edit.logLine,},],- updatedNode: getUpdatedNodeReference({...result, node}),+ updatedNode: getUpdatedNodeReference({project, ...result, node}),};};diff --git a/packages/codemods/src/set-composition-default-props.ts b/packages/codemods/src/set-composition-default-props.tsindex bf4be24799..4a49b59931 100644--- a/packages/codemods/src/set-composition-default-props.ts+++ b/packages/codemods/src/set-composition-default-props.ts@@ -59,7 +59,9 @@ export const setCompositionDefaultProps = <Project extends CodemodProject>({node,props: {defaultProps: {}},});- input = inserted.project.files[node.filePath];+ input =+ inserted.changes.find((change) => change.filePath === node.filePath)+ ?.nextContents ?? input;element = findJsxElementPathForDeletion(parseAst(input),inserted.updatedNode.nodePath,@@ -115,6 +117,6 @@ export const setCompositionDefaultProps = <Project extends CodemodProject>({return {...result,logLine,- updatedNode: getUpdatedNodeReference({...result, node}),+ updatedNode: getUpdatedNodeReference({project, ...result, node}),};};diff --git a/packages/codemods/src/split-sequences.ts b/packages/codemods/src/split-sequences.tsindex bd1383a2e3..aade4fe751 100644--- a/packages/codemods/src/split-sequences.ts+++ b/packages/codemods/src/split-sequences.ts@@ -18,9 +18,7 @@ export type SplitSequencesOptions<Project extends CodemodProject> = {export const splitSequences = async <Project extends CodemodProject>({project,splits,-}: SplitSequencesOptions<Project>): Promise<- DuplicateJsxNodesResult<Project>-> => {+}: SplitSequencesOptions<Project>): Promise<DuplicateJsxNodesResult> => {if (splits.length === 0) {throw new Error('Expected at least one sequence to split');}diff --git a/packages/codemods/src/test/apply-visual-control.test.ts b/packages/codemods/src/test/apply-visual-control.test.tsindex ddd21fa28d..e4a0391347 100644--- a/packages/codemods/src/test/apply-visual-control.test.ts+++ b/packages/codemods/src/test/apply-visual-control.test.ts@@ -11,7 +11,7 @@ test('updates visual controls without changing surrounding source', () => {"const optional = visualControl('optional')",'',].join('\r\n');- const {project, updatedControls} = updateVisualControls({+ const {changes, updatedControls} = updateVisualControls({project: {rootDir: '/', files: {'Root.tsx': input}},filePath: 'Root.tsx',changes: [@@ -41,7 +41,7 @@ test('updates visual controls without changing surrounding source', () => {{id: 'mode', line: 5},{id: 'optional', line: 6},]);- expect(project.files['Root.tsx']).toBe(+ expect(changes[0].nextContents).toBe(input.replace('OPACITY', '0.5').replace('"slow"', "'fast' as const")@@ -53,7 +53,7 @@ test('formats object values using the existing source style', () => {const input = `const untouched = {keep:"this spacing"}const settings = visualControl("settings", { old: true })`;- const {project} = updateVisualControls({+ const {changes} = updateVisualControls({project: {rootDir: '/', files: {'Root.tsx': input}},filePath: 'Root.tsx',changes: [@@ -69,7 +69,7 @@ const settings = visualControl("settings", { old: true })],});- expect(project.files['Root.tsx'])+ expect(changes[0].nextContents).toBe(`const untouched = {keep:"this spacing"}const settings = visualControl("settings", { title: "Hello", "dash-key": true })`);@@ -85,7 +85,7 @@ test('wraps long visual-control values using CRLF and tab indentation', () => {')','',].join('\r\n');- const {project} = updateVisualControls({+ const {changes} = updateVisualControls({project: {rootDir: '/', files: {'Root.tsx': input}},filePath: 'Root.tsx',changes: [@@ -103,7 +103,7 @@ test('wraps long visual-control values using CRLF and tab indentation', () => {],});- expect(project.files['Root.tsx']).toBe(+ expect(changes[0].nextContents).toBe(['import {visualControl} from "@remotion/studio"','',@@ -123,7 +123,7 @@ test('wraps long visual-control values using CRLF and tab indentation', () => {test('an outer visual control replacement supersedes nested controls', () => {const input ="const value = visualControl('outer', {nested: visualControl('inner', 1)});\n";- const {project, updatedControls} = updateVisualControls({+ const {changes, updatedControls} = updateVisualControls({project: {rootDir: '/', files: {'Root.tsx': input}},filePath: 'Root.tsx',changes: [@@ -143,7 +143,7 @@ test('an outer visual control replacement supersedes nested controls', () => {});expect(updatedControls).toEqual([{id: 'outer', line: 1}]);- expect(project.files['Root.tsx']).toBe(+ expect(changes[0].nextContents).toBe("const value = visualControl('outer', 2);\n",);});@@ -182,7 +182,4 @@ test('rejects dynamic identifiers and leaves unmatched visual controls unchanged});expect(unchanged.changes).toEqual([]);expect(unchanged.updatedControls).toEqual([]);- expect(unchanged.project.files['Root.tsx']).toBe(- "const value = visualControl('other', 1);\n",- );});diff --git a/packages/codemods/src/test/composition-source-edits.test.ts b/packages/codemods/src/test/composition-source-edits.test.tsindex eecef94a92..6a6acffb47 100644--- a/packages/codemods/src/test/composition-source-edits.test.ts+++ b/packages/codemods/src/test/composition-source-edits.test.ts@@ -1,11 +1,13 @@import {expect, test} from 'bun:test';import {addComposition,+ applyCodemodChanges,deleteComposition,duplicateComposition,renameComposition,updateCompositionMetadata,} from '../index';+import {getChangedContents} from './get-changed-contents';const compositionFile = 'Root.tsx';@@ -35,36 +37,39 @@ for (const [indent, eol] of ['</>;','',].join(eol);+ const project = {rootDir: '/', files: {[compositionFile]: input}};const renamed = renameComposition({- project: {rootDir: '/', files: {[compositionFile]: input}},+ project,compositionFile,compositionId: 'Original',newId: 'Renamed',});- expect(renamed.project.files[compositionFile]).toBe(+ expect(getChangedContents(renamed, compositionFile)).toBe(input.replace('id="Original"', 'id="Renamed"'),);+ const afterRename = applyCodemodChanges(project, renamed.changes);const duplicated = duplicateComposition({- project: renamed.project,+ project: afterRename,compositionFile,compositionId: 'Renamed',newId: 'Copy',});- expect(duplicated.project.files[compositionFile]).toBe(- renamed.project.files[compositionFile].replace(+ expect(getChangedContents(duplicated, compositionFile)).toBe(+ getChangedContents(renamed, compositionFile).replace(composition.replace('Original', 'Renamed'),composition.replace('Original', 'Renamed') +eol +composition.replace('Original', 'Copy'),),);+ const afterDuplicate = applyCodemodChanges(afterRename, duplicated.changes);const deleted = deleteComposition({- project: duplicated.project,+ project: afterDuplicate,compositionFile,compositionId: 'Copy',});- expect(deleted.project.files[compositionFile]).toBe(- renamed.project.files[compositionFile],+ expect(getChangedContents(deleted, compositionFile)).toBe(+ getChangedContents(renamed, compositionFile),);});}@@ -100,7 +105,7 @@ test('new compositions append to fragments and folders and wrap standalone roots});const inserted ='<Composition\n id="Fresh"\n component={Fresh}\n durationInFrames={90}\n fps={30}\n width={1920}\n height={1080}\n />';- expect(result.project.files[compositionFile]).toBe(+ expect(getChangedContents(result, compositionFile)).toBe("import {Fresh} from './Fresh';\n" +input.replace(root, expected.replace('INSERT', inserted)),);@@ -124,7 +129,7 @@ export const Root = () => (tag: 'Still',metadata: {width: 500, height: 400},});- const output = result.project.files[compositionFile];+ const output = getChangedContents(result, compositionFile);expect(output).toContain("import {Composition, Still} from 'remotion';");expect(output).toContain(' <Still id="Poster" width={500} height={400}>\n {/* keep the child */}\n <Child />\n </Still>',@@ -146,21 +151,23 @@ test('rename preserves expression quotes and delete replaces standalone and cond`enabled ? ${original} : null`,]) {const input = `${imports}export const Root = () => ${expression};\n`;+ const project = {rootDir: '/', files: {[compositionFile]: input}};const renamed = renameComposition({- project: {rootDir: '/', files: {[compositionFile]: input}},+ project,compositionFile,compositionId: 'Original',newId: 'Renamed',});- expect(renamed.project.files[compositionFile]).toBe(+ expect(getChangedContents(renamed, compositionFile)).toBe(input.replace('Original', 'Renamed'),);+ const afterRename = applyCodemodChanges(project, renamed.changes);const deleted = deleteComposition({- project: renamed.project,+ project: afterRename,compositionFile,compositionId: 'Renamed',});- expect(deleted.project.files[compositionFile]).toBe(+ expect(getChangedContents(deleted, compositionFile)).toBe(imports +(expression.startsWith('enabled')? 'export const Root = () => enabled ? null : null;\n'@@ -189,7 +196,7 @@ test('updates computed and shorthand metadata while adding missing values withoucompositionId: 'Original',metadata: {durationInFrames: 240, fps: 60, width: 1920, height: 1080},});- expect(result.project.files[compositionFile]).toBe(+ expect(getChangedContents(result, compositionFile)).toBe(input.replace('{ WIDTH } height>','{1920} height={1080} fps={60} durationInFrames={240}>',@@ -218,7 +225,7 @@ test('adds missing composition metadata using multiline source style', () => {compositionId: 'Original',metadata: {durationInFrames: 90, fps: 30, width: 1920, height: 1080},});- expect(result.project.files[compositionFile]).toBe(+ expect(getChangedContents(result, compositionFile)).toBe(input.replace(`${indent}/>`,[@@ -244,7 +251,7 @@ export const Root=()=> <Still id={'Original'} height = "720"/>;compositionId: 'Original',metadata: {width: 1920, height: 1080},});- expect(result.project.files[compositionFile]).toBe(+ expect(getChangedContents(result, compositionFile)).toBe(input.replace('height = "720"', 'height = {1080} width={1920}'),);});@@ -260,8 +267,9 @@ test('composition edits resolve named aliases and namespace imports without chan]) {const original = `<${originalTag} id="Original" fps={30} durationInFrames={90}><Child /></${originalTag}>`;const input = `${imports}\nexport const Root = () => ${original};\n`;+ const project = {rootDir: '/', files: {[compositionFile]: input}};const copy = duplicateComposition({- project: {rootDir: '/', files: {[compositionFile]: input}},+ project,compositionFile,compositionId: 'Original',newId: 'Poster',@@ -269,16 +277,16 @@ test('composition edits resolve named aliases and namespace imports without chanmetadata: {width: 500, height: 400},});const renamed = renameComposition({- project: copy.project,+ project: applyCodemodChanges(project, copy.changes),compositionFile,compositionId: 'Poster',newId: 'Renamed',});- expect(renamed.project.files[compositionFile]).toContain(original);- expect(renamed.project.files[compositionFile]).toContain(+ expect(getChangedContents(renamed, compositionFile)).toContain(original);+ expect(getChangedContents(renamed, compositionFile)).toContain(`<${expectedTag} id="Renamed" width={500} height={400}>`,);- expect(renamed.project.files[compositionFile]).toContain(+ expect(getChangedContents(renamed, compositionFile)).toContain(`</${expectedTag}>`,);}diff --git a/packages/codemods/src/test/folder-source-edits.test.ts b/packages/codemods/src/test/folder-source-edits.test.tsindex 035a60886e..d2063adb51 100644--- a/packages/codemods/src/test/folder-source-edits.test.ts+++ b/packages/codemods/src/test/folder-source-edits.test.ts@@ -6,6 +6,7 @@ import {renameFolder,unwrapFolder,} from '../index';+import {getChangedContents} from './get-changed-contents';const compositionFile = 'Root.tsx';@@ -21,12 +22,13 @@ export const Root = () => (</Folder>);`;- const output = renameFolder({+ const outputResult = renameFolder({project: {rootDir: '/', files: {[compositionFile]: input}},compositionFile,folder: {name: 'Old name', parentName: null},newName: 'New name',- }).project.files[compositionFile];+ });+ const output = getChangedContents(outputResult, compositionFile);expect(output).toBe(input.replace("'Old name'", "'New name'"));});@@ -44,11 +46,12 @@ test('creates top-level and nested folders without formatting the file', () => {')','',].join('\r\n');- const topLevel = addFolder({+ const topLevelResult = addFolder({project: {rootDir: '/', files: {[compositionFile]: input}},compositionFile,folder: {name: 'Top level', parentName: null},- }).project.files[compositionFile];+ });+ const topLevel = getChangedContents(topLevelResult, compositionFile);expect(topLevel).toBe(input.replace(@@ -61,11 +64,12 @@ test('creates top-level and nested folders without formatting the file', () => {),);- const nested = addFolder({+ const nestedResult = addFolder({project: {rootDir: '/', files: {[compositionFile]: topLevel}},compositionFile,folder: {name: 'Nested', parentName: 'Existing'},- }).project.files[compositionFile];+ });+ const nested = getChangedContents(nestedResult, compositionFile);expect(nested).toBe(topLevel.replace(' <Folder name="Existing" />',@@ -94,11 +98,12 @@ export const Root = () => (</>);`;- const output = unwrapFolder({+ const outputResult = unwrapFolder({project: {rootDir: '/', files: {[compositionFile]: input}},compositionFile,folder: {name: 'Remove', parentName: null},- }).project.files[compositionFile];+ });+ const output = getChangedContents(outputResult, compositionFile);expect(output).toBe(input.replace(@@ -136,12 +141,13 @@ export const Root = () => {);};`;- const output = moveComposition({+ const outputResult = moveComposition({project: {rootDir: '/', files: {[compositionFile]: input}},compositionFile,compositionId: 'Move',destination: {type: 'folder', folder: {name: 'Target', parentName: null}},- }).project.files[compositionFile];+ });+ const output = getChangedContents(outputResult, compositionFile);expect(output).toBe(input@@ -180,7 +186,7 @@ export const Root = () => {);};`;- const output = moveFolder({+ const outputResult = moveFolder({project: {rootDir: '/', files: {[compositionFile]: input}},compositionFile,folder: {name: 'Move', parentName: null},@@ -188,7 +194,8 @@ export const Root = () => {type: 'after',target: {type: 'folder', name: 'Target', parentName: null},},- }).project.files[compositionFile];+ });+ const output = getChangedContents(outputResult, compositionFile);expect(output).toBe(input@@ -258,7 +265,7 @@ export const Standalone = () => <Composition id="Standalone" />;compositionId: 'Move',destination: {type: 'folder', folder: {name: 'Parent', parentName: null}},});- expect(moved.project.files[compositionFile]).toContain(+ expect(getChangedContents(moved, compositionFile)).toContain('<Folder name="Child" />\n <Composition id="Move" />\n </Folder>',);expect(project.files[compositionFile]).toBe(input);diff --git a/packages/codemods/src/test/formatting.test.ts b/packages/codemods/src/test/formatting.test.tsindex 17f416f782..c436dd8504 100644--- a/packages/codemods/src/test/formatting.test.ts+++ b/packages/codemods/src/test/formatting.test.ts@@ -1,9 +1,11 @@import {expect, test} from 'bun:test';import {+ applyCodemodChanges,getJsxNodes,updateJsxNodeKeyframes,updateJsxNodeProps,} from '../index';+import {getChangedContents} from './get-changed-contents';for (const indentation of ['\t', ' ', ' ']) {for (const endOfLine of ['\n', '\r\n']) {@@ -45,23 +47,25 @@ export const Video = () => {const expected = input.replace('render = {', 'render={').replace(format('\t\t/>'), format("\t\t\ttitle={'Hello'}\n\t\t/>"));- expect(changed.project.files[filePath]).toBe(expected);+ expect(getChangedContents(changed, filePath)).toBe(expected);+ const afterChange = applyCodemodChanges(project, changed.changes);const repeated = updateJsxNodeProps({- project: changed.project,+ project: afterChange,node: changed.updatedNode,props: {title: 'Hello'},});- expect(repeated.project.files[filePath]).toBe(expected);+ const afterRepeat = applyCodemodChanges(afterChange, repeated.changes);+ expect(afterRepeat.files[filePath]).toBe(expected);const animated = await updateJsxNodeKeyframes({- project: repeated.project,+ project: afterRepeat,node: repeated.updatedNode,updates: [{key: 'style.opacity', operation: {type: 'add', frame: 0, value: 0}},],});- expect(animated.project.files[filePath]).toBe(+ expect(getChangedContents(animated, filePath)).toBe(expected.replace('{AbsoluteFill}',diff --git a/packages/codemods/src/test/generate-canvas-capture-composition.test.ts b/packages/codemods/src/test/generate-canvas-capture-composition.test.tsindex 67ba41a512..c97881be12 100644--- a/packages/codemods/src/test/generate-canvas-capture-composition.test.ts+++ b/packages/codemods/src/test/generate-canvas-capture-composition.test.ts@@ -6,6 +6,7 @@ import {parseCanvasCaptureData,} from '@remotion/studio-shared';import {addCanvasCaptureComposition, type CodemodProject} from '../index';+import {getChangedContents} from './get-changed-contents';test('creates and registers an interactive Canvas Capture composition', () => {const fixtureDirectory = path.join(__dirname, 'fixtures');@@ -55,11 +56,11 @@ test('creates and registers an interactive Canvas Capture composition', () => {.replaceAll('\r\n', '\n').replaceAll('\r', '\n');- expect(result.project.files[componentFile]).toBe(expected);- expect(result.project.files[compositionFile]).toContain(+ expect(getChangedContents(result, componentFile)).toBe(expected);+ expect(getChangedContents(result, compositionFile)).toContain("import {CanvasCaptureComposition} from './CanvasCaptureComposition';",);- expect(result.project.files[compositionFile]).toMatch(+ expect(getChangedContents(result, compositionFile)).toMatch(/<Folder name="Captures">\s*<CanvasCaptureComposition \/>\s*<\/Folder>/,);expect(result.changes.map((change) => change.filePath)).toEqual([diff --git a/packages/codemods/src/test/get-changed-contents.ts b/packages/codemods/src/test/get-changed-contents.tsnew file mode 100644index 0000000000..3250d452ae--- /dev/null+++ b/packages/codemods/src/test/get-changed-contents.ts@@ -0,0 +1,12 @@+import type {CodemodResult} from '../index';++export const getChangedContents = (result: CodemodResult, filePath: string) => {+ const contents = result.changes.find(+ (change) => change.filePath === filePath,+ )?.nextContents;+ if (contents === null || contents === undefined) {+ throw new Error(`Expected a changed file: ${filePath}`);+ }++ return contents;+};diff --git a/packages/codemods/src/test/insert-solid.test.ts b/packages/codemods/src/test/insert-solid.test.tsindex 21dccc57ed..96d46d2da6 100644--- a/packages/codemods/src/test/insert-solid.test.ts+++ b/packages/codemods/src/test/insert-solid.test.ts@@ -98,7 +98,7 @@ export const Root = () => <Composition id = "MyComp" component={MyComposition}/>wrapInSequence: null,});- expect(result.project.files['/project/src/index.tsx'])+ expect(result.output).toBe(`import {Composition, AbsoluteFill, Solid} from 'remotion';// Keep the deliberately non-Prettier formatting in this file.@@ -178,13 +178,7 @@ export const Root = () => <Composition id="MyComp" component={MyComposition}/>;wrapInSequence: null,});- expect(assetResult.project.files['/project/src/index.tsx']).toContain(- '<CanvasImage\n',- );- expect(componentResult.project.files['/project/src/index.tsx']).toContain(- '<Chart\n',- );- expect(componentResult.project.files['/project/src/index.tsx']).toContain(- 'title="Revenue"',- );+ expect(assetResult.output).toContain('<CanvasImage\n');+ expect(componentResult.output).toContain('<Chart\n');+ expect(componentResult.output).toContain('title="Revenue"');});diff --git a/packages/codemods/src/test/public-api.test.ts b/packages/codemods/src/test/public-api.test.tsindex 763cf2300c..c60ad2f69f 100644--- a/packages/codemods/src/test/public-api.test.ts+++ b/packages/codemods/src/test/public-api.test.ts@@ -1,5 +1,10 @@import {expect, test} from 'bun:test';-import {addSolid, deleteJsxNodes} from '../index';+import {+ addSolid,+ applyCodemodChanges,+ deleteJsxNodes,+ type CodemodProject,+} from '../index';const makeProject = () => ({entryPoint: 'src/index.ts',@@ -35,11 +40,12 @@ test('addSolid() immutably updates a virtual project', () => {project,width: 1280,});+ const updated = applyCodemodChanges(project, result.changes);- expect(result.project.entryPoint).toBe('src/index.ts');- expect(result.project).not.toBe(project);+ expect(updated.entryPoint).toBe('src/index.ts');+ expect(updated).not.toBe(project);expect(project.files['src/Video.tsx']).not.toContain('<Solid');- expect(result.project.files['src/Video.tsx']).toContain(+ expect(updated.files['src/Video.tsx']).toContain('<Solid width={1280} height={720}',);expect(result.insertedNode.filePath).toBe('src/Video.tsx');@@ -48,7 +54,7 @@ test('addSolid() immutably updates a virtual project', () => {{filePath: 'src/Video.tsx',previousContents: project.files['src/Video.tsx'],- nextContents: result.project.files['src/Video.tsx'],+ nextContents: updated.files['src/Video.tsx'],},]);});@@ -62,20 +68,23 @@ test('deleteJsxNodes() deletes nodes from multiple files', async () => {project,width: 1280,});+ const afterFirst = applyCodemodChanges(project, first.changes);const second = addSolid({compositionFile: 'src/Root2.tsx',compositionId: 'Demo2',height: 720,- project: first.project,+ project: afterFirst,width: 1280,});+ const afterSecond = applyCodemodChanges(afterFirst, second.changes);const result = await deleteJsxNodes({nodes: [first.insertedNode, second.insertedNode],- project: second.project,+ project: afterSecond,});+ const updated = applyCodemodChanges(afterSecond, result.changes);- expect(result.project.files['src/Video.tsx']).not.toContain('<Solid');- expect(result.project.files['src/Video2.tsx']).not.toContain('<Solid');+ expect(updated.files['src/Video.tsx']).not.toContain('<Solid');+ expect(updated.files['src/Video2.tsx']).not.toContain('<Solid');expect(result.changes.map((change) => change.filePath)).toEqual(['src/Video.tsx','src/Video2.tsx',@@ -92,7 +101,8 @@ test('deleteJsxNodes() deletes the Sequence wrapper identified by a node path',project,width: 1280,});- const sourceWithSolid = added.project.files['src/Video.tsx'];+ const afterAdd = applyCodemodChanges(project, added.changes);+ const sourceWithSolid = afterAdd.files['src/Video.tsx'];expect(sourceWithSolid).toContain('<Sequence from={10}');const result = await deleteJsxNodes({nodes: [@@ -101,18 +111,54 @@ test('deleteJsxNodes() deletes the Sequence wrapper identified by a node path',nodePath: added.insertedNode.nodePath,},],- project: added.project,+ project: afterAdd,});+ const updated = applyCodemodChanges(afterAdd, result.changes);- expect(result.project.entryPoint).toBe('src/index.ts');- expect(result.project).not.toBe(added.project);- expect(added.project.files['src/Video.tsx']).toContain('<Solid');- expect(result.project.files['src/Video.tsx']).not.toContain('<Solid');+ expect(updated.entryPoint).toBe('src/index.ts');+ expect(updated).not.toBe(afterAdd);+ expect(afterAdd.files['src/Video.tsx']).toContain('<Solid');+ expect(updated.files['src/Video.tsx']).not.toContain('<Solid');expect(result.changes).toEqual([{filePath: 'src/Video.tsx',previousContents: sourceWithSolid,- nextContents: result.project.files['src/Video.tsx'],+ nextContents: updated.files['src/Video.tsx'],},]);});++test('applyCodemodChanges checks every file before applying a transaction', () => {+ const project: CodemodProject & {entryPoint: string} = makeProject();+ const changes = [+ {+ filePath: 'src/Video.tsx',+ previousContents: project.files['src/Video.tsx'],+ nextContents: 'updated video',+ },+ {+ filePath: 'src/New.tsx',+ previousContents: null,+ nextContents: 'new component',+ },+ ];+ const updated = applyCodemodChanges(project, changes);+ expect(updated.files['src/Video.tsx']).toBe('updated video');+ expect(updated.files['src/New.tsx']).toBe('new component');+ expect(project.files['src/New.tsx']).toBeUndefined();++ const undo = changes.map((change) => ({+ ...change,+ previousContents: change.nextContents,+ nextContents: change.previousContents,+ }));+ expect(applyCodemodChanges(updated, undo).files).toEqual(project.files);++ expect(() =>+ applyCodemodChanges(project, [+ changes[0],+ {...changes[1], previousContents: 'stale'},+ ]),+ ).toThrow('Source changed before applying codemod: src/New.tsx');+ expect(project.files['src/Video.tsx']).not.toBe('updated video');+});diff --git a/packages/codemods/src/test/public-editing.test.ts b/packages/codemods/src/test/public-editing.test.tsindex e6a7d6b65e..0ab722f347 100644--- a/packages/codemods/src/test/public-editing.test.ts+++ b/packages/codemods/src/test/public-editing.test.ts@@ -6,6 +6,7 @@ import {addFolder,addMedia,addSolid,+ applyCodemodChanges,deleteComposition,deleteEffects,deleteJsxNodes,@@ -33,6 +34,7 @@ import {updateMultipleJsxNodeProps,type CodemodProject,} from '../index';+import {getChangedContents} from './get-changed-contents';const compositionFile = 'src/Root.tsx';const filePath = 'src/Video.tsx';@@ -87,21 +89,23 @@ test('discover, inspect, edit, animate, and remove JSX through the public API',node,props: {children: 'Goodbye', 'style.opacity': 0.75, title: 'Example'},});- expect(changed.project.entryPoint).toBe(project.entryPoint);+ const afterChange = applyCodemodChanges(project, changed.changes);+ expect(afterChange.entryPoint).toBe(project.entryPoint);expect(project.files[filePath]).toContain('Hello');- expect(changed.project.files[filePath]).toContain('Goodbye');- expect(changed.project.files[filePath]).toContain(+ expect(getChangedContents(changed, filePath)).toContain('Goodbye');+ expect(getChangedContents(changed, filePath)).toContain('const unrelated = {value:"keep"};',);const animated = await updateJsxNodeKeyframes({- project: changed.project,+ project: afterChange,node: changed.updatedNode,updates: [{key: 'style.opacity', operation: {type: 'add', frame: 0, value: 0}},{key: 'style.opacity', operation: {type: 'add', frame: 30, value: 1}},],});- expect(animated.project.files[filePath]).toContain('useCurrentFrame');+ const afterAnimation = applyCodemodChanges(afterChange, animated.changes);+ expect(getChangedContents(animated, filePath)).toContain('useCurrentFrame');expect(animated.nodePathRemappings.some((entry) =>@@ -110,7 +114,7 @@ test('discover, inspect, edit, animate, and remove JSX through the public API',).toBe(true);expect(getJsxNodeProps({- project: animated.project,+ project: afterAnimation,node: animated.updatedNode,keys: ['style.opacity'],}).props['style.opacity'],@@ -122,19 +126,24 @@ test('discover, inspect, edit, animate, and remove JSX through the public API',],});const withoutTitle = updateJsxNodeProps({- project: animated.project,+ project: afterAnimation,node: animated.updatedNode,props: {title: undefined},});- expect(withoutTitle.project.files[filePath]).not.toContain('title=');+ expect(getChangedContents(withoutTitle, filePath)).not.toContain('title=');+ const afterRemoveTitle = applyCodemodChanges(+ afterAnimation,+ withoutTitle.changes,+ );const deleted = await deleteJsxNodes({- project: withoutTitle.project,+ project: afterRemoveTitle,nodes: [withoutTitle.updatedNode],});expect(- getJsxNodes({project: deleted.project, filePath}).map(- (entry) => entry.tagName,- ),+ getJsxNodes({+ project: applyCodemodChanges(afterRemoveTitle, deleted.changes),+ filePath,+ }).map((entry) => entry.tagName),).toEqual(['AbsoluteFill']);expect(deleted.nodePathRemappings.some((entry) => entry.newNodePath === null),@@ -154,31 +163,30 @@ test('insert media and components, reorder copies, and delete nodes across filesdurationInFrames: 30,dimensions: {width: 100, height: 100},});- expect(media.project.files[filePath]).toMatch(+ expect(getChangedContents(media, filePath)).toMatch(/staticFile\(["']photo\.png["']\)/,);+ const afterMedia = applyCodemodChanges(project, media.changes);expect(getJsxNodeProps({- project: media.project,+ project: afterMedia,node: media.insertedNode,keys: ['from'],}).props.from,).toMatchObject({codeValue: 10});const added = await addComponent({- project: media.project,+ project: afterMedia,compositionFile,compositionId: 'Demo',importName: 'Title',importPath: './Title',props: {text: 'A title'},});- expect(added.project.files[filePath]).toContain("from './Title'");+ expect(getChangedContents(added, filePath)).toContain("from './Title'");+ const afterAdd = applyCodemodChanges(afterMedia, added.changes);const duplicated = await duplicateJsxNodes({- project: added.project,- nodes: [- added.insertedNode,- findNode(added.project, 'div', 'src/Title.tsx'),- ],+ project: afterAdd,+ nodes: [added.insertedNode, findNode(afterAdd, 'div', 'src/Title.tsx')],});expect(duplicated.insertedNodes).toHaveLength(2);expect(duplicated.changes.map((change) => change.filePath)).toEqual([@@ -188,22 +196,25 @@ test('insert media and components, reorder copies, and delete nodes across filesconst copiedTitle = duplicated.insertedNodes.find((node) => node.filePath === filePath,)!;+ const afterDuplicate = applyCodemodChanges(afterAdd, duplicated.changes);const reordered = await reorderJsxNode({- project: duplicated.project,+ project: afterDuplicate,node: copiedTitle,target: added.insertedNode,position: 'before',});+ const afterReorder = applyCodemodChanges(afterDuplicate, reordered.changes);const updatedCopy = updateJsxNodeProps({- project: reordered.project,+ project: afterReorder,node: reordered.updatedNode,props: {text: 'Copied title'},});expect(- updatedCopy.project.files[filePath].indexOf('Copied title'),- ).toBeLessThan(updatedCopy.project.files[filePath].indexOf('A title'));+ getChangedContents(updatedCopy, filePath).indexOf('Copied title'),+ ).toBeLessThan(getChangedContents(updatedCopy, filePath).indexOf('A title'));+ const afterUpdate = applyCodemodChanges(afterReorder, updatedCopy.changes);const deleted = await deleteJsxNodes({- project: updatedCopy.project,+ project: afterUpdate,nodes: [updatedCopy.updatedNode,duplicated.insertedNodes.find(@@ -211,15 +222,14 @@ test('insert media and components, reorder copies, and delete nodes across files)!,],});+ const afterDelete = applyCodemodChanges(afterUpdate, deleted.changes);expect(- getJsxNodes({project: deleted.project, filePath}).filter(+ getJsxNodes({project: afterDelete, filePath}).filter((node) => node.tagName === 'Title',),).toHaveLength(1);- expect(deleted.project.files['src/Title.tsx']).toContain('{text}');- expect(Object.keys(deleted.project.files)).toEqual(- Object.keys(project.files),- );+ expect(getChangedContents(deleted, 'src/Title.tsx')).toContain('{text}');+ expect(Object.keys(afterDelete.files)).toEqual(Object.keys(project.files));});test('split timeline media and detach audio', async () => {@@ -235,9 +245,10 @@ export const VideoComposition = () => <><Video src="video.mp4" from={10} duratio});expect(split.insertedNodes).toHaveLength(2);const secondVideo = split.insertedNodes[0];+ const afterSplit = applyCodemodChanges(project, split.changes);expect(getJsxNodeProps({- project: split.project,+ project: afterSplit,node: secondVideo,keys: ['from', 'durationInFrames', 'trimBefore'],}).props,@@ -247,19 +258,20 @@ export const VideoComposition = () => <><Video src="video.mp4" from={10} duratiotrimBefore: {codeValue: 35},});const detached = await detachAudio({- project: split.project,+ project: afterSplit,node: secondVideo,});+ const afterDetach = applyCodemodChanges(afterSplit, detached.changes);expect(getJsxNodeProps({- project: detached.project,+ project: afterDetach,node: detached.updatedNode,keys: ['muted'],}).props.muted,).toMatchObject({codeValue: true});expect(getJsxNodeProps({- project: detached.project,+ project: afterDetach,node: detached.insertedNode,keys: ['src', 'trimBefore'],}).props,@@ -276,81 +288,117 @@ test('manage composition registrations and nested folders without changing compo`export const Root = () => {\n${helper}\nreturn `,).replace('/>;\n', '/>;\n};\n');- let {project} = addComposition({- project: original,- compositionFile,- compositionId: 'Second',- component: {importName: 'Title', importPath: './Title'},- metadata: {width: 1920, height: 1080, fps: 30, durationInFrames: 60},- });+ let project = applyCodemodChanges(+ original,+ addComposition({+ project: original,+ compositionFile,+ compositionId: 'Second',+ component: {importName: 'Title', importPath: './Title'},+ metadata: {width: 1920, height: 1080, fps: 30, durationInFrames: 60},+ }).changes,+ );expect(project.files[compositionFile]).toContain(helper);- project = setCompositionDefaultProps({- project,- compositionFile,- compositionId: 'Second',- defaultProps: {text: 'Title'},- }).project;- project = duplicateComposition({+ project = applyCodemodChanges(project,- compositionFile,- compositionId: 'Second',- newId: 'Portrait',- metadata: {width: 1080, height: 1920},- }).project;- project = renameComposition({+ setCompositionDefaultProps({+ project,+ compositionFile,+ compositionId: 'Second',+ defaultProps: {text: 'Title'},+ }).changes,+ );+ project = applyCodemodChanges(project,- compositionFile,- compositionId: 'Portrait',- newId: 'Vertical',- }).project;- project = updateCompositionMetadata({+ duplicateComposition({+ project,+ compositionFile,+ compositionId: 'Second',+ newId: 'Portrait',+ metadata: {width: 1080, height: 1920},+ }).changes,+ );+ project = applyCodemodChanges(project,- compositionFile,- compositionId: 'Vertical',- metadata: {fps: 60, durationInFrames: 120},- }).project;- project = addFolder({+ renameComposition({+ project,+ compositionFile,+ compositionId: 'Portrait',+ newId: 'Vertical',+ }).changes,+ );+ project = applyCodemodChanges(project,- compositionFile,- folder: {name: 'Social', parentName: null},- }).project;- project = addFolder({+ updateCompositionMetadata({+ project,+ compositionFile,+ compositionId: 'Vertical',+ metadata: {fps: 60, durationInFrames: 120},+ }).changes,+ );+ project = applyCodemodChanges(project,- compositionFile,- folder: {name: 'Archive', parentName: 'Social'},- }).project;- project = moveComposition({+ addFolder({+ project,+ compositionFile,+ folder: {name: 'Social', parentName: null},+ }).changes,+ );+ project = applyCodemodChanges(project,- compositionFile,- compositionId: 'Vertical',- destination: {- type: 'folder',+ addFolder({+ project,+ compositionFile,folder: {name: 'Archive', parentName: 'Social'},- },- }).project;- project = renameFolder({+ }).changes,+ );+ project = applyCodemodChanges(project,- compositionFile,- folder: {name: 'Archive', parentName: 'Social'},- newName: 'Published',- }).project;- project = moveFolder({+ moveComposition({+ project,+ compositionFile,+ compositionId: 'Vertical',+ destination: {+ type: 'folder',+ folder: {name: 'Archive', parentName: 'Social'},+ },+ }).changes,+ );+ project = applyCodemodChanges(project,- compositionFile,- folder: {name: 'Published', parentName: 'Social'},- destination: {type: 'root'},- }).project;- project = moveFolder({+ renameFolder({+ project,+ compositionFile,+ folder: {name: 'Archive', parentName: 'Social'},+ newName: 'Published',+ }).changes,+ );+ project = applyCodemodChanges(project,- compositionFile,- folder: {name: 'Published', parentName: null},- destination: {type: 'folder', folder: {name: 'Social', parentName: null}},- }).project;- project = unwrapFolder({+ moveFolder({+ project,+ compositionFile,+ folder: {name: 'Published', parentName: 'Social'},+ destination: {type: 'root'},+ }).changes,+ );+ project = applyCodemodChanges(project,- compositionFile,- folder: {name: 'Social', parentName: null},- }).project;+ moveFolder({+ project,+ compositionFile,+ folder: {name: 'Published', parentName: null},+ destination: {type: 'folder', folder: {name: 'Social', parentName: null}},+ }).changes,+ );+ project = applyCodemodChanges(+ project,+ unwrapFolder({+ project,+ compositionFile,+ folder: {name: 'Social', parentName: null},+ }).changes,+ );expect(project.files[compositionFile]).not.toContain('name="Social"');expect(project.files[compositionFile]).toContain('name="Published"');const composition = getJsxNodes({project, filePath: compositionFile}).find(@@ -372,11 +420,14 @@ test('manage composition registrations and nested folders without changing compodurationInFrames: {codeValue: 120},defaultProps: {codeValue: {text: 'Title'}},});- project = deleteComposition({+ project = applyCodemodChanges(project,- compositionFile,- compositionId: 'Second',- }).project;+ deleteComposition({+ project,+ compositionFile,+ compositionId: 'Second',+ }).changes,+ );expect(project.files[compositionFile]).not.toContain('id="Second"');expect(project.files[filePath]).toBe(original.files[filePath]);expect(project.files['src/Title.tsx']).toBe(original.files['src/Title.tsx']);@@ -393,40 +444,46 @@ test('add, duplicate, reorder, edit, animate, and delete effects', async () => {importPath: '@remotion/effects/blur',props: {radius: 1},});+ const afterFirst = applyCodemodChanges(project, first.changes);const second = await addEffect({- project: first.project,+ project: afterFirst,node: first.insertedEffect,importName: 'brightness',importPath: '@remotion/effects/brightness',props: {amount: 1},});+ const afterSecond = applyCodemodChanges(afterFirst, second.changes);const duplicate = await duplicateEffects({- project: second.project,+ project: afterSecond,effects: [first.insertedEffect, second.insertedEffect],});expect(duplicate.insertedEffects.map((effect) => effect.effectIndex)).toEqual([1, 3],);+ const afterDuplicate = applyCodemodChanges(afterSecond, duplicate.changes);const reordered = await reorderEffect({- project: duplicate.project,+ project: afterDuplicate,effect: duplicate.insertedEffects[1],toIndex: 0,});+ const afterReorder = applyCodemodChanges(afterDuplicate, reordered.changes);const edited = await updateEffectProps({- project: reordered.project,+ project: afterReorder,effect: reordered.updatedEffect,props: {amount: 2},});+ const afterEdit = applyCodemodChanges(afterReorder, edited.changes);const animated = await updateEffectKeyframes({- project: edited.project,+ project: afterEdit,effect: edited.updatedEffect,updates: [{key: 'amount', operation: {type: 'add', frame: 0, value: 1}},{key: 'amount', operation: {type: 'add', frame: 30, value: 2}},],});+ const afterAnimation = applyCodemodChanges(afterEdit, animated.changes);const status = getJsxNodeProps({- project: animated.project,+ project: afterAnimation,node: animated.updatedEffect,keys: [],effectKeys: [['amount'], ['radius'], ['radius'], ['amount']],@@ -437,21 +494,22 @@ test('add, duplicate, reorder, edit, animate, and delete effects', async () => {props: {amount: {status: 'keyframed'}},});const deleted = await deleteEffects({- project: animated.project,+ project: afterAnimation,effects: [animated.updatedEffect,{...animated.updatedEffect, effectIndex: 3},],});+ const afterDelete = applyCodemodChanges(afterAnimation, deleted.changes);expect(getJsxNodeProps({- project: deleted.project,+ project: afterDelete,node: animated.updatedEffect,keys: [],effectKeys: [['radius'], ['radius']],}).effects.map((effect) => (effect.canUpdate ? effect.callee : null)),).toEqual(['blur', 'blur']);- expect(deleted.project.files[filePath]).toContain(+ expect(getChangedContents(deleted, filePath)).toContain('const unrelated = {value:"keep"};',);expect(project.files[filePath]).not.toContain('effects=');@@ -515,6 +573,7 @@ test('existing addSolid returns remappings usable by public discovery', () => {height: 100,from: 15,});+ const afterInsert = applyCodemodChanges(project, inserted.changes);expect(inserted.nodePathRemappings.some((entry) =>@@ -525,7 +584,7 @@ test('existing addSolid returns remappings usable by public discovery', () => {).toBe(true);expect(getJsxNodeProps({- project: inserted.project,+ project: afterInsert,node: inserted.insertedNode,keys: ['from'],}).props.from,@@ -545,28 +604,32 @@ test('nested copies return root references and insertion preserves relative keysdurationInFrames: 60,});expect(media.insertedNode.filePath).toBe(filePath);- expect(Object.keys(media.project.files)).toEqual(Object.keys(original.files));+ const afterMedia = applyCodemodChanges(original, media.changes);+ expect(Object.keys(afterMedia.files)).toEqual(Object.keys(original.files));const copy = await duplicateJsxNodes({- project: media.project,+ project: afterMedia,nodes: [media.insertedNode],});expect(copy.insertedNodes).toHaveLength(1);expect(copy.nodePathRemappings.filter((entry) => entry.oldNodePath === null),).toHaveLength(2);+ const afterCopy = applyCodemodChanges(afterMedia, copy.changes);const split = await splitSequences({- project: copy.project,+ project: afterCopy,splits: [{node: copy.insertedNodes[0], frame: 30}],});expect(split.insertedNodes).toHaveLength(1);+ const afterSplit = applyCodemodChanges(afterCopy, split.changes);const deleted = await deleteJsxNodes({- project: split.project,+ project: afterSplit,nodes: split.insertedNodes,});expect(- getJsxNodes({project: deleted.project, filePath}).filter(- (node) => node.tagName === 'Sequence',- ),+ getJsxNodes({+ project: applyCodemodChanges(afterSplit, deleted.changes),+ filePath,+ }).filter((node) => node.tagName === 'Sequence'),).toHaveLength(2);});@@ -601,9 +664,9 @@ test('node discovery and edits use original source locations with tabs and CRLF'node,props: {'style.opacity': 0.25},});- expect(edited.project.files[filePath]).toContain('opacity: 0.25');- expect(edited.project.files[filePath].startsWith('\uFEFF')).toBe(true);- expect(edited.project.files[filePath]).toContain('\r\n');+ expect(getChangedContents(edited, filePath)).toContain('opacity: 0.25');+ expect(getChangedContents(edited, filePath).startsWith('\uFEFF')).toBe(true);+ expect(getChangedContents(edited, filePath)).toContain('\r\n');});test('batch structured prop edits across files and preserve edit results in request order', () => {@@ -636,9 +699,10 @@ test('batch structured prop edits across files and preserve edit results in requ'second.tsx','first.tsx',]);+ const updated = applyCodemodChanges(project, result.changes);expect(getJsxNodeProps({- project: result.project,+ project: updated,node: result.updatedNodes[0],keys: ['style.opacity', 'title'],}).props,@@ -648,7 +712,7 @@ test('batch structured prop edits across files and preserve edit results in requ});expect(getJsxNodeProps({- project: result.project,+ project: updated,node: result.updatedNodes[1],keys: ['title'],}).props.title,@@ -672,11 +736,13 @@ export const Root = () => <Composition id="Comp" defaultProps={{mode: 'old'}} />enumPaths: [['mode']],});expect(result.logLine).toBe(3);- expect(result.project.files['Root.tsx']).toContain(+ expect(getChangedContents(result, 'Root.tsx')).toContain('const untouched = "keep this spacing";',);- expect(result.project.files['Root.tsx']).toContain("mode: 'fast' as const");- expect(result.project.files['Root.tsx']).toMatch(+ expect(getChangedContents(result, 'Root.tsx')).toContain(+ "mode: 'fast' as const",+ );+ expect(getChangedContents(result, 'Root.tsx')).toMatch(/date: new Date\(\s*'2026-07-29T00:00:00\.000Z',?\s*\)/,);});@@ -696,25 +762,27 @@ test('default prop enum serialization shares node lookup, insertion, and spreaddefaultProps: {mode: 'fast'},enumPaths,});+ const afterInsert = applyCodemodChanges(original, inserted.changes);const updated = setCompositionDefaultProps({- project: inserted.project,+ project: afterInsert,compositionFile,compositionId: 'Target',defaultProps: {mode: 'slow'},enumPaths,});+ const afterUpdate = applyCodemodChanges(afterInsert, updated.changes);expect(getJsxNodeProps({- project: updated.project,+ project: afterUpdate,node: updated.updatedNode,keys: ['defaultProps'],}).props.defaultProps,).toMatchObject({status: 'static', codeValue: {mode: 'slow'}});- expect(updated.project.files[compositionFile]).toContain(+ expect(getChangedContents(updated, compositionFile)).toContain("const untouched = 'keep spacing';",);if (enumPaths?.length) {- expect(updated.project.files[compositionFile]).toContain(+ expect(getChangedContents(updated, compositionFile)).toContain("mode: 'slow' as const",);}diff --git a/packages/codemods/src/test/registration-workflows.test.ts b/packages/codemods/src/test/registration-workflows.test.tsindex b2b89964b2..b18237441a 100644--- a/packages/codemods/src/test/registration-workflows.test.ts+++ b/packages/codemods/src/test/registration-workflows.test.ts@@ -1,6 +1,7 @@import {expect, test} from 'bun:test';import {addComposition,+ applyCodemodChanges,moveComposition,moveFolder,renameFolder,@@ -39,14 +40,17 @@ export const Root = () => (}),).toThrow('A folder named "Shared" already exists in the destination');- let {project} = addComposition({- project: original,- compositionFile,- compositionId: 'Fresh',- component: {importName: 'Fresh', importPath: './Fresh'},- metadata: {durationInFrames: 90, fps: 30, width: 1920, height: 1080},- folder: {name: 'Shared', parentName: 'Other'},- });+ let project = applyCodemodChanges(+ original,+ addComposition({+ project: original,+ compositionFile,+ compositionId: 'Fresh',+ component: {importName: 'Fresh', importPath: './Fresh'},+ metadata: {durationInFrames: 90, fps: 30, width: 1920, height: 1080},+ folder: {name: 'Shared', parentName: 'Other'},+ }).changes,+ );const added = project.files[compositionFile];expect(added).toContain(` <Folder name="Other"><Folder name="Shared">@@ -54,20 +58,26 @@ export const Root = () => (<Compositionid="Fresh"`);- project = renameFolder({+ project = applyCodemodChanges(project,- compositionFile,- folder: {name: 'Shared', parentName: 'Parent'},- newName: 'Renamed',- }).project;+ renameFolder({+ project,+ compositionFile,+ folder: {name: 'Shared', parentName: 'Parent'},+ newName: 'Renamed',+ }).changes,+ );expect(project.files[compositionFile]).toBe(added.replace('<Folder name="Shared">', '<Folder name="Renamed">'),);- project = unwrapFolder({+ project = applyCodemodChanges(project,- compositionFile,- folder: {name: 'Renamed', parentName: 'Parent'},- }).project;+ unwrapFolder({+ project,+ compositionFile,+ folder: {name: 'Renamed', parentName: 'Parent'},+ }).changes,+ );expect(project.files[compositionFile]).toContain(` <Folder name="Parent"><Composition id="NestedA" component={Video} /></Folder>`);@@ -93,12 +103,16 @@ export const Root = () => {);};`;- const {project} = moveComposition({- project: {rootDir: '/', files: {[compositionFile]: input}},- compositionFile,- compositionId: 'Nested',- destination: {type: 'root'},- });+ const original = {rootDir: '/', files: {[compositionFile]: input}};+ const project = applyCodemodChanges(+ original,+ moveComposition({+ project: original,+ compositionFile,+ compositionId: 'Nested',+ destination: {type: 'root'},+ }).changes,+ );expect(project.files[compositionFile]).toBe(input.replace(diff --git a/packages/codemods/src/test/set-composition-default-props.test.ts b/packages/codemods/src/test/set-composition-default-props.test.tsindex 38b2259f85..0e76a3e43e 100644--- a/packages/codemods/src/test/set-composition-default-props.test.ts+++ b/packages/codemods/src/test/set-composition-default-props.test.ts@@ -2,6 +2,7 @@ import {expect, test} from 'bun:test';import {readFileSync} from 'node:fs';import path from 'node:path';import {setCompositionDefaultProps} from '../index';+import {getChangedContents} from './get-changed-contents';test('updates default props without changing surrounding source', () => {const input = readFileSync(@@ -21,7 +22,7 @@ test('updates default props without changing surrounding source', () => {enumPaths: [],});- expect(result.project.files['Root.tsx']).toBe(expected);+ expect(getChangedContents(result, 'Root.tsx')).toBe(expected);expect(result.logLine).toBe(27);});@@ -44,7 +45,7 @@ test('replaces multiline default props with a compact value', () => {enumPaths: [],});- expect(result.project.files['Root.tsx']).toBe(expected);+ expect(getChangedContents(result, 'Root.tsx')).toBe(expected);});test('formats multiline default props without Prettier', () => {@@ -72,7 +73,7 @@ export const Root=()=>(enumPaths: [['mode']],});- expect(result.project.files['Root.tsx'])+ expect(getChangedContents(result, 'Root.tsx')).toBe(`import {Composition} from 'remotion'const untouched = {keep:"this spacing"}@@ -114,7 +115,7 @@ test('preserves CRLF, spaces, double quotes, and bracket spacing', () => {enumPaths: [],});- expect(result.project.files['Root.tsx']).toBe(+ expect(getChangedContents(result, 'Root.tsx')).toBe(input.replace('defaultProps={{ old: "value" }}','defaultProps={{ title: "Hello" }}',@@ -143,7 +144,7 @@ export const Root = () => (enumPaths: [['items', '[]', 'mode']],});- expect(result.project.files['Root.tsx'])+ expect(getChangedContents(result, 'Root.tsx')).toBe(`import {Composition} from "remotion";export const Root = () => (<Composition id="Comp" defaultProps={{diff --git a/packages/codemods/src/unwrap-folder.ts b/packages/codemods/src/unwrap-folder.tsindex 020a9aa289..77ab180478 100644--- a/packages/codemods/src/unwrap-folder.ts+++ b/packages/codemods/src/unwrap-folder.ts@@ -28,9 +28,6 @@ export const unwrapFolder = <Project extends CodemodProject>({parseAst(nextContents);return getCodemodResult({project,- nextProject: {- ...project,- files: {...project.files, [filePath]: nextContents},- },+ edits: [{filePath, nextContents}],});};diff --git a/packages/codemods/src/update-composition-metadata.ts b/packages/codemods/src/update-composition-metadata.tsindex 2629b41077..57036e3d0c 100644--- a/packages/codemods/src/update-composition-metadata.ts+++ b/packages/codemods/src/update-composition-metadata.ts@@ -24,7 +24,7 @@ export const updateCompositionMetadata = <Project extends CodemodProject>({compositionFile,compositionId,metadata,-}: UpdateCompositionMetadataOptions<Project>): CodemodResult<Project> => {+}: UpdateCompositionMetadataOptions<Project>): CodemodResult => {const node = requireComposition({project, compositionFile, compositionId});validateMetadata(metadata);if (@@ -35,7 +35,7 @@ export const updateCompositionMetadata = <Project extends CodemodProject>({}if (Object.values(metadata).every((value) => value === undefined)) {- return getCodemodResult({project, nextProject: project});+ return {changes: []};}const input = project.files[node.filePath];@@ -145,9 +145,6 @@ export const updateCompositionMetadata = <Project extends CodemodProject>({parseAst(output);return getCodemodResult({project,- nextProject: {- ...project,- files: {...project.files, [node.filePath]: output},- },+ edits: [{filePath: node.filePath, nextContents: output}],});};diff --git a/packages/codemods/src/update-effect-keyframes.ts b/packages/codemods/src/update-effect-keyframes.tsindex 0645822df9..5597b2de04 100644--- a/packages/codemods/src/update-effect-keyframes.ts+++ b/packages/codemods/src/update-effect-keyframes.ts@@ -53,7 +53,7 @@ export const updateEffectKeyframes = async <Project extends CodemodProject>({...result,...details,updatedEffect: {- ...getUpdatedNodeReference({...result, node: effect}),+ ...getUpdatedNodeReference({project, ...result, node: effect}),effectIndex: effect.effectIndex,},};diff --git a/packages/codemods/src/update-effect-props.ts b/packages/codemods/src/update-effect-props.tsindex 03d6c732a2..1654e54795 100644--- a/packages/codemods/src/update-effect-props.ts+++ b/packages/codemods/src/update-effect-props.ts@@ -100,7 +100,7 @@ export const updateEffectProps = async <Project extends CodemodProject>({...result,results,updatedEffect: {- ...getUpdatedNodeReference({...result, node: effect}),+ ...getUpdatedNodeReference({project, ...result, node: effect}),effectIndex: effect.effectIndex,},};diff --git a/packages/codemods/src/update-jsx-node-keyframes.ts b/packages/codemods/src/update-jsx-node-keyframes.tsindex 7a5fab5934..e6af988252 100644--- a/packages/codemods/src/update-jsx-node-keyframes.ts+++ b/packages/codemods/src/update-jsx-node-keyframes.ts@@ -58,6 +58,6 @@ export const updateJsxNodeKeyframes = async <Project extends CodemodProject>({return {...result,...details,- updatedNode: getUpdatedNodeReference({...result, node}),+ updatedNode: getUpdatedNodeReference({project, ...result, node}),};};diff --git a/packages/codemods/src/update-jsx-node-props.ts b/packages/codemods/src/update-jsx-node-props.tsindex 84f22eab37..5f0a4ada83 100644--- a/packages/codemods/src/update-jsx-node-props.ts+++ b/packages/codemods/src/update-jsx-node-props.ts@@ -136,7 +136,7 @@ export const updateMultipleJsxNodeProps = <Project extends CodemodProject>({results,formatted: true,updatedNodes: changes.map(({node}) =>- getUpdatedNodeReference({...result, node}),+ getUpdatedNodeReference({project, ...result, node}),),};};diff --git a/packages/codemods/src/update-visual-controls.ts b/packages/codemods/src/update-visual-controls.tsindex 6b6e6f3394..fad7c90331 100644--- a/packages/codemods/src/update-visual-controls.ts+++ b/packages/codemods/src/update-visual-controls.ts@@ -45,16 +45,15 @@ export type UpdateVisualControlsOptions<Project extends CodemodProject> = {changes: VisualControlChange[];};-export type UpdateVisualControlsResult<Project extends CodemodProject> =- CodemodResult<Project> & {- updatedControls: {id: string; line: number}[];- };+export type UpdateVisualControlsResult = CodemodResult & {+ updatedControls: {id: string; line: number}[];+};export const updateVisualControls = <Project extends CodemodProject>({project,filePath,changes,-}: UpdateVisualControlsOptions<Project>): UpdateVisualControlsResult<Project> => {+}: UpdateVisualControlsOptions<Project>): UpdateVisualControlsResult => {const resolvedFilePath = findProjectFile({project, filePath});const input = project.files[resolvedFilePath];const file = parseAst(input);@@ -149,13 +148,12 @@ export const updateVisualControls = <Project extends CodemodProject>({return {...getCodemodResult({project,- nextProject: {- ...project,- files: {- ...project.files,- [resolvedFilePath]: applySourceEdits({input, edits}),+ edits: [+ {+ filePath: resolvedFilePath,+ nextContents: applySourceEdits({input, edits}),},- },+ ],}),updatedControls,};diff --git a/packages/docs/docs/codemods/add-canvas-capture-composition.mdx b/packages/docs/docs/codemods/add-canvas-capture-composition.mdxindex 28eba7208b..45a8c29c40 100644--- a/packages/docs/docs/codemods/add-canvas-capture-composition.mdx+++ b/packages/docs/docs/codemods/add-canvas-capture-composition.mdx@@ -111,10 +111,6 @@ The generated component uses `@remotion/media` and `@remotion/mac-cursors`. Thes## Return value-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesTwo `{filePath, previousContents, nextContents}` entries: the modified registration file and the created component file. The new component's `previousContents` is `null`. Save both changes to persist the operation; the video asset is not created or copied.diff --git a/packages/docs/docs/codemods/add-component.mdx b/packages/docs/docs/codemods/add-component.mdxindex 7e5a30a6e1..e0f6873e7f 100644--- a/packages/docs/docs/codemods/add-component.mdx+++ b/packages/docs/docs/codemods/add-component.mdx@@ -77,10 +77,6 @@ An `{x, y}` position in pixels. By default, content starts at the composition orA promise resolving to an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/add-composition.mdx b/packages/docs/docs/codemods/add-composition.mdxindex 3f56d1982b..5fcecbddc9 100644--- a/packages/docs/docs/codemods/add-composition.mdx+++ b/packages/docs/docs/codemods/add-composition.mdx@@ -88,10 +88,6 @@ An existing folder reference `{name, parentName}`. By default, adds the compositReturns an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array containing the registration file's `{filePath, previousContents, nextContents}` change. No component-file change is returned.diff --git a/packages/docs/docs/codemods/add-effect.mdx b/packages/docs/docs/codemods/add-effect.mdxindex 4c58de95d1..4df25dfa75 100644--- a/packages/docs/docs/codemods/add-effect.mdx+++ b/packages/docs/docs/codemods/add-effect.mdx@@ -59,10 +59,6 @@ Serializable effect configuration. Defaults to `{}`.A promise resolving to an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/add-folder.mdx b/packages/docs/docs/codemods/add-folder.mdxindex 3cd7092806..41e781a303 100644--- a/packages/docs/docs/codemods/add-folder.mdx+++ b/packages/docs/docs/codemods/add-folder.mdx@@ -56,10 +56,6 @@ The slash-separated path of the parent folder, such as `Social/Published`. Use `Returns an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/add-media.mdx b/packages/docs/docs/codemods/add-media.mdxindex 4d7d10d30b..6fb754968b 100644--- a/packages/docs/docs/codemods/add-media.mdx+++ b/packages/docs/docs/codemods/add-media.mdx@@ -81,10 +81,6 @@ An `{x, y}` position in pixels. By default, content starts at the composition orA promise resolving to an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/add-solid.mdx b/packages/docs/docs/codemods/add-solid.mdxindex 09511e5bf1..e565f2f155 100644--- a/packages/docs/docs/codemods/add-solid.mdx+++ b/packages/docs/docs/codemods/add-solid.mdx@@ -27,7 +27,6 @@ const result = addSolid({height: 1080,});-console.log(result.project.files);console.log(result.changes);console.log(result.insertedNode);```@@ -70,10 +69,6 @@ Positions the solid at `{x, y}` pixels and adds a CSS translation. By default, tAn object with the following properties.-### project--A new project containing the transformed source. Unchanged project fields are preserved.-### changesAn array describing each changed file with its `filePath`, `previousContents`, and `nextContents`.diff --git a/packages/docs/docs/codemods/apply-codemod-changes.mdx b/packages/docs/docs/codemods/apply-codemod-changes.mdxnew file mode 100644index 0000000000..1426b540eb--- /dev/null+++ b/packages/docs/docs/codemods/apply-codemod-changes.mdx@@ -0,0 +1,61 @@+---+image: /generated/articles-docs-codemods-apply-codemod-changes.png+title: 'applyCodemodChanges()'+crumb: '@remotion/codemods'+---++# applyCodemodChanges()<AvailableFrom v="4.0.528" />++Applies the file changes returned by a codemod to an in-memory project. The input project remains unchanged.++```ts twoslash title="apply-changes.ts"+import {applyCodemodChanges, updateJsxNodeProps, type CodemodProject, type JsxNodeReference} from '@remotion/codemods';++declare const project: CodemodProject;+declare const node: JsxNodeReference;++const result = updateJsxNodeProps({+ project,+ node,+ props: {'style.opacity': 0.5},+});++const nextProject = applyCodemodChanges(project, result.changes);+console.log(nextProject.files);++const undoChanges = result.changes.map((change) => ({+ filePath: change.filePath,+ previousContents: change.nextContents,+ nextContents: change.previousContents,+}));+const restoredProject = applyCodemodChanges(nextProject, undoChanges);+const redoneProject = applyCodemodChanges(restoredProject, result.changes);+```++Store each mutation's changes together as one undo entry. Undo with the inverted changes, and redo with the original changes. The editor owns the history stack.++## Parameters++### project++The project whose files are to be updated. Additional project fields are preserved.++### changes++The `CodemodFileChange[]` returned by a mutation. Each entry contains `filePath`, `previousContents`, and `nextContents`. `null` in `previousContents` indicates a new file; `null` in `nextContents` removes a file.++## Return value++A new project with the changes applied. An empty `changes` array returns the original project.++## Errors++Throws if a file's current contents do not match `previousContents`, or if the array contains more than one change for the same file. All changes are checked before any are applied.++## Compatibility++<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />++## See also++- [`@remotion/codemods`](/docs/codemods)diff --git a/packages/docs/docs/codemods/delete-composition.mdx b/packages/docs/docs/codemods/delete-composition.mdxindex 1ed89aa35b..0d1f79049c 100644--- a/packages/docs/docs/codemods/delete-composition.mdx+++ b/packages/docs/docs/codemods/delete-composition.mdx@@ -48,10 +48,6 @@ The static ID of the composition to edit.Returns an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/delete-effects.mdx b/packages/docs/docs/codemods/delete-effects.mdxindex a1196e8e59..56b66fe420 100644--- a/packages/docs/docs/codemods/delete-effects.mdx+++ b/packages/docs/docs/codemods/delete-effects.mdx@@ -60,10 +60,6 @@ const result = await deleteEffects({A promise resolving to an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/delete-jsx-nodes.mdx b/packages/docs/docs/codemods/delete-jsx-nodes.mdxindex a4c2eb1725..e821fe1c8f 100644--- a/packages/docs/docs/codemods/delete-jsx-nodes.mdx+++ b/packages/docs/docs/codemods/delete-jsx-nodes.mdx@@ -26,7 +26,6 @@ const result = await deleteJsxNodes({nodes: [{filePath: 'src/Video.tsx', nodePath}],});-console.log(result.project.files);console.log(result.changes);```@@ -56,10 +55,6 @@ The `SequenceNodePath` identifying the JSX element to delete. Obtain it from [`gA promise resolving to an object with the following properties.-### project--A new project containing the transformed source. Unchanged project fields are preserved.-### changesAn array describing each changed file with its `filePath`, `previousContents`, and `nextContents`.diff --git a/packages/docs/docs/codemods/detach-audio.mdx b/packages/docs/docs/codemods/detach-audio.mdxindex efb4691cfd..4bfaecc155 100644--- a/packages/docs/docs/codemods/detach-audio.mdx+++ b/packages/docs/docs/codemods/detach-audio.mdx@@ -44,10 +44,6 @@ A [`JsxNodeReference`](/docs/codemods#node-references) from [`getJsxNodes()`](/dA promise resolving to an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/duplicate-composition.mdx b/packages/docs/docs/codemods/duplicate-composition.mdxindex 595f6f6f22..45a0baaf5c 100644--- a/packages/docs/docs/codemods/duplicate-composition.mdx+++ b/packages/docs/docs/codemods/duplicate-composition.mdx@@ -64,10 +64,6 @@ Overrides for `width`, `height`, `fps`, and `durationInFrames`. Omitted values aReturns an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/duplicate-effects.mdx b/packages/docs/docs/codemods/duplicate-effects.mdxindex 7b2cdbf29a..4cd6392918 100644--- a/packages/docs/docs/codemods/duplicate-effects.mdx+++ b/packages/docs/docs/codemods/duplicate-effects.mdx@@ -44,10 +44,6 @@ Effect references to duplicate. References may span files and nodes; indices refA promise resolving to an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/duplicate-jsx-nodes.mdx b/packages/docs/docs/codemods/duplicate-jsx-nodes.mdxindex 9cbd28268b..6be9600039 100644--- a/packages/docs/docs/codemods/duplicate-jsx-nodes.mdx+++ b/packages/docs/docs/codemods/duplicate-jsx-nodes.mdx@@ -44,10 +44,6 @@ The node references to duplicate. They may belong to different files. All refereA promise resolving to an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/index.mdx b/packages/docs/docs/codemods/index.mdxindex b013906f4f..0aefe993cf 100644--- a/packages/docs/docs/codemods/index.mdx+++ b/packages/docs/docs/codemods/index.mdx@@ -15,7 +15,7 @@ _Draft API_: This API is not yet stable. We are in the experimental phase of thi:::-The package accepts file paths and source code and returns a new project together with the files that changed. It does not read or write the filesystem, execute the project, download media, or install packages. You control how changes are previewed, saved, and compiled.+The package accepts file paths and source code and returns the files that changed. It does not read or write the filesystem, execute the project, download media, or install packages. You control how changes are previewed, saved, and compiled.## Installation@@ -49,14 +49,14 @@ export const Root = () => <Composition id="Demo" component={Video} width={1920}};```-Mutations preserve additional project fields, such as an `entryPoint`. Treat each returned project as the next source snapshot.+Include the files needed for the edit. A JSX prop edit needs its target file; resolving an imported composition component also needs the files along the import path. Mutations leave the input project unchanged.## Editing a node<AvailableFrom v="4.0.528" />Find a node, inspect the properties you want to edit, and pass its reference to a mutation.```ts twoslash title="edit.ts"-import {getJsxNodes, getJsxNodeProps, updateJsxNodeProps, type CodemodProject} from '@remotion/codemods';+import {applyCodemodChanges, getJsxNodes, getJsxNodeProps, updateJsxNodeProps, type CodemodProject} from '@remotion/codemods';declare const project: CodemodProject;@@ -70,7 +70,8 @@ if (node) {node,props: {'style.opacity': 0.5},});- console.log(result.project, result.changes, result.updatedNode);+ const nextProject = applyCodemodChanges(project, result.changes);+ console.log(nextProject.files, result.updatedNode);}}```@@ -105,17 +106,13 @@ Adding, deleting, duplicating, or reordering effects can shift effect indices. NEvery mutation returns a `CodemodResult`, synchronously or through a promise as documented on its page.-### project--A project with the modified source files. The input project remains unchanged.-### changesAn array of `CodemodFileChange` objects.#### filePath-The changed file's key in `project.files`.+The changed file's key in the input project's `files` map, or the path of a newly created file.#### previousContents@@ -129,6 +126,12 @@ The next source, or `null` if the file was deleted.JSX, effect, and keyframe mutations return these mappings in addition to the shared result. See [node references](#node-references).+## Applying changes++Use [`applyCodemodChanges()`](/docs/codemods/apply-codemod-changes) to produce a new project. The function checks every `previousContents` value before applying any changes, throws if a file has changed since the codemod ran, and preserves other project fields. An empty `changes` array returns the input project.++For undo and redo, store the file changes as one transaction. Swap `previousContents` and `nextContents` to undo it, and apply the original changes to redo it. Apply changes in the reverse order when undoing multiple transactions.+## Supported editsCode must be valid JavaScript or TypeScript with supported JSX structures. Prop inspection distinguishes static values, recognized keyframes, and computed expressions. The package does not evaluate arbitrary JavaScript. The `props` form of prop updates rejects computed values; [structured `updates`](/docs/codemods/update-jsx-node-props#updates) permit explicit replacement. Setting a recognized keyframed prop to a static value replaces its animation.diff --git a/packages/docs/docs/codemods/move-composition.mdx b/packages/docs/docs/codemods/move-composition.mdxindex 15088267ac..8708f81f4d 100644--- a/packages/docs/docs/codemods/move-composition.mdx+++ b/packages/docs/docs/codemods/move-composition.mdx@@ -53,10 +53,6 @@ Where to move the item within the same file. Use `{type: 'root'}`, `{type: 'foldReturns an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/move-folder.mdx b/packages/docs/docs/codemods/move-folder.mdxindex 3431fcc9b8..6b6c9d367c 100644--- a/packages/docs/docs/codemods/move-folder.mdx+++ b/packages/docs/docs/codemods/move-folder.mdx@@ -61,10 +61,6 @@ Where to move the item within the same file. Use `{type: 'root'}`, `{type: 'foldReturns an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/rename-composition.mdx b/packages/docs/docs/codemods/rename-composition.mdxindex 5ac18ecba4..859a4b5e9e 100644--- a/packages/docs/docs/codemods/rename-composition.mdx+++ b/packages/docs/docs/codemods/rename-composition.mdx@@ -53,10 +53,6 @@ The new ID, containing only ASCII letters, numbers, CJK characters, or hyphens.Returns an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/rename-folder.mdx b/packages/docs/docs/codemods/rename-folder.mdxindex 259fb128cf..ac4c13c2fa 100644--- a/packages/docs/docs/codemods/rename-folder.mdx+++ b/packages/docs/docs/codemods/rename-folder.mdx@@ -61,10 +61,6 @@ The new non-empty name, without `/`. It must be unused in the parent folder.Returns an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/reorder-effect.mdx b/packages/docs/docs/codemods/reorder-effect.mdxindex d5793f0275..0436f9b48b 100644--- a/packages/docs/docs/codemods/reorder-effect.mdx+++ b/packages/docs/docs/codemods/reorder-effect.mdx@@ -49,10 +49,6 @@ The final zero-based index. It must be an integer within the existing array.A promise resolving to an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/reorder-jsx-node.mdx b/packages/docs/docs/codemods/reorder-jsx-node.mdxindex 28e178d0e4..0824d9d528 100644--- a/packages/docs/docs/codemods/reorder-jsx-node.mdx+++ b/packages/docs/docs/codemods/reorder-jsx-node.mdx@@ -55,10 +55,6 @@ Either `before` or `after`.A promise resolving to an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/set-composition-default-props.mdx b/packages/docs/docs/codemods/set-composition-default-props.mdxindex 39a0a80bc6..096960e4bb 100644--- a/packages/docs/docs/codemods/set-composition-default-props.mdx+++ b/packages/docs/docs/codemods/set-composition-default-props.mdx@@ -57,10 +57,6 @@ Paths whose values should be written with an `as const` assertion to preserve liReturns an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/split-sequences.mdx b/packages/docs/docs/codemods/split-sequences.mdxindex a0e98dfc1f..9f5bbc0b16 100644--- a/packages/docs/docs/codemods/split-sequences.mdx+++ b/packages/docs/docs/codemods/split-sequences.mdx@@ -52,10 +52,6 @@ The integer frame at which to split, in the same parent timeline coordinate systA promise resolving to an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/table-of-contents.tsx b/packages/docs/docs/codemods/table-of-contents.tsxindex 1c7a30e348..3923438fe3 100644--- a/packages/docs/docs/codemods/table-of-contents.tsx+++ b/packages/docs/docs/codemods/table-of-contents.tsx@@ -47,6 +47,10 @@ export const TableOfContents: React.FC = () => {<strong>addSolid()</strong><div>Add a solid to a composition.</div></TOCItem>+ <TOCItem link="/docs/codemods/apply-codemod-changes">+ <strong>applyCodemodChanges()</strong>+ <div>Applies file changes to an in-memory project.</div>+ </TOCItem><TOCItem link="/docs/codemods/delete-composition"><strong>deleteComposition()</strong><div>Removes a composition or still registration.</div>diff --git a/packages/docs/docs/codemods/unwrap-folder.mdx b/packages/docs/docs/codemods/unwrap-folder.mdxindex f5de09ea2d..2402f91c8d 100644--- a/packages/docs/docs/codemods/unwrap-folder.mdx+++ b/packages/docs/docs/codemods/unwrap-folder.mdx@@ -56,10 +56,6 @@ The slash-separated path of the parent folder, such as `Social/Published`. Use `Returns an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/update-composition-metadata.mdx b/packages/docs/docs/codemods/update-composition-metadata.mdxindex 70a85315b9..dd93bf3c77 100644--- a/packages/docs/docs/codemods/update-composition-metadata.mdx+++ b/packages/docs/docs/codemods/update-composition-metadata.mdx@@ -71,10 +71,6 @@ A positive integer duration in frames. Omitted values are unchanged.Returns an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/update-effect-keyframes.mdx b/packages/docs/docs/codemods/update-effect-keyframes.mdxindex 3a999c7b24..97c749a534 100644--- a/packages/docs/docs/codemods/update-effect-keyframes.mdx+++ b/packages/docs/docs/codemods/update-effect-keyframes.mdx@@ -66,10 +66,6 @@ The composition's `width`, `height`, `fps`, and `durationInFrames`. Supply theseA promise resolving to an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/update-effect-props.mdx b/packages/docs/docs/codemods/update-effect-props.mdxindex f67a06da56..c9666543db 100644--- a/packages/docs/docs/codemods/update-effect-props.mdx+++ b/packages/docs/docs/codemods/update-effect-props.mdx@@ -73,10 +73,6 @@ A Remotion `InteractivitySchema` for schema-specific defaults and enum variants.A promise resolving to an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/update-jsx-node-keyframes.mdx b/packages/docs/docs/codemods/update-jsx-node-keyframes.mdxindex 6f4430c507..ea39ee61f9 100644--- a/packages/docs/docs/codemods/update-jsx-node-keyframes.mdx+++ b/packages/docs/docs/codemods/update-jsx-node-keyframes.mdx@@ -66,10 +66,6 @@ The composition's `width`, `height`, `fps`, and `durationInFrames`. Supply theseA promise resolving to an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/update-jsx-node-props.mdx b/packages/docs/docs/codemods/update-jsx-node-props.mdxindex dbb1b59ed7..6564cd3cda 100644--- a/packages/docs/docs/codemods/update-jsx-node-props.mdx+++ b/packages/docs/docs/codemods/update-jsx-node-props.mdx@@ -85,10 +85,6 @@ Formatting options for generated source. Defaults to `null`, which follows the eReturns an object with the following properties.-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/update-multiple-jsx-node-props.mdx b/packages/docs/docs/codemods/update-multiple-jsx-node-props.mdxindex 2b99187185..49b604bd3e 100644--- a/packages/docs/docs/codemods/update-multiple-jsx-node-props.mdx+++ b/packages/docs/docs/codemods/update-multiple-jsx-node-props.mdx@@ -29,7 +29,7 @@ const result = updateMultipleJsxNodeProps({],});-console.log(result.project, result.updatedNodes);+console.log(result.changes, result.updatedNodes);```## Options@@ -70,10 +70,6 @@ If any edit fails, no updated project is returned and the input project remains## Return value-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/docs/codemods/update-visual-controls.mdx b/packages/docs/docs/codemods/update-visual-controls.mdxindex 90b2c0efc6..ff2df2d3d9 100644--- a/packages/docs/docs/codemods/update-visual-controls.mdx+++ b/packages/docs/docs/codemods/update-visual-controls.mdx@@ -32,7 +32,7 @@ const result = updateVisualControls({],});-console.log(result.project, result.updatedControls);+console.log(result.changes, result.updatedControls);```## Options@@ -67,10 +67,6 @@ Paths within the value to preserve as enum literals with `as const`. Each path i## Return value-### project--The updated project. Unchanged files and extra project fields are preserved.-### changesAn array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex c5c6f84399..c1213441ed 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -2083,6 +2083,7 @@ const sidebars: SidebarsConfig = {'codemods/add-folder','codemods/add-media','codemods/add-solid',+ 'codemods/apply-codemod-changes','codemods/delete-composition','codemods/delete-effects','codemods/delete-jsx-nodes',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex aa309918f7..614bf4d8af 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -1566,6 +1566,15 @@ export const articles = [noAi: false,slug: 'codemods/add-solid',},+ {+ id: 'codemods/apply-codemod-changes',+ title: 'applyCodemodChanges()',+ relativePath: 'docs/codemods/apply-codemod-changes.mdx',+ compId: 'articles-docs-codemods-apply-codemod-changes',+ crumb: '@remotion/codemods',+ noAi: false,+ slug: 'codemods/apply-codemod-changes',+ },{id: 'codemods/delete-composition',title: 'deleteComposition()',diff --git a/packages/docs/static/generated/articles-docs-codemods-apply-codemod-changes.png b/packages/docs/static/generated/articles-docs-codemods-apply-codemod-changes.pngnew file mode 100644index 0000000000..cda80701fbBinary files /dev/null and b/packages/docs/static/generated/articles-docs-codemods-apply-codemod-changes.png differdiff --git a/packages/it-tests/src/codemods/codemods.test.ts b/packages/it-tests/src/codemods/codemods.test.tsindex 1539164615..16f1ca6046 100644--- a/packages/it-tests/src/codemods/codemods.test.ts+++ b/packages/it-tests/src/codemods/codemods.test.ts@@ -2,6 +2,7 @@ import {expect, test} from 'bun:test';import {readFileSync} from 'fs';import {resolve} from 'path';import {+ applyCodemodChanges,deleteComposition,duplicateComposition,getJsxNodeProps,@@ -22,30 +23,39 @@ const contents = readFileSync(compositionFile, 'utf-8');const original = {rootDir: '/', files: {[compositionFile]: contents}};test('edits composition registrations through the packaged public API', () => {- let {project} = renameComposition({- project: original,- compositionFile,- compositionId: 'one',- newId: 'Renamed',- });+ let project = applyCodemodChanges(+ original,+ renameComposition({+ project: original,+ compositionFile,+ compositionId: 'one',+ newId: 'Renamed',+ }).changes,+ );expect(project.files[compositionFile]).toBe(contents.replace('id="one"', 'id="Renamed"'),);- project = duplicateComposition({+ project = applyCodemodChanges(project,- compositionFile,- compositionId: 'Renamed',- newId: 'Copy',- metadata: {width: 998, height: 999, fps: 24, durationInFrames: 200},- }).project;- project = duplicateComposition({+ duplicateComposition({+ project,+ compositionFile,+ compositionId: 'Renamed',+ newId: 'Copy',+ metadata: {width: 998, height: 999, fps: 24, durationInFrames: 200},+ }).changes,+ );+ project = applyCodemodChanges(project,- compositionFile,- compositionId: 'Copy',- newId: 'Poster',- tag: 'Still',- metadata: {width: 500, height: 400},- }).project;+ duplicateComposition({+ project,+ compositionFile,+ compositionId: 'Copy',+ newId: 'Poster',+ tag: 'Still',+ metadata: {width: 500, height: 400},+ }).changes,+ );const registrations = getJsxNodes({project, filePath: compositionFile}).filter(@@ -82,11 +92,14 @@ test('edits composition registrations through the packaged public API', () => {}),}),});- project = deleteComposition({+ project = applyCodemodChanges(project,- compositionFile,- compositionId: 'Renamed',- }).project;+ deleteComposition({+ project,+ compositionFile,+ compositionId: 'Renamed',+ }).changes,+ );expect(project.files[compositionFile]).not.toContain('id="Renamed"');expect(project.files[compositionFile]).toContain('id="Copy"');expect(project.files[compositionFile]).toContain('id="Poster"');@@ -101,12 +114,15 @@ test('renames registrations in functions, variables, and expression attributes',['six', 'Variable', 'id="six"', 'id="Variable"'],['seven', 'Expression', "id={'seven'}", "id={'Expression'}"],]) {- project = renameComposition({+ project = applyCodemodChanges(project,- compositionFile,- compositionId,- newId,- }).project;+ renameComposition({+ project,+ compositionFile,+ compositionId,+ newId,+ }).changes,+ );expected = expected.replace(before, after);expect(project.files[compositionFile]).toBe(expected);}diff --git a/packages/it-tests/src/codemods/visual-controls.test.ts b/packages/it-tests/src/codemods/visual-controls.test.tsindex 34f60bd459..7b025f163e 100644--- a/packages/it-tests/src/codemods/visual-controls.test.ts+++ b/packages/it-tests/src/codemods/visual-controls.test.ts@@ -1,5 +1,5 @@import {expect, test} from 'bun:test';-import {updateVisualControls} from '@remotion/codemods';+import {applyCodemodChanges, updateVisualControls} from '@remotion/codemods';const contents = `import {makeTransform, matrix3d} from '@remotion/animation-utils';@@ -37,8 +37,9 @@ export const VisualControls = () => {`;test('updates multiple visual controls through the packaged public API', () => {- const {project} = updateVisualControls({- project: {rootDir: '/', files: {'Root.tsx': contents}},+ const original = {rootDir: '/', files: {'Root.tsx': contents}};+ const result = updateVisualControls({+ project: original,filePath: 'Root.tsx',changes: [{@@ -55,6 +56,7 @@ test('updates multiple visual controls through the packaged public API', () => {},],});+ const project = applyCodemodChanges(original, result.changes);expect(project.files['Root.tsx']).toContain(`visualControl('my-matrix-4', 123`,diff --git a/packages/player-example/src/BrowserBundlerExample.tsx b/packages/player-example/src/BrowserBundlerExample.tsxindex 948d0c9066..f30adbb28e 100644--- a/packages/player-example/src/BrowserBundlerExample.tsx+++ b/packages/player-example/src/BrowserBundlerExample.tsx@@ -208,7 +208,9 @@ export const BrowserBundlerExample: React.FC = () => {rootDir: '/',},});- const nextSource = result.project.files['src/Video.tsx'];+ const nextSource =+ result.changes.find((change) => change.filePath === 'src/Video.tsx')+ ?.nextContents ?? sourceRef.current;if (!nextSource) {throw new Error('The codemod did not return Video.tsx.');}@@ -418,7 +420,10 @@ export const BrowserBundlerExample: React.FC = () => {},width: 1280,});- const nextSource = result.project.files['src/Video.tsx'];+ const nextSource =+ result.changes.find(+ (change) => change.filePath === 'src/Video.tsx',+ )?.nextContents ?? source;if (!nextSource) {throw new Error('The codemod did not return Video.tsx.');}diff --git a/packages/studio-server/src/codemods/apply-codemod-to-file.ts b/packages/studio-server/src/codemods/apply-codemod-to-file.tsindex 90335f462f..d2dd6ad5c0 100644--- a/packages/studio-server/src/codemods/apply-codemod-to-file.ts+++ b/packages/studio-server/src/codemods/apply-codemod-to-file.ts@@ -4,7 +4,7 @@ import path from 'node:path';import {addCanvasCaptureComposition,updateVisualControls,- type CodemodProject,+ type CodemodResult,addComposition,addFolder,deleteComposition,@@ -54,7 +54,7 @@ export const applyCodemodToFile = async ({}: {filePath: string;codeMod: RecastCodemod;-}): Promise<CodemodProject> => {+}): Promise<CodemodResult> => {checkIfTypeScriptFile(filePath);const input = await readFile(filePath, 'utf-8');@@ -67,7 +67,7 @@ export const applyCodemodToFile = async ({...options,filePath,changes: codeMod.changes,- }).project;+ });}if (codeMod.type === 'new-composition') {@@ -104,16 +104,20 @@ export const applyCodemodToFile = async ({return addCanvasCaptureComposition({...composition,capture: codeMod.canvasCapture,- }).project;+ });}- const result = addComposition(composition).project;+ const result = addComposition(composition);return {...result,- files: {- ...result.files,- [componentFilePath]: emptyCompositionComponent(codeMod.componentName),- },+ changes: [+ ...result.changes,+ {+ filePath: componentFilePath,+ previousContents: null,+ nextContents: emptyCompositionComponent(codeMod.componentName),+ },+ ],};}@@ -122,12 +126,11 @@ export const applyCodemodToFile = async ({...options,compositionId: codeMod.idToRename,newId: codeMod.newId,- }).project;+ });}if (codeMod.type === 'delete-composition') {- return deleteComposition({...options, compositionId: codeMod.idToDelete})- .project;+ return deleteComposition({...options, compositionId: codeMod.idToDelete});}if (@@ -160,7 +163,7 @@ export const applyCodemodToFile = async ({compositionId: codeMod.idToUpdate,metadata,});- return result.project;+ return result;}if (codeMod.type === 'move-composition-to-folder') {@@ -177,7 +180,7 @@ export const applyCodemodToFile = async ({parentName: codeMod.parentName,},},- }).project;+ });}if (codeMod.type === 'move-composition-or-folder') {@@ -216,7 +219,7 @@ export const applyCodemodToFile = async ({},destination,});- return result.project;+ return result;}const folder = {name: codeMod.folderName, parentName: codeMod.parentName};@@ -226,5 +229,5 @@ export const applyCodemodToFile = async ({: codeMod.type === 'rename-folder'? renameFolder({...options, folder, newName: codeMod.newName}): unwrapFolder({...options, folder});- return folderResult.project;+ return folderResult;};diff --git a/packages/studio-server/src/codemods/update-effect-props/update-effect-props.ts b/packages/studio-server/src/codemods/update-effect-props/update-effect-props.tsindex 0173b5642b..e2f6e12f47 100644--- a/packages/studio-server/src/codemods/update-effect-props/update-effect-props.ts+++ b/packages/studio-server/src/codemods/update-effect-props/update-effect-props.ts@@ -36,5 +36,8 @@ export const updateEffectProps = async ({updates: [update],schema,});- return {...result.results[0], output: result.project.files['source.tsx']};+ return {+ ...result.results[0],+ output: result.changes[0]?.nextContents ?? input,+ };};diff --git a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.tsindex 042db7533f..127aa25798 100644--- a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts+++ b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts@@ -39,7 +39,7 @@ export const updateSequenceKeyframes = async ({videoConfig: videoConfigValues ?? undefined,...options,});- return {...result, output: result.project.files['source.tsx']};+ return {...result, output: result.changes[0]?.nextContents ?? input};};export const updateEffectKeyframes = async ({@@ -58,5 +58,5 @@ export const updateEffectKeyframes = async ({videoConfig: videoConfigValues ?? undefined,...options,});- return {...result, output: result.project.files['source.tsx']};+ return {...result, output: result.changes[0]?.nextContents ?? input};};diff --git a/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts b/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.tsindex 6cb6f14c90..50c30e25eb 100644--- a/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts+++ b/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts@@ -56,7 +56,7 @@ export const updateMultipleSequenceProps = ({),prettierConfigOverride,});- const output = result.project.files['source.tsx'];+ const output = result.changes[0]?.nextContents ?? input;const {results} = result;return {output, formatted: true, results};diff --git a/packages/studio-server/src/preview-server/routes/add-effect.ts b/packages/studio-server/src/preview-server/routes/add-effect.tsindex 8109e8eb1f..8a49f6ce99 100644--- a/packages/studio-server/src/preview-server/routes/add-effect.ts+++ b/packages/studio-server/src/preview-server/routes/add-effect.ts@@ -57,7 +57,7 @@ export const addEffectHandler: ApiHandler<importPath: effectImportPath,props: effectConfig,});- const output = result.project.files[absolutePath];+ const output = result.changes[0]?.nextContents ?? fileContents;const {formatted, effectLabel, nodeLabel, logLine} =result.editDetails[0];diff --git a/packages/studio-server/src/preview-server/routes/apply-codemod.ts b/packages/studio-server/src/preview-server/routes/apply-codemod.tsindex a87830bb69..59635e4230 100644--- a/packages/studio-server/src/preview-server/routes/apply-codemod.ts+++ b/packages/studio-server/src/preview-server/routes/apply-codemod.ts@@ -242,12 +242,14 @@ export const applyCodemodHandler: ApiHandler<}const input = readFileSync(filePath, 'utf-8');- const nextProject = await applyCodemodToFile({+ const result = await applyCodemodToFile({filePath,codeMod: codemod,});- const formatted = nextProject.files[filePath];+ const formatted =+ result.changes.find((change) => change.filePath === filePath)+ ?.nextContents ?? input;const diff = simpleDiff({oldLines: input.split('\n'),@@ -255,6 +257,23 @@ export const applyCodemodHandler: ApiHandler<});if (!dryRun) {+ if (readFileSync(filePath, 'utf-8') !== input) {+ throw new Error(+ `Source changed before applying codemod: ${filePath}`,+ );+ }++ for (const change of result.changes) {+ const currentContents = existsSync(change.filePath)+ ? readFileSync(change.filePath, 'utf-8')+ : null;+ if (currentContents !== change.previousContents) {+ throw new Error(+ `Source changed before applying codemod: ${change.filePath}`,+ );+ }+ }+const {entryType, undoMessage, redoMessage} =getCodemodUndoDescription(codemod);const snapshots: Parameters<@@ -277,7 +296,14 @@ export const applyCodemodHandler: ApiHandler<throw new Error('Could not determine the new component file path');}- componentFileContents = nextProject.files[componentFilePath];+ componentFileContents =+ result.changes.find(+ (change) => change.filePath === componentFilePath,+ )?.nextContents ?? null;+ if (componentFileContents === null) {+ throw new Error('Could not create the composition component');+ }+snapshots.push({filePath: componentFilePath,oldContents: null,diff --git a/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts b/packages/studio-server/src/preview-server/routes/apply-visual-control-change.tsindex e980c265e4..b82220831e 100644--- a/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts+++ b/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts@@ -42,7 +42,7 @@ export const applyVisualControlHandler: ApiHandler<filePath: absolutePath,changes,});- const output = result.project.files[absolutePath];+ const output = result.changes[0]?.nextContents ?? fileContents;const logLine =result.updatedControls.findLast((control) => control.id === changes[0]?.id,diff --git a/packages/studio-server/src/preview-server/routes/delete-effect.ts b/packages/studio-server/src/preview-server/routes/delete-effect.tsindex d34c173fae..dcad6b8f5b 100644--- a/packages/studio-server/src/preview-server/routes/delete-effect.ts+++ b/packages/studio-server/src/preview-server/routes/delete-effect.ts@@ -72,7 +72,7 @@ export const deleteEffectHandler: ApiHandler<item.type === 'all-effects' ? null : item.effectIndex,})),});- const output = result.project.files[absolutePath];+ const output = result.changes[0]?.nextContents ?? fileContents;const {formatted, effectLabels, logLines} = result.editDetails[0];return {diff --git a/packages/studio-server/src/preview-server/routes/delete-jsx-nodes.ts b/packages/studio-server/src/preview-server/routes/delete-jsx-nodes.tsindex 7ef4f02971..d73577633a 100644--- a/packages/studio-server/src/preview-server/routes/delete-jsx-nodes.ts+++ b/packages/studio-server/src/preview-server/routes/delete-jsx-nodes.ts@@ -77,7 +77,7 @@ export const deleteJsxNodesHandler: ApiHandler<nodePath: item.nodePath,})),});- const output = result.project.files[absolutePath];+ const output = result.changes[0]?.nextContents ?? fileContents;const {nodeLabels, logLines} = result.editDetails[0];const nodePathRemappings = result.nodePathRemappings.map(({oldNodePath, newNodePath}) => ({oldNodePath, newNodePath}),diff --git a/packages/studio-server/src/preview-server/routes/duplicate-effect.ts b/packages/studio-server/src/preview-server/routes/duplicate-effect.tsindex 31a6376c6c..5f358f6964 100644--- a/packages/studio-server/src/preview-server/routes/duplicate-effect.ts+++ b/packages/studio-server/src/preview-server/routes/duplicate-effect.ts@@ -71,7 +71,7 @@ export const duplicateEffectHandler: ApiHandler<effectIndex: item.effectIndex,})),});- const output = result.project.files[absolutePath];+ const output = result.changes[0]?.nextContents ?? fileContents;const {formatted, effectLabels, logLines} = result.editDetails[0];return {diff --git a/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts b/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.tsindex e46867502e..3fec10b5d7 100644--- a/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts+++ b/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts@@ -60,7 +60,7 @@ export const duplicateJsxNodeHandler: ApiHandler<nodePath: item.nodePath,})),});- const output = result.project.files[absolutePath];+ const output = result.changes[0]?.nextContents ?? fileContents;const {nodeLabels, logLines} = result.editDetails[0];const nodePathRemappings = result.nodePathRemappings.map(({oldNodePath, newNodePath}) => ({oldNodePath, newNodePath}),diff --git a/packages/studio-server/src/preview-server/routes/insert-element.ts b/packages/studio-server/src/preview-server/routes/insert-element.tsindex c690208cae..9d784aba3a 100644--- a/packages/studio-server/src/preview-server/routes/insert-element.ts+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts@@ -211,13 +211,25 @@ export const insertElementHandler: ApiHandler<registrationFilePath,'utf-8',);- const nextProject = await applyCodemodToFile({+ const codemodResult = await applyCodemodToFile({filePath: registrationFilePath,codeMod: newComposition.codemod,});const registrationFileNewContents =- nextProject.files[registrationFilePath];- const componentFileContents = nextProject.files[componentFilePath];+ codemodResult.changes.find(+ (change) => change.filePath === registrationFilePath,+ )?.nextContents ?? registrationFileOldContents;+ const componentFileContents = codemodResult.changes.find(+ (change) => change.filePath === componentFilePath,+ )?.nextContents;++ if (+ componentFileContents === null ||+ componentFileContents === undefined+ ) {+ throw new Error('Could not create the composition component');+ }+compositionCreation = {componentFileContents,componentFilePath,diff --git a/packages/studio-server/src/preview-server/routes/reorder-effect.ts b/packages/studio-server/src/preview-server/routes/reorder-effect.tsindex 58cc004073..6528e74c32 100644--- a/packages/studio-server/src/preview-server/routes/reorder-effect.ts+++ b/packages/studio-server/src/preview-server/routes/reorder-effect.ts@@ -52,7 +52,7 @@ export const reorderEffectHandler: ApiHandler<},toIndex,});- const output = result.project.files[absolutePath];+ const output = result.changes[0]?.nextContents ?? fileContents;const {formatted, effectLabel, logLine} = result.editDetails[0];pushToUndoStack({diff --git a/packages/studio-server/src/preview-server/routes/reorder-sequence.ts b/packages/studio-server/src/preview-server/routes/reorder-sequence.tsindex 7d405110ab..ab7fdced52 100644--- a/packages/studio-server/src/preview-server/routes/reorder-sequence.ts+++ b/packages/studio-server/src/preview-server/routes/reorder-sequence.ts@@ -49,7 +49,7 @@ export const reorderSequenceHandler: ApiHandler<target: {filePath: absolutePath, nodePath: targetNodePath.nodePath},position,});- const output = result.project.files[absolutePath];+ const output = result.changes[0]?.nextContents ?? fileContents;const {sequenceLabel, logLine} = result.editDetails[0];const nodePathRemappings = result.nodePathRemappings.map(({oldNodePath, newNodePath}) => ({oldNodePath, newNodePath}),diff --git a/packages/studio-server/src/preview-server/routes/replace-video-source.ts b/packages/studio-server/src/preview-server/routes/replace-video-source.tsindex dcb9895787..10de3f55a9 100644--- a/packages/studio-server/src/preview-server/routes/replace-video-source.ts+++ b/packages/studio-server/src/preview-server/routes/replace-video-source.ts@@ -47,7 +47,7 @@ export const replaceVideoSourceHandler: ApiHandler<},],});- const output = result.project.files[absolutePath];+ const output = result.changes[0]?.nextContents ?? fileContents;const {logLine} = result;const nodePathRemappings = result.nodePathRemappings.map(({oldNodePath, newNodePath}) => ({oldNodePath, newNodePath}),diff --git a/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts b/packages/studio-server/src/preview-server/routes/split-jsx-sequence.tsindex 95fa367505..07056a9d24 100644--- a/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts+++ b/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts@@ -62,7 +62,7 @@ export const splitJsxSequenceHandler: ApiHandler<}),),});- const output = result.project.files[absolutePath];+ const output = result.changes[0]?.nextContents ?? fileContents;const {nodeLabels, logLines} = result.editDetails[0];const nodePathRemappings = result.nodePathRemappings.map(({oldNodePath, newNodePath}) => ({oldNodePath, newNodePath}),diff --git a/packages/studio-server/src/preview-server/routes/split-video-from-audio.ts b/packages/studio-server/src/preview-server/routes/split-video-from-audio.tsindex d02c91d2f7..d702a62de4 100644--- a/packages/studio-server/src/preview-server/routes/split-video-from-audio.ts+++ b/packages/studio-server/src/preview-server/routes/split-video-from-audio.ts@@ -43,7 +43,7 @@ export const splitVideoFromAudioHandler: ApiHandler<project: {files: {[absolutePath]: fileContents}, rootDir: remotionRoot},node: {filePath: absolutePath, nodePath},});- const output = result.project.files[absolutePath];+ const output = result.changes[0]?.nextContents ?? fileContents;const {formatted, nodeLabel, logLine} = result.editDetails[0];const nodePathRemappings = result.nodePathRemappings.map(({oldNodePath, newNodePath}) => ({oldNodePath, newNodePath}),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 bd25a0e757..9dffea0528 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@@ -55,7 +55,7 @@ export const updateDefaultPropsHandler: ApiHandler<enumPaths,});const {logLine} = result;- const output = result.project.files[projectInfo.rootFile];+ const output = result.changes[0]?.nextContents ?? fileContents;pushToUndoStack({filePath: projectInfo.rootFile,diff --git a/packages/studio-server/src/test/apply-codemod.test.ts b/packages/studio-server/src/test/apply-codemod.test.tsindex ae8bceef73..c250eae474 100644--- a/packages/studio-server/src/test/apply-codemod.test.ts+++ b/packages/studio-server/src/test/apply-codemod.test.ts@@ -116,7 +116,9 @@ export const Root = () => <Folder name="Before" />;},});- expect(output.files[filePath]).toBe(input.replace('"Before"', '"After"'));+ expect(output.changes[0].nextContents).toBe(+ input.replace('"Before"', '"After"'),+ );} finally {rmSync(remotionRoot, {recursive: true, force: true});}@@ -144,7 +146,8 @@ export const Root=()=> <Composition id='Comp' width = { WIDTH }/>;},});- expect(output.files[filePath]).toBe(`import {Composition} from 'remotion';+ expect(output.changes[0].nextContents)+ .toBe(`import {Composition} from 'remotion';const untouched = { value : "keep" };export const Root=()=> <Composition id='Comp' width = {1920} durationInFrames={90} height={1080}/>;`);@@ -177,7 +180,9 @@ export const Root=()=> visualControl('opacity', OPACITY);},});- expect(output.files[filePath]).toBe(input.replace('OPACITY', '0.5'));+ expect(output.changes[0].nextContents).toBe(+ input.replace('OPACITY', '0.5'),+ );} finally {rmSync(remotionRoot, {recursive: true, force: true});}diff --git a/packages/template-recorder/scripts/server/register-composition.ts b/packages/template-recorder/scripts/server/register-composition.tsindex 783cd85996..947f1914ea 100644--- a/packages/template-recorder/scripts/server/register-composition.ts+++ b/packages/template-recorder/scripts/server/register-composition.ts@@ -1,6 +1,7 @@import { existsSync, readFileSync, writeFileSync } from "fs";import path from "path";import {+ applyCodemodChanges,duplicateComposition,setCompositionDefaultProps,} from "@remotion/codemods";@@ -63,13 +64,16 @@ export const registerComposition = async ({newId: projectName,});const result = setCompositionDefaultProps({- project: duplicated.project,+ project: applyCodemodChanges(+ { rootDir, files: { [rootPath]: src } },+ duplicated.changes,+ ),compositionFile: rootPath,compositionId: projectName,defaultProps: getDefaultPropsForNewProject(),});- const withDefaultScene = result.project.files[rootPath];- if (withDefaultScene === undefined) {+ const withDefaultScene = result.changes[0]?.nextContents;+ if (withDefaultScene === undefined || withDefaultScene === null) {throw new Error("Could not find the updated composition file");}