🎥 Make videos programmatically with React
`@remotion/studio-server`: Cache AST node paths to survive stale source maps
Jonny Burgeraedbe2c3c890
diff --git a/packages/example/e2e/node-path-cache.test.mts b/packages/example/e2e/node-path-cache.test.mtsnew file mode 100644index 0000000000..ed9ae5c32d--- /dev/null+++ b/packages/example/e2e/node-path-cache.test.mts@@ -0,0 +1,104 @@+import fs from 'fs';+import {expect, test} from '@playwright/test';+import {newVideoFile, STUDIO_URL} from './constants.mts';+import {startStudio, stopStudio} from './studio-server.mts';++test.describe('node-path cache for stale source maps', () => {+ let originalContent: string;++ test.beforeEach(async () => {+ originalContent = fs.readFileSync(newVideoFile, 'utf-8');+ await startStudio();+ });++ test.afterEach(async () => {+ fs.writeFileSync(newVideoFile, originalContent);+ await stopStudio();+ });++ // Regression test for the following scenario:+ //+ // 1. NewVideo.tsx has <Video> on line 22:+ //+ // export const Component = () => {+ // return <Video src={src} />; // line 22+ // };+ //+ // 2. The studio updates a prop via the API (suppressing the webpack rebuild).+ // Prettier then wraps the return in parentheses, shifting <Video> to line 23:+ //+ // export const Component = () => {+ // return (+ // <Video src={src} style={{}} /> // now line 23+ // );+ // };+ //+ // 3. On reload, the stale source map still resolves to line 22, but the tag+ // is now on line 23. Without the node-path cache, subscribe-to-sequence-props+ // would fail because lineColumnToNodePath(ast, 22) finds nothing.+ //+ // The cache stores (fileName, line, column) → AST nodePath on first successful+ // resolution. When the same stale coordinates are sent again, the cached+ // nodePath is reused (and verified against the current AST).++ test('subscribe-to-sequence-props succeeds with stale line number after file reformatting', async () => {+ const content = fs.readFileSync(newVideoFile, 'utf-8');+ const lines = content.split('\n');+ const videoLineIndex = lines.findIndex((l) => l.includes('<Video'));+ expect(videoLineIndex).toBeGreaterThan(-1);+ const videoLine = videoLineIndex + 1; // 1-indexed++ // 1. Initial subscription → resolves line to AST nodePath and caches it+ const res1 = await fetch(`${STUDIO_URL}/api/subscribe-to-sequence-props`, {+ method: 'POST',+ headers: {'content-type': 'application/json'},+ body: JSON.stringify({+ fileName: 'src/NewVideo.tsx',+ line: videoLine,+ column: 0,+ keys: ['src'],+ clientId: 'e2e-cache-test-1',+ }),+ });+ const result1 = await res1.json();+ expect(result1.canUpdate).toBe(true);+ expect(result1.nodePath).toBeTruthy();++ // 2. Simulate prettier wrapping the return in parentheses,+ // shifting <Video> down by one line.+ const editedContent = content.replace(+ 'return <Video src={src} />;',+ 'return (\n\t\t<Video src={src} />\n\t);',+ );+ expect(editedContent).not.toBe(content);+ fs.writeFileSync(newVideoFile, editedContent);++ // Verify the tag actually moved+ const editedLines = editedContent.split('\n');+ const newVideoLineIndex = editedLines.findIndex((l) =>+ l.includes('<Video'),+ );+ expect(newVideoLineIndex + 1).toBe(videoLine + 1);++ // 3. Subscribe again with the ORIGINAL (stale) line number.+ // Without the cache, this would fail because the tag is no longer on this line.+ // With the cache, the previously resolved nodePath is reused.+ const res2 = await fetch(`${STUDIO_URL}/api/subscribe-to-sequence-props`, {+ method: 'POST',+ headers: {'content-type': 'application/json'},+ body: JSON.stringify({+ fileName: 'src/NewVideo.tsx',+ line: videoLine, // stale line number+ column: 0,+ keys: ['src'],+ clientId: 'e2e-cache-test-2',+ }),+ });+ const result2 = await res2.json();+ expect(result2.canUpdate).toBe(true);+ expect(result2.nodePath).toBeTruthy();++ // The nodePath should be the same — both refer to the same <Video> element+ expect(result2.nodePath).toEqual(result1.nodePath);+ });+});diff --git a/packages/studio-server/src/preview-server/node-path-cache.ts b/packages/studio-server/src/preview-server/node-path-cache.tsnew file mode 100644index 0000000000..35e2187357--- /dev/null+++ b/packages/studio-server/src/preview-server/node-path-cache.ts@@ -0,0 +1,62 @@+import type {SequenceNodePath} from '@remotion/studio-shared';++// Cache mapping source-mapped locations to resolved AST node paths.+//+// Problem: When the studio modifies a file (e.g. updating sequence props),+// we suppress the webpack rebuild so the source map becomes stale.+// If prettier then reformats the file, tags can shift lines:+//+// Before (source map says line 22):+// export const Component = () => {+// return <Video src={src} />; // line 22+// };+//+// After adding style={{}} + prettier wrapping:+// export const Component = () => {+// return (+// <Video src={src} style={{}} /> // now line 23+// );+// };+//+// On reload, the stale source map still resolves to line 22, but the+// actual file now has the <Video> tag on line 23. Without caching,+// lineColumnToNodePath(ast, 22) fails to find the tag.+//+// Solution: After a successful line→nodePath resolution, we cache the+// mapping. On subsequent requests with the same stale coordinates, the+// cached nodePath is used directly (verified against the current AST).+// The cache is cleared when webpack rebuilds (compiler.hooks.done),+// at which point source maps are fresh and line-based lookup works again.++type CacheKey = string;++const makeCacheKey = (+ fileName: string,+ line: number,+ column: number,+): CacheKey => {+ return `${fileName}:${line}:${column}`;+};++const cache = new Map<CacheKey, SequenceNodePath>();++export const getCachedNodePath = (+ fileName: string,+ line: number,+ column: number,+): SequenceNodePath | undefined => {+ return cache.get(makeCacheKey(fileName, line, column));+};++export const setCachedNodePath = (+ fileName: string,+ line: number,+ column: number,+ nodePath: SequenceNodePath,+): void => {+ cache.set(makeCacheKey(fileName, line, column), nodePath);+};++export const clearNodePathCache = (): void => {+ cache.clear();+};diff --git a/packages/studio-server/src/preview-server/routes/subscribe-to-sequence-props.ts b/packages/studio-server/src/preview-server/routes/subscribe-to-sequence-props.tsindex 9369659d0f..5646d4361d 100644--- a/packages/studio-server/src/preview-server/routes/subscribe-to-sequence-props.ts+++ b/packages/studio-server/src/preview-server/routes/subscribe-to-sequence-props.ts@@ -8,10 +8,11 @@ import {subscribeToSequencePropsWatchers} from '../sequence-props-watchers';export const subscribeToSequenceProps: ApiHandler<SubscribeToSequencePropsRequest,SubscribeToSequencePropsResponse-> = ({input: {fileName, line, keys, clientId}, remotionRoot}) => {+> = ({input: {fileName, line, column, keys, clientId}, remotionRoot}) => {const result = subscribeToSequencePropsWatchers({fileName,line,+ column,keys,remotionRoot,clientId,diff --git a/packages/studio-server/src/preview-server/sequence-props-watchers.ts b/packages/studio-server/src/preview-server/sequence-props-watchers.tsindex 553b82f2ac..20cea526ef 100644--- a/packages/studio-server/src/preview-server/sequence-props-watchers.ts+++ b/packages/studio-server/src/preview-server/sequence-props-watchers.ts@@ -5,9 +5,11 @@ import type {} from '@remotion/studio-shared';import {installFileWatcher} from '../file-watcher';import {waitForLiveEventsListener} from './live-events';+import {getCachedNodePath, setCachedNodePath} from './node-path-cache';import {computeSequencePropsStatusFromContent,computeSequencePropsStatusByLine,+ computeSequencePropsStatus,} from './routes/can-update-sequence-props';type WatcherInfo = {@@ -29,30 +31,58 @@ const makeWatcherKey = ({export const subscribeToSequencePropsWatchers = ({fileName,line,+ column,keys,remotionRoot,clientId,}: {fileName: string;line: number;+ column: number;keys: string[];remotionRoot: string;clientId: string;}): CanUpdateSequencePropsResponse => {const absolutePath = path.resolve(remotionRoot, fileName);- // Initial lookup by line+column to resolve the nodePath- const initialResult = computeSequencePropsStatusByLine({- fileName,- line,- keys,- remotionRoot,- });+ // Try cached nodePath first (handles stale source maps after suppressed rebuilds)+ const cachedNodePath = getCachedNodePath(fileName, line, column);+ let initialResult: CanUpdateSequencePropsResponse;++ if (cachedNodePath) {+ const cachedResult = computeSequencePropsStatus({+ fileName,+ nodePath: cachedNodePath,+ keys,+ remotionRoot,+ });+ if (cachedResult.canUpdate) {+ initialResult = cachedResult;+ } else {+ // Cached nodePath no longer valid, fall back to line-based lookup+ initialResult = computeSequencePropsStatusByLine({+ fileName,+ line,+ keys,+ remotionRoot,+ });+ }+ } else {+ initialResult = computeSequencePropsStatusByLine({+ fileName,+ line,+ keys,+ remotionRoot,+ });+ }if (!initialResult.canUpdate) {return initialResult;}+ // Cache the resolved nodePath for future lookups with stale source maps+ setCachedNodePath(fileName, line, column, initialResult.nodePath);+const {nodePath} = initialResult;const watcherKey = makeWatcherKey({absolutePath, nodePath});diff --git a/packages/studio-server/src/preview-server/start-server.ts b/packages/studio-server/src/preview-server/start-server.tsindex f0eb62c870..91a8e9c646 100644--- a/packages/studio-server/src/preview-server/start-server.ts+++ b/packages/studio-server/src/preview-server/start-server.ts@@ -20,6 +20,7 @@ import {wdm} from './dev-middleware';import {setupWebpackHmr} from './hot-middleware';import type {LiveEventsServer} from './live-events';import {makeLiveEventsRouter} from './live-events';+import {clearNodePathCache} from './node-path-cache';import {getRedoStack, getUndoStack} from './undo-stack';import {setWatchIgnoreNextChangePlugin} from './watch-ignore-next-change';@@ -136,6 +137,9 @@ export const startServer = async (options: {};});setupWebpackHmr(compiler, options.logLevel, liveEventsServer);+ compiler.hooks.done.tap('remotion-node-path-cache', () => {+ clearNodePathCache();+ });const server = http.createServer((request, response) => {if (options.enableCrossSiteIsolation) {