🎥 Make videos programmatically with React
`@remotion/browser-studio`: Add virtual project operations (#9814)
Jonny Burgerf9578ae89f35
diff --git a/packages/browser-studio/bundle.ts b/packages/browser-studio/bundle.tsindex 4c95ca3394..906c9a6300 100644--- a/packages/browser-studio/bundle.ts+++ b/packages/browser-studio/bundle.ts@@ -35,8 +35,20 @@ if (!output.success) {process.exit(1);}+const externalStudioSharedImport =+ /\bfrom\s*["']@remotion\/studio-shared["']|\bimport\s*\(\s*["']@remotion\/studio-shared["']|\brequire\s*\(\s*["']@remotion\/studio-shared["']/;+for (const file of output.outputs) {const str = await file.text();+ if (+ path.basename(file.path) === 'browser-studio-render-entry.mjs' &&+ externalStudioSharedImport.test(str)+ ) {+ throw new Error(+ 'Browser Studio must bundle @remotion/studio-shared into its render entry so it cannot link against an incompatible published version.',+ );+ }+const out = path.join('dist', 'esm', file.path);await Bun.write(out, str);diff --git a/packages/browser-studio/src/BrowserStudio.tsx b/packages/browser-studio/src/BrowserStudio.tsxindex a93f24b591..2028e03075 100644--- a/packages/browser-studio/src/BrowserStudio.tsx+++ b/packages/browser-studio/src/BrowserStudio.tsx@@ -1,6 +1,10 @@import {studioHtml} from '@remotion/studio-shared/studio-html';import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';import {createBrowserStudioOperations} from './browser-studio-operations';+import {+ areBrowserStudioProjectsEqual,+ createBrowserStudioPublicFileManager,+} from './browser-studio-project-controller';import {browserStudioDependencyVersions} from './dependency-versions';import {Spinner} from './Spinner';import type {@@ -14,6 +18,11 @@ const makeInitialState = (): CompileState => ({status: 'idle',});+// The host and iframe may use different studio-shared versions, so this+// handshake intentionally has no shared runtime import.+const BROWSER_STUDIO_OPERATIONS_READY_EVENT =+ 'remotion-browser-studio-operations-ready';+const localStudioRenderEntry = new URL('./browser-studio-render-entry.mjs',import.meta.url,@@ -59,19 +68,6 @@ const errorStyle: React.CSSProperties = {whiteSpace: 'pre-wrap',};-const makeStaticFiles = (- publicFiles: BrowserStudioProps['project']['publicFiles'],-) =>- Object.entries(publicFiles ?? {}).map(([name, contents]) => ({- lastModified: 0,- name: name.replace(/^\//, ''),- sizeInBytes:- typeof contents === 'string'- ? new Blob([contents]).size- : contents.length,- src: `/public/${name.replace(/^\//, '')}`,- }));-export const BrowserStudio: React.FC<BrowserStudioProps> = ({project,readOnly,@@ -84,40 +80,81 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({const [iframeHtml, setIframeHtml] = useState<string | null>(null);const [iframeLoaded, setIframeLoaded] = useState(false);const iframeRef = useRef<HTMLIFrameElement | null>(null);+ const publicFileManager = useMemo(+ () =>+ createBrowserStudioPublicFileManager({+ createObjectUrl: null,+ revokeObjectUrl: null,+ }),+ [],+ );++ useEffect(() => {+ return () => publicFileManager.dispose();+ }, [publicFileManager]);- const incomingProjectKey = useMemo(() => JSON.stringify(project), [project]);const [editedProject, setEditedProject] = useState<{project: BrowserStudioProps['project'];- sourceKey: string;+ sourceProject: BrowserStudioProps['project'];} | null>(null);+ const incomingProjectMatchesEditSource =+ editedProject !== null &&+ areBrowserStudioProjectsEqual(editedProject.sourceProject, project);const activeProject =- editedProject?.sourceKey === incomingProjectKey+ editedProject && incomingProjectMatchesEditSource? editedProject.project: project;const activeProjectRef = useRef(activeProject);activeProjectRef.current = activeProject;+ const incomingProjectRef = useRef(project);+ incomingProjectRef.current = project;+ const onProjectChangeRef = useRef(onProjectChange);+ onProjectChangeRef.current = onProjectChange;const updateProject = useCallback((nextProject: BrowserStudioProps['project']) => {activeProjectRef.current = nextProject;setEditedProject({project: nextProject,- sourceKey: incomingProjectKey,+ sourceProject: incomingProjectRef.current,});- onProjectChange?.(nextProject);+ onProjectChangeRef.current?.(nextProject);},- [incomingProjectKey, onProjectChange],+ [],);const browserStudioOperations = useMemo(() =>createBrowserStudioOperations({dependencyVersions: browserStudioDependencyVersions,+ getStaticFiles: publicFileManager.getStaticFiles,getProject: () => activeProjectRef.current,onProjectChange: updateProject,}),- [updateProject],+ [publicFileManager, updateProject],);+ const previousIncomingProject = useRef(project);+ const incomingProjectAcknowledgesEdit =+ editedProject !== null &&+ areBrowserStudioProjectsEqual(editedProject.project, project);++ useEffect(() => {+ if (+ !areBrowserStudioProjectsEqual(+ previousIncomingProject.current,+ project,+ ) &&+ !incomingProjectAcknowledgesEdit+ ) {+ browserStudioOperations.resetHistory();+ }++ if (incomingProjectAcknowledgesEdit) {+ setEditedProject(null);+ }++ previousIncomingProject.current = project;+ }, [browserStudioOperations, incomingProjectAcknowledgesEdit, project]);useEffect(() => {setIframeLoaded(false);@@ -176,7 +213,10 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({numberOfAudioTags: 0,packageManager: 'unknown',projectName: 'template-blank',- publicFiles: makeStaticFiles(activeProject.publicFiles),+ publicFiles: publicFileManager.getStaticFiles({+ lastModifiedByPath: null,+ project: activeProject,+ }),publicFolderExists: null,fileSystemPlatform: null,publicPath: '',@@ -246,6 +286,7 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({iframeSrc,onCompileStateChange,activeProject,+ publicFileManager,readOnly,]);@@ -269,6 +310,14 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({contentDocument.write(iframeHtml);contentWindow.remotion_browserStudio = browserStudioOperations;contentDocument.close();++ const activeContentWindow = iframe.contentWindow;+ if (activeContentWindow) {+ activeContentWindow.remotion_browserStudio = browserStudioOperations;+ activeContentWindow.dispatchEvent(+ new Event(BROWSER_STUDIO_OPERATIONS_READY_EVENT),+ );+ }}, [browserStudioOperations, iframeHtml, iframeLoaded, iframeSrc]);return (diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.tsindex f7f4272d20..e6f5a54708 100644--- a/packages/browser-studio/src/browser-studio-operations.ts+++ b/packages/browser-studio/src/browser-studio-operations.ts@@ -7,32 +7,46 @@ import type {BrowserStudioOperations,InsertJsxElementResponse,} from '@remotion/studio-shared';+import {createBrowserStudioProjectController} from './browser-studio-project-controller';import {makeBrowserStudioProjectArchive} from './download-project';import type {VirtualProject} from './types';export {insertSolidIntoProject} from '@remotion/studio-codemods';+export type BrowserStudioOperationsController = BrowserStudioOperations & {+ resetHistory: () => void;+};+export const createBrowserStudioOperations = ({dependencyVersions,+ getStaticFiles,getProject,onProjectChange,}: {- dependencyVersions?: Record<string, string>;+ dependencyVersions: Record<string, string>;+ getStaticFiles: Parameters<+ typeof createBrowserStudioProjectController+ >[0]['getStaticFiles'];getProject: () => VirtualProject;onProjectChange: (project: VirtualProject) => void;-}): BrowserStudioOperations => {+}): BrowserStudioOperationsController => {+ const controller = createBrowserStudioProjectController({+ getStaticFiles,+ getProject,+ onProjectChange,+ });+return {- ...(dependencyVersions- ? {- downloadProject: () =>- Promise.resolve(- makeBrowserStudioProjectArchive({- dependencyVersions,- project: getProject(),- }),- ),- }- : {}),+ deleteStaticFile: controller.deleteStaticFile,+ downloadProject: () =>+ Promise.resolve(+ makeBrowserStudioProjectArchive({+ dependencyVersions,+ project: getProject(),+ }),+ ),+ findInFile: controller.findInFile,+ getFileSource: controller.getFileSource,getCompositionFile: (compositionId) =>getCompositionFile({compositionId, project: getProject()}),getCompositionComponentInfo: (request) =>@@ -41,11 +55,14 @@ export const createBrowserStudioOperations = ({),insertSolid: (request) => {try {- const project = insertSolidIntoProject({- project: getProject(),- request,+ controller.applyMutation({+ fileName: request.compositionFile,+ mutate: (project) =>+ insertSolidIntoProject({+ project,+ request,+ }),});- onProjectChange(project);return Promise.resolve({success: true});} catch (error) {return Promise.resolve({@@ -55,5 +72,11 @@ export const createBrowserStudioOperations = ({} satisfies InsertJsxElementResponse);}},+ redo: controller.redo,+ renameStaticFile: controller.renameStaticFile,+ resetHistory: controller.resetHistory,+ subscribeToEvent: controller.subscribeToEvent,+ undo: controller.undo,+ writeStaticFile: controller.writeStaticFile,};};diff --git a/packages/browser-studio/src/browser-studio-project-controller.ts b/packages/browser-studio/src/browser-studio-project-controller.tsnew file mode 100644index 0000000000..a77d9f0367--- /dev/null+++ b/packages/browser-studio/src/browser-studio-project-controller.ts@@ -0,0 +1,529 @@+import {findSearchPosition} from '@remotion/studio-codemods';+import type {+ BrowserStudioOperations,+ EventSourceEvent,+ RedoResponse,+ UndoResponse,+} from '@remotion/studio-shared';+import type {VirtualProject} from './types';++type HistoryEntry = {+ before: VirtualProject;+ after: VirtualProject;+ fileName: string;+};++type ProjectMutation = {+ fileName: string;+ mutate: (project: VirtualProject) => VirtualProject;+};++const MAX_HISTORY_ENTRIES = 100;++const normalizePublicFilePath = (path: string) => {+ const withoutLeadingSlash = path.startsWith('/') ? path.slice(1) : path;++ if (+ withoutLeadingSlash.length === 0 ||+ withoutLeadingSlash.includes('\\') ||+ withoutLeadingSlash.includes('\0') ||+ withoutLeadingSlash+ .split('/')+ .some((segment) => segment === '' || segment === '.' || segment === '..')+ ) {+ throw new Error(`Invalid public file path: ${path}`);+ }++ return withoutLeadingSlash;+};++const getCanonicalPublicFiles = (project: VirtualProject) => {+ const canonicalFiles: Record<string, Uint8Array | string> = {};++ for (const [path, contents] of Object.entries(project.publicFiles ?? {})) {+ const canonicalPath = normalizePublicFilePath(path);+ if (Object.hasOwn(canonicalFiles, canonicalPath)) {+ throw new Error(`Multiple public files resolve to ${canonicalPath}`);+ }++ canonicalFiles[canonicalPath] = contents;+ }++ return canonicalFiles;+};++const arePublicFileContentsEqual = (+ left: Uint8Array | string | undefined,+ right: Uint8Array | string | undefined,+) => {+ if (left === right) {+ return true;+ }++ if (typeof left === 'string' || typeof right === 'string') {+ return false;+ }++ if (!left || !right || left.length !== right.length) {+ return false;+ }++ return left.every((value, index) => value === right[index]);+};++const areStringRecordsEqual = (+ left: Record<string, string>,+ right: Record<string, string>,+) => {+ const leftEntries = Object.entries(left);+ if (leftEntries.length !== Object.keys(right).length) {+ return false;+ }++ return leftEntries.every(([path, contents]) => right[path] === contents);+};++const arePublicFileRecordsEqual = (+ left: Record<string, Uint8Array | string> | undefined,+ right: Record<string, Uint8Array | string> | undefined,+) => {+ const leftEntries = Object.entries(left ?? {});+ if (leftEntries.length !== Object.keys(right ?? {}).length) {+ return false;+ }++ return leftEntries.every(([path, contents]) =>+ arePublicFileContentsEqual(contents, right?.[path]),+ );+};++export const areBrowserStudioProjectsEqual = (+ left: VirtualProject,+ right: VirtualProject,+) => {+ if (left === right) {+ return true;+ }++ return (+ left.entryPoint === right.entryPoint &&+ left.rootDir === right.rootDir &&+ areStringRecordsEqual(left.files, right.files) &&+ arePublicFileRecordsEqual(left.publicFiles, right.publicFiles)+ );+};++const getChangedPublicFilePaths = (+ previousProject: VirtualProject,+ nextProject: VirtualProject,+) => {+ const previous = getCanonicalPublicFiles(previousProject);+ const next = getCanonicalPublicFiles(nextProject);+ const paths = new Set([...Object.keys(previous), ...Object.keys(next)]);++ return [...paths].filter(+ (path) => !arePublicFileContentsEqual(previous[path], next[path]),+ );+};++const encodePublicFilePath = (path: string) =>+ path+ .split('/')+ .map((segment) => encodeURIComponent(segment))+ .join('/');++export const getBrowserStudioStaticFiles = ({+ getSrc,+ lastModifiedByPath,+ project,+}: {+ getSrc: ((name: string, contents: Uint8Array | string) => string) | null;+ lastModifiedByPath: ReadonlyMap<string, number> | null;+ project: VirtualProject;+}) => {+ return Object.entries(getCanonicalPublicFiles(project)).map(+ ([name, contents]) => ({+ lastModified:+ lastModifiedByPath === null ? 0 : (lastModifiedByPath.get(name) ?? 0),+ name,+ sizeInBytes:+ typeof contents === 'string'+ ? new TextEncoder().encode(contents).byteLength+ : contents.byteLength,+ src:+ getSrc === null+ ? `/${encodePublicFilePath(name)}`+ : getSrc(name, contents),+ }),+ );+};++export const createBrowserStudioPublicFileManager = ({+ createObjectUrl,+ revokeObjectUrl,+}: {+ createObjectUrl: ((blob: Blob) => string) | null;+ revokeObjectUrl: ((url: string) => void) | null;+}) => {+ const resolvedCreateObjectUrl =+ createObjectUrl === null+ ? (blob: Blob) => URL.createObjectURL(blob)+ : createObjectUrl;+ const resolvedRevokeObjectUrl =+ revokeObjectUrl === null+ ? (url: string) => URL.revokeObjectURL(url)+ : revokeObjectUrl;+ const objectUrls = new Map<+ string,+ {contents: Uint8Array | string; url: string}+ >();++ const getObjectUrl = (name: string, contents: Uint8Array | string) => {+ const existing = objectUrls.get(name);+ if (arePublicFileContentsEqual(existing?.contents, contents)) {+ return existing!.url;+ }++ if (existing) {+ resolvedRevokeObjectUrl(existing.url);+ }++ const blobContents =+ typeof contents === 'string' ? contents : contents.slice().buffer;+ const url = resolvedCreateObjectUrl(new Blob([blobContents]));+ objectUrls.set(name, {+ contents: typeof contents === 'string' ? contents : contents.slice(),+ url,+ });+ return url;+ };++ const getStaticFiles = ({+ lastModifiedByPath,+ project,+ }: {+ lastModifiedByPath: ReadonlyMap<string, number> | null;+ project: VirtualProject;+ }) => {+ const currentNames = new Set(Object.keys(getCanonicalPublicFiles(project)));+ for (const [name, entry] of objectUrls) {+ if (!currentNames.has(name)) {+ resolvedRevokeObjectUrl(entry.url);+ objectUrls.delete(name);+ }+ }++ return getBrowserStudioStaticFiles({+ getSrc: getObjectUrl,+ lastModifiedByPath,+ project,+ });+ };++ return {+ dispose: () => {+ for (const {url} of objectUrls.values()) {+ resolvedRevokeObjectUrl(url);+ }++ objectUrls.clear();+ },+ getStaticFiles,+ };+};++const getFileSource = ({+ fileName,+ project,+}: {+ fileName: string;+ project: VirtualProject;+}) => {+ const withoutQuery = fileName.split(/[?#]/)[0];+ const normalizedFileName = withoutQuery.replace(/\\/g, '/');+ const rootDir = project.rootDir.replace(/\/$/, '');++ const directCandidates = [+ normalizedFileName,+ normalizedFileName.startsWith('/')+ ? normalizedFileName+ : `${rootDir}/${normalizedFileName.replace(/^\.\//, '')}`,+ ];++ for (const candidate of directCandidates) {+ const contents = project.files[candidate];+ if (contents !== undefined) {+ return contents;+ }+ }++ const matchingEntries = Object.entries(project.files).filter(([path]) => {+ const relativePath = path.startsWith(`${rootDir}/`)+ ? path.slice(rootDir.length + 1)+ : path.replace(/^\//, '');+ return (+ normalizedFileName === relativePath ||+ normalizedFileName.endsWith(`/${relativePath}`)+ );+ });++ return matchingEntries.length === 1 ? matchingEntries[0][1] : null;+};++export type BrowserStudioProjectController = {+ applyMutation: (mutation: ProjectMutation) => VirtualProject;+ deleteStaticFile: BrowserStudioOperations['deleteStaticFile'];+ findInFile: BrowserStudioOperations['findInFile'];+ getFileSource: BrowserStudioOperations['getFileSource'];+ redo: BrowserStudioOperations['redo'];+ resetHistory: () => void;+ renameStaticFile: BrowserStudioOperations['renameStaticFile'];+ subscribeToEvent: BrowserStudioOperations['subscribeToEvent'];+ undo: BrowserStudioOperations['undo'];+ writeStaticFile: BrowserStudioOperations['writeStaticFile'];+};++export type BrowserStudioStaticFilesGetter = (input: {+ lastModifiedByPath: ReadonlyMap<string, number> | null;+ project: VirtualProject;+}) => ReturnType<typeof getBrowserStudioStaticFiles>;++export const createBrowserStudioProjectController = ({+ getStaticFiles,+ getProject,+ onProjectChange,+}: {+ getStaticFiles: BrowserStudioStaticFilesGetter | null;+ getProject: () => VirtualProject;+ onProjectChange: (project: VirtualProject) => void;+}): BrowserStudioProjectController => {+ const resolvedGetStaticFiles: BrowserStudioStaticFilesGetter =+ getStaticFiles === null+ ? ({lastModifiedByPath: revisionByPath, project}) =>+ getBrowserStudioStaticFiles({+ getSrc: null,+ lastModifiedByPath: revisionByPath,+ project,+ })+ : getStaticFiles;+ const undoStack: HistoryEntry[] = [];+ const redoStack: HistoryEntry[] = [];+ const listeners = new Set<(event: EventSourceEvent) => void>();+ const lastModifiedByPath = new Map<string, number>();+ let publicFileRevision = 0;++ const getUndoRedoEvent = (): EventSourceEvent => ({+ type: 'undo-redo-stack-changed',+ undoFile: undoStack.at(-1)?.fileName ?? null,+ redoFile: redoStack.at(-1)?.fileName ?? null,+ });++ const getPublicFilesEvent = (): EventSourceEvent => ({+ type: 'new-public-folder',+ files: resolvedGetStaticFiles({+ lastModifiedByPath,+ project: getProject(),+ }),+ folderExists: '/public',+ });++ const emit = (event: EventSourceEvent) => {+ for (const listener of listeners) {+ listener(event);+ }+ };++ const updatePublicFileRevisions = (+ previousProject: VirtualProject,+ nextProject: VirtualProject,+ ) => {+ const changedPaths = getChangedPublicFilePaths(+ previousProject,+ nextProject,+ );+ for (const path of changedPaths) {+ publicFileRevision++;+ lastModifiedByPath.set(path, publicFileRevision);+ }++ return changedPaths.length > 0;+ };++ const commitProject = ({+ previousProject,+ nextProject,+ }: {+ previousProject: VirtualProject;+ nextProject: VirtualProject;+ }) => {+ const publicFilesChanged = updatePublicFileRevisions(+ previousProject,+ nextProject,+ );+ onProjectChange(nextProject);+ if (publicFilesChanged) {+ emit(getPublicFilesEvent());+ }++ emit(getUndoRedoEvent());+ };++ const applyMutation = ({fileName, mutate}: ProjectMutation) => {+ const before = getProject();+ const after = mutate(before);++ if (after === before) {+ return before;+ }++ undoStack.push({before, after, fileName});+ if (undoStack.length > MAX_HISTORY_ENTRIES) {+ undoStack.shift();+ }++ redoStack.length = 0;+ commitProject({previousProject: before, nextProject: after});+ return after;+ };++ const undo = (): Promise<UndoResponse> => {+ const entry = undoStack.pop();+ if (!entry) {+ return Promise.resolve({success: false, reason: 'Nothing to undo'});+ }++ redoStack.push(entry);+ commitProject({+ previousProject: getProject(),+ nextProject: entry.before,+ });+ return Promise.resolve({success: true});+ };++ const redo = (): Promise<RedoResponse> => {+ const entry = redoStack.pop();+ if (!entry) {+ return Promise.resolve({success: false, reason: 'Nothing to redo'});+ }++ undoStack.push(entry);+ commitProject({+ previousProject: getProject(),+ nextProject: entry.after,+ });+ return Promise.resolve({success: true});+ };++ return {+ applyMutation,+ deleteStaticFile: ({relativePath}) => {+ try {+ const canonicalPath = normalizePublicFilePath(relativePath);+ const publicFiles = getCanonicalPublicFiles(getProject());+ const existed = publicFiles[canonicalPath] !== undefined;+ if (!existed) {+ return Promise.resolve({success: true, existed: false});+ }++ applyMutation({+ fileName: canonicalPath,+ mutate: (project) => {+ const nextPublicFiles = getCanonicalPublicFiles(project);+ delete nextPublicFiles[canonicalPath];+ return {...project, publicFiles: nextPublicFiles};+ },+ });+ return Promise.resolve({success: true, existed: true});+ } catch (error) {+ return Promise.reject(error);+ }+ },+ findInFile: (request) => {+ const contents = getFileSource({+ fileName: request.fileName,+ project: getProject(),+ });+ if (contents === null) {+ return Promise.reject(new Error(`Could not find ${request.fileName}`));+ }++ return Promise.resolve(findSearchPosition({...request, contents}));+ },+ getFileSource: (fileName) =>+ Promise.resolve(getFileSource({fileName, project: getProject()})),+ redo,+ resetHistory: () => {+ undoStack.length = 0;+ redoStack.length = 0;+ emit(getUndoRedoEvent());+ },+ renameStaticFile: ({oldRelativePath, newRelativePath}) => {+ try {+ const oldPath = normalizePublicFilePath(oldRelativePath);+ const newPath = normalizePublicFilePath(newRelativePath);+ if (oldPath === newPath) {+ return Promise.resolve({success: true});+ }++ const publicFiles = getCanonicalPublicFiles(getProject());+ if (publicFiles[oldPath] === undefined) {+ throw new Error(`${oldRelativePath} does not exist`);+ }++ if (publicFiles[newPath] !== undefined) {+ throw new Error(`${newRelativePath} already exists`);+ }++ applyMutation({+ fileName: oldPath,+ mutate: (project) => {+ const nextPublicFiles = getCanonicalPublicFiles(project);+ nextPublicFiles[newPath] = nextPublicFiles[oldPath];+ delete nextPublicFiles[oldPath];+ return {...project, publicFiles: nextPublicFiles};+ },+ });+ return Promise.resolve({success: true});+ } catch (error) {+ return Promise.reject(error);+ }+ },+ subscribeToEvent: (listener) => {+ listeners.add(listener);+ listener({+ type: 'init',+ clientId: 'browser-studio',+ undoFile: undoStack.at(-1)?.fileName ?? null,+ redoFile: redoStack.at(-1)?.fileName ?? null,+ });+ listener(getPublicFilesEvent());++ return () => {+ listeners.delete(listener);+ };+ },+ undo,+ writeStaticFile: ({contents, filePath}) => {+ try {+ const canonicalPath = normalizePublicFilePath(filePath);+ const nextContents =+ typeof contents === 'string'+ ? contents+ : new Uint8Array(contents.slice(0));+ applyMutation({+ fileName: canonicalPath,+ mutate: (project) => ({+ ...project,+ publicFiles: {+ ...getCanonicalPublicFiles(project),+ [canonicalPath]: nextContents,+ },+ }),+ });+ return Promise.resolve();+ } catch (error) {+ return Promise.reject(error);+ }+ },+ };+};diff --git a/packages/browser-studio/src/dev/studio-render-entry-external.ts b/packages/browser-studio/src/dev/studio-render-entry-external.tsindex f8ce899b92..38eed0e90a 100644--- a/packages/browser-studio/src/dev/studio-render-entry-external.ts+++ b/packages/browser-studio/src/dev/studio-render-entry-external.ts@@ -4,7 +4,6 @@ export const studioRenderEntryExternal = ['@remotion/media-utils','@remotion/player','@remotion/renderer',- '@remotion/studio-shared','@remotion/timeline-utils','@remotion/web-renderer','@remotion/zod-types',diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.tsindex 990fc281f3..f6383fa617 100644--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts@@ -50,6 +50,29 @@ test('adds multiple Solids without duplicating the import', () => {expect(composition.match(/<Solid /g)).toHaveLength(2);});+test('adds a Solid at a timeline frame', () => {+ const project = createBlankTemplateProject();+ const updated = insertSolidIntoProject({+ project,+ request: {+ compositionFile: '/project/src/Composition.tsx',+ compositionId: 'MyComp',+ from: 42,+ element: {+ type: 'solid',+ width: 1280,+ height: 720,+ position: {x: 100, y: 50},+ },+ },+ });+ const composition = updated.files['/project/src/Composition.tsx'];++ expect(composition).toContain('<Sequence from={42}');+ expect(composition).toContain("translate: '100px 50px'");+ expect(composition).toContain('<Solid width={1280} height={720}');+});+test('resolves an imported composition component', async () => {const project: VirtualProject = {rootDir: '/project',@@ -78,6 +101,8 @@ export const MyComponent = () => <AbsoluteFill>Existing</AbsoluteFill>;let currentProject = project;const operations = createBrowserStudioOperations({+ dependencyVersions: {},+ getStaticFiles: null,getProject: () => currentProject,onProjectChange: (nextProject) => {currentProject = nextProject;@@ -141,3 +166,35 @@ registerRoot(Root);expect(output).toContain('<RemotionSequence>');expect(output).toContain('<RemotionSolid width={1280}');});++test('reports invalid timeline Solid input without changing the project', async () => {+ const project = createBlankTemplateProject();+ let currentProject = project;+ const operations = createBrowserStudioOperations({+ dependencyVersions: {},+ getStaticFiles: null,+ getProject: () => currentProject,+ onProjectChange: (nextProject) => {+ currentProject = nextProject;+ },+ });++ const result = await operations.insertSolid({+ compositionFile: '/project/src/Composition.tsx',+ compositionId: 'MyComp',+ from: 1.5,+ element: {+ type: 'solid',+ width: 1280,+ height: 720,+ position: null,+ },+ });++ expect(result.success).toBe(false);+ if (!result.success) {+ expect(result.reason).toBe('from must be a non-negative integer');+ }++ expect(currentProject).toBe(project);+});diff --git a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts b/packages/browser-studio/src/test/browser-studio-project-operations.test.tsnew file mode 100644index 0000000000..1e0d3411a5--- /dev/null+++ b/packages/browser-studio/src/test/browser-studio-project-operations.test.ts@@ -0,0 +1,237 @@+import {expect, test} from 'bun:test';+import type {EventSourceEvent} from '@remotion/studio-shared';+import {createBrowserStudioOperations} from '../browser-studio-operations';+import {+ areBrowserStudioProjectsEqual,+ createBrowserStudioPublicFileManager,+} from '../browser-studio-project-controller';+import {createBlankTemplateProject} from '../templates/blank';+import type {VirtualProject} from '../types';++test('mutates virtual files, emits events, and preserves undo and redo history', async () => {+ const initialProject = createBlankTemplateProject();+ let project: VirtualProject = {+ ...initialProject,+ publicFiles: {'existing.txt': 'existing'},+ };+ const revokedUrls: string[] = [];+ let nextObjectUrl = 0;+ const publicFileManager = createBrowserStudioPublicFileManager({+ createObjectUrl: () => `blob:virtual-${++nextObjectUrl}`,+ revokeObjectUrl: (url) => revokedUrls.push(url),+ });+ const operations = createBrowserStudioOperations({+ dependencyVersions: {},+ getStaticFiles: publicFileManager.getStaticFiles,+ getProject: () => project,+ onProjectChange: (nextProject) => {+ project = nextProject;+ },+ });+ const events: EventSourceEvent[] = [];+ const unsubscribe = operations.subscribeToEvent((event) =>+ events.push(event),+ );++ expect(events.slice(0, 2).map((event) => event.type)).toEqual([+ 'init',+ 'new-public-folder',+ ]);+ expect(+ await operations.findInFile({+ fileName: 'webpack://remotion/./src/Composition.tsx',+ lineNumber: 1,+ columnNumber: 1,+ search: 'durationInFrames',+ }),+ ).toEqual({lineNumber: 14, columnNumber: 7});++ const insertResult = await operations.insertSolid({+ compositionFile: '/project/src/Composition.tsx',+ compositionId: 'MyComp',+ element: {+ type: 'solid',+ width: 1280,+ height: 720,+ position: null,+ },+ from: null,+ });+ expect(insertResult).toEqual({success: true});+ expect(project.files['/project/src/Composition.tsx']).toContain(+ '<Solid width={1280}',+ );++ const {redo, undo} = operations;+ expect(await undo()).toEqual({success: true});+ expect(project.files['/project/src/Composition.tsx']).toBe(+ initialProject.files['/project/src/Composition.tsx'],+ );+ expect(await redo()).toEqual({success: true});+ expect(project.files['/project/src/Composition.tsx']).toContain(+ '<Solid width={1280}',+ );++ const {writeStaticFile} = operations;+ await writeStaticFile({+ contents: new Uint8Array([0, 127, 128, 255]).buffer,+ filePath: '/nested/upload.bin',+ });+ expect(project.publicFiles?.['nested/upload.bin']).toEqual(+ new Uint8Array([0, 127, 128, 255]),+ );++ const publicFolderEvents = events.filter(+ (event): event is Extract<EventSourceEvent, {type: 'new-public-folder'}> =>+ event.type === 'new-public-folder',+ );+ const uploadedFile = publicFolderEvents+ .at(-1)+ ?.files.find((file) => file.name === 'nested/upload.bin');+ expect(uploadedFile).toMatchObject({+ lastModified: 1,+ name: 'nested/upload.bin',+ sizeInBytes: 4,+ src: 'blob:virtual-2',+ });++ const {renameStaticFile} = operations;+ await renameStaticFile({+ oldRelativePath: 'nested/upload.bin',+ newRelativePath: 'renamed.bin',+ });+ expect(project.publicFiles?.['nested/upload.bin']).toBeUndefined();+ expect(project.publicFiles?.['renamed.bin']).toEqual(+ new Uint8Array([0, 127, 128, 255]),+ );++ const {deleteStaticFile} = operations;+ expect(await deleteStaticFile({relativePath: 'renamed.bin'})).toEqual({+ success: true,+ existed: true,+ });+ expect(project.publicFiles?.['renamed.bin']).toBeUndefined();++ expect(await undo()).toEqual({success: true});+ expect(project.publicFiles?.['renamed.bin']).toEqual(+ new Uint8Array([0, 127, 128, 255]),+ );+ expect(await undo()).toEqual({success: true});+ expect(project.publicFiles?.['nested/upload.bin']).toEqual(+ new Uint8Array([0, 127, 128, 255]),+ );++ expect(+ await operations.getFileSource(+ 'webpack://remotion/./src/Composition.tsx?source',+ ),+ ).toContain('<Solid width={1280}');++ const eventCount = events.length;+ unsubscribe();+ await undo();+ expect(events).toHaveLength(eventCount);+ publicFileManager.dispose();+ expect(revokedUrls).toContain('blob:virtual-2');+});++test('rejects unsafe public paths and conflicting renames', async () => {+ let project: VirtualProject = {+ ...createBlankTemplateProject(),+ publicFiles: {'existing.txt': 'existing'},+ };+ const operations = createBrowserStudioOperations({+ dependencyVersions: {},+ getStaticFiles: null,+ getProject: () => project,+ onProjectChange: (nextProject) => {+ project = nextProject;+ },+ });+ const {renameStaticFile, writeStaticFile} = operations;++ await expect(+ writeStaticFile({contents: 'unsafe', filePath: '../outside.txt'}),+ ).rejects.toThrow('Invalid public file path');+ await writeStaticFile({contents: 'new', filePath: 'new.txt'});+ await expect(+ renameStaticFile({+ oldRelativePath: 'new.txt',+ newRelativePath: 'existing.txt',+ }),+ ).rejects.toThrow('already exists');++ operations.resetHistory();+ expect(await operations.undo()).toEqual({+ success: false,+ reason: 'Nothing to undo',+ });+});++test('refreshes object URLs if a supplied byte array is mutated', () => {+ const contents = new Uint8Array([1, 2, 3]);+ const revokedUrls: string[] = [];+ let nextObjectUrl = 0;+ const publicFileManager = createBrowserStudioPublicFileManager({+ createObjectUrl: () => `blob:mutable-${++nextObjectUrl}`,+ revokeObjectUrl: (url) => revokedUrls.push(url),+ });+ const project: VirtualProject = {+ ...createBlankTemplateProject(),+ publicFiles: {'mutable.bin': contents},+ };++ expect(+ publicFileManager.getStaticFiles({lastModifiedByPath: null, project})[0]+ .src,+ ).toBe('blob:mutable-1');+ contents[0] = 4;+ expect(+ publicFileManager.getStaticFiles({lastModifiedByPath: null, project})[0]+ .src,+ ).toBe('blob:mutable-2');+ expect(revokedUrls).toEqual(['blob:mutable-1']);++ publicFileManager.dispose();+});++test('uses the platform object URL implementation when overrides are null', () => {+ const publicFileManager = createBrowserStudioPublicFileManager({+ createObjectUrl: null,+ revokeObjectUrl: null,+ });+ const project: VirtualProject = {+ ...createBlankTemplateProject(),+ publicFiles: {'default.txt': 'contents'},+ };++ const [file] = publicFileManager.getStaticFiles({+ lastModifiedByPath: null,+ project,+ });+ if (!file) {+ throw new Error('Expected the virtual static file');+ }++ expect(file.src.startsWith('blob:')).toBe(true);+ publicFileManager.dispose();+});++test('compares deep-cloned virtual projects without serializing binary assets', () => {+ const left: VirtualProject = {+ ...createBlankTemplateProject(),+ publicFiles: {'asset.bin': new Uint8Array([0, 127, 128, 255])},+ };+ const equalClone: VirtualProject = {+ ...left,+ files: {...left.files},+ publicFiles: {'asset.bin': new Uint8Array([0, 127, 128, 255])},+ };+ const changedClone: VirtualProject = {+ ...equalClone,+ publicFiles: {'asset.bin': new Uint8Array([0, 127, 128, 254])},+ };++ expect(areBrowserStudioProjectsEqual(left, equalClone)).toBe(true);+ expect(areBrowserStudioProjectsEqual(left, changedClone)).toBe(false);+});diff --git a/packages/browser-studio/src/test/download-project.test.ts b/packages/browser-studio/src/test/download-project.test.tsindex ef45de9068..5e00fd3c2f 100644--- a/packages/browser-studio/src/test/download-project.test.ts+++ b/packages/browser-studio/src/test/download-project.test.ts@@ -20,6 +20,7 @@ test('downloads the current Browser Studio project as a runnable archive', async};const operations = createBrowserStudioOperations({dependencyVersions,+ getStaticFiles: null,getProject: () => project,onProjectChange: (nextProject) => {project = nextProject;@@ -39,10 +40,7 @@ test('downloads the current Browser Studio project as a runnable archive', async});expect(insertResult).toEqual({success: true});- const archive = await operations.downloadProject?.();- if (!archive) {- throw new Error('Expected Browser Studio to support project downloads');- }+ const archive = await operations.downloadProject();const files = unzipSync(archive.data);const packageJson = JSON.parse(strFromU8(files['package.json'])) as Record<diff --git a/packages/core/src/static-file.ts b/packages/core/src/static-file.tsindex e6a8b9bc38..35e0117581 100644--- a/packages/core/src/static-file.ts+++ b/packages/core/src/static-file.ts@@ -138,6 +138,18 @@ export const staticFile = (path: string) => {);}+ if (typeof window !== 'undefined') {+ // This lookup is primarily used by Browser Studio, where virtual assets+ // have blob: URLs. Regular Studio sources are already encoded using the+ // same per-path-segment encoding as the fallback below.+ const matchingStaticFile = window.remotion_staticFiles?.find(+ (file) => file.name === trimLeadingSlash(path),+ );+ if (matchingStaticFile) {+ return matchingStaticFile.src;+ }+ }+const preprocessed = encodeBySplitting(path);const preparsed = inner(preprocessed);diff --git a/packages/core/src/test/static-file-safe-uri.test.ts b/packages/core/src/test/static-file-safe-uri.test.tsindex ee81621999..a180fdfb2d 100644--- a/packages/core/src/test/static-file-safe-uri.test.ts+++ b/packages/core/src/test/static-file-safe-uri.test.ts@@ -54,3 +54,37 @@ test('should keep spaces', () => {'/static-abcdef/mediaparsernextsteps/Screenshot%202025-01-31%20at%2008.13.54.png',);});++test('should use static file sources while preserving regular Studio encoding', () => {+ const previousStaticFiles = window.remotion_staticFiles;+ const regularStudioName = 'regular/special #?% ü.png';+ const regularStudioSrc =+ '/static-abcdef/regular/special%20%23%3F%25%20%C3%BC.png';+ window.remotion_staticFiles = [+ {+ lastModified: 0,+ name: 'virtual/image.png',+ sizeInBytes: 10,+ src: 'blob:http://localhost:3000/virtual-image',+ },+ {+ lastModified: 0,+ name: regularStudioName,+ sizeInBytes: 10,+ src: regularStudioSrc,+ },+ ];++ try {+ expect(staticFile('/virtual/image.png')).toBe(+ 'blob:http://localhost:3000/virtual-image',+ );+ expect(staticFile(regularStudioName)).toBe(regularStudioSrc);++ window.remotion_staticFiles = [];+ expect(staticFile(regularStudioName)).toBe(regularStudioSrc);+ expect(staticFile('missing.png')).toBe('/static-abcdef/missing.png');+ } finally {+ window.remotion_staticFiles = previousStaticFiles;+ }+});diff --git a/packages/studio-codemods/src/find-search-position.ts b/packages/studio-codemods/src/find-search-position.tsnew file mode 100644index 0000000000..7b6cda9830--- /dev/null+++ b/packages/studio-codemods/src/find-search-position.ts@@ -0,0 +1,29 @@+export const findSearchPosition = ({+ contents,+ lineNumber,+ columnNumber,+ search,+}: {+ contents: string;+ lineNumber: number;+ columnNumber: number;+ search: string;+}) => {+ const lines = contents.split(/\r?\n/);+ const startLineIndex = Math.max(0, lineNumber - 1);++ for (let lineIndex = startLineIndex; lineIndex < lines.length; lineIndex++) {+ const startColumnIndex =+ lineIndex === startLineIndex ? Math.max(0, columnNumber - 1) : 0;+ const foundColumnIndex = lines[lineIndex].indexOf(search, startColumnIndex);++ if (foundColumnIndex !== -1) {+ return {+ lineNumber: lineIndex + 1,+ columnNumber: foundColumnIndex + 1,+ };+ }+ }++ return {lineNumber, columnNumber};+};diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.tsindex 08a8e40453..e1aaa870bc 100644--- a/packages/studio-codemods/src/index.ts+++ b/packages/studio-codemods/src/index.ts@@ -4,6 +4,8 @@ import type {InsertJsxElementRequest,} from '@remotion/studio-shared';+export {findSearchPosition} from './find-search-position';+export type CodemodProject = {files: Record<string, string>;rootDir: string;@@ -879,21 +881,29 @@ const roundCoordinate = (value: number) => {};const solidElement = ({+ from,height,localName,position,+ sequenceLocalName,width,}: {+ from: number | null;height: number;localName: string;position: {x: number; y: number} | null;+ sequenceLocalName: string | null;width: number;}) => {const translate = position? `, translate: '${roundCoordinate(position.x)}px ${roundCoordinate(position.y)}px'`: '';+ const solid = `<${localName} width={${width}} height={${height}} color="gray" style={{position: 'absolute'${translate}}} />`;+ if (from === null || sequenceLocalName === null) {+ return solid;+ }- return `<${localName} width={${width}} height={${height}} color="gray" style={{position: 'absolute'${translate}}} />`;+ return `<${sequenceLocalName} from={${from}} style={{position: 'absolute'${translate}}}>${solid}</${sequenceLocalName}>`;};const appendToJsxRoot = ({@@ -1006,12 +1016,14 @@ const applyTextEdits = (source: string, edits: TextEdit[]) => {export const insertSolidIntoSource = ({exportName,+ from = null,height,position,source,width,}: {exportName: string | 'default';+ from?: number | null;height: number;position: {x: number; y: number} | null;source: string;@@ -1041,13 +1053,14 @@ export const insertSolidIntoSource = ({const openingElement =root.type === 'JSXElement' ? getNode(root, 'openingElement') : null;const isSelfClosing = openingElement?.selfClosing === true;- const sequenceImport = isSelfClosing- ? chooseLocalName({- ast,- candidates: ['Sequence', 'RemotionSequence'],- importedName: 'Sequence',- })- : null;+ const sequenceImport =+ isSelfClosing || from !== null+ ? chooseLocalName({+ ast,+ candidates: ['Sequence', 'RemotionSequence'],+ importedName: 'Sequence',+ })+ : null;const imports = [...(solidImport.addImport? [{importedName: 'Solid', localName: solidImport.localName}]@@ -1058,9 +1071,11 @@ export const insertSolidIntoSource = ({];const unit = indentationUnit(source);const element = solidElement({+ from,height,localName: solidImport.localName,position,+ sequenceLocalName: sequenceImport?.localName ?? null,width,});const rootEdit =@@ -1106,10 +1121,27 @@ export const insertSolidIntoProject = <Project extends CodemodProject>({throw new Error('This codemod only supports adding <Solid>');}- if (request.from !== null) {- throw new Error(- 'This codemod only supports adding <Solid> at the current root',- );+ if (!Number.isFinite(request.element.width) || request.element.width < 1) {+ throw new Error('width must be a positive number');+ }++ if (!Number.isFinite(request.element.height) || request.element.height < 1) {+ throw new Error('height must be a positive number');+ }++ if (+ request.element.position !== null &&+ (!Number.isFinite(request.element.position.x) ||+ !Number.isFinite(request.element.position.y))+ ) {+ throw new Error('Position must be finite');+ }++ if (+ request.from !== null &&+ (!Number.isInteger(request.from) || request.from < 0)+ ) {+ throw new Error('from must be a non-negative integer');}const resolved = resolveCompositionComponent({@@ -1119,6 +1151,7 @@ export const insertSolidIntoProject = <Project extends CodemodProject>({});const {output} = insertSolidIntoSource({exportName: resolved.exportName,+ from: request.from,height: request.element.height,position: request.element.position,source: resolved.source,diff --git a/packages/studio-codemods/src/test/find-search-position.test.ts b/packages/studio-codemods/src/test/find-search-position.test.tsnew file mode 100644index 0000000000..49f72058a5--- /dev/null+++ b/packages/studio-codemods/src/test/find-search-position.test.ts@@ -0,0 +1,47 @@+import {expect, test} from 'bun:test';+import {findSearchPosition} from '../find-search-position';++test('finds a property after the component location', () => {+ const contents = [+ 'const MyComp = () => (',+ '\t<Sequence',+ '\t\tstyle={{',+ '\t\t\topacity: 0.5,',+ '\t\t}}',+ '\t/>',+ ');',+ ].join('\n');++ expect(+ findSearchPosition({+ contents,+ lineNumber: 2,+ columnNumber: 2,+ search: 'opacity',+ }),+ ).toEqual({lineNumber: 4, columnNumber: 4});+});++test('starts searching at the source column', () => {+ const contents = 'opacity: 1; <Sequence opacity={0.5} />';++ expect(+ findSearchPosition({+ contents,+ lineNumber: 1,+ columnNumber: 13,+ search: 'opacity',+ }),+ ).toEqual({lineNumber: 1, columnNumber: 23});+});++test('keeps the component location if the property is not found', () => {+ expect(+ findSearchPosition({+ contents: '<Sequence />',+ lineNumber: 1,+ columnNumber: 2,+ search: 'opacity',+ }),+ ).toEqual({lineNumber: 1, columnNumber: 2});+});diff --git a/packages/studio-codemods/src/test/insert-solid.test.ts b/packages/studio-codemods/src/test/insert-solid.test.tsindex 09163b385f..f694ef54d2 100644--- a/packages/studio-codemods/src/test/insert-solid.test.ts+++ b/packages/studio-codemods/src/test/insert-solid.test.ts@@ -21,3 +21,19 @@ export const MyComposition = () => <AbsoluteFill>Existing</AbsoluteFill>;);expect(result.line).toBe(3);});++test('inserts a timeline Solid in a positioned Sequence', () => {+ const result = insertSolidIntoSource({+ exportName: 'MyComposition',+ from: 42,+ height: 720,+ position: {x: 120.25, y: 80},+ source: `export const MyComposition = () => null;\n`,+ width: 1280,+ });++ expect(result.output).toContain("import {Solid, Sequence} from 'remotion';");+ expect(result.output).toContain('<Sequence from={42}');+ expect(result.output).toContain("translate: '120.3px 80px'");+ expect(result.output).toContain('<Solid width={1280} height={720}');+});diff --git a/packages/studio-server/src/preview-server/routes/find-in-file.ts b/packages/studio-server/src/preview-server/routes/find-in-file.tsindex fabd5e4e1f..fedc6d44a9 100644--- a/packages/studio-server/src/preview-server/routes/find-in-file.ts+++ b/packages/studio-server/src/preview-server/routes/find-in-file.ts@@ -1,40 +1,13 @@import fs from 'node:fs';import path from 'node:path';+import {findSearchPosition} from '@remotion/studio-codemods';import type {FindInFileRequest,FindInFileResponse,} from '@remotion/studio-shared';import type {ApiHandler} from '../api-types';-export const findSearchPosition = ({- contents,- lineNumber,- columnNumber,- search,-}: {- contents: string;- lineNumber: number;- columnNumber: number;- search: string;-}) => {- const lines = contents.split(/\r?\n/);- const startLineIndex = Math.max(0, lineNumber - 1);-- for (let lineIndex = startLineIndex; lineIndex < lines.length; lineIndex++) {- const startColumnIndex =- lineIndex === startLineIndex ? Math.max(0, columnNumber - 1) : 0;- const foundColumnIndex = lines[lineIndex].indexOf(search, startColumnIndex);-- if (foundColumnIndex !== -1) {- return {- lineNumber: lineIndex + 1,- columnNumber: foundColumnIndex + 1,- };- }- }-- return {lineNumber, columnNumber};-};+export {findSearchPosition} from '@remotion/studio-codemods';export const findInFileHandler: ApiHandler<FindInFileRequest,diff --git a/packages/studio-shared/src/browser-studio-operations.ts b/packages/studio-shared/src/browser-studio-operations.tsindex 0fdd8d4a28..c25f285de8 100644--- a/packages/studio-shared/src/browser-studio-operations.ts+++ b/packages/studio-shared/src/browser-studio-operations.ts@@ -1,15 +1,34 @@import type {CompositionComponentInfoRequest,CompositionComponentInfoResponse,+ DeleteStaticFileRequest,+ DeleteStaticFileResponse,+ FindInFileRequest,+ FindInFileResponse,InsertJsxElementRequest,InsertJsxElementResponse,+ RedoResponse,+ RenameStaticFileRequest,+ RenameStaticFileResponse,+ UndoResponse,} from './api-requests';+import type {EventSourceEvent} from './event-source-event';++export type WriteStaticFileRequest = {+ contents: string | ArrayBuffer;+ filePath: string;+};export type BrowserStudioOperations = {- downloadProject?: () => Promise<{+ deleteStaticFile: (+ request: DeleteStaticFileRequest,+ ) => Promise<DeleteStaticFileResponse>;+ downloadProject: () => Promise<{data: Uint8Array;fileName: string;}>;+ findInFile: (request: FindInFileRequest) => Promise<FindInFileResponse>;+ getFileSource: (fileName: string) => Promise<string | null>;getCompositionFile: (compositionId: string) => string | null;getCompositionComponentInfo: (request: CompositionComponentInfoRequest,@@ -17,6 +36,13 @@ export type BrowserStudioOperations = {insertSolid: (request: InsertJsxElementRequest,) => Promise<InsertJsxElementResponse>;+ redo: () => Promise<RedoResponse>;+ renameStaticFile: (+ request: RenameStaticFileRequest,+ ) => Promise<RenameStaticFileResponse>;+ subscribeToEvent: (listener: (event: EventSourceEvent) => void) => () => void;+ undo: () => Promise<UndoResponse>;+ writeStaticFile: (request: WriteStaticFileRequest) => Promise<void>;};declare global {diff --git a/packages/studio/src/api/delete-static-file.ts b/packages/studio/src/api/delete-static-file.tsindex bb27361401..7c15934511 100644--- a/packages/studio/src/api/delete-static-file.ts+++ b/packages/studio/src/api/delete-static-file.ts@@ -1,6 +1,7 @@import type {DeleteStaticFileResponse} from '@remotion/studio-shared';import {getRemotionEnvironment} from 'remotion';import {callApi} from '../components/call-api';+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';export const deleteStaticFile = async (relativePath: string,@@ -9,16 +10,21 @@ export const deleteStaticFile = async (throw new Error('deleteStaticFile() is only available in the Studio');}- if (window.remotion_isReadOnlyStudio) {- throw new Error('deleteStaticFile() is not available in Read-Only Studio');- }-if (relativePath.startsWith(window.remotion_staticBase)) {relativePath = relativePath.substring(window.remotion_staticBase.length + 1,);}+ const browserStudioOperations = getBrowserStudioOperations();+ if (browserStudioOperations) {+ return browserStudioOperations.deleteStaticFile({relativePath});+ }++ if (window.remotion_isReadOnlyStudio) {+ throw new Error('deleteStaticFile() is not available in Read-Only Studio');+ }+const res = await callApi('/api/delete-static-file', {relativePath});return res;};diff --git a/packages/studio/src/api/rename-static-file.ts b/packages/studio/src/api/rename-static-file.tsindex 665268e433..356adcc590 100644--- a/packages/studio/src/api/rename-static-file.ts+++ b/packages/studio/src/api/rename-static-file.ts@@ -1,6 +1,7 @@import type {RenameStaticFileResponse} from '@remotion/studio-shared';import {getRemotionEnvironment} from 'remotion';import {callApi} from '../components/call-api';+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';export const renameStaticFile = ({oldRelativePath,@@ -13,6 +14,14 @@ export const renameStaticFile = ({throw new Error('renameStaticFile() is only available in the Studio');}+ const browserStudioOperations = getBrowserStudioOperations();+ if (browserStudioOperations) {+ return browserStudioOperations.renameStaticFile({+ oldRelativePath,+ newRelativePath,+ });+ }+if (window.remotion_isReadOnlyStudio) {throw new Error('renameStaticFile() is not available in Read-Only Studio');}diff --git a/packages/studio/src/api/watch-public-folder.ts b/packages/studio/src/api/watch-public-folder.tsindex 09e08d2f50..c8124e40f2 100644--- a/packages/studio/src/api/watch-public-folder.ts+++ b/packages/studio/src/api/watch-public-folder.ts@@ -1,4 +1,5 @@import {getRemotionEnvironment} from 'remotion';+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';import {getStaticFiles, type StaticFile} from './get-static-files';type WatcherCallback = (newFiles: StaticFile[]) => void;@@ -20,7 +21,7 @@ export const watchPublicFolder = (return {cancel: () => undefined};}- if (window.remotion_isReadOnlyStudio) {+ if (window.remotion_isReadOnlyStudio && !getBrowserStudioOperations()) {throw new Error('watchPublicFolder() is not available in read-only Studio');}diff --git a/packages/studio/src/api/watch-static-file.ts b/packages/studio/src/api/watch-static-file.tsindex ba437cfd99..f90258b345 100644--- a/packages/studio/src/api/watch-static-file.ts+++ b/packages/studio/src/api/watch-static-file.ts@@ -1,4 +1,5 @@import {getRemotionEnvironment} from 'remotion';+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';import type {StaticFile} from './get-static-files';import {watchPublicFolder} from './watch-public-folder';@@ -24,7 +25,7 @@ export const watchStaticFile = (return {cancel: () => undefined};}- if (window.remotion_isReadOnlyStudio) {+ if (window.remotion_isReadOnlyStudio && !getBrowserStudioOperations()) {// eslint-disable-next-line no-consoleconsole.warn('watchStaticFile() is only available in an interactive Studio.',diff --git a/packages/studio/src/api/write-static-file.ts b/packages/studio/src/api/write-static-file.tsindex 78dfb15b24..5b0f6bc231 100644--- a/packages/studio/src/api/write-static-file.ts+++ b/packages/studio/src/api/write-static-file.ts@@ -1,3 +1,5 @@+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';+export const writeStaticFile = async ({contents,filePath,@@ -5,6 +7,15 @@ export const writeStaticFile = async ({contents: string | ArrayBuffer;filePath: string;}): Promise<void> => {+ if (filePath.includes('\\')) {+ return Promise.reject(new Error('File path cannot contain backslashes'));+ }++ const browserStudioOperations = getBrowserStudioOperations();+ if (browserStudioOperations) {+ return browserStudioOperations.writeStaticFile({contents, filePath});+ }+if (window.remotion_isReadOnlyStudio) {throw new Error('writeStaticFile() is not available in read-only Studio');}@@ -14,10 +25,6 @@ export const writeStaticFile = async ({window.location.origin,);- if (filePath.includes('\\')) {- return Promise.reject(new Error('File path cannot contain backslashes'));- }-url.search = new URLSearchParams({filePath,}).toString();diff --git a/packages/studio/src/components/AssetSelector.tsx b/packages/studio/src/components/AssetSelector.tsxindex 70f6e5e602..410ef758e8 100644--- a/packages/studio/src/components/AssetSelector.tsx+++ b/packages/studio/src/components/AssetSelector.tsx@@ -1,5 +1,6 @@import React, {useCallback, useContext, useMemo, useState} from 'react';import {writeStaticFile} from '../api/write-static-file';+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';import {StudioServerConnectionCtx} from '../helpers/client-id';import {BACKGROUND, WHITE_ALPHA_06, LIGHT_TEXT} from '../helpers/colors';import {buildAssetFolderStructure} from '../helpers/create-folder-tree';@@ -53,7 +54,9 @@ export const AssetSelector: React.FC<{const [dropLocation, setDropLocation] = useState<string | null>(null);const connectionStatus = useContext(StudioServerConnectionCtx).previewServerState.type;- const shouldAllowUpload = connectionStatus === 'connected' && !readOnlyStudio;+ const shouldAllowUpload =+ getBrowserStudioOperations() !== null ||+ (connectionStatus === 'connected' && !readOnlyStudio);const list: React.CSSProperties = useMemo(() => {return {diff --git a/packages/studio/src/components/AssetSelectorItem.tsx b/packages/studio/src/components/AssetSelectorItem.tsxindex f00f1df9b1..cc7babd70b 100644--- a/packages/studio/src/components/AssetSelectorItem.tsx+++ b/packages/studio/src/components/AssetSelectorItem.tsx@@ -10,6 +10,7 @@ import React, {import {Internals, staticFile, type StaticFile} from 'remotion';import {NoReactInternals} from 'remotion/no-react';import {deleteStaticFile} from '../api/delete-static-file';+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';import {StudioServerConnectionCtx} from '../helpers/client-id';import {BACKGROUND,@@ -96,16 +97,20 @@ const revealIconStyle: React.CSSProperties = {};export const getAssetActionAvailability = ({+ browserStudioCanMutateAssets,readOnlyStudio,connectionStatus,publicFolderExists,}: {+ browserStudioCanMutateAssets: boolean | null;readOnlyStudio: boolean;connectionStatus: 'init' | 'connected' | 'disconnected';publicFolderExists: string | null;}) => {return {- mutationsDisabled: readOnlyStudio || connectionStatus !== 'connected',+ mutationsDisabled:+ browserStudioCanMutateAssets !== true &&+ (readOnlyStudio || connectionStatus !== 'connected'),fileExplorerDisabled:publicFolderExists === null ||readOnlyStudio ||@@ -575,6 +580,8 @@ const AssetSelectorItem: React.FC<{}, [relativePath]);const {mutationsDisabled, fileExplorerDisabled} = getAssetActionAvailability({+ browserStudioCanMutateAssets:+ getBrowserStudioOperations() === null ? null : true,readOnlyStudio,connectionStatus,publicFolderExists: window.remotion_publicFolderExists,diff --git a/packages/studio/src/components/CurrentAsset.tsx b/packages/studio/src/components/CurrentAsset.tsxindex daf4033f30..597ba82629 100644--- a/packages/studio/src/components/CurrentAsset.tsx+++ b/packages/studio/src/components/CurrentAsset.tsx@@ -1,6 +1,7 @@import {formatBytes} from '@remotion/studio-shared';import React, {useCallback, useContext, useMemo} from 'react';import {Internals, staticFile} from 'remotion';+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';import {StudioServerConnectionCtx} from '../helpers/client-id';import {formatMediaDuration} from '../helpers/format-media-duration';import {getPreviewFileType} from '../helpers/get-preview-file-type';@@ -119,8 +120,8 @@ export const AssetInfo: React.FC<{const imageMetadata = useImageMetadata(imageSrc);const canRename =onAssetClick === undefined &&- connectionStatus === 'connected' &&- !readOnlyStudio;+ (getBrowserStudioOperations() !== null ||+ (connectionStatus === 'connected' && !readOnlyStudio));const onRename = useCallback((newName: string) => {renameFile(newName).catch(() => undefined);diff --git a/packages/studio/src/components/InspectorPanel/use-composition-actions.ts b/packages/studio/src/components/InspectorPanel/use-composition-actions.tsindex 7ee29e623d..5df7b54025 100644--- a/packages/studio/src/components/InspectorPanel/use-composition-actions.ts+++ b/packages/studio/src/components/InspectorPanel/use-composition-actions.ts@@ -41,9 +41,8 @@ export const useCompositionActions = () => {);const compositionFile =resolvedCompositionLocation?.source ??- (currentCompositionId- ? (browserStudioOperations?.getCompositionFile(currentCompositionId) ??- null)+ (currentCompositionId && browserStudioOperations+ ? browserStudioOperations.getCompositionFile(currentCompositionId): null);const compositionComponentInfo = useCachedCompositionComponentInfo({compositionFile,diff --git a/packages/studio/src/components/MenuToolbar.tsx b/packages/studio/src/components/MenuToolbar.tsxindex 5c959c0a8f..59e77b2709 100644--- a/packages/studio/src/components/MenuToolbar.tsx+++ b/packages/studio/src/components/MenuToolbar.tsx@@ -1,5 +1,7 @@import type {SetStateAction} from 'react';-import React, {useCallback, useMemo, useState} from 'react';+import React, {useCallback, useContext, useMemo, useState} from 'react';+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';+import {StudioServerConnectionCtx} from '../helpers/client-id';import {BACKGROUND, BORDER_BLACK, WHITE} from '../helpers/colors';import {useMobileLayout} from '../helpers/mobile-layout';import {useMenuStructure} from '../helpers/use-menu-structure';@@ -34,6 +36,12 @@ export const MenuToolbar: React.FC<{readonly readOnlyStudio: boolean;}> = ({readOnlyStudio}) => {const [selected, setSelected] = useState<string | null>(null);+ const {previewServerState} = useContext(StudioServerConnectionCtx);+ const browserStudioOperations = getBrowserStudioOperations();+ const canUndoAndRedo =+ !readOnlyStudio ||+ (previewServerState.type === 'connected' &&+ browserStudioOperations !== null);const mobileLayout = useMobileLayout();@@ -154,7 +162,7 @@ export const MenuToolbar: React.FC<{<MenuBuildIndicator /><div style={flex} /><div style={fixedWidthRight}>- {readOnlyStudio ? null : <UndoRedoButtons />}+ {canUndoAndRedo ? <UndoRedoButtons /> : null}<SidebarCollapserControl side="right" /></div></Row>diff --git a/packages/studio/src/components/Timeline/Timeline.tsx b/packages/studio/src/components/Timeline/Timeline.tsxindex 2896ddbe80..c7402900c7 100644--- a/packages/studio/src/components/Timeline/Timeline.tsx+++ b/packages/studio/src/components/Timeline/Timeline.tsx@@ -93,9 +93,8 @@ const TimelineContextMenuArea: React.FC<{);const compositionFile =resolvedCompositionLocation?.source ??- (currentCompositionId- ? (browserStudioOperations?.getCompositionFile(currentCompositionId) ??- null)+ (currentCompositionId && browserStudioOperations+ ? browserStudioOperations.getCompositionFile(currentCompositionId): null);const compositionComponentInfo = useCachedCompositionComponentInfo({compositionFile,diff --git a/packages/studio/src/components/UndoRedoButtons.tsx b/packages/studio/src/components/UndoRedoButtons.tsxindex 7a8621fcb5..6f603bc395 100644--- a/packages/studio/src/components/UndoRedoButtons.tsx+++ b/packages/studio/src/components/UndoRedoButtons.tsx@@ -7,6 +7,7 @@ import React, {useState,} from 'react';import {cmdOrCtrlCharacter} from '../error-overlay/remotion-overlay/ShortcutHint';+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';import {StudioServerConnectionCtx} from '../helpers/client-id';import {isMac} from '../helpers/is-mac';import {@@ -54,7 +55,11 @@ export const UndoRedoButtons: React.FC = () => {}undoInFlight.current = true;- callApi('/api/undo', {})+ const browserStudioOperations = getBrowserStudioOperations();+ const promise = browserStudioOperations+ ? browserStudioOperations.undo()+ : callApi('/api/undo', {});+ promise.catch(() => {// Ignore errors})@@ -69,7 +74,11 @@ export const UndoRedoButtons: React.FC = () => {}redoInFlight.current = true;- callApi('/api/redo', {})+ const browserStudioOperations = getBrowserStudioOperations();+ const promise = browserStudioOperations+ ? browserStudioOperations.redo()+ : callApi('/api/redo', {});+ promise.catch(() => {// Ignore errors})diff --git a/packages/studio/src/components/use-static-files.ts b/packages/studio/src/components/use-static-files.tsindex b592191bf1..48274ed89c 100644--- a/packages/studio/src/components/use-static-files.ts+++ b/packages/studio/src/components/use-static-files.ts@@ -2,6 +2,8 @@ import React, {createContext, useContext, useEffect, useState} from 'react';import {useRemotionEnvironment} from 'remotion';import {type StaticFile, getStaticFiles} from '../api/get-static-files';import {watchPublicFolder} from '../api/watch-public-folder';+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';+import {StudioServerConnectionCtx} from '../helpers/client-id';const StaticFilesContext = createContext<StaticFile[]>([]);@@ -10,13 +12,17 @@ export const StaticFilesProvider: React.FC<{}> = ({children}) => {const [files, setFiles] = useState(() => getStaticFiles());const env = useRemotionEnvironment();+ const {previewServerState} = useContext(StudioServerConnectionCtx);+ const browserStudioCanWatch =+ previewServerState.type === 'connected' &&+ getBrowserStudioOperations() !== null;useEffect(() => {if (!env.isStudio) {return;}- if (env.isReadOnlyStudio) {+ if (env.isReadOnlyStudio && !browserStudioCanWatch) {return;}@@ -25,7 +31,7 @@ export const StaticFilesProvider: React.FC<{});return cancel;- }, [env.isStudio, env.isReadOnlyStudio]);+ }, [browserStudioCanWatch, env.isStudio, env.isReadOnlyStudio]);return React.createElement(StaticFilesContext.Provider,diff --git a/packages/studio/src/error-overlay/react-overlay/effects/resolve-file-source.ts b/packages/studio/src/error-overlay/react-overlay/effects/resolve-file-source.tsindex f669ae2c22..91b003117e 100644--- a/packages/studio/src/error-overlay/react-overlay/effects/resolve-file-source.ts+++ b/packages/studio/src/error-overlay/react-overlay/effects/resolve-file-source.ts@@ -2,15 +2,28 @@ import type {ErrorLocation,SymbolicatedStackFrame,} from '@remotion/studio-shared';+import {getBrowserStudioOperations} from '../../../helpers/browser-studio-operations';export const resolveFileSource = async (location: ErrorLocation,contextLines: number,): Promise<SymbolicatedStackFrame> => {- const res = await fetch(- `/api/file-source?f=${encodeURIComponent(location.fileName)}`,- );- const text = await res.text();+ const browserStudioOperations = getBrowserStudioOperations();+ let text: string;+ if (browserStudioOperations) {+ const browserSource = await browserStudioOperations.getFileSource(+ location.fileName,+ );+ if (browserSource === null) {+ throw new Error(`Could not find ${location.fileName}`);+ }++ text = browserSource;+ } else {+ text = await (+ await fetch(`/api/file-source?f=${encodeURIComponent(location.fileName)}`)+ ).text();+ }const lines = text.split('\n')diff --git a/packages/studio/src/helpers/client-id.tsx b/packages/studio/src/helpers/client-id.tsxindex f2f03791cb..6430bebcfc 100644--- a/packages/studio/src/helpers/client-id.tsx+++ b/packages/studio/src/helpers/client-id.tsx@@ -5,6 +5,7 @@ import {Internals} from 'remotion';import {showNotification} from '../components/Notifications/NotificationCenter';import playBeepSound from '../components/PlayBeepSound';import {renderJobsRef} from '../components/RenderQueue/context';+import {getBrowserStudioOperations} from './browser-studio-operations';import {subscribeToPreviewServerConnectionState,subscribeToPreviewServerEvents,@@ -20,6 +21,11 @@ type Context = {) => () => void;};+// Browser Studio may be hosted by a different studio-shared version, so this+// handshake intentionally has no shared runtime import.+const BROWSER_STUDIO_OPERATIONS_READY_EVENT =+ 'remotion-browser-studio-operations-ready';+export const StudioServerConnectionCtx = React.createContext<Context>({previewServerState: {type: 'init',@@ -39,6 +45,9 @@ export const PreviewServerConnection: React.FC<{readonly readOnlyStudio: boolean;}> = ({children, readOnlyStudio}) => {const listeners = useRef<Listeners>([]);+ const latestUndoRedoEvent = useRef<+ Extract<EventSourceEvent, {type: 'undo-redo-stack-changed'}> | undefined+ >(undefined);const subscribeToEvent = useCallback((@@ -46,6 +55,9 @@ export const PreviewServerConnection: React.FC<{listener: (event: EventSourceEvent) => void,) => {listeners.current.push({type, listener});+ if (type === 'undo-redo-stack-changed' && latestUndoRedoEvent.current) {+ listener(latestUndoRedoEvent.current);+ }return () => {listeners.current = listeners.current.filter(@@ -61,10 +73,6 @@ export const PreviewServerConnection: React.FC<{});useEffect(() => {- if (readOnlyStudio) {- return;- }-const handleEvent = (newEvent: EventSourceEvent) => {if (newEvent.type === 'new-input-props' ||@@ -75,17 +83,22 @@ export const PreviewServerConnection: React.FC<{}if (newEvent.type === 'init') {+ latestUndoRedoEvent.current = {+ type: 'undo-redo-stack-changed',+ undoFile: newEvent.undoFile,+ redoFile: newEvent.redoFile,+ };listeners.current.forEach((l) => {if (l.type === 'undo-redo-stack-changed') {- l.listener({- type: 'undo-redo-stack-changed',- undoFile: newEvent.undoFile,- redoFile: newEvent.redoFile,- });+ l.listener(latestUndoRedoEvent.current!);}});}+ if (newEvent.type === 'undo-redo-stack-changed') {+ latestUndoRedoEvent.current = newEvent;+ }+if (newEvent.type === 'render-queue-updated') {renderJobsRef.current?.updateRenderJobs(newEvent.queue);for (const job of newEvent.queue) {@@ -125,6 +138,46 @@ export const PreviewServerConnection: React.FC<{});};+ let unsubscribeFromBrowserStudio: (() => void) | null = null;+ const connectToBrowserStudio = () => {+ if (unsubscribeFromBrowserStudio) {+ return true;+ }++ const browserStudioOperations = getBrowserStudioOperations();+ if (!browserStudioOperations) {+ return false;+ }++ setState({type: 'connected', clientId: 'browser-studio'});+ unsubscribeFromBrowserStudio =+ browserStudioOperations.subscribeToEvent(handleEvent);+ return true;+ };++ if (connectToBrowserStudio()) {+ return () => unsubscribeFromBrowserStudio?.();+ }++ if (readOnlyStudio) {+ window.addEventListener(+ BROWSER_STUDIO_OPERATIONS_READY_EVENT,+ connectToBrowserStudio,+ );+ const animationFrame = window.requestAnimationFrame(() => {+ connectToBrowserStudio();+ });++ return () => {+ window.cancelAnimationFrame(animationFrame);+ window.removeEventListener(+ BROWSER_STUDIO_OPERATIONS_READY_EVENT,+ connectToBrowserStudio,+ );+ unsubscribeFromBrowserStudio?.();+ };+ }+const unsubscribeFromEvents = subscribeToPreviewServerEvents(handleEvent);const unsubscribeFromConnectionState =subscribeToPreviewServerConnectionState(setState);diff --git a/packages/studio/src/helpers/open-in-editor.ts b/packages/studio/src/helpers/open-in-editor.tsindex 5417821f93..6676986571 100644--- a/packages/studio/src/helpers/open-in-editor.ts+++ b/packages/studio/src/helpers/open-in-editor.ts@@ -49,12 +49,16 @@ export const openOriginalPositionInEditorAtProperty = async ({originalPosition: CodePosition;property: string;}) => {- const position = await callApi('/api/find-in-file', {+ const request = {fileName: originalPosition.source,lineNumber: originalPosition.line,columnNumber: originalPosition.column,search: property,- });+ };+ const browserStudioOperations = getBrowserStudioOperations();+ const position = browserStudioOperations+ ? await browserStudioOperations.findInFile(request)+ : await callApi('/api/find-in-file', request);await openOriginalPositionInEditor({source: originalPosition.source,diff --git a/packages/studio/src/test/asset-context-menu.test.ts b/packages/studio/src/test/asset-context-menu.test.tsindex a3b58ce636..1764343c52 100644--- a/packages/studio/src/test/asset-context-menu.test.ts+++ b/packages/studio/src/test/asset-context-menu.test.ts@@ -21,6 +21,7 @@ const getItem = (test('keeps copy and open-in-new-window asset actions enabled in read-only Studio', () => {const availability = getAssetActionAvailability({+ browserStudioCanMutateAssets: null,readOnlyStudio: true,connectionStatus: 'init',publicFolderExists: '/project/public',@@ -46,6 +47,7 @@ test('keeps copy and open-in-new-window asset actions enabled in read-only Studitest('only offers file-manager actions when a local public folder is available', () => {const availability = getAssetActionAvailability({+ browserStudioCanMutateAssets: null,readOnlyStudio: true,connectionStatus: 'init',publicFolderExists: null,@@ -56,6 +58,7 @@ test('only offers file-manager actions when a local public folder is available',test('disables asset mutations while an editable Studio is disconnected', () => {const availability = getAssetActionAvailability({+ browserStudioCanMutateAssets: null,readOnlyStudio: false,connectionStatus: 'disconnected',publicFolderExists: '/project/public',@@ -67,6 +70,20 @@ test('disables asset mutations while an editable Studio is disconnected', () =>});});+test('enables supported Browser Studio asset mutations', () => {+ const availability = getAssetActionAvailability({+ browserStudioCanMutateAssets: true,+ readOnlyStudio: true,+ connectionStatus: 'connected',+ publicFolderExists: '/public',+ });++ expect(availability).toEqual({+ fileExplorerDisabled: true,+ mutationsDisabled: false,+ });+});+test('disables drag insertion in read-only Studio', () => {expect(getCanDragAsset({diff --git a/packages/studio/src/test/browser-studio-static-files.test.ts b/packages/studio/src/test/browser-studio-static-files.test.tsnew file mode 100644index 0000000000..d18ca324a7--- /dev/null+++ b/packages/studio/src/test/browser-studio-static-files.test.ts@@ -0,0 +1,65 @@+import {afterEach, expect, test} from 'bun:test';+import {deleteStaticFile} from '../api/delete-static-file';+import {renameStaticFile} from '../api/rename-static-file';+import {writeStaticFile} from '../api/write-static-file';+import {makeBrowserStudioOperations} from './make-browser-studio-operations';++const originalWindowDescriptor = Object.getOwnPropertyDescriptor(+ globalThis,+ 'window',+);++afterEach(() => {+ if (originalWindowDescriptor) {+ Object.defineProperty(globalThis, 'window', originalWindowDescriptor);+ return;+ }++ Reflect.deleteProperty(globalThis, 'window');+});++test('routes static-file mutations through Browser Studio operations', async () => {+ const calls: string[] = [];+ const operations = makeBrowserStudioOperations({+ deleteStaticFile: ({relativePath}) => {+ calls.push(`delete:${relativePath}`);+ return Promise.resolve({success: true, existed: true});+ },+ renameStaticFile: ({oldRelativePath, newRelativePath}) => {+ calls.push(`rename:${oldRelativePath}:${newRelativePath}`);+ return Promise.resolve({success: true});+ },+ writeStaticFile: ({contents, filePath}) => {+ calls.push(`write:${filePath}:${String(contents)}`);+ return Promise.resolve();+ },+ });++ Object.defineProperty(globalThis, 'window', {+ configurable: true,+ value: {+ remotion_browserStudio: operations,+ remotion_isPlayer: false,+ remotion_isReadOnlyStudio: true,+ remotion_isStudio: true,+ remotion_staticBase: '/static-abcdef',+ },+ });++ await writeStaticFile({contents: 'contents', filePath: 'nested/file.txt'});+ expect(await deleteStaticFile('/static-abcdef/nested/file.txt')).toEqual({+ success: true,+ existed: true,+ });+ expect(+ await renameStaticFile({+ oldRelativePath: 'nested/file.txt',+ newRelativePath: 'renamed.txt',+ }),+ ).toEqual({success: true});+ expect(calls).toEqual([+ 'write:nested/file.txt:contents',+ 'delete:nested/file.txt',+ 'rename:nested/file.txt:renamed.txt',+ ]);+});diff --git a/packages/studio/src/test/make-browser-studio-operations.ts b/packages/studio/src/test/make-browser-studio-operations.tsnew file mode 100644index 0000000000..20f03ec7c6--- /dev/null+++ b/packages/studio/src/test/make-browser-studio-operations.ts@@ -0,0 +1,26 @@+import type {BrowserStudioOperations} from '@remotion/studio-shared';++const unusedOperation = (name: keyof BrowserStudioOperations): never => {+ throw new Error(`Unexpected Browser Studio operation: ${name}`);+};++export const makeBrowserStudioOperations = (+ overrides: Partial<BrowserStudioOperations>,+): BrowserStudioOperations => {+ return {+ deleteStaticFile: () => unusedOperation('deleteStaticFile'),+ downloadProject: () => unusedOperation('downloadProject'),+ findInFile: () => unusedOperation('findInFile'),+ getCompositionComponentInfo: () =>+ unusedOperation('getCompositionComponentInfo'),+ getCompositionFile: () => unusedOperation('getCompositionFile'),+ getFileSource: () => unusedOperation('getFileSource'),+ insertSolid: () => unusedOperation('insertSolid'),+ redo: () => unusedOperation('redo'),+ renameStaticFile: () => unusedOperation('renameStaticFile'),+ subscribeToEvent: () => unusedOperation('subscribeToEvent'),+ undo: () => unusedOperation('undo'),+ writeStaticFile: () => unusedOperation('writeStaticFile'),+ ...overrides,+ };+};diff --git a/packages/studio/src/test/resolve-file-source.test.ts b/packages/studio/src/test/resolve-file-source.test.tsindex da9bef052d..adeff9fbe4 100644--- a/packages/studio/src/test/resolve-file-source.test.ts+++ b/packages/studio/src/test/resolve-file-source.test.ts@@ -1,5 +1,6 @@import {expect, test} from 'bun:test';import {resolveFileSource} from '../error-overlay/react-overlay/effects/resolve-file-source';+import {makeBrowserStudioOperations} from './make-browser-studio-operations';test('resolves file source using a GET request', async () => {const previousFetch = globalThis.fetch;@@ -41,3 +42,89 @@ test('resolves file source using a GET request', async () => {globalThis.fetch = previousFetch;}});++test('resolves file source using a Browser Studio operation', async () => {+ const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');+ const previousFetch = globalThis.fetch;+ let fetchCalled = false;+ const operations = makeBrowserStudioOperations({+ getFileSource: () => Promise.resolve('const fromBrowserStudio = true;'),+ });++ Object.defineProperty(globalThis, 'window', {+ configurable: true,+ value: {remotion_browserStudio: operations},+ });+ globalThis.fetch = (() => {+ fetchCalled = true;+ throw new Error('fetch should not be called');+ }) as unknown as typeof fetch;++ try {+ const resolved = await resolveFileSource(+ {+ columnNumber: 1,+ fileName: 'webpack://remotion/./src/Composition.tsx',+ lineNumber: 1,+ message: 'Example error',+ },+ 0,+ );++ expect(fetchCalled).toBe(false);+ expect(resolved.originalScriptCode).toEqual([+ {+ content: 'const fromBrowserStudio = true;',+ highlight: true,+ lineNumber: 1,+ },+ ]);+ } finally {+ globalThis.fetch = previousFetch;+ if (previousWindow) {+ Object.defineProperty(globalThis, 'window', previousWindow);+ } else {+ Reflect.deleteProperty(globalThis, 'window');+ }+ }+});++test('does not fall back to the server when Browser Studio cannot find a file', async () => {+ const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');+ const previousFetch = globalThis.fetch;+ let fetchCalled = false;+ const operations = makeBrowserStudioOperations({+ getFileSource: () => Promise.resolve(null),+ });++ Object.defineProperty(globalThis, 'window', {+ configurable: true,+ value: {remotion_browserStudio: operations},+ });+ globalThis.fetch = (() => {+ fetchCalled = true;+ throw new Error('fetch should not be called');+ }) as unknown as typeof fetch;++ try {+ await expect(+ resolveFileSource(+ {+ columnNumber: 1,+ fileName: 'webpack://remotion/./src/missing.tsx',+ lineNumber: 1,+ message: 'Example error',+ },+ 0,+ ),+ ).rejects.toThrow('Could not find webpack://remotion/./src/missing.tsx');+ expect(fetchCalled).toBe(false);+ } finally {+ globalThis.fetch = previousFetch;+ if (previousWindow) {+ Object.defineProperty(globalThis, 'window', previousWindow);+ } else {+ Reflect.deleteProperty(globalThis, 'window');+ }+ }+});