import path from 'node:path'; import type {LogLevel} from '@remotion/renderer'; import {RenderInternals} from '@remotion/renderer'; import { stringifySequenceSubscriptionKey, type SubscribeToSequencePropsResponse, type SourceFileVersion, type UpdateSequencePropsSubscriptionRequest, } from '@remotion/studio-shared'; import type {JsxComponentIdentity, SequenceNodePath} from 'remotion'; import {installFileWatcher} from '../file-watcher'; import {JsxElementIdentityMismatchError} from './jsx-component-identity'; import {JsxElementNotFoundAtLocationError} from './jsx-element-not-found-at-location-error'; import {waitForLiveEventsListener} from './live-events'; import {getCachedNodePath, setCachedNodePath} from './node-path-cache'; import { computeSequencePropsStatus, computeSequencePropsStatusFromContent, computeSequencePropsStatusFromFilenameByLocation, } from './routes/can-update-sequence-props'; type WatcherInfo = { sourceVersion: SourceFileVersion | null; componentIdentity: JsxComponentIdentity | null; assetKeys: string[]; effects: string[][]; effectChain: string; unwatch: () => void; refCount: number; currentNodePath: Extract< SubscribeToSequencePropsResponse, {success: true} >['nodePath']; }; const sequencePropsWatchers: Record> = {}; const getWatcherKey = ( nodePath: { absolutePath: string; nodePath: SequenceNodePath; sequenceKeys: string[]; effectKeys: string[][]; }, assetKeys: string[], ) => `${stringifySequenceSubscriptionKey(nodePath)}:${assetKeys.join('\0')}`; const getSequencePropsStatus = ({ fileName, line, column, preferredNodePath, requireExactNodePath, resolvedNodePath, componentIdentity, keys, assetKeys, effects, remotionRoot, logLevel, fileContentsCache, }: { fileName: string; line: number; column: number; preferredNodePath: SequenceNodePath | null; requireExactNodePath: boolean; resolvedNodePath: SequenceNodePath | null; componentIdentity: JsxComponentIdentity | null; keys: string[]; assetKeys: string[]; effects: string[][]; remotionRoot: string; logLevel: LogLevel; fileContentsCache: Map | null; }): SubscribeToSequencePropsResponse => { if (preferredNodePath) { try { const fromNodePath = computeSequencePropsStatus({ fileName, nodePath: preferredNodePath, componentIdentity, keys, assetKeys, effects, remotionRoot, fileContentsCache, }); return { status: fromNodePath, nodePath: { absolutePath: path.resolve(remotionRoot, fileName), nodePath: preferredNodePath, sequenceKeys: keys, effectKeys: effects, videoConfigValues: null, }, success: true, }; } catch (error) { if ( !( error instanceof JsxElementIdentityMismatchError || error instanceof JsxElementNotFoundAtLocationError ) ) { throw error; } } } if (requireExactNodePath) { return {success: false, status: {canUpdate: false, reason: 'not-found'}}; } // Try cached nodePath first (handles stale source maps after suppressed rebuilds) const cachedNodePath = getCachedNodePath(fileName, line, column); if (cachedNodePath) { const cachedResult = (() => { try { return computeSequencePropsStatus({ fileName, nodePath: cachedNodePath, componentIdentity, keys, assetKeys, effects, remotionRoot, fileContentsCache, }); } catch (error) { if ( error instanceof JsxElementIdentityMismatchError || error instanceof JsxElementNotFoundAtLocationError ) { return null; } throw error; } })(); if (cachedResult?.canUpdate) { return { status: cachedResult, nodePath: { absolutePath: path.resolve(remotionRoot, fileName), nodePath: cachedNodePath, sequenceKeys: keys, effectKeys: effects, videoConfigValues: null, }, success: true, }; } } if (resolvedNodePath) { try { return { status: computeSequencePropsStatus({ fileName, nodePath: resolvedNodePath, componentIdentity, keys, assetKeys, effects, remotionRoot, fileContentsCache, }), nodePath: { absolutePath: path.resolve(remotionRoot, fileName), nodePath: resolvedNodePath, sequenceKeys: keys, effectKeys: effects, videoConfigValues: null, }, success: true, }; } catch (error) { if ( !( error instanceof JsxElementIdentityMismatchError || error instanceof JsxElementNotFoundAtLocationError ) ) { throw error; } } } const status = computeSequencePropsStatusFromFilenameByLocation({ fileName, line, column, componentIdentity, keys, assetKeys, effects, remotionRoot, logLevel, fileContentsCache, }); return status; }; export const subscribeToSequencePropsWatchers = ({ fileName, line, column, nodePath: preferredNodePath, requireExactNodePath, resolvedNodePath = null, componentIdentity, keys, assetKeys, effects, remotionRoot, clientId, logLevel, fileContentsCache, }: { fileName: string; line: number; column: number; nodePath: SequenceNodePath | null; requireExactNodePath: boolean; resolvedNodePath?: SequenceNodePath | null; componentIdentity: JsxComponentIdentity | null; keys: string[]; assetKeys: string[]; effects: string[][]; remotionRoot: string; clientId: string; logLevel: LogLevel; fileContentsCache: Map | null; }): SubscribeToSequencePropsResponse => { const initialResult = getSequencePropsStatus({ fileName, line, column, preferredNodePath, requireExactNodePath, resolvedNodePath, componentIdentity, keys, assetKeys, effects, remotionRoot, logLevel, fileContentsCache, }); if (!initialResult.success) { return initialResult; } const absolutePath = path.resolve(remotionRoot, fileName); // A preferred path may have been remapped while these coordinates still // come from the previous bundle. Caching that pair can make a later mount // at the same location inherit a different sibling's props after Refresh. // Only a location-based subscription can establish a location cache entry. if (preferredNodePath === null) { setCachedNodePath(fileName, line, column, initialResult.nodePath.nodePath); } const {nodePath} = initialResult; const watcherKey = getWatcherKey(nodePath, assetKeys); const existingWatcher = sequencePropsWatchers[clientId]?.[watcherKey]; if (existingWatcher) { existingWatcher.refCount++; existingWatcher.effects = effects; existingWatcher.currentNodePath = nodePath; existingWatcher.effectChain = initialResult.status.effects .map((effect) => effect.canUpdate && effect.callee) .join(','); return initialResult; } const watcherInfo: WatcherInfo = { sourceVersion: null, componentIdentity, assetKeys, effects, effectChain: initialResult.status.effects .map((effect) => effect.canUpdate && effect.callee) .join(','), unwatch: () => undefined, refCount: 1, currentNodePath: nodePath, }; const {unwatch} = installFileWatcher({ file: absolutePath, existenceOnly: false, onChange: (event) => { if (event.type === 'deleted') { return; } watcherInfo.sourceVersion = event.sourceVersion; // Even the editing client needs the saved expression: its optimistic // numeric value only describes the instance that initiated the edit. if (event.type === 'changed' && event.skipSequencePropsUpdate) { return; } try { const sourceNodePath = watcherInfo.currentNodePath; const result = computeSequencePropsStatusFromContent({ fileContents: event.content, nodePath: sourceNodePath.nodePath, componentIdentity, keys, assetKeys, effects: watcherInfo.effects, }); const effectChain = result.effects .map((effect) => effect.canUpdate && effect.callee) .join(','); if (effectChain !== watcherInfo.effectChain) { RenderInternals.Log.verbose( {indent: false, logLevel}, 'Effect chain changed, not sending "sequence-props-updated" event', ); return; } waitForLiveEventsListener().then((listener) => { listener.sendEventToClientId(clientId, { type: 'sequence-props-updated', fileName, nodePath: sourceNodePath, sourceVersion: event.sourceVersion, result, }); }); } catch (error) { if ( error instanceof JsxElementNotFoundAtLocationError || error instanceof JsxElementIdentityMismatchError ) { waitForLiveEventsListener().then((listener) => { listener.sendEventToClientId(clientId, { type: 'lost-node-path', fileName, line, column, sourceVersion: event.sourceVersion, }); }); return; } RenderInternals.Log.error({indent: false, logLevel}, error); } }, }); watcherInfo.unwatch = unwatch; if (!sequencePropsWatchers[clientId]) { sequencePropsWatchers[clientId] = {}; } sequencePropsWatchers[clientId][watcherKey] = watcherInfo; return initialResult; }; export const updateSequencePropsSubscription = ({ request: {subscription, effects}, remotionRoot, fileContentsCache, }: { request: UpdateSequencePropsSubscriptionRequest; remotionRoot: string; fileContentsCache: Map; }): SubscribeToSequencePropsResponse => { const watcher = sequencePropsWatchers[subscription.clientId]?.[ getWatcherKey(subscription.nodePath, subscription.assetKeys) ]; if (!watcher) { return {success: false, status: {canUpdate: false, reason: 'not-found'}}; } const status = computeSequencePropsStatus({ fileName: subscription.fileName, nodePath: watcher.currentNodePath.nodePath, componentIdentity: watcher.componentIdentity, keys: watcher.currentNodePath.sequenceKeys, assetKeys: watcher.assetKeys, effects, remotionRoot, fileContentsCache, }); watcher.effects = effects; watcher.effectChain = status.effects .map((effect) => effect.canUpdate && effect.callee) .join(','); watcher.currentNodePath = {...watcher.currentNodePath, effectKeys: effects}; return { success: true, nodePath: watcher.currentNodePath, status, sourceVersion: watcher.sourceVersion, }; }; export const updateSequencePropsForEffectEdit = ( requests: UpdateSequencePropsSubscriptionRequest[], remotionRoot: string, ) => { if (requests.length === 0) return {}; const fileContentsCache = new Map(); return { sequenceProps: requests.map((request) => ({ request, result: updateSequencePropsSubscription({ request, remotionRoot, fileContentsCache, }), })), }; }; export const unsubscribeFromSequencePropsWatchers = ({ fileName, nodePath, remotionRoot, clientId, sequenceKeys, assetKeys, effectKeys, }: { fileName: string; nodePath: SequenceNodePath; remotionRoot: string; clientId: string; sequenceKeys: string[]; assetKeys: string[]; effectKeys: string[][]; }) => { const absolutePath = path.resolve(remotionRoot, fileName); const watcherKey = getWatcherKey( { absolutePath, nodePath, sequenceKeys, effectKeys, }, assetKeys, ); if ( !sequencePropsWatchers[clientId] || !sequencePropsWatchers[clientId][watcherKey] ) { return; } sequencePropsWatchers[clientId][watcherKey].refCount--; if (sequencePropsWatchers[clientId][watcherKey].refCount <= 0) { sequencePropsWatchers[clientId][watcherKey].unwatch(); delete sequencePropsWatchers[clientId][watcherKey]; } }; export const unsubscribeClientSequencePropsWatchers = (clientId: string) => { if (!sequencePropsWatchers[clientId]) { return; } Object.values(sequencePropsWatchers[clientId]).forEach((watcher) => { watcher.unwatch(); }); delete sequencePropsWatchers[clientId]; };