Skip to content

🎥 Make videos programmatically with React

`@remotion/studio-server`: Abstract import path codemods (#8013)

Jonny Burger9efc99dc2423
diff --git a/packages/studio-server/src/codemods/add-effect.ts b/packages/studio-server/src/codemods/add-effect.ts
index ee215b77a6..4a450fa49a 100644
--- a/packages/studio-server/src/codemods/add-effect.ts
+++ b/packages/studio-server/src/codemods/add-effect.ts
@@ -4,8 +4,6 @@ import type {
Expression,
File,
FunctionDeclaration,
- ImportDeclaration,
- ImportSpecifier,
JSXAttribute,
JSXOpeningElement,
ObjectExpression,
@@ -15,6 +13,7 @@ import type {
import {stringifyDefaultProps} from '@remotion/studio-shared';
import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
+import {ensureNamedImport} from '../helpers/imports';
import {findJsxElementAtNodePath} from '../preview-server/routes/can-update-sequence-props';
import {formatFileContent} from './format-file-content';
import {parseAst, serializeAst} from './parse-ast';
@@ -59,14 +58,6 @@ const parseValueExpression = (value: unknown): Expression => {
return stmt.expression.right as Expression;
};
-const getImportedName = (specifier: ImportSpecifier) => {
- if (specifier.imported.type === 'Identifier') {
- return specifier.imported.name;
- }
-
- return specifier.imported.value;
-};
-
const declarationBindsName = (
declaration: ClassDeclaration | FunctionDeclaration | VariableDeclaration,
name: string,
@@ -115,21 +106,6 @@ const hasTopLevelBinding = ({ast, name}: {ast: File; name: string}) => {
});
};
-const insertImportDeclaration = (
- ast: File,
- importDeclaration: ImportDeclaration,
-) => {
- const {body} = ast.program;
- let lastImportIndex = -1;
- for (let i = 0; i < body.length; i++) {
- if (body[i].type === 'ImportDeclaration') {
- lastImportIndex = i;
- }
- }
-
- body.splice(lastImportIndex + 1, 0, importDeclaration);
-};
-
const getAvailableLocalName = ({
ast,
effectName,
@@ -165,57 +141,13 @@ export const ensureEffectImport = ({
effectName: string;
effectImportPath: string;
}) => {
- let importDeclaration: ImportDeclaration | null = null;
-
- for (const node of ast.program.body) {
- if (
- node.type !== 'ImportDeclaration' ||
- node.source.value !== effectImportPath
- ) {
- continue;
- }
-
- importDeclaration = node;
- const matchingSpecifier = node.specifiers?.find((importSpecifier) => {
- return (
- importSpecifier.type === 'ImportSpecifier' &&
- getImportedName(importSpecifier) === effectName
- );
- });
-
- if (matchingSpecifier?.local?.name) {
- return matchingSpecifier.local.name;
- }
- }
-
const localName = getAvailableLocalName({ast, effectName});
- const imported = b.identifier(effectName);
- const local = localName === effectName ? null : b.identifier(localName);
- const specifier = b.importSpecifier(
- imported,
- local,
- ) as unknown as ImportSpecifier;
-
- if (
- importDeclaration &&
- !importDeclaration.specifiers?.some(
- (importSpecifier) => importSpecifier.type === 'ImportNamespaceSpecifier',
- )
- ) {
- importDeclaration.specifiers = [
- ...(importDeclaration.specifiers ?? []),
- specifier,
- ];
- return localName;
- }
-
- const newImport = b.importDeclaration(
- [],
- b.stringLiteral(effectImportPath),
- ) as unknown as ImportDeclaration;
- newImport.specifiers = [specifier];
- insertImportDeclaration(ast, newImport);
- return localName;
+ return ensureNamedImport({
+ ast,
+ importedName: effectName,
+ sourcePath: effectImportPath,
+ localName,
+ });
};
const getEffectsArray = (attr: JSXAttribute): ArrayExpression => {
diff --git a/packages/studio-server/src/codemods/parse-ast.ts b/packages/studio-server/src/codemods/parse-ast.ts
index 1e50c5d121..09b62651db 100644
--- a/packages/studio-server/src/codemods/parse-ast.ts
+++ b/packages/studio-server/src/codemods/parse-ast.ts
@@ -1,6 +1,7 @@
import type {File} from '@babel/types';
import * as recast from 'recast';
import * as tsParser from 'recast/parsers/babel-ts';
+import {normalizeImportSpacing} from '../helpers/imports';
export const parseAst = (input: string) => {
return recast.parse(input, {
@@ -9,7 +10,9 @@ export const parseAst = (input: string) => {
};
export const serializeAst = (ast: File) => {
- return recast.print(ast, {
- parser: tsParser,
- }).code;
+ return normalizeImportSpacing(
+ recast.print(ast, {
+ parser: tsParser,
+ }).code,
+ );
};
diff --git a/packages/studio-server/src/codemods/update-keyframes/ensure-imports-and-frame-hook.ts b/packages/studio-server/src/codemods/update-keyframes/ensure-imports-and-frame-hook.ts
index f9843b13ee..f674897cb5 100644
--- a/packages/studio-server/src/codemods/update-keyframes/ensure-imports-and-frame-hook.ts
+++ b/packages/studio-server/src/codemods/update-keyframes/ensure-imports-and-frame-hook.ts
@@ -3,10 +3,9 @@ import type {
File,
FunctionDeclaration,
FunctionExpression,
- ImportDeclaration,
- ImportSpecifier,
} from '@babel/types';
import * as recast from 'recast';
+import {ensureNamedImports} from '../../helpers/imports';
const b = recast.types.builders;
const n = recast.types.namedTypes;
@@ -39,77 +38,11 @@ export const findEnclosingFunctionPath = (
return null;
};
-const findRemotionImport = (ast: File): ImportDeclaration | null => {
- for (const stmt of ast.program.body) {
- if (
- stmt.type === 'ImportDeclaration' &&
- stmt.source.type === 'StringLiteral' &&
- stmt.source.value === 'remotion'
- ) {
- return stmt;
- }
- }
-
- return null;
-};
-
-const insertImportDeclaration = (
- ast: File,
- importDecl: ImportDeclaration,
-): void => {
- const {body} = ast.program;
- let lastImportIndex = -1;
- for (let i = 0; i < body.length; i++) {
- if (body[i].type === 'ImportDeclaration') {
- lastImportIndex = i;
- }
- }
-
- body.splice(lastImportIndex + 1, 0, importDecl);
-};
-
export const ensureRemotionImports = (
ast: File,
names: ReadonlySet<string>,
-): void => {
- if (names.size === 0) {
- return;
- }
-
- let remotionImport = findRemotionImport(ast);
- if (!remotionImport) {
- remotionImport = b.importDeclaration(
- [],
- b.stringLiteral('remotion'),
- ) as unknown as ImportDeclaration;
- insertImportDeclaration(ast, remotionImport);
- }
-
- const existingNames = new Set<string>();
- for (const specifier of remotionImport.specifiers ?? []) {
- if (specifier.type !== 'ImportSpecifier') {
- continue;
- }
-
- const {imported} = specifier as ImportSpecifier;
- if (imported.type === 'Identifier') {
- existingNames.add(imported.name);
- } else if (imported.type === 'StringLiteral') {
- existingNames.add(imported.value);
- }
- }
-
- for (const name of names) {
- if (existingNames.has(name)) {
- continue;
- }
-
- remotionImport.specifiers = remotionImport.specifiers ?? [];
- remotionImport.specifiers.push(
- b.importSpecifier(b.identifier(name)) as unknown as ImportSpecifier,
- );
- existingNames.add(name);
- }
+) => {
+ ensureNamedImports({ast, importedNames: names, sourcePath: 'remotion'});
};
const componentBodyHasFrameDeclaration = (
diff --git a/packages/studio-server/src/helpers/imports.ts b/packages/studio-server/src/helpers/imports.ts
new file mode 100644
index 0000000000..681021578b
--- /dev/null
+++ b/packages/studio-server/src/helpers/imports.ts
@@ -0,0 +1,191 @@
+import type {File, ImportDeclaration, ImportSpecifier} from '@babel/types';
+import * as recast from 'recast';
+
+const b = recast.types.builders;
+
+export const getImportedName = (specifier: ImportSpecifier) => {
+ if (specifier.imported.type === 'Identifier') {
+ return specifier.imported.name;
+ }
+
+ return specifier.imported.value;
+};
+
+export const findImportDeclaration = (
+ ast: File,
+ sourcePath: string,
+): ImportDeclaration | null => {
+ for (const stmt of ast.program.body) {
+ if (
+ stmt.type === 'ImportDeclaration' &&
+ stmt.source.type === 'StringLiteral' &&
+ stmt.source.value === sourcePath
+ ) {
+ return stmt;
+ }
+ }
+
+ return null;
+};
+
+const findImportDeclarations = (
+ ast: File,
+ sourcePath: string,
+): ImportDeclaration[] => {
+ return ast.program.body.filter(
+ (stmt): stmt is ImportDeclaration =>
+ stmt.type === 'ImportDeclaration' &&
+ stmt.source.type === 'StringLiteral' &&
+ stmt.source.value === sourcePath,
+ );
+};
+
+export const insertImportDeclaration = (
+ ast: File,
+ importDeclaration: ImportDeclaration,
+) => {
+ const {body} = ast.program;
+ let lastImportIndex = -1;
+ for (let i = 0; i < body.length; i++) {
+ if (body[i].type === 'ImportDeclaration') {
+ lastImportIndex = i;
+ }
+ }
+
+ body.splice(lastImportIndex + 1, 0, importDeclaration);
+};
+
+export const normalizeImportSpacing = (input: string) => {
+ return input.replace(/(import[^\n]*\n)\n+(?=import\b)/g, '$1');
+};
+
+const hasNamespaceSpecifier = (importDeclaration: ImportDeclaration) => {
+ return importDeclaration.specifiers?.some(
+ (specifier) => specifier.type === 'ImportNamespaceSpecifier',
+ );
+};
+
+export const ensureNamedImport = ({
+ ast,
+ importedName,
+ sourcePath,
+ localName,
+}: {
+ ast: File;
+ importedName: string;
+ sourcePath: string;
+ localName: string;
+}) => {
+ const existingImports = findImportDeclarations(ast, sourcePath);
+
+ for (const existingImportDeclaration of existingImports) {
+ const matchingSpecifier = existingImportDeclaration.specifiers?.find(
+ (importSpecifierCandidate) =>
+ importSpecifierCandidate.type === 'ImportSpecifier' &&
+ getImportedName(importSpecifierCandidate) === importedName,
+ );
+
+ if (matchingSpecifier) {
+ return matchingSpecifier.local?.name ?? importedName;
+ }
+ }
+
+ const existingImport = existingImports.find(
+ (candidateImportDeclaration) =>
+ !hasNamespaceSpecifier(candidateImportDeclaration),
+ );
+
+ if (existingImport) {
+ const importSpecifier = b.importSpecifier(
+ b.identifier(importedName),
+ localName === importedName ? null : b.identifier(localName),
+ ) as unknown as ImportSpecifier;
+
+ existingImport.specifiers = [
+ ...(existingImport.specifiers ?? []),
+ importSpecifier,
+ ];
+ return localName;
+ }
+
+ const specifier = b.importSpecifier(
+ b.identifier(importedName),
+ localName === importedName ? null : b.identifier(localName),
+ ) as unknown as ImportSpecifier;
+ const importDeclaration = b.importDeclaration(
+ [specifier as never],
+ b.stringLiteral(sourcePath),
+ ) as unknown as ImportDeclaration;
+ insertImportDeclaration(ast, importDeclaration);
+ return localName;
+};
+
+export const ensureNamedImports = ({
+ ast,
+ importedNames,
+ sourcePath,
+}: {
+ ast: File;
+ importedNames: ReadonlySet<string>;
+ sourcePath: string;
+}) => {
+ if (importedNames.size === 0) {
+ return;
+ }
+
+ const existingImports = findImportDeclarations(ast, sourcePath);
+ const existingNames = new Set<string>();
+
+ for (const existingImportDeclaration of existingImports) {
+ for (const importSpecifierCandidate of existingImportDeclaration.specifiers ??
+ []) {
+ if (importSpecifierCandidate.type !== 'ImportSpecifier') {
+ continue;
+ }
+
+ existingNames.add(getImportedName(importSpecifierCandidate));
+ }
+ }
+
+ const existingImport = existingImports.find(
+ (candidateImportDeclaration) =>
+ !hasNamespaceSpecifier(candidateImportDeclaration),
+ );
+
+ if (existingImport) {
+ for (const importedName of importedNames) {
+ if (existingNames.has(importedName)) {
+ continue;
+ }
+
+ existingImport.specifiers = [
+ ...(existingImport.specifiers ?? []),
+ b.importSpecifier(
+ b.identifier(importedName),
+ ) as unknown as ImportSpecifier,
+ ];
+ existingNames.add(importedName);
+ }
+
+ return;
+ }
+
+ const specifiers = [...importedNames]
+ .filter((importedName) => !existingNames.has(importedName))
+ .map(
+ (importedName) =>
+ b.importSpecifier(
+ b.identifier(importedName),
+ ) as unknown as ImportSpecifier,
+ );
+
+ if (specifiers.length === 0) {
+ return;
+ }
+
+ const importDeclaration = b.importDeclaration(
+ specifiers as never,
+ b.stringLiteral(sourcePath),
+ ) as unknown as ImportDeclaration;
+ insertImportDeclaration(ast, importDeclaration);
+};
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.ts
index 4c2e0c6d97..12f86139f4 100644
--- a/packages/studio-server/src/helpers/resolve-composition-component.ts
+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts
@@ -8,7 +8,6 @@ import type {
File,
FunctionDeclaration,
ImportDeclaration,
- ImportSpecifier,
JSXAttribute,
JSXElement,
VariableDeclaration,
@@ -18,6 +17,7 @@ import type {namedTypes} from 'ast-types';
import * as recast from 'recast';
import {formatFileContent} from '../codemods/format-file-content';
import {parseAst, serializeAst} from '../codemods/parse-ast';
+import {ensureNamedImport} from './imports';
type SourceLocation = {
line: number;
@@ -846,14 +846,6 @@ const addElementToNullComponentReturn = ({
return returnStatement.loc?.start.line ?? 1;
};
-const getImportedName = (specifier: ImportSpecifier) => {
- if (specifier.imported.type === 'Identifier') {
- return specifier.imported.name;
- }
-
- return specifier.imported.value;
-};
-
const declarationBindsName = (
declaration: FunctionDeclaration | ClassDeclaration | VariableDeclaration,
name: string,
@@ -914,85 +906,13 @@ const getAvailableSolidLocalName = (ast: File) => {
return available;
};
-const insertImportDeclaration = (
- ast: File,
- importDeclaration: ImportDeclaration,
-) => {
- const {body} = ast.program;
- let lastImportIndex = -1;
- for (let i = 0; i < body.length; i++) {
- if (body[i].type === 'ImportDeclaration') {
- lastImportIndex = i;
- }
- }
-
- body.splice(lastImportIndex + 1, 0, importDeclaration);
-};
-
-const addSolidImport = ({
- ast,
- localName,
- remotionImport,
-}: {
- ast: File;
- localName: string;
- remotionImport: ImportDeclaration | null;
-}) => {
- const imported = recast.types.builders.identifier('Solid');
- const local =
- localName === 'Solid' ? null : recast.types.builders.identifier(localName);
- const specifier = recast.types.builders.importSpecifier(
- imported,
- local,
- ) as unknown as ImportSpecifier;
-
- const canAddToExistingRemotionImport =
- remotionImport &&
- !remotionImport.specifiers?.some(
- (importSpecifier) => importSpecifier.type === 'ImportNamespaceSpecifier',
- );
-
- if (canAddToExistingRemotionImport) {
- remotionImport.specifiers = [
- ...(remotionImport.specifiers ?? []),
- specifier,
- ];
- return;
- }
-
- const importDeclaration = recast.types.builders.importDeclaration(
- [],
- recast.types.builders.stringLiteral('remotion'),
- ) as unknown as ImportDeclaration;
- importDeclaration.specifiers = [specifier];
- insertImportDeclaration(ast, importDeclaration);
-};
-
const ensureSolidImport = (ast: File) => {
- let remotionImport: ImportDeclaration | null = null;
-
- for (const node of ast.program.body) {
- if (node.type !== 'ImportDeclaration' || node.source.value !== 'remotion') {
- continue;
- }
-
- remotionImport = node;
-
- const solidSpecifier = node.specifiers?.find((specifier) => {
- return (
- specifier.type === 'ImportSpecifier' &&
- getImportedName(specifier) === 'Solid'
- );
- });
-
- if (solidSpecifier?.local?.name) {
- return solidSpecifier.local.name;
- }
- }
-
- const localName = getAvailableSolidLocalName(ast);
- addSolidImport({ast, localName, remotionImport});
- return localName;
+ return ensureNamedImport({
+ ast,
+ importedName: 'Solid',
+ sourcePath: 'remotion',
+ localName: getAvailableSolidLocalName(ast),
+ });
};
const addElementToComponentRoot = ({
diff --git a/packages/studio-server/src/test/add-effect.test.ts b/packages/studio-server/src/test/add-effect.test.ts
index 3d106683bf..6b3cc638b0 100644
--- a/packages/studio-server/src/test/add-effect.test.ts
+++ b/packages/studio-server/src/test/add-effect.test.ts
@@ -24,6 +24,9 @@ test('addEffect adds an effects prop and import', async () => {
expect(output).toContain(
"import {brightness} from '@remotion/effects/brightness';",
);
+ expect(output).not.toContain(
+ "import {Solid} from 'remotion';\n\nimport {brightness} from '@remotion/effects/brightness';",
+ );
expect(output).toContain('effects={[');
expect(output).toContain('brightness({');
expect(output).toContain('amount: 1.2');
@@ -118,3 +121,27 @@ test('addEffect rejects non-Remotion effect imports', async () => {
}),
).rejects.toThrow(/Unsupported effect import/);
});
+
+test('addEffect does not duplicate an existing effect import', async () => {
+ const input = `import {Solid} from 'remotion';
+import {brightness} from '@remotion/effects/brightness';
+
+export const Comp = () => {
+\treturn <Solid width={100} height={100} />;
+};
+`;
+ const {output} = await addEffect({
+ input,
+ sequenceNodePath: lineColumnToNodePath(input, 5),
+ effectName: 'brightness',
+ effectImportPath: '@remotion/effects/brightness',
+ effectConfig: {amount: 1.2},
+ });
+
+ expect(
+ output.match(
+ /import \{brightness\} from '@remotion\/effects\/brightness';/g,
+ )?.length,
+ ).toBe(1);
+ expect(output.match(/brightness\(/g)?.length).toBe(1);
+});
diff --git a/packages/studio-server/src/test/paste-effects.test.ts b/packages/studio-server/src/test/paste-effects.test.ts
index b58c7c4202..6ab543d576 100644
--- a/packages/studio-server/src/test/paste-effects.test.ts
+++ b/packages/studio-server/src/test/paste-effects.test.ts
@@ -128,3 +128,28 @@ test('pasteEffects inserts imports for copied effects', async () => {
expect(output).toContain("import {tint} from '@remotion/effects/tint';");
expect(output).toMatch(/tint\(\{\s*color: ['"]red['"],?\s*\}\)/);
});
+
+test('pasteEffects does not duplicate an existing copied effect import', async () => {
+ const input = buildInput(`<>
+ <HtmlInCanvas />
+ </>`);
+ const target = makeNodePath(input, 9);
+
+ const {output} = await pasteEffects({
+ input,
+ targetFileName: 'Comp.tsx',
+ targetSequenceNodePath: target.nodePath,
+ type: 'effects-additive',
+ effects: [
+ {
+ callee: 'tint',
+ importPath: '@remotion/effects/tint',
+ params: {color: 'red'},
+ },
+ ],
+ });
+
+ expect(
+ output.match(/import \{tint\} from '@remotion\/effects\/tint';/g)?.length,
+ ).toBe(1);
+});