Add .gitignore to exclude all node packages and lock files

This commit is contained in:
Adolfo Reyna
2026-02-23 21:56:04 -05:00
parent faae96c9ed
commit dcc5c6c044
9747 changed files with 1555105 additions and 2 deletions
+18
View File
@@ -0,0 +1,18 @@
# @remotion/bundler
Bundle Remotion compositions using Webpack
[![NPM Downloads](https://img.shields.io/npm/dm/@remotion/bundler.svg?style=flat&color=black&label=Downloads)](https://npmcharts.com/compare/@remotion/bundler?minimal=true)
## Installation
```bash
npm install @remotion/bundler --save-exact
```
When installing a Remotion package, make sure to align the version of all `remotion` and `@remotion/*` packages to the same version.
Remove the `^` character from the version number to use the exact version.
## Usage
See the [documentation](https://www.remotion.dev/docs/bundler) for more information.
@@ -0,0 +1,53 @@
import type { GitSource, RenderDefaults } from '@remotion/studio-shared';
import webpack from 'webpack';
import type { WebpackOverrideFn } from './webpack-config';
export type MandatoryLegacyBundleOptions = {
webpackOverride: WebpackOverrideFn;
outDir: string | null;
enableCaching: boolean;
publicPath: string | null;
rootDir: string | null;
publicDir: string | null;
onPublicDirCopyProgress: (bytes: number) => void;
onSymlinkDetected: (path: string) => void;
keyboardShortcutsEnabled: boolean;
askAIEnabled: boolean;
};
export type LegacyBundleOptions = Partial<MandatoryLegacyBundleOptions>;
export declare const getConfig: ({ entryPoint, outDir, resolvedRemotionRoot, onProgress, options, bufferStateDelayInMilliseconds, maxTimelineTracks, experimentalClientSideRenderingEnabled, }: {
outDir: string;
entryPoint: string;
resolvedRemotionRoot: string;
bufferStateDelayInMilliseconds: number | null;
experimentalClientSideRenderingEnabled: boolean;
maxTimelineTracks: number | null;
onProgress?: (progress: number) => void;
options?: LegacyBundleOptions;
}) => Promise<[string, webpack.Configuration]>;
type NewBundleOptions = {
entryPoint: string;
onProgress: (progress: number) => void;
ignoreRegisterRootWarning: boolean;
onDirectoryCreated: (dir: string) => void;
gitSource: GitSource | null;
maxTimelineTracks: number | null;
bufferStateDelayInMilliseconds: number | null;
audioLatencyHint: AudioContextLatencyCategory | null;
experimentalClientSideRenderingEnabled: boolean;
renderDefaults: RenderDefaults | null;
};
type MandatoryBundleOptions = {
entryPoint: string;
} & NewBundleOptions & MandatoryLegacyBundleOptions;
export type BundleOptions = {
entryPoint: string;
} & Partial<NewBundleOptions> & LegacyBundleOptions;
type Arguments = [options: BundleOptions] | [
entryPoint: string,
onProgress?: (progress: number) => void,
options?: LegacyBundleOptions
];
export declare const findClosestFolderWithItem: (currentDir: string, file: string) => string | null;
export declare const internalBundle: (actualArgs: MandatoryBundleOptions) => Promise<string>;
export declare function bundle(...args: Arguments): Promise<string>;
export {};
@@ -0,0 +1,288 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.internalBundle = exports.findClosestFolderWithItem = exports.getConfig = void 0;
exports.bundle = bundle;
const studio_shared_1 = require("@remotion/studio-shared");
const node_fs_1 = __importStar(require("node:fs"));
const node_os_1 = __importDefault(require("node:os"));
const node_path_1 = __importDefault(require("node:path"));
const node_util_1 = require("node:util");
const node_worker_threads_1 = require("node:worker_threads");
const webpack_1 = __importDefault(require("webpack"));
const copy_dir_1 = require("./copy-dir");
const index_html_1 = require("./index-html");
const read_recursively_1 = require("./read-recursively");
const webpack_config_1 = require("./webpack-config");
const promisified = (0, node_util_1.promisify)(webpack_1.default);
const prepareOutDir = async (specified) => {
if (specified) {
await node_fs_1.default.promises.mkdir(specified, { recursive: true });
return specified;
}
return node_fs_1.default.promises.mkdtemp(node_path_1.default.join(node_os_1.default.tmpdir(), 'remotion-webpack-bundle-'));
};
const trimLeadingSlash = (p) => {
if (p.startsWith('/')) {
return trimLeadingSlash(p.substr(1));
}
return p;
};
const trimTrailingSlash = (p) => {
if (p.endsWith('/')) {
return trimTrailingSlash(p.substr(0, p.length - 1));
}
return p;
};
const getConfig = ({ entryPoint, outDir, resolvedRemotionRoot, onProgress, options, bufferStateDelayInMilliseconds, maxTimelineTracks, experimentalClientSideRenderingEnabled, }) => {
var _a, _b, _c, _d;
return (0, webpack_config_1.webpackConfig)({
entry: node_path_1.default.join(require.resolve('@remotion/studio/renderEntry'), '..', 'esm', 'renderEntry.mjs'),
userDefinedComponent: entryPoint,
outDir,
environment: 'production',
webpackOverride: (_a = options === null || options === void 0 ? void 0 : options.webpackOverride) !== null && _a !== void 0 ? _a : ((f) => f),
onProgress: (p) => {
onProgress === null || onProgress === void 0 ? void 0 : onProgress(p);
},
enableCaching: (_b = options === null || options === void 0 ? void 0 : options.enableCaching) !== null && _b !== void 0 ? _b : true,
maxTimelineTracks,
remotionRoot: resolvedRemotionRoot,
keyboardShortcutsEnabled: (_c = options === null || options === void 0 ? void 0 : options.keyboardShortcutsEnabled) !== null && _c !== void 0 ? _c : true,
bufferStateDelayInMilliseconds,
poll: null,
experimentalClientSideRenderingEnabled,
askAIEnabled: (_d = options === null || options === void 0 ? void 0 : options.askAIEnabled) !== null && _d !== void 0 ? _d : true,
});
};
exports.getConfig = getConfig;
const convertArgumentsIntoOptions = (args) => {
var _a;
if (args.length === 0) {
throw new TypeError('bundle() was called without arguments');
}
const firstArg = args[0];
if (typeof firstArg === 'string') {
return {
entryPoint: firstArg,
onProgress: args[1],
...((_a = args[2]) !== null && _a !== void 0 ? _a : {}),
};
}
if (typeof firstArg.entryPoint !== 'string') {
throw new TypeError('bundle() was called without the `entryPoint` option');
}
return firstArg;
};
const recursionLimit = 5;
const findClosestFolderWithItem = (currentDir, file) => {
let possibleFile = '';
for (let i = 0; i < recursionLimit; i++) {
possibleFile = node_path_1.default.join(currentDir, file);
const exists = node_fs_1.default.existsSync(possibleFile);
if (exists) {
return node_path_1.default.dirname(possibleFile);
}
currentDir = node_path_1.default.dirname(currentDir);
}
return null;
};
exports.findClosestFolderWithItem = findClosestFolderWithItem;
const findClosestPackageJsonFolder = (currentDir) => {
return (0, exports.findClosestFolderWithItem)(currentDir, 'package.json');
};
const validateEntryPoint = async (entryPoint) => {
const contents = await node_fs_1.promises.readFile(entryPoint, 'utf8');
if (!contents.includes('registerRoot')) {
throw new Error([
`You passed ${entryPoint} as your entry point, but this file does not contain "registerRoot".`,
'You should use the file that calls registerRoot() as the entry point.',
'To ignore this error, pass "ignoreRegisterRootWarning" to bundle().',
'This error cannot be ignored on the CLI.',
].join(' '));
}
};
const internalBundle = async (actualArgs) => {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
const entryPoint = node_path_1.default.resolve(process.cwd(), actualArgs.entryPoint);
const resolvedRemotionRoot = (_b = (_a = actualArgs === null || actualArgs === void 0 ? void 0 : actualArgs.rootDir) !== null && _a !== void 0 ? _a : findClosestPackageJsonFolder(entryPoint)) !== null && _b !== void 0 ? _b : process.cwd();
if (!actualArgs.ignoreRegisterRootWarning) {
await validateEntryPoint(entryPoint);
}
const outDir = await prepareOutDir((_c = actualArgs === null || actualArgs === void 0 ? void 0 : actualArgs.outDir) !== null && _c !== void 0 ? _c : null);
(_d = actualArgs.onDirectoryCreated) === null || _d === void 0 ? void 0 : _d.call(actualArgs, outDir);
// The config might use an override which might use
// `process.cwd()`. The context should always be the Remotion root.
// This is not supported in worker threads (used for tests)
const currentCwd = process.cwd();
if (node_worker_threads_1.isMainThread) {
process.chdir(resolvedRemotionRoot);
}
const { onProgress, ...options } = actualArgs;
const [, config] = await (0, exports.getConfig)({
outDir,
entryPoint,
resolvedRemotionRoot,
onProgress,
options,
// Should be null to keep cache hash working
bufferStateDelayInMilliseconds: (_e = actualArgs.bufferStateDelayInMilliseconds) !== null && _e !== void 0 ? _e : null,
maxTimelineTracks: actualArgs.maxTimelineTracks,
experimentalClientSideRenderingEnabled: actualArgs.experimentalClientSideRenderingEnabled,
});
const output = (await promisified([config]));
if (node_worker_threads_1.isMainThread) {
process.chdir(currentCwd);
}
if (!output) {
throw new Error('Expected webpack output');
}
const { errors } = output.toJson();
if (errors !== undefined && errors.length > 0) {
throw new Error(errors[0].message + '\n' + errors[0].details);
}
const publicPath = (_f = actualArgs === null || actualArgs === void 0 ? void 0 : actualArgs.publicPath) !== null && _f !== void 0 ? _f : '/';
const staticHash = '/' +
[trimTrailingSlash(trimLeadingSlash(publicPath)), 'public']
.filter(Boolean)
.join('/');
const from = (options === null || options === void 0 ? void 0 : options.publicDir)
? node_path_1.default.resolve(resolvedRemotionRoot, options.publicDir)
: node_path_1.default.join(resolvedRemotionRoot, 'public');
const to = node_path_1.default.join(outDir, 'public');
let symlinkWarningShown = false;
const showSymlinkWarning = (ent, src) => {
if (symlinkWarningShown) {
return;
}
const absolutePath = node_path_1.default.join(src, ent.name);
if (options.onSymlinkDetected) {
options.onSymlinkDetected(absolutePath);
return;
}
symlinkWarningShown = true;
// eslint-disable-next-line no-console
console.warn(`\nFound a symbolic link in the public folder (${absolutePath}). The symlink will be forwarded into the bundle.`);
};
if (node_fs_1.default.existsSync(from)) {
await (0, copy_dir_1.copyDir)({
src: from,
dest: to,
onSymlinkDetected: showSymlinkWarning,
onProgress: (prog) => {
var _a;
return (_a = options.onPublicDirCopyProgress) === null || _a === void 0 ? void 0 : _a.call(options, prog);
},
copiedBytes: 0,
lastReportedProgress: 0,
});
}
const html = (0, index_html_1.indexHtml)({
staticHash,
publicPath,
editorName: null,
inputProps: null,
remotionRoot: resolvedRemotionRoot,
studioServerCommand: null,
renderQueue: null,
numberOfAudioTags: 0,
publicFiles: (0, read_recursively_1.readRecursively)({
folder: '.',
startPath: from,
staticHash,
limit: 10000,
}).map((f) => {
return {
...f,
name: f.name.split(node_path_1.default.sep).join('/'),
};
}),
includeFavicon: true,
title: 'Remotion Bundle',
renderDefaults: (_g = actualArgs.renderDefaults) !== null && _g !== void 0 ? _g : undefined,
publicFolderExists: `${publicPath + (publicPath.endsWith('/') ? '' : '/')}public`,
gitSource: (_h = actualArgs.gitSource) !== null && _h !== void 0 ? _h : null,
projectName: (0, studio_shared_1.getProjectName)({
gitSource: (_j = actualArgs.gitSource) !== null && _j !== void 0 ? _j : null,
resolvedRemotionRoot,
basename: node_path_1.default.basename,
}),
installedDependencies: null,
packageManager: 'unknown',
// Actual log level is set in setPropsAndEnv()
logLevel: 'info',
mode: 'bundle',
audioLatencyHint: (_k = actualArgs.audioLatencyHint) !== null && _k !== void 0 ? _k : 'interactive',
});
node_fs_1.default.writeFileSync(node_path_1.default.join(outDir, 'index.html'), html);
node_fs_1.default.copyFileSync(node_path_1.default.join(__dirname, '../favicon.ico'), node_path_1.default.join(outDir, 'favicon.ico'));
node_fs_1.default.copyFileSync(node_path_1.default.resolve(require.resolve('source-map'), '..', 'lib', 'mappings.wasm'), node_path_1.default.join(outDir, studio_shared_1.SOURCE_MAP_ENDPOINT.replace('/', '')));
return outDir;
};
exports.internalBundle = internalBundle;
/*
* @description Bundles a Remotion project using Webpack and prepares it for rendering.
* @see [Documentation](https://remotion.dev/docs/bundle)
*/
async function bundle(...args) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
const actualArgs = convertArgumentsIntoOptions(args);
const result = await (0, exports.internalBundle)({
bufferStateDelayInMilliseconds: (_a = actualArgs.bufferStateDelayInMilliseconds) !== null && _a !== void 0 ? _a : null,
enableCaching: (_b = actualArgs.enableCaching) !== null && _b !== void 0 ? _b : true,
entryPoint: actualArgs.entryPoint,
gitSource: (_c = actualArgs.gitSource) !== null && _c !== void 0 ? _c : null,
ignoreRegisterRootWarning: (_d = actualArgs.ignoreRegisterRootWarning) !== null && _d !== void 0 ? _d : false,
maxTimelineTracks: (_e = actualArgs.maxTimelineTracks) !== null && _e !== void 0 ? _e : null,
onDirectoryCreated: (_f = actualArgs.onDirectoryCreated) !== null && _f !== void 0 ? _f : (() => { }),
onProgress: (_g = actualArgs.onProgress) !== null && _g !== void 0 ? _g : (() => { }),
onPublicDirCopyProgress: (_h = actualArgs.onPublicDirCopyProgress) !== null && _h !== void 0 ? _h : (() => { }),
onSymlinkDetected: (_j = actualArgs.onSymlinkDetected) !== null && _j !== void 0 ? _j : (() => { }),
outDir: (_k = actualArgs.outDir) !== null && _k !== void 0 ? _k : null,
publicDir: (_l = actualArgs.publicDir) !== null && _l !== void 0 ? _l : null,
publicPath: (_m = actualArgs.publicPath) !== null && _m !== void 0 ? _m : null,
rootDir: (_o = actualArgs.rootDir) !== null && _o !== void 0 ? _o : null,
webpackOverride: (_p = actualArgs.webpackOverride) !== null && _p !== void 0 ? _p : ((f) => f),
audioLatencyHint: (_q = actualArgs.audioLatencyHint) !== null && _q !== void 0 ? _q : null,
experimentalClientSideRenderingEnabled: (_r = actualArgs.experimentalClientSideRenderingEnabled) !== null && _r !== void 0 ? _r : false,
renderDefaults: (_s = actualArgs.renderDefaults) !== null && _s !== void 0 ? _s : null,
askAIEnabled: (_t = actualArgs.askAIEnabled) !== null && _t !== void 0 ? _t : true,
keyboardShortcutsEnabled: (_u = actualArgs.keyboardShortcutsEnabled) !== null && _u !== void 0 ? _u : true,
});
return result;
}
@@ -0,0 +1,20 @@
import type { Compiler } from 'webpack';
export declare class CaseSensitivePathsPlugin {
fs: Compiler['inputFileSystem'];
context: string;
cacheMap: Map<string, string[]>;
deferrerMap: Map<string, Promise<string[]>>;
/**
* Check if resource need to be checked
*/
isCheckable(res: string, type?: string, issuer?: string): boolean;
/**
* Check if file exists with case sensitive
*/
checkFileExistsWithCase(res: string): Promise<unknown>;
/**
* reset this plugin, wait for the next compilation
*/
reset(): void;
apply(compiler: Compiler): void;
}
@@ -0,0 +1,143 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CaseSensitivePathsPlugin = void 0;
const path_1 = __importDefault(require("path"));
// Inlined from https://github.com/umijs/case-sensitive-paths-webpack-plugin/blob/master/src/index.ts
/**
* The MIT License (MIT)
Copyright (c) 2022-present UmiJS Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
const PLUGIN_NAME = 'CaseSensitive';
class CaseSensitivePathsPlugin {
constructor() {
this.context = '';
this.cacheMap = new Map();
this.deferrerMap = new Map();
}
/**
* Check if resource need to be checked
*/
isCheckable(res, type, issuer) {
return (
// skip base64 url in css files
type !== 'asset/inline' &&
// skip resources which outside project
res.startsWith(this.context) &&
// skip node_modules
!/(\/|\\)node_modules\1/.test(res) &&
// skip duplicated css resource by unknown reason
res !== issuer);
}
/**
* Check if file exists with case sensitive
*/
checkFileExistsWithCase(res) {
return new Promise((resolve, reject) => {
let full = res;
let caseError = null;
const deferrers = [];
// check every level directories for resource, except outside project
while (full.length > this.context.length) {
const { dir, base: current } = path_1.default.parse(full);
let deferrer;
if (this.cacheMap.get(dir)) {
// use cache first
deferrer = Promise.resolve(this.cacheMap.get(dir));
}
else if (this.deferrerMap.get(dir)) {
// wait another same directory to be resolved
deferrer = this.deferrerMap.get(dir);
}
else {
// read directory for the first time
deferrer = new Promise((resolve2) => {
this.fs.readdir(dir, (_, files = []) => {
// save cache, resolve promise and release deferrer
this.cacheMap.set(dir, files);
resolve2(files);
this.deferrerMap.delete(dir);
});
});
// save deferrer for another called
this.deferrerMap.set(dir, deferrer);
}
// check current file synchronously, for performance
deferrer.then((files) => {
// try to find correct name
// if current file not exists in current directory and there has no existing error
if (!files.includes(current) && !caseError) {
const correctName = files.find((file) => file.toLowerCase() === current.toLowerCase());
// only throw first error for the single resource
if (correctName) {
caseError = new Error(`Capitalization mismatch in \`${path_1.default.join(res)}\`: \`${current}\` does not match the name on disk \`${correctName}\``);
reject(caseError);
}
}
});
deferrers.push(deferrer);
// continue to check upper directory
full = dir;
}
Promise.all(deferrers).then(() => {
// resolve if no error
if (!caseError) {
resolve(caseError);
}
});
});
}
/**
* reset this plugin, wait for the next compilation
*/
reset() {
this.cacheMap = new Map();
this.deferrerMap = new Map();
}
apply(compiler) {
this.context = compiler.options.context || process.cwd();
this.fs = compiler.inputFileSystem;
compiler.hooks.normalModuleFactory.tap(PLUGIN_NAME, (factory) => {
factory.hooks.afterResolve.tapAsync(PLUGIN_NAME, (data, done) => {
var _a, _b;
// compatible with webpack 4.x
const { createData = data } = data;
if (createData.resource &&
this.isCheckable(createData.resource, createData.type, (_b = (_a = createData.resourceResolveData) === null || _a === void 0 ? void 0 : _a.context) === null || _b === void 0 ? void 0 : _b.issuer)) {
this.checkFileExistsWithCase(createData.resource
.replace(/\?.+$/, '')
// replace escaped \0# with # see: https://github.com/webpack/enhanced-resolve#escaping
.replace('\u0000#', '#')).then(() => done(null), (err) => done(err));
}
else {
done(null);
}
});
});
compiler.hooks.done.tap(PLUGIN_NAME, () => {
this.reset();
});
}
}
exports.CaseSensitivePathsPlugin = CaseSensitivePathsPlugin;
@@ -0,0 +1,9 @@
import fs from 'node:fs';
export declare function copyDir({ src, dest, onSymlinkDetected, onProgress, copiedBytes, lastReportedProgress, }: {
src: string;
dest: string;
onSymlinkDetected: (entry: fs.Dirent, dir: string) => void;
onProgress: (bytes: number) => void;
copiedBytes: number;
lastReportedProgress: number;
}): Promise<number>;
@@ -0,0 +1,43 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.copyDir = copyDir;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
async function copyDir({ src, dest, onSymlinkDetected, onProgress, copiedBytes = 0, lastReportedProgress = 0, }) {
await node_fs_1.default.promises.mkdir(dest, { recursive: true });
const entries = await node_fs_1.default.promises.readdir(src, { withFileTypes: true });
for (const entry of entries) {
const srcPath = node_path_1.default.join(src, entry.name);
const destPath = node_path_1.default.join(dest, entry.name);
if (entry.isDirectory()) {
copiedBytes = await copyDir({
src: srcPath,
dest: destPath,
onSymlinkDetected,
onProgress,
copiedBytes,
lastReportedProgress,
});
}
else if (entry.isSymbolicLink()) {
const realpath = await node_fs_1.default.promises.realpath(srcPath);
onSymlinkDetected(entry, src);
await node_fs_1.default.promises.symlink(realpath, destPath);
}
else {
const [, { size }] = await Promise.all([
node_fs_1.default.promises.copyFile(srcPath, destPath),
node_fs_1.default.promises.stat(srcPath),
]);
copiedBytes += size;
if (copiedBytes - lastReportedProgress > 1024 * 1024 * 10) {
onProgress(copiedBytes);
lastReportedProgress = copiedBytes;
}
}
}
return copiedBytes;
}
@@ -0,0 +1,4 @@
import type webpack from 'webpack';
import type { LoaderOptions } from './interfaces';
declare function ESBuildLoader(this: webpack.LoaderContext<LoaderOptions>, source: string): Promise<void>;
export default ESBuildLoader;
@@ -0,0 +1,55 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const esbuild_1 = require("esbuild");
const node_path_1 = __importDefault(require("node:path"));
const isTsExtensionPtrn = /\.ts$/i;
const isTypescriptInstalled = () => {
try {
require.resolve('typescript');
return true;
}
catch (_a) {
return false;
}
};
async function ESBuildLoader(source) {
var _a, _b, _c;
const done = this.async();
const options = this.getOptions();
const { implementation, remotionRoot, ...esbuildTransformOptions } = options;
const tsConfigPath = node_path_1.default.join(remotionRoot, 'tsconfig.json');
if (implementation && typeof implementation.transform !== 'function') {
done(new TypeError(`esbuild-loader: options.implementation.transform must be an ESBuild transform function. Received ${typeof implementation.transform}`));
return;
}
const transform = (_a = implementation === null || implementation === void 0 ? void 0 : implementation.transform) !== null && _a !== void 0 ? _a : esbuild_1.transform;
const transformOptions = {
...esbuildTransformOptions,
target: (_b = options.target) !== null && _b !== void 0 ? _b : 'es2015',
loader: (_c = options.loader) !== null && _c !== void 0 ? _c : 'js',
sourcemap: this.sourceMap,
sourcefile: this.resourcePath,
};
if (!('tsconfigRaw' in transformOptions) && isTypescriptInstalled()) {
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const typescript = require('typescript');
const tsConfig = typescript.readConfigFile(tsConfigPath, typescript.sys.readFile);
transformOptions.tsconfigRaw = tsConfig.config;
}
// https://github.com/privatenumber/esbuild-loader/pull/107
if (transformOptions.loader === 'tsx' &&
isTsExtensionPtrn.test(this.resourcePath)) {
transformOptions.loader = 'ts';
}
try {
const { code, map } = await transform(source, transformOptions);
done(null, code, map && JSON.parse(map));
}
catch (error) {
done(error);
}
}
exports.default = ESBuildLoader;
@@ -0,0 +1,12 @@
import type { transform, TransformOptions } from 'esbuild';
type Implementation = {
transform: typeof transform;
};
type Except<ObjectType, Properties> = {
[Key in keyof ObjectType as Key extends Properties ? never : Key]: ObjectType[Key];
};
export type LoaderOptions = Except<TransformOptions, 'sourcemap' | 'sourcefile'> & {
implementation: Implementation;
remotionRoot: string;
};
export {};
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,39 @@
/**
* Source code is adapted from https://github.com/WebHotelier/webpack-fast-refresh#readme and rewritten in Typescript. This file is MIT licensed.
*/
/**
* MIT License
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
declare function registerExportsForReactRefresh(moduleExports: unknown, moduleID: unknown): void;
declare function isReactRefreshBoundary(moduleExports: unknown): boolean;
declare function getRefreshBoundarySignature(moduleExports: unknown): any[];
declare function shouldInvalidateReactRefreshBoundary(prevExports: unknown, nextExports: unknown): boolean;
declare function scheduleUpdate(): void;
declare const _default: {
registerExportsForReactRefresh: typeof registerExportsForReactRefresh;
isReactRefreshBoundary: typeof isReactRefreshBoundary;
shouldInvalidateReactRefreshBoundary: typeof shouldInvalidateReactRefreshBoundary;
getRefreshBoundarySignature: typeof getRefreshBoundarySignature;
scheduleUpdate: typeof scheduleUpdate;
};
export default _default;
@@ -0,0 +1,146 @@
"use strict";
/**
* Source code is adapted from https://github.com/WebHotelier/webpack-fast-refresh#readme and rewritten in Typescript. This file is MIT licensed.
*/
/**
* MIT License
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
Object.defineProperty(exports, "__esModule", { value: true });
// This file is copied from the Metro JavaScript bundler, with minor tweaks for
// webpack compatibility.
//
// https://github.com/facebook/metro/blob/d6b9685c730d0d63577db40f41369157f28dfa3a/packages/metro/src/lib/polyfills/require.js
const RefreshRuntime = require('react-refresh/runtime');
function isSafeExport(key) {
return (key === '__esModule' ||
key === '__N_SSG' ||
key === '__N_SSP' ||
key === 'config');
}
function registerExportsForReactRefresh(moduleExports, moduleID) {
RefreshRuntime.register(moduleExports, moduleID + ' %exports%');
if (moduleExports === null ||
moduleExports === undefined ||
typeof moduleExports !== 'object') {
// Exit if we can't iterate over exports.
// (This is important for legacy environments.)
return;
}
for (const key in moduleExports) {
if (isSafeExport(key)) {
continue;
}
// @ts-expect-error
const exportValue = moduleExports[key];
const typeID = moduleID + ' %exports% ' + key;
RefreshRuntime.register(exportValue, typeID);
}
}
function isReactRefreshBoundary(moduleExports) {
if (RefreshRuntime.isLikelyComponentType(moduleExports)) {
return true;
}
if (moduleExports === null ||
moduleExports === undefined ||
typeof moduleExports !== 'object') {
// Exit if we can't iterate over exports.
return false;
}
let hasExports = false;
let areAllExportsComponents = true;
for (const key in moduleExports) {
hasExports = true;
if (isSafeExport(key)) {
continue;
}
// @ts-expect-error
const exportValue = moduleExports[key];
if (!RefreshRuntime.isLikelyComponentType(exportValue)) {
areAllExportsComponents = false;
}
}
return hasExports && areAllExportsComponents;
}
function getRefreshBoundarySignature(moduleExports) {
const signature = [];
signature.push(RefreshRuntime.getFamilyByType(moduleExports));
if (moduleExports === null ||
moduleExports === undefined ||
typeof moduleExports !== 'object') {
// Exit if we can't iterate over exports.
// (This is important for legacy environments.)
return signature;
}
for (const key in moduleExports) {
if (isSafeExport(key)) {
continue;
}
// @ts-expect-error
const exportValue = moduleExports[key];
signature.push(key);
signature.push(RefreshRuntime.getFamilyByType(exportValue));
}
return signature;
}
function shouldInvalidateReactRefreshBoundary(prevExports, nextExports) {
const prevSignature = getRefreshBoundarySignature(prevExports);
const nextSignature = getRefreshBoundarySignature(nextExports);
if (prevSignature.length !== nextSignature.length) {
return true;
}
for (let i = 0; i < nextSignature.length; i++) {
if (prevSignature[i] !== nextSignature[i]) {
return true;
}
}
return false;
}
function scheduleUpdate() {
var _a, _b;
const execute = () => {
try {
RefreshRuntime.performReactRefresh();
}
catch (err) {
// eslint-disable-next-line no-console
console.warn('Warning: Failed to re-render. We will retry on the next Fast Refresh event.\n' +
err);
}
};
// Only trigger refresh if the webpack HMR state is idle
if (((_a = __webpack_module__.hot) === null || _a === void 0 ? void 0 : _a.status()) === 'idle') {
return;
}
(_b = __webpack_module__.hot) === null || _b === void 0 ? void 0 : _b.addStatusHandler((status) => {
if (status === 'idle') {
execute();
}
});
}
exports.default = {
registerExportsForReactRefresh,
isReactRefreshBoundary,
shouldInvalidateReactRefreshBoundary,
getRefreshBoundarySignature,
scheduleUpdate,
};
@@ -0,0 +1,30 @@
/**
* Source code is adapted from https://github.com/WebHotelier/webpack-fast-refresh#readme and rewritten in Typescript. This file is MIT licensed.
*/
/**
* The MIT License (MIT)
*
* Copyright (c) 2020 Vercel, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import type webpack from 'webpack';
export declare class ReactFreshWebpackPlugin {
apply(compiler: webpack.Compiler): void;
}
@@ -0,0 +1,59 @@
"use strict";
/**
* Source code is adapted from https://github.com/WebHotelier/webpack-fast-refresh#readme and rewritten in Typescript. This file is MIT licensed.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReactFreshWebpackPlugin = void 0;
const webpack_1 = require("webpack");
class ReactRefreshRuntimeModule extends webpack_1.RuntimeModule {
constructor() {
super('react refresh', 5);
}
generate() {
const { runtimeTemplate } = this.compilation;
return webpack_1.Template.asString([
`${webpack_1.RuntimeGlobals.interceptModuleExecution}.push(${runtimeTemplate.basicFunction('options', [
`const originalFactory = options.factory;`,
`options.factory = ${runtimeTemplate.basicFunction('moduleObject, moduleExports, webpackRequire', [
// Legacy CSS implementations will `eval` browser code in a Node.js
// context to extract CSS. For backwards compatibility, we need to check
// we're in a browser context before continuing.
`const hasRefresh = typeof self !== "undefined" && !!self.$RefreshInterceptModuleExecution$;`,
`const cleanup = hasRefresh ? self.$RefreshInterceptModuleExecution$(moduleObject.id) : () => {};`,
'try {',
webpack_1.Template.indent('originalFactory.call(this, moduleObject, moduleExports, webpackRequire);'),
'} finally {',
webpack_1.Template.indent(`cleanup();`),
'}',
])}`,
])})`,
]);
}
}
class ReactFreshWebpackPlugin {
apply(compiler) {
const webpackMajorVersion = parseInt(webpack_1.version !== null && webpack_1.version !== void 0 ? webpack_1.version : '', 10);
if (webpackMajorVersion < 5) {
throw new Error(`ReactFreshWebpackPlugin does not support webpack v${webpackMajorVersion}.`);
}
compiler.hooks.compilation.tap(this.constructor.name, (compilation) => {
compilation.mainTemplate.hooks.localVars.tap(this.constructor.name, (source) => webpack_1.Template.asString([
source,
'',
'// noop fns to prevent runtime errors during initialization',
'if (typeof self !== "undefined") {',
webpack_1.Template.indent('self.$RefreshReg$ = function () {};'),
webpack_1.Template.indent('self.$RefreshSig$ = function () {'),
webpack_1.Template.indent(webpack_1.Template.indent('return function (type) {')),
webpack_1.Template.indent(webpack_1.Template.indent(webpack_1.Template.indent('return type;'))),
webpack_1.Template.indent(webpack_1.Template.indent('};')),
webpack_1.Template.indent('};'),
'}',
]));
compilation.hooks.additionalTreeRuntimeRequirements.tap(this.constructor.name, (chunk) => {
compilation.addRuntimeModule(chunk, new ReactRefreshRuntimeModule());
});
});
}
}
exports.ReactFreshWebpackPlugin = ReactFreshWebpackPlugin;
@@ -0,0 +1,129 @@
/**
* ⚠️ Be careful when refactoring this file!
* This gets injected into every file of the browser.
* You cannot have returns, optional chains, inverse the if statement etc.
* Check the Typescript output in dist/ to see that no extra `var` statements were produced
*/
/**
* Source code is adapted from https://github.com/WebHotelier/webpack-fast-refresh#readme and rewritten in Typescript. This file is MIT licensed.
*/
/**
* The MIT License (MIT)
*
* Copyright (c) 2020 Vercel, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import type { LoaderDefinition } from 'webpack';
declare global {
const __webpack_hash__: unknown;
interface HotNotifierInfo {
type: 'self-declined' | 'declined' | 'unaccepted' | 'accepted' | 'disposed' | 'accept-errored' | 'self-accept-errored' | 'self-accept-error-handler-errored';
/**
* The module in question.
*/
moduleId: number;
/**
* For errors: the module id owning the accept handler.
*/
dependencyId?: number | undefined;
/**
* For declined/accepted/unaccepted: the chain from where the update was propagated.
*/
chain?: number[] | undefined;
/**
* For declined: the module id of the declining parent
*/
parentId?: number | undefined;
/**
* For accepted: the modules that are outdated and will be disposed
*/
outdatedModules?: number[] | undefined;
/**
* For accepted: The location of accept handlers that will handle the update
*/
outdatedDependencies?: {
[dependencyId: number]: number[];
} | undefined;
/**
* For errors: the thrown error
*/
error?: Error | undefined;
/**
* For self-accept-error-handler-errored: the error thrown by the module
* before the error handler tried to handle it.
*/
originalError?: Error | undefined;
}
interface AcceptOptions {
/**
* If true the update process continues even if some modules are not accepted (and would bubble to the entry point).
*/
ignoreUnaccepted?: boolean | undefined;
/**
* Ignore changes made to declined modules.
*/
ignoreDeclined?: boolean | undefined;
/**
* Ignore errors throw in accept handlers, error handlers and while reevaluating module.
*/
ignoreErrored?: boolean | undefined;
/**
* Notifier for declined modules.
*/
onDeclined?: ((info: HotNotifierInfo) => void) | undefined;
/**
* Notifier for unaccepted modules.
*/
onUnaccepted?: ((info: HotNotifierInfo) => void) | undefined;
/**
* Notifier for accepted modules.
*/
onAccepted?: ((info: HotNotifierInfo) => void) | undefined;
/**
* Notifier for disposed modules.
*/
onDisposed?: ((info: HotNotifierInfo) => void) | undefined;
/**
* Notifier for errors.
*/
onErrored?: ((info: HotNotifierInfo) => void) | undefined;
/**
* Indicates that apply() is automatically called by check function
*/
autoApply?: boolean | undefined;
}
const __webpack_module__: {
id: string;
exports: unknown;
hot: {
accept: () => void;
dispose: (onDispose: (data: Record<string, unknown>) => void) => void;
invalidate: () => void;
data?: Record<string, unknown>;
addStatusHandler(callback: (status: string) => void): void;
status(): string;
apply(options?: AcceptOptions): Promise<ModuleId[]>;
check(autoApply?: boolean): Promise<null | ModuleId[]>;
};
};
type ModuleId = string | number;
}
declare const ReactRefreshLoader: LoaderDefinition;
export default ReactRefreshLoader;
@@ -0,0 +1,80 @@
"use strict";
/**
* ⚠️ Be careful when refactoring this file!
* This gets injected into every file of the browser.
* You cannot have returns, optional chains, inverse the if statement etc.
* Check the Typescript output in dist/ to see that no extra `var` statements were produced
*/
Object.defineProperty(exports, "__esModule", { value: true });
// This file is copied from the @vercel/next.js, with removed TS annotations
//
// https://github.com/vercel/next.js/blob/canary/packages/react-refresh-utils/loader.ts
// This function gets unwrapped into global scope, which is why we don't invert
// if-blocks. Also, you cannot use `return`.
function RefreshModuleRuntime() {
var _a, _b;
// Legacy CSS implementations will `eval` browser code in a Node.js context
// to extract CSS. For backwards compatibility, we need to check we're in a
// browser context before continuing.
if (typeof self !== 'undefined' &&
// AMP / No-JS mode does not inject these helpers:
'$RefreshHelpers$' in self) {
const currentExports = __webpack_module__.exports;
const prevExports = (_b = (_a = __webpack_module__.hot.data) === null || _a === void 0 ? void 0 : _a.prevExports) !== null && _b !== void 0 ? _b : null;
// This cannot happen in MainTemplate because the exports mismatch between
// templating and execution.
self.$RefreshHelpers$.registerExportsForReactRefresh(currentExports, __webpack_module__.id);
// A module can be accepted automatically based on its exports, e.g. when
// it is a Refresh Boundary.
if (self.$RefreshHelpers$.isReactRefreshBoundary(currentExports)) {
// Save the previous exports on update so we can compare the boundary
// signatures.
__webpack_module__.hot.dispose((data) => {
data.prevExports = currentExports;
});
// Unconditionally accept an update to this module, we'll check if it's
// still a Refresh Boundary later.
__webpack_module__.hot.accept();
// This field is set when the previous version of this module was a
// Refresh Boundary, letting us know we need to check for invalidation or
// enqueue an update.
if (prevExports !== null) {
// A boundary can become ineligible if its exports are incompatible
// with the previous exports.
//
// For example, if you add/remove/change exports, we'll want to
// re-execute the importing modules, and force those components to
// re-render. Similarly, if you convert a class component to a
// function, we want to invalidate the boundary.
if (self.$RefreshHelpers$.shouldInvalidateReactRefreshBoundary(prevExports, currentExports)) {
__webpack_module__.hot.invalidate();
}
else {
self.$RefreshHelpers$.scheduleUpdate();
}
}
}
else {
// Since we just executed the code for the module, it's possible that the
// new exports made it ineligible for being a boundary.
// We only care about the case when we were _previously_ a boundary,
// because we already accepted this update (accidental side effect).
const isNoLongerABoundary = prevExports !== null;
if (isNoLongerABoundary) {
__webpack_module__.hot.invalidate();
}
}
}
}
let refreshModuleRuntime = RefreshModuleRuntime.toString();
refreshModuleRuntime = refreshModuleRuntime.slice(refreshModuleRuntime.indexOf('{') + 1, refreshModuleRuntime.lastIndexOf('}'));
const ReactRefreshLoader = function (source, inputSourceMap) {
// Importing a module that declares the global variables _a and _b
// will conflict with the global variables that React Fast Refresh uses.
// https://github.com/remotion-dev/remotion/issues/3699
const renamedSymbols = refreshModuleRuntime
.replace(/_a/g, '_remotion_globalVariableA')
.replace(/_b/g, '_remotion_globalVariableB');
this.callback(null, `${source}\n;${renamedSymbols}`, inputSourceMap);
};
exports.default = ReactRefreshLoader;
@@ -0,0 +1,35 @@
/**
* Source code is adapted from https://github.com/WebHotelier/webpack-fast-refresh#readme and rewritten in Typescript. This file is MIT licensed.
*/
/**
* The MIT License (MIT)
*
* Copyright (c) 2020 Vercel, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
declare global {
interface Window {
$RefreshReg$: (type: string, id?: string) => void;
$RefreshSig$: () => (type: string) => unknown;
$RefreshHelpers$: typeof RefreshHelpers;
$RefreshInterceptModuleExecution$: (webpackId: unknown) => () => void;
}
}
import RefreshHelpers from './helpers';
@@ -0,0 +1,33 @@
"use strict";
/// <reference lib="dom" />
/// <reference lib="dom.iterable" />
/**
* Source code is adapted from https://github.com/WebHotelier/webpack-fast-refresh#readme and rewritten in Typescript. This file is MIT licensed.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const RefreshRuntime = require('react-refresh/runtime');
const helpers_1 = __importDefault(require("./helpers"));
// Hook into ReactDOM initialization
RefreshRuntime.injectIntoGlobalHook(self);
// noop fns to prevent runtime errors during initialization
self.$RefreshReg$ = () => undefined;
self.$RefreshSig$ = () => (type) => type;
// Register global helpers
self.$RefreshHelpers$ = helpers_1.default;
// Register a helper for module execution interception
self.$RefreshInterceptModuleExecution$ = function (webpackModuleId) {
const prevRefreshReg = self.$RefreshReg$;
const prevRefreshSig = self.$RefreshSig$;
self.$RefreshReg$ = (type, id) => {
RefreshRuntime.register(type, webpackModuleId + ' ' + id);
};
self.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
// Modeled after `useEffect` cleanup pattern:
return () => {
self.$RefreshReg$ = prevRefreshReg;
self.$RefreshSig$ = prevRefreshSig;
};
};
@@ -0,0 +1,5 @@
import type { Compiler } from 'webpack';
export declare class AllowDependencyExpressionPlugin {
filter(error: Error): boolean;
apply(compiler: Compiler): void;
}
@@ -0,0 +1,25 @@
"use strict";
// When Webpack cannot resolve these dependencies, it will not print an error message.
Object.defineProperty(exports, "__esModule", { value: true });
exports.AllowDependencyExpressionPlugin = void 0;
// If importing TypeScript, it will give this warning:
// WARNING in ./node_modules/typescript/lib/typescript.js 6304:33-52
// Critical dependency: the request of a dependency is an expression
class AllowDependencyExpressionPlugin {
filter(error) {
if (error.message.includes('the request of a dependency is an expression')) {
return false;
}
return true;
}
apply(compiler) {
compiler.hooks.afterCompile.tap('Com', (compilation) => {
compilation.errors = compilation.errors.filter(this.filter);
});
compiler.hooks.afterEmit.tap('AllowOptionalDependenciesPlugin', (compilation) => {
compilation.errors = compilation.errors.filter(this.filter);
compilation.warnings = compilation.warnings.filter(this.filter);
});
}
}
exports.AllowDependencyExpressionPlugin = AllowDependencyExpressionPlugin;
@@ -0,0 +1,5 @@
import type { Compiler } from 'webpack';
export declare class IgnorePackFileCacheWarningsPlugin {
filter(error: Error): boolean;
apply(compiler: Compiler): void;
}
@@ -0,0 +1,21 @@
"use strict";
// Suppress the frequent Webpack warnings about serializing large strings in the cache
Object.defineProperty(exports, "__esModule", { value: true });
exports.IgnorePackFileCacheWarningsPlugin = void 0;
class IgnorePackFileCacheWarningsPlugin {
filter(error) {
if (error.message.includes('Serializing big strings')) {
return false;
}
return true;
}
apply(compiler) {
compiler.hooks.afterCompile.tap('IgnorePackFileCacheWarningsPlugin', (compilation) => {
compilation.warnings = compilation.warnings.filter(this.filter);
});
compiler.hooks.afterEmit.tap('IgnorePackFileCacheWarningsPlugin', (compilation) => {
compilation.warnings = compilation.warnings.filter(this.filter);
});
}
}
exports.IgnorePackFileCacheWarningsPlugin = IgnorePackFileCacheWarningsPlugin;
@@ -0,0 +1,26 @@
import type { GitSource, PackageManager, RenderDefaults } from '@remotion/studio-shared';
import type { LogLevel, StaticFile } from 'remotion';
export declare const indexHtml: ({ publicPath, editorName, inputProps, envVariables, staticHash, remotionRoot, studioServerCommand, renderQueue, completedClientRenders, numberOfAudioTags, publicFiles, includeFavicon, title, renderDefaults, publicFolderExists, gitSource, projectName, installedDependencies, packageManager, audioLatencyHint, logLevel, mode, }: {
staticHash: string;
publicPath: string;
editorName: string | null;
inputProps: object | null;
envVariables?: Record<string, string>;
remotionRoot: string;
studioServerCommand: string | null;
renderQueue: unknown | null;
completedClientRenders?: unknown | null;
numberOfAudioTags: number;
audioLatencyHint: AudioContextLatencyCategory;
publicFiles: StaticFile[];
publicFolderExists: string | null;
includeFavicon: boolean;
title: string;
renderDefaults: RenderDefaults | undefined;
gitSource: GitSource | null;
projectName: string;
installedDependencies: string[] | null;
packageManager: PackageManager | "unknown";
logLevel: LogLevel;
mode: "dev" | "bundle";
}) => string;
@@ -0,0 +1,76 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.indexHtml = void 0;
const remotion_1 = require("remotion");
const indexHtml = ({ publicPath, editorName, inputProps, envVariables, staticHash, remotionRoot, studioServerCommand, renderQueue, completedClientRenders, numberOfAudioTags, publicFiles, includeFavicon, title, renderDefaults, publicFolderExists, gitSource, projectName, installedDependencies, packageManager, audioLatencyHint, logLevel, mode, }) =>
// Must setup remotion_editorName and remotion.remotion_projectName before bundle.js is loaded
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
${includeFavicon
? `<link id="__remotion_favicon" rel="icon" type="image/png" href="${publicPath}favicon.ico" />`
: ''}
<title>${title}</title>
</head>
<body>
<script>window.remotion_numberOfAudioTags = ${numberOfAudioTags};</script>
<script>window.remotion_audioLatencyHint = "${audioLatencyHint}";</script>
${mode === 'dev' ? `<script>window.remotion_logLevel = "${logLevel}";</script>` : ''}
<script>window.remotion_staticBase = "${staticHash}";</script>
${editorName
? `<script>window.remotion_editorName = "${editorName}";</script>`
: '<script>window.remotion_editorName = null;</script>'}
<script>window.remotion_projectName = ${JSON.stringify(projectName)};</script>
<script>window.remotion_publicPath = ${JSON.stringify(publicPath)};</script>
<script>window.remotion_audioEnabled = true;</script>
<script>window.remotion_videoEnabled = true;</script>
<script>window.remotion_renderDefaults = ${JSON.stringify(renderDefaults)};</script>
<script>window.remotion_cwd = ${JSON.stringify(remotionRoot)};</script>
<script>window.remotion_studioServerCommand = ${studioServerCommand ? JSON.stringify(studioServerCommand) : 'null'};</script>
${inputProps
? `<script>window.remotion_inputProps = ${JSON.stringify(JSON.stringify(inputProps))};</script>`
: ''}
${renderQueue
? `<script>window.remotion_initialRenderQueue = ${JSON.stringify(renderQueue)};</script>`
: ''}
${completedClientRenders
? `<script>window.remotion_initialClientRenders = ${JSON.stringify(completedClientRenders)};</script>`
: ''}
${envVariables
? `<script>window.process = {env: ${JSON.stringify(envVariables)}};</script>`
: ''}
${gitSource
? `<script>window.remotion_gitSource = ${JSON.stringify(gitSource)};</script>`
: ''}
${mode === 'dev'
? `
<script>window.remotion_isStudio = true;</script>
<script>window.remotion_isReadOnlyStudio = false;</script>`.trimStart()
: ''}
<script>window.remotion_staticFiles = ${JSON.stringify(publicFiles)}</script>
<script>window.remotion_installedPackages = ${JSON.stringify(installedDependencies)}</script>
<script>window.remotion_packageManager = ${JSON.stringify(packageManager)}</script>
<script>window.remotion_publicFolderExists = ${publicFolderExists ? `"${publicFolderExists}"` : 'null'};</script>
<script>
window.siteVersion = '11';
window.remotion_version = '${remotion_1.VERSION}';
</script>
<div id="video-container"></div>
<div id="${remotion_1.Internals.REMOTION_STUDIO_CONTAINER_ELEMENT}"></div>
<div id="menuportal-0"></div>
<div id="menuportal-1"></div>
<div id="menuportal-2"></div>
<div id="menuportal-3"></div>
<div id="menuportal-4"></div>
<div id="menuportal-5"></div>
<div id="remotion-error-overlay"></div>
<div id="server-disconnected-overlay"></div>
<script src="${publicPath}bundle.js"></script>
</body>
</html>
`.trim();
exports.indexHtml = indexHtml;
@@ -0,0 +1,83 @@
import esbuild = require('esbuild');
import webpack = require('webpack');
export declare const BundlerInternals: {
esbuild: typeof esbuild;
webpackConfig: ({ entry, userDefinedComponent, outDir, environment, webpackOverride, onProgress, enableCaching, maxTimelineTracks, remotionRoot, keyboardShortcutsEnabled, bufferStateDelayInMilliseconds, poll, experimentalClientSideRenderingEnabled, askAIEnabled, }: {
entry: string;
userDefinedComponent: string;
outDir: string | null;
environment: "development" | "production";
webpackOverride: import("./webpack-config").WebpackOverrideFn;
onProgress?: (f: number) => void;
enableCaching?: boolean;
maxTimelineTracks: number | null;
keyboardShortcutsEnabled: boolean;
bufferStateDelayInMilliseconds: number | null;
remotionRoot: string;
poll: number | null;
askAIEnabled: boolean;
experimentalClientSideRenderingEnabled: boolean;
}) => Promise<[string, import("./webpack-config").WebpackConfiguration]>;
indexHtml: ({ publicPath, editorName, inputProps, envVariables, staticHash, remotionRoot, studioServerCommand, renderQueue, completedClientRenders, numberOfAudioTags, publicFiles, includeFavicon, title, renderDefaults, publicFolderExists, gitSource, projectName, installedDependencies, packageManager, audioLatencyHint, logLevel, mode, }: {
staticHash: string;
publicPath: string;
editorName: string | null;
inputProps: object | null;
envVariables?: Record<string, string>;
remotionRoot: string;
studioServerCommand: string | null;
renderQueue: unknown | null;
completedClientRenders?: unknown | null;
numberOfAudioTags: number;
audioLatencyHint: AudioContextLatencyCategory;
publicFiles: import("remotion").StaticFile[];
publicFolderExists: string | null;
includeFavicon: boolean;
title: string;
renderDefaults: import("@remotion/studio-shared").RenderDefaults | undefined;
gitSource: import("@remotion/studio-shared").GitSource | null;
projectName: string;
installedDependencies: string[] | null;
packageManager: import("@remotion/studio-shared").PackageManager | "unknown";
logLevel: import("remotion").LogLevel;
mode: "dev" | "bundle";
}) => string;
cacheExists: (remotionRoot: string, environment: "development" | "production", hash: string) => "exists" | "other-exists" | "does-not-exist";
clearCache: (remotionRoot: string, env: "development" | "production") => Promise<void>;
getConfig: ({ entryPoint, outDir, resolvedRemotionRoot, onProgress, options, bufferStateDelayInMilliseconds, maxTimelineTracks, experimentalClientSideRenderingEnabled, }: {
outDir: string;
entryPoint: string;
resolvedRemotionRoot: string;
bufferStateDelayInMilliseconds: number | null;
experimentalClientSideRenderingEnabled: boolean;
maxTimelineTracks: number | null;
onProgress?: (progress: number) => void;
options?: import("./bundle").LegacyBundleOptions;
}) => Promise<[string, webpack.Configuration]>;
readRecursively: ({ folder, output, startPath, staticHash, limit, }: {
folder: string;
startPath: string;
output?: import("remotion").StaticFile[];
staticHash: string;
limit: number;
}) => import("remotion").StaticFile[];
findClosestFolderWithItem: (currentDir: string, file: string) => string | null;
internalBundle: (actualArgs: {
entryPoint: string;
} & {
entryPoint: string;
onProgress: (progress: number) => void;
ignoreRegisterRootWarning: boolean;
onDirectoryCreated: (dir: string) => void;
gitSource: import("@remotion/studio-shared").GitSource | null;
maxTimelineTracks: number | null;
bufferStateDelayInMilliseconds: number | null;
audioLatencyHint: AudioContextLatencyCategory | null;
experimentalClientSideRenderingEnabled: boolean;
renderDefaults: import("@remotion/studio-shared").RenderDefaults | null;
} & import("./bundle").MandatoryLegacyBundleOptions) => Promise<string>;
};
export type { GitSource } from '@remotion/studio-shared';
export { bundle, BundleOptions, LegacyBundleOptions, MandatoryLegacyBundleOptions, } from './bundle';
export { WebpackConfiguration, WebpackOverrideFn } from './webpack-config';
export { webpack };
@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.webpack = exports.bundle = exports.BundlerInternals = void 0;
const bundle_1 = require("./bundle");
const index_html_1 = require("./index-html");
const read_recursively_1 = require("./read-recursively");
const webpack_cache_1 = require("./webpack-cache");
const webpack_config_1 = require("./webpack-config");
const esbuild = require("esbuild");
const webpack = require("webpack");
exports.webpack = webpack;
exports.BundlerInternals = {
esbuild,
webpackConfig: webpack_config_1.webpackConfig,
indexHtml: index_html_1.indexHtml,
cacheExists: webpack_cache_1.cacheExists,
clearCache: webpack_cache_1.clearCache,
getConfig: bundle_1.getConfig,
readRecursively: read_recursively_1.readRecursively,
findClosestFolderWithItem: bundle_1.findClosestFolderWithItem,
internalBundle: bundle_1.internalBundle,
};
var bundle_2 = require("./bundle");
Object.defineProperty(exports, "bundle", { enumerable: true, get: function () { return bundle_2.bundle; } });
@@ -0,0 +1,5 @@
import type { Compiler } from 'webpack';
export declare class AllowOptionalDependenciesPlugin {
filter(error: Error): boolean;
apply(compiler: Compiler): void;
}
@@ -0,0 +1,37 @@
"use strict";
// When Webpack cannot resolve these dependencies, it will not print an error message.
Object.defineProperty(exports, "__esModule", { value: true });
exports.AllowOptionalDependenciesPlugin = void 0;
const OPTIONAL_DEPENDENCIES = [
'zod',
'@remotion/zod-types',
'react-native-reanimated',
'react-native-reanimated/package.json',
];
const SOURCE_MAP_IGNORE = ['path', 'fs'];
class AllowOptionalDependenciesPlugin {
filter(error) {
for (const dependency of OPTIONAL_DEPENDENCIES) {
if (error.message.includes(`Can't resolve '${dependency}'`)) {
return false;
}
}
for (const dependency of SOURCE_MAP_IGNORE) {
if (error.message.includes(`Can't resolve '${dependency}'`) &&
error.message.includes('source-map')) {
return false;
}
}
return true;
}
apply(compiler) {
compiler.hooks.afterCompile.tap('Com', (compilation) => {
compilation.errors = compilation.errors.filter(this.filter);
});
compiler.hooks.afterEmit.tap('AllowOptionalDependenciesPlugin', (compilation) => {
compilation.errors = compilation.errors.filter(this.filter);
compilation.warnings = compilation.warnings.filter(this.filter);
});
}
}
exports.AllowOptionalDependenciesPlugin = AllowOptionalDependenciesPlugin;
@@ -0,0 +1,8 @@
import type { StaticFile } from 'remotion';
export declare const readRecursively: ({ folder, output, startPath, staticHash, limit, }: {
folder: string;
startPath: string;
output?: StaticFile[];
staticHash: string;
limit: number;
}) => StaticFile[];
@@ -0,0 +1,113 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.readRecursively = void 0;
const node_fs_1 = __importStar(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
// There can be symbolic links that point to files that don't exist.
// https://github.com/remotion-dev/remotion/issues/2587
const statOrNull = (p) => {
try {
return (0, node_fs_1.statSync)(p);
}
catch (_a) {
return null;
}
};
const encodeBySplitting = (p) => {
// Intentional: split by path.sep, then join by /
const splitBySlash = p.split(node_path_1.default.sep);
const encodedArray = splitBySlash.map((element) => {
return encodeURIComponent(element);
});
const merged = encodedArray.join('/');
return merged;
};
const readRecursively = ({ folder, output = [], startPath, staticHash, limit, }) => {
const absFolder = node_path_1.default.join(startPath, folder);
if (!node_fs_1.default.existsSync(absFolder)) {
return [];
}
const files = node_fs_1.default.readdirSync(absFolder);
for (const file of files) {
if (output.length >= limit) {
break;
}
if (file.startsWith('.DS_Store')) {
continue;
}
const stat = statOrNull(node_path_1.default.join(absFolder, file));
if (!stat) {
continue;
}
if (stat.isDirectory()) {
(0, exports.readRecursively)({
startPath,
folder: node_path_1.default.join(folder, file),
output,
staticHash,
limit,
});
}
else if (stat.isFile()) {
output.push({
name: node_path_1.default.join(folder, file),
lastModified: Math.floor(stat.mtimeMs),
sizeInBytes: stat.size,
src: staticHash + '/' + encodeBySplitting(node_path_1.default.join(folder, file)),
});
}
else if (stat.isSymbolicLink()) {
const realpath = node_fs_1.default.realpathSync(node_path_1.default.join(folder, file));
const realStat = statOrNull(realpath);
if (!realStat) {
continue;
}
if (realStat.isFile()) {
output.push({
name: realpath,
lastModified: Math.floor(realStat.mtimeMs),
sizeInBytes: realStat.size,
src: staticHash + '/' + encodeBySplitting(realpath),
});
}
}
}
return output.sort((a, b) => a.name.localeCompare(b.name));
};
exports.readRecursively = readRecursively;
@@ -0,0 +1 @@
export declare const injectCSS: (css: string) => void;
@@ -0,0 +1,142 @@
"use strict";
// https://github.com/remotion-dev/remotion/issues/3412#issuecomment-1910120552
Object.defineProperty(exports, "__esModule", { value: true });
exports.injectCSS = void 0;
function getEnvVar() {
const parts = ['proc', 'ess', '.', 'en', 'v', '.', 'NOD', 'E_EN', 'V'];
return parts.join('');
}
const getEnvVariables = () => {
if (window.remotion_isStudio) {
// For the Studio, we already set the environment variables in index-html.ts.
// We just add NODE_ENV here.
if (!process.env.NODE_ENV) {
throw new Error(`${getEnvVar()} is not set`);
}
return {
NODE_ENV: process.env.NODE_ENV,
};
}
const param = window.remotion_envVariables;
if (!param) {
return {};
}
return { ...JSON.parse(param), NODE_ENV: process.env.NODE_ENV };
};
const setupEnvVariables = () => {
const env = getEnvVariables();
if (!window.process) {
window.process = {};
}
if (!window.process.env) {
window.process.env = {};
}
Object.keys(env).forEach((key) => {
window.process.env[key] = env[key];
});
};
setupEnvVariables();
const injected = {};
const injectCSS = (css) => {
// Skip in node
if (typeof document === 'undefined') {
return;
}
if (injected[css]) {
return;
}
const head = document.head || document.getElementsByTagName('head')[0];
const style = document.createElement('style');
style.appendChild(document.createTextNode(css));
head.prepend(style);
injected[css] = true;
};
exports.injectCSS = injectCSS;
(0, exports.injectCSS)(`
.css-reset, .css-reset * {
font-size: 16px;
line-height: 1.5;
color: white;
font-family: Arial, Helvetica, sans-serif;
background: transparent;
box-sizing: border-box;
}
.algolia-docsearch-suggestion--highlight {
font-size: 15px;
line-height: 1.25;
}
.__remotion-info-button-container code {
font-family: monospace;
font-size: 14px;
color: #0584f2
}
.__remotion-vertical-scrollbar::-webkit-scrollbar {
width: 6px;
}
.__remotion-vertical-scrollbar::-webkit-scrollbar-thumb {
background-color: rgba(0, 0, 0, 0.0);
}
.__remotion-vertical-scrollbar:hover::-webkit-scrollbar-thumb {
background-color: rgba(0, 0, 0, 0.6);
}
.__remotion-vertical-scrollbar:hover::-webkit-scrollbar-thumb:hover {
background-color: rgba(0, 0, 0, 1);
}
.__remotion-horizontal-scrollbar::-webkit-scrollbar {
height: 6px;
}
.__remotion-horizontal-scrollbar::-webkit-scrollbar-thumb {
background-color: rgba(0, 0, 0, 0.0);
}
.__remotion-horizontal-scrollbar:hover::-webkit-scrollbar-thumb {
background-color: rgba(0, 0, 0, 0.6);
}
.__remotion-horizontal-scrollbar:hover::-webkit-scrollbar-thumb:hover {
background-color: rgba(0, 0, 0, 1);
}
@-moz-document url-prefix() {
.__remotion-vertical-scrollbar {
scrollbar-width: thin;
scrollbar-color: rgba(0, 0, 0, 0.6) rgba(0, 0, 0, 0);
}
.__remotion-vertical-scrollbar:hover {
scrollbar-color: rgba(0, 0, 0, 1) rgba(0, 0, 0, 0);
}
.__remotion-horizontal-scrollbar {
scrollbar-width: thin;
scrollbar-color: rgba(0, 0, 0, 0.6) rgba(0, 0, 0, 0);
}
.__remotion-horizontal-scrollbar:hover {
scrollbar-width: thin;
scrollbar-color: rgba(0, 0, 0, 1) rgba(0, 0, 0, 0);
}
}
.__remotion-timeline-slider {
appearance: none;
width: 100px;
border-radius: 3px;
height: 6px;
background-color: rgba(255, 255, 255, 0.1);
accent-color: #ffffff;
}
.__remotion-timeline-slider::-moz-range-thumb {
width: 14px;
height: 14px;
border-radius: 50%;
background-color: #ffffff;
appearance: none;
}
`);
@@ -0,0 +1 @@
export declare const jsonStringifyWithCircularReferences: (circ: unknown) => string;
@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.jsonStringifyWithCircularReferences = void 0;
const jsonStringifyWithCircularReferences = (circ) => {
let seen = [];
const val = JSON.stringify(circ, (_, value) => {
if (typeof value === 'object' && value !== null && seen) {
if (seen.includes(value)) {
return '[Circular]';
}
seen.push(value);
}
return value;
});
seen = null;
return val;
};
exports.jsonStringifyWithCircularReferences = jsonStringifyWithCircularReferences;
@@ -0,0 +1 @@
export declare const validatePublicDir: (p: string) => void;
@@ -0,0 +1,30 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.validatePublicDir = void 0;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const validatePublicDir = (p) => {
const { root } = node_path_1.default.parse(process.cwd());
if (p === root) {
throw new Error(`The public directory was specified as "${p}", which is the root directory. This is not allowed.`);
}
try {
const stat = node_fs_1.default.lstatSync(p);
if (!stat.isDirectory()) {
throw new Error(`The public directory was specified as "${p}", and while this path exists on the filesystem, it is not a directory.`);
}
}
catch (_a) {
// Path does not exist
// Check if the parent path exists
const parentPath = node_path_1.default.dirname(p);
const exists = node_fs_1.default.existsSync(parentPath);
if (!exists) {
throw new Error(`The public directory was specified as "${p}", but this folder does not exist and the parent directory "${parentPath}" does also not exist. Create at least the parent directory.`);
}
}
};
exports.validatePublicDir = validatePublicDir;
@@ -0,0 +1,14 @@
type Environment = 'development' | 'production';
type CacheState = 'exists' | 'other-exists' | 'does-not-exist';
declare global {
namespace NodeJS {
interface ProcessVersions {
pnp?: string;
}
}
}
export declare const getWebpackCacheEnvDir: (environment: Environment) => string;
export declare const getWebpackCacheName: (environment: Environment, hash: string) => string;
export declare const clearCache: (remotionRoot: string, env: Environment) => Promise<void>;
export declare const cacheExists: (remotionRoot: string, environment: Environment, hash: string) => CacheState;
export {};
@@ -0,0 +1,83 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.cacheExists = exports.clearCache = exports.getWebpackCacheName = exports.getWebpackCacheEnvDir = void 0;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const version_1 = require("remotion/version");
// Inlined from https://github.com/webpack/webpack/blob/4c2ee7a4ddb8db2362ca83b6c4190523387ba7ee/lib/config/defaults.js#L265
// An algorithm to determine where Webpack will cache the depencies
const getWebpackCacheDir = (remotionRoot) => {
let dir = remotionRoot;
for (;;) {
try {
if (node_fs_1.default.statSync(node_path_1.default.join(dir, 'package.json')).isFile()) {
break;
}
}
catch (_a) { }
const parent = node_path_1.default.dirname(dir);
if (dir === parent) {
dir = undefined;
break;
}
dir = parent;
}
if (!dir) {
return node_path_1.default.resolve(remotionRoot, '.cache/webpack');
}
if (process.versions.pnp === '1') {
return node_path_1.default.resolve(dir, '.pnp/.cache/webpack');
}
if (process.versions.pnp === '3') {
return node_path_1.default.resolve(dir, '.yarn/.cache/webpack');
}
return node_path_1.default.resolve(dir, 'node_modules/.cache/webpack');
};
const getPrefix = (environment) => {
return `remotion-${environment}-${version_1.VERSION}`;
};
const getWebpackCacheEnvDir = (environment) => {
return getPrefix(environment);
};
exports.getWebpackCacheEnvDir = getWebpackCacheEnvDir;
const getWebpackCacheName = (environment, hash) => {
return [(0, exports.getWebpackCacheEnvDir)(environment), hash].join(node_path_1.default.sep);
};
exports.getWebpackCacheName = getWebpackCacheName;
const remotionCacheLocationForEnv = (remotionRoot, environment) => {
return node_path_1.default.join(getWebpackCacheDir(remotionRoot), (0, exports.getWebpackCacheEnvDir)(environment));
};
const remotionCacheLocation = (remotionRoot, environment, hash) => {
return node_path_1.default.join(getWebpackCacheDir(remotionRoot), (0, exports.getWebpackCacheName)(environment, hash));
};
const clearCache = (remotionRoot, env) => {
return node_fs_1.default.promises.rm(remotionCacheLocationForEnv(remotionRoot, env), {
recursive: true,
});
};
exports.clearCache = clearCache;
const hasOtherCache = ({ remotionRoot, environment, }) => {
const cacheDir = node_fs_1.default.readdirSync(getWebpackCacheDir(remotionRoot));
if (cacheDir.find((c) => {
return c.startsWith(getPrefix(environment));
})) {
return true;
}
return false;
};
const cacheExists = (remotionRoot, environment, hash) => {
if (node_fs_1.default.existsSync(remotionCacheLocation(remotionRoot, environment, hash))) {
return 'exists';
}
if (!node_fs_1.default.existsSync(getWebpackCacheDir(remotionRoot))) {
return 'does-not-exist';
}
if (hasOtherCache({ remotionRoot, environment })) {
return 'other-exists';
}
return 'does-not-exist';
};
exports.cacheExists = cacheExists;
@@ -0,0 +1,19 @@
import type { Configuration } from 'webpack';
export type WebpackConfiguration = Configuration;
export type WebpackOverrideFn = (currentConfiguration: WebpackConfiguration) => WebpackConfiguration | Promise<WebpackConfiguration>;
export declare const webpackConfig: ({ entry, userDefinedComponent, outDir, environment, webpackOverride, onProgress, enableCaching, maxTimelineTracks, remotionRoot, keyboardShortcutsEnabled, bufferStateDelayInMilliseconds, poll, experimentalClientSideRenderingEnabled, askAIEnabled, }: {
entry: string;
userDefinedComponent: string;
outDir: string | null;
environment: "development" | "production";
webpackOverride: WebpackOverrideFn;
onProgress?: (f: number) => void;
enableCaching?: boolean;
maxTimelineTracks: number | null;
keyboardShortcutsEnabled: boolean;
bufferStateDelayInMilliseconds: number | null;
remotionRoot: string;
poll: number | null;
askAIEnabled: boolean;
experimentalClientSideRenderingEnabled: boolean;
}) => Promise<[string, WebpackConfiguration]>;
@@ -0,0 +1,234 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.webpackConfig = void 0;
const node_crypto_1 = require("node:crypto");
const node_path_1 = __importDefault(require("node:path"));
const react_dom_1 = __importDefault(require("react-dom"));
const no_react_1 = require("remotion/no-react");
const webpack_1 = __importStar(require("webpack"));
const case_sensitive_paths_1 = require("./case-sensitive-paths");
const fast_refresh_1 = require("./fast-refresh");
const hide_expression_dependency_1 = require("./hide-expression-dependency");
const ignore_packfilecache_warnings_1 = require("./ignore-packfilecache-warnings");
const optional_dependencies_1 = require("./optional-dependencies");
const stringify_with_circular_references_1 = require("./stringify-with-circular-references");
const webpack_cache_1 = require("./webpack-cache");
const esbuild = require("esbuild");
if (!(react_dom_1.default === null || react_dom_1.default === void 0 ? void 0 : react_dom_1.default.version)) {
throw new Error('Could not find "react-dom" package. Did you install it?');
}
const reactDomVersion = react_dom_1.default.version.split('.')[0];
if (reactDomVersion === '0') {
throw new Error(`Version ${reactDomVersion} of "react-dom" is not supported by Remotion`);
}
const shouldUseReactDomClient = no_react_1.NoReactInternals.ENABLE_V5_BREAKING_CHANGES
? true
: parseInt(reactDomVersion, 10) >= 18;
function truthy(value) {
return Boolean(value);
}
const webpackConfig = async ({ entry, userDefinedComponent, outDir, environment, webpackOverride = (f) => f, onProgress, enableCaching = true, maxTimelineTracks, remotionRoot, keyboardShortcutsEnabled, bufferStateDelayInMilliseconds, poll, experimentalClientSideRenderingEnabled, askAIEnabled, }) => {
const esbuildLoaderOptions = {
target: 'chrome85',
loader: 'tsx',
implementation: esbuild,
remotionRoot,
};
let lastProgress = 0;
const isBun = typeof Bun !== 'undefined';
const define = new webpack_1.default.DefinePlugin({
'process.env.MAX_TIMELINE_TRACKS': maxTimelineTracks,
'process.env.ASK_AI_ENABLED': askAIEnabled,
'process.env.KEYBOARD_SHORTCUTS_ENABLED': keyboardShortcutsEnabled,
'process.env.BUFFER_STATE_DELAY_IN_MILLISECONDS': bufferStateDelayInMilliseconds,
'process.env.EXPERIMENTAL_CLIENT_SIDE_RENDERING_ENABLED': experimentalClientSideRenderingEnabled,
});
const conf = await webpackOverride({
optimization: {
minimize: false,
},
experiments: {
lazyCompilation: isBun
? false
: environment === 'production'
? false
: {
entries: false,
},
},
watchOptions: {
poll: poll !== null && poll !== void 0 ? poll : undefined,
aggregateTimeout: 0,
ignored: ['**/.git/**', '**/.turbo/**', '**/node_modules/**'],
},
// Higher source map quality in development to power line numbers for stack traces
devtool: environment === 'development' ? 'source-map' : 'cheap-module-source-map',
entry: [
// Fast Refresh must come first,
// because setup-environment imports ReactDOM.
// If React DOM is imported before Fast Refresh, Fast Refresh does not work
environment === 'development'
? require.resolve('./fast-refresh/runtime.js')
: null,
require.resolve('./setup-environment'),
userDefinedComponent,
require.resolve('../react-shim.js'),
entry,
].filter(Boolean),
mode: environment,
plugins: environment === 'development'
? [
new fast_refresh_1.ReactFreshWebpackPlugin(),
new case_sensitive_paths_1.CaseSensitivePathsPlugin(),
new webpack_1.default.HotModuleReplacementPlugin(),
define,
new optional_dependencies_1.AllowOptionalDependenciesPlugin(),
new hide_expression_dependency_1.AllowDependencyExpressionPlugin(),
new ignore_packfilecache_warnings_1.IgnorePackFileCacheWarningsPlugin(),
]
: [
new webpack_1.ProgressPlugin((p) => {
if (onProgress) {
if ((p === 1 && p > lastProgress) || p - lastProgress > 0.05) {
lastProgress = p;
onProgress(Number((p * 100).toFixed(2)));
}
}
}),
define,
new optional_dependencies_1.AllowOptionalDependenciesPlugin(),
new hide_expression_dependency_1.AllowDependencyExpressionPlugin(),
new ignore_packfilecache_warnings_1.IgnorePackFileCacheWarningsPlugin(),
],
output: {
hashFunction: 'xxhash64',
filename: no_react_1.NoReactInternals.bundleName,
devtoolModuleFilenameTemplate: '[resource-path]',
assetModuleFilename: environment === 'development' ? '[path][name][ext]' : '[hash][ext]',
},
resolve: {
extensions: ['.ts', '.tsx', '.web.js', '.js', '.jsx', '.mjs', '.cjs'],
alias: {
// Only one version of react
'react/jsx-runtime': require.resolve('react/jsx-runtime'),
'react/jsx-dev-runtime': require.resolve('react/jsx-dev-runtime'),
react: require.resolve('react'),
// Needed to not fail on this: https://github.com/remotion-dev/remotion/issues/5045
'remotion/no-react': node_path_1.default.resolve(require.resolve('remotion'), '..', '..', 'esm', 'no-react.mjs'),
'remotion/version': node_path_1.default.resolve(require.resolve('remotion'), '..', '..', 'esm', 'version.mjs'),
remotion: node_path_1.default.resolve(require.resolve('remotion'), '..', '..', 'esm', 'index.mjs'),
'@remotion/media-parser/worker': node_path_1.default.resolve(require.resolve('@remotion/media-parser'), '..', 'esm', 'worker.mjs'),
// test visual controls before removing this
'@remotion/studio': require.resolve('@remotion/studio'),
'react-dom/client': shouldUseReactDomClient
? require.resolve('react-dom/client')
: require.resolve('react-dom'),
},
},
module: {
rules: [
{
test: /\.css$/i,
use: [require.resolve('style-loader'), require.resolve('css-loader')],
type: 'javascript/auto',
},
{
test: /\.(png|svg|jpg|jpeg|webp|gif|bmp|webm|mp4|mov|mp3|m4a|wav|aac)$/,
type: 'asset/resource',
},
{
test: /\.tsx?$/,
use: [
{
loader: require.resolve('./esbuild-loader/index.js'),
options: esbuildLoaderOptions,
},
// Keep the order to match babel-loader
environment === 'development'
? {
loader: require.resolve('./fast-refresh/loader.js'),
}
: null,
].filter(truthy),
},
{
test: /\.(woff(2)?|otf|ttf|eot)(\?v=\d+\.\d+\.\d+)?$/,
type: 'asset/resource',
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: require.resolve('./esbuild-loader/index.js'),
options: esbuildLoaderOptions,
},
environment === 'development'
? {
loader: require.resolve('./fast-refresh/loader.js'),
}
: null,
].filter(truthy),
},
],
},
});
const hash = (0, node_crypto_1.createHash)('md5')
.update((0, stringify_with_circular_references_1.jsonStringifyWithCircularReferences)(conf))
.digest('hex');
return [
hash,
{
...conf,
cache: enableCaching
? {
type: 'filesystem',
name: (0, webpack_cache_1.getWebpackCacheName)(environment, hash),
version: hash,
}
: false,
output: {
...conf.output,
...(outDir ? { path: outDir } : {}),
},
context: remotionRoot,
},
];
};
exports.webpackConfig = webpackConfig;
Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

@@ -0,0 +1,55 @@
{
"repository": {
"url": "https://github.com/remotion-dev/remotion/tree/main/packages/bundler"
},
"name": "@remotion/bundler",
"version": "4.0.423",
"description": "Bundle Remotion compositions using Webpack",
"main": "dist/index.js",
"sideEffects": false,
"bugs": {
"url": "https://github.com/remotion-dev/remotion/issues"
},
"scripts": {
"formatting": "prettier --experimental-cli src --check",
"lint": "eslint src",
"test": "bun test src",
"make": "tsc -d"
},
"author": "Jonny Burger <jonny@remotion.dev>",
"license": "SEE LICENSE IN LICENSE.md",
"dependencies": {
"css-loader": "5.2.7",
"esbuild": "0.25.0",
"react-refresh": "0.9.0",
"remotion": "4.0.423",
"@remotion/studio": "4.0.423",
"@remotion/studio-shared": "4.0.423",
"@remotion/media-parser": "4.0.423",
"style-loader": "4.0.0",
"source-map": "0.7.3",
"webpack": "5.105.0"
},
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
},
"devDependencies": {
"react": "19.2.3",
"react-dom": "19.2.3",
"@remotion/eslint-config-internal": "4.0.423",
"eslint": "9.19.0"
},
"keywords": [
"remotion",
"ffmpeg",
"video",
"react",
"webpack",
"player"
],
"publishConfig": {
"access": "public"
},
"homepage": "https://www.remotion.dev/docs/bundler"
}
@@ -0,0 +1,7 @@
import * as React from 'react';
if (typeof globalThis === 'undefined') {
window.React = React;
} else {
globalThis.React = React;
}
+18
View File
@@ -0,0 +1,18 @@
# @remotion/cli
Control Remotion features using the `npx remotion` command
[![NPM Downloads](https://img.shields.io/npm/dm/@remotion/cli.svg?style=flat&color=black&label=Downloads)](https://npmcharts.com/compare/@remotion/cli?minimal=true)
## Installation
```bash
npm install @remotion/cli --save-exact
```
When installing a Remotion package, make sure to align the version of all `remotion` and `@remotion/*` packages to the same version.
Remove the `^` character from the version number to use the exact version.
## Usage
See the [documentation](https://www.remotion.dev/docs/cli) for more information.
@@ -0,0 +1,8 @@
import { type LogLevel } from '@remotion/renderer';
export declare const addCommand: ({ remotionRoot, packageManager, packageNames, logLevel, args, }: {
remotionRoot: string;
packageManager: string | undefined;
packageNames: string[];
logLevel: LogLevel;
args: string[];
}) => Promise<void>;
+167
View File
@@ -0,0 +1,167 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.addCommand = void 0;
const renderer_1 = require("@remotion/renderer");
const studio_server_1 = require("@remotion/studio-server");
const node_child_process_1 = require("node:child_process");
const node_fs_1 = __importDefault(require("node:fs"));
const chalk_1 = require("./chalk");
const extra_packages_1 = require("./extra-packages");
const list_of_remotion_packages_1 = require("./list-of-remotion-packages");
const log_1 = require("./log");
const resolve_from_1 = require("./resolve-from");
const getInstalledVersion = (remotionRoot, pkg) => {
try {
const pkgJsonPath = (0, resolve_from_1.resolveFrom)(remotionRoot, `${pkg}/package.json`);
const file = node_fs_1.default.readFileSync(pkgJsonPath, 'utf-8');
const packageJson = JSON.parse(file);
return packageJson.version;
}
catch (_a) {
return null;
}
};
const addCommand = async ({ remotionRoot, packageManager, packageNames, logLevel, args, }) => {
// Validate that all package names are Remotion packages
const invalidPackages = packageNames.filter((pkg) => !list_of_remotion_packages_1.listOfRemotionPackages.includes(pkg) && !extra_packages_1.EXTRA_PACKAGES[pkg]);
if (invalidPackages.length > 0) {
throw new Error(`The following packages are not Remotion packages: ${invalidPackages.join(', ')}. Must be one of the Remotion packages or one of the supported extra packages: ${Object.keys(extra_packages_1.EXTRA_PACKAGES).join(', ')}.`);
}
const { dependencies, devDependencies, optionalDependencies, peerDependencies, } = studio_server_1.StudioServerInternals.getInstalledDependencies(remotionRoot);
// Check if packages are already installed
const allDeps = [
...dependencies,
...devDependencies,
...optionalDependencies,
...peerDependencies,
];
const alreadyInstalled = [];
const toInstall = [];
const toUpgrade = [];
for (const pkg of packageNames) {
const isInstalled = allDeps.includes(pkg);
const requiredVersion = extra_packages_1.EXTRA_PACKAGES[pkg];
if (!isInstalled) {
toInstall.push(pkg);
}
else if (requiredVersion) {
// For extra packages, check if the version is correct
const installedVersion = getInstalledVersion(remotionRoot, pkg);
if (installedVersion !== requiredVersion) {
toUpgrade.push({
pkg,
from: installedVersion !== null && installedVersion !== void 0 ? installedVersion : 'unknown',
to: requiredVersion,
});
toInstall.push(pkg);
}
else {
alreadyInstalled.push(pkg);
}
}
else {
alreadyInstalled.push(pkg);
}
}
// Log already installed packages
for (const pkg of alreadyInstalled) {
log_1.Log.info({ indent: false, logLevel }, `${pkg} ${chalk_1.chalk.gray('(already installed)')}`);
}
// Log packages that will be upgraded
for (const { pkg, from, to } of toUpgrade) {
log_1.Log.info({ indent: false, logLevel }, `${pkg} ${chalk_1.chalk.yellow(`${from}${to}`)}`);
}
// If nothing to install, return early
if (toInstall.length === 0) {
return;
}
const installedRemotionPackages = list_of_remotion_packages_1.listOfRemotionPackages.filter((pkg) => allDeps.includes(pkg));
// Get the version from the first installed Remotion package
const packageJsonPath = `${remotionRoot}/node_modules/${installedRemotionPackages[0]}/package.json`;
let targetVersion = null;
if (installedRemotionPackages.length > 0) {
try {
const packageJson = require(packageJsonPath);
targetVersion = packageJson.version;
const packageList = toInstall.length === 1
? toInstall[0]
: `${toInstall.length} packages (${toInstall.join(', ')})`;
log_1.Log.info({ indent: false, logLevel }, `Installing ${packageList}`);
}
catch (err) {
throw new Error(`Could not determine version of installed Remotion packages: ${err.message}`);
}
}
else {
// If no Remotion packages are installed, we can only install extra packages
const notExtraPackages = toInstall.filter((pkg) => !extra_packages_1.EXTRA_PACKAGES[pkg]);
if (notExtraPackages.length > 0) {
throw new Error('No Remotion packages found in your project. Install Remotion first.');
}
}
const manager = studio_server_1.StudioServerInternals.getPackageManager({
remotionRoot,
packageManager,
dirUp: 0,
logLevel,
});
if (manager === 'unknown') {
throw new Error(`No lockfile was found in your project (one of ${studio_server_1.StudioServerInternals.lockFilePaths
.map((p) => p.path)
.join(', ')}). Install dependencies using your favorite manager!`);
}
const packagesWithVersions = toInstall.map((pkg) => {
if (extra_packages_1.EXTRA_PACKAGES[pkg]) {
return `${pkg}@${extra_packages_1.EXTRA_PACKAGES[pkg]}`;
}
return `${pkg}@${targetVersion}`;
});
const command = studio_server_1.StudioServerInternals.getInstallCommand({
manager: manager.manager,
packages: packagesWithVersions,
version: '',
additionalArgs: args,
});
log_1.Log.info({ indent: false, logLevel }, chalk_1.chalk.gray(`$ ${manager.manager} ${command.join(' ')}`));
const task = (0, node_child_process_1.spawn)(manager.manager, command, {
env: {
...process.env,
ADBLOCK: '1',
DISABLE_OPENCOLLECTIVE: '1',
npm_config_loglevel: 'error',
},
stdio: renderer_1.RenderInternals.isEqualOrBelowLogLevel(logLevel, 'info')
? 'inherit'
: 'ignore',
});
await new Promise((resolve) => {
task.on('close', (code) => {
if (code === 0) {
resolve();
}
else if (renderer_1.RenderInternals.isEqualOrBelowLogLevel(logLevel, 'info')) {
throw new Error(`Failed to install packages, see logs above`);
}
else {
throw new Error(`Failed to install packages, run with --log=info to see logs`);
}
});
});
const upgradedPkgs = new Set(toUpgrade.map((u) => u.pkg));
for (const pkg of toInstall) {
if (upgradedPkgs.has(pkg)) {
// Already logged as upgrade
continue;
}
if (extra_packages_1.EXTRA_PACKAGES[pkg]) {
log_1.Log.info({ indent: false, logLevel }, `+ ${pkg}@${extra_packages_1.EXTRA_PACKAGES[pkg]}`);
}
else {
log_1.Log.info({ indent: false, logLevel }, `+ ${pkg}@${targetVersion}`);
}
}
};
exports.addCommand = addCommand;
@@ -0,0 +1,2 @@
import type { LogLevel } from '@remotion/renderer';
export declare const benchmarkCommand: (remotionRoot: string, args: string[], logLevel: LogLevel) => Promise<void>;
@@ -0,0 +1,402 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.benchmarkCommand = void 0;
const renderer_1 = require("@remotion/renderer");
const client_1 = require("@remotion/renderer/client");
const no_react_1 = require("remotion/no-react");
const browser_download_bar_1 = require("./browser-download-bar");
const chalk_1 = require("./chalk");
const cleanup_before_quit_1 = require("./cleanup-before-quit");
const config_1 = require("./config");
const preview_server_1 = require("./config/preview-server");
const convert_entry_point_to_serve_url_1 = require("./convert-entry-point-to-serve-url");
const entry_point_1 = require("./entry-point");
const get_cli_options_1 = require("./get-cli-options");
const image_formats_1 = require("./image-formats");
const log_1 = require("./log");
const make_progress_bar_1 = require("./make-progress-bar");
const parsed_cli_1 = require("./parsed-cli");
const progress_bar_1 = require("./progress-bar");
const setup_cache_1 = require("./setup-cache");
const should_use_non_overlaying_logger_1 = require("./should-use-non-overlaying-logger");
const show_compositions_picker_1 = require("./show-compositions-picker");
const truthy_1 = require("./truthy");
const DEFAULT_RUNS = 3;
const { audioBitrateOption, x264Option, offthreadVideoCacheSizeInBytesOption, scaleOption, crfOption, jpegQualityOption, videoBitrateOption, enforceAudioOption, mutedOption, videoCodecOption, colorSpaceOption, disallowParallelEncodingOption, enableMultiprocessOnLinuxOption, glOption, numberOfGifLoopsOption, encodingMaxRateOption, encodingBufferSizeOption, delayRenderTimeoutInMillisecondsOption, headlessOption, overwriteOption, binariesDirectoryOption, forSeamlessAacConcatenationOption, publicPathOption, publicDirOption, metadataOption, hardwareAccelerationOption, chromeModeOption, offthreadVideoThreadsOption, mediaCacheSizeInBytesOption, darkModeOption, askAIOption, experimentalClientSideRenderingOption, keyboardShortcutsOption, } = client_1.BrowserSafeApis.options;
const getValidConcurrency = (cliConcurrency) => {
const { concurrencies } = parsed_cli_1.parsedCli;
if (!concurrencies) {
return [renderer_1.RenderInternals.resolveConcurrency(cliConcurrency)];
}
return String(concurrencies)
.split(',')
.map((c) => parseInt(c.trim(), 10));
};
const runBenchmark = async (runs, options, onProgress) => {
const timeTaken = [];
for (let run = 0; run < runs; ++run) {
const startTime = performance.now();
await renderer_1.RenderInternals.internalRenderMedia({
onProgress: ({ progress }) => onProgress === null || onProgress === void 0 ? void 0 : onProgress(run, progress),
...options,
});
const endTime = performance.now();
timeTaken.push(endTime - startTime);
}
return timeTaken;
};
const formatTime = (time) => {
let ret = '';
const hours = Math.floor(time / (60 * 60 * 1000));
if (hours) {
ret = `${hours}h`;
}
time %= 60 * 60 * 1000;
const minutes = Math.floor(time / (60 * 1000));
if (minutes) {
ret = `${ret}${minutes}m`;
}
time %= 60 * 1000;
const seconds = (time / 1000).toFixed(5);
if (seconds) {
ret = `${ret}${seconds}s`;
}
return ret;
};
const avg = (time) => time.reduce((prev, curr) => prev + curr) / time.length;
const stdDev = (time) => {
const mean = avg(time);
return Math.sqrt(time.map((x) => (x - mean) ** 2).reduce((a, b) => a + b) / time.length);
};
const getResults = (results, runs) => {
const mean = avg(results);
const dev = stdDev(results);
const max = Math.max(...results);
const min = Math.min(...results);
return ` Time (${chalk_1.chalk.green('mean')} ± ${chalk_1.chalk.green('σ')}): ${chalk_1.chalk.green(formatTime(mean))} ± ${chalk_1.chalk.green(formatTime(dev))}\n Range (${chalk_1.chalk.blue('min')} ... ${chalk_1.chalk.red('max')}): ${chalk_1.chalk.blue(formatTime(min))} ... ${chalk_1.chalk.red(formatTime(max))} \t ${chalk_1.chalk.gray(`${runs} runs`)}
`;
};
const makeBenchmarkProgressBar = ({ totalRuns, run, progress, doneIn, }) => {
const totalProgress = (run + progress) / totalRuns;
return [
`Rendering (${run + 1} out of ${totalRuns} runs)`,
(0, make_progress_bar_1.makeProgressBar)(totalProgress, false),
doneIn === null
? `${(totalProgress * 100).toFixed(2)}% `
: chalk_1.chalk.gray(doneIn),
].join(' ');
};
const benchmarkCommand = async (remotionRoot, args, logLevel) => {
var _a, _b, _c;
const runs = (_a = parsed_cli_1.parsedCli.runs) !== null && _a !== void 0 ? _a : DEFAULT_RUNS;
const { file, reason, remainingArgs } = (0, entry_point_1.findEntryPoint)({
args,
remotionRoot,
logLevel,
allowDirectory: true,
});
if (!file) {
log_1.Log.error({ indent: false, logLevel }, 'No entry file passed.');
log_1.Log.info({ indent: false, logLevel }, 'Pass an additional argument specifying the entry file');
log_1.Log.info({ indent: false, logLevel });
log_1.Log.info({ indent: false, logLevel }, `$ remotion benchmark <entry file>`);
process.exit(1);
}
const fullEntryPoint = (0, convert_entry_point_to_serve_url_1.convertEntryPointToServeUrl)(file);
const { inputProps, envVariables, browserExecutable, proResProfile, frameRange: defaultFrameRange, pixelFormat, everyNthFrame, ffmpegOverride, height, width, concurrency: unparsedConcurrency, disableWebSecurity, userAgent, ignoreCertificateErrors, } = (0, get_cli_options_1.getCliOptions)({
isStill: false,
logLevel,
indent: false,
});
log_1.Log.verbose({ indent: false, logLevel }, 'Entry point:', fullEntryPoint, 'reason:', reason);
const scale = scaleOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const enableMultiProcessOnLinux = enableMultiprocessOnLinuxOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const gl = glOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const headless = headlessOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const publicPath = publicPathOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const publicDir = publicDirOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const chromeMode = chromeModeOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const darkMode = darkModeOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const experimentalClientSideRenderingEnabled = experimentalClientSideRenderingOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const askAIEnabled = askAIOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const keyboardShortcutsEnabled = keyboardShortcutsOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
if (experimentalClientSideRenderingEnabled) {
log_1.Log.warn({ indent: false, logLevel }, 'Enabling WIP client-side rendering. Please see caveats on https://www.remotion.dev/docs/client-side-rendering/.');
}
const chromiumOptions = {
disableWebSecurity,
enableMultiProcessOnLinux,
gl,
headless,
ignoreCertificateErrors,
userAgent,
darkMode,
};
const onBrowserDownload = (0, browser_download_bar_1.defaultBrowserDownloadProgress)({
indent: false,
logLevel,
quiet: (0, parsed_cli_1.quietFlagProvided)(),
onProgress: () => undefined,
});
const indent = false;
await renderer_1.RenderInternals.internalEnsureBrowser({
browserExecutable,
indent,
logLevel,
onBrowserDownload,
chromeMode,
});
const browserInstance = renderer_1.RenderInternals.internalOpenBrowser({
browser: 'chrome',
browserExecutable,
chromiumOptions,
forceDeviceScaleFactor: scale,
indent,
viewport: null,
logLevel,
onBrowserDownload,
chromeMode,
});
const { urlOrBundle: bundleLocation, cleanup: cleanupBundle } = await (0, setup_cache_1.bundleOnCliOrTakeServeUrl)({
fullPath: fullEntryPoint,
publicDir,
remotionRoot,
onProgress: () => undefined,
indentOutput: false,
logLevel,
onDirectoryCreated: (dir) => {
(0, cleanup_before_quit_1.registerCleanupJob)(`Delete ${dir}`, () => renderer_1.RenderInternals.deleteDirectory(dir));
},
quietProgress: false,
quietFlag: (0, parsed_cli_1.quietFlagProvided)(),
outDir: null,
// Not needed for benchmark
gitSource: null,
bufferStateDelayInMilliseconds: null,
maxTimelineTracks: null,
publicPath,
audioLatencyHint: null,
experimentalClientSideRenderingEnabled,
askAIEnabled,
keyboardShortcutsEnabled,
});
(0, cleanup_before_quit_1.registerCleanupJob)(`Deleting bundle`, () => cleanupBundle());
const puppeteerInstance = await browserInstance;
const serializedInputPropsWithCustomSchema = no_react_1.NoReactInternals.serializeJSONWithSpecialTypes({
data: inputProps !== null && inputProps !== void 0 ? inputProps : {},
indent: undefined,
staticBase: null,
}).serializedString;
const comps = await renderer_1.RenderInternals.internalGetCompositions({
serveUrlOrWebpackUrl: bundleLocation,
serializedInputPropsWithCustomSchema,
envVariables,
chromiumOptions,
timeoutInMilliseconds: delayRenderTimeoutInMillisecondsOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value,
port: (0, preview_server_1.getRendererPortFromConfigFileAndCliFlag)(),
puppeteerInstance,
browserExecutable,
indent: false,
onBrowserLog: null,
// Intentionally disabling server to not cache results
server: undefined,
logLevel,
offthreadVideoCacheSizeInBytes: offthreadVideoCacheSizeInBytesOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value,
offthreadVideoThreads: offthreadVideoThreadsOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value,
binariesDirectory: binariesDirectoryOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value,
onBrowserDownload,
chromeMode,
mediaCacheSizeInBytes: mediaCacheSizeInBytesOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value,
onLog: renderer_1.RenderInternals.defaultOnLog,
});
const ids = (remainingArgs[0]
? String(remainingArgs[0])
.split(',')
.map((c) => c.trim())
.filter(truthy_1.truthy)
: await (0, show_compositions_picker_1.showMultiCompositionsPicker)(comps, logLevel));
const compositions = ids.map((compId) => {
const composition = comps.find((c) => c.id === compId);
if (!composition) {
throw new Error(`No composition with the ID "${compId}" found.`);
}
return composition;
});
if (compositions.length === 0) {
log_1.Log.error({ indent: false, logLevel }, 'No composition IDs passed. Add another argument to the command specifying at least 1 composition ID.');
}
const benchmark = {};
let count = 1;
const x264Preset = x264Option.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const audioBitrate = audioBitrateOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const configFileCrf = crfOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const jpegQuality = jpegQualityOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const videoBitrate = videoBitrateOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const enforceAudioTrack = enforceAudioOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const muted = mutedOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const disallowParallelEncoding = disallowParallelEncodingOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const numberOfGifLoops = numberOfGifLoopsOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const encodingMaxRate = encodingMaxRateOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const encodingBufferSize = encodingBufferSizeOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const delayRenderInMilliseconds = delayRenderTimeoutInMillisecondsOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const overwrite = overwriteOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}, true).value;
const metadata = metadataOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
for (const composition of compositions) {
const { value: videoCodec, source: codecReason } = videoCodecOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}, {
downloadName: null,
outName: null,
configFile: (_b = config_1.ConfigInternals.getOutputCodecOrUndefined()) !== null && _b !== void 0 ? _b : null,
uiCodec: null,
compositionCodec: (_c = composition.defaultCodec) !== null && _c !== void 0 ? _c : null,
});
const concurrency = getValidConcurrency(unparsedConcurrency);
benchmark[composition.id] = {};
for (const con of concurrency) {
const benchmarkProgress = (0, progress_bar_1.createOverwriteableCliOutput)({
quiet: (0, parsed_cli_1.quietFlagProvided)(),
cancelSignal: null,
updatesDontOverwrite: (0, should_use_non_overlaying_logger_1.shouldUseNonOverlayingLogger)({ logLevel }),
indent: false,
});
log_1.Log.info({ indent: false, logLevel });
log_1.Log.info({ indent: false, logLevel }, `${chalk_1.chalk.bold(`Benchmark #${count++}:`)} ${chalk_1.chalk.gray(`composition=${composition.id} concurrency=${con} codec=${videoCodec} (${codecReason})`)}`);
const timeTaken = await runBenchmark(runs, {
outputLocation: null,
composition: {
...composition,
width: width !== null && width !== void 0 ? width : composition.width,
height: height !== null && height !== void 0 ? height : composition.height,
},
crf: configFileCrf !== null && configFileCrf !== void 0 ? configFileCrf : null,
envVariables,
frameRange: defaultFrameRange,
imageFormat: (0, image_formats_1.getVideoImageFormat)({
codec: videoCodec,
uiImageFormat: null,
}),
serializedInputPropsWithCustomSchema,
overwrite,
pixelFormat,
proResProfile,
x264Preset,
jpegQuality,
chromiumOptions,
timeoutInMilliseconds: delayRenderInMilliseconds,
scale,
port: (0, preview_server_1.getRendererPortFromConfigFileAndCliFlag)(),
numberOfGifLoops,
everyNthFrame,
logLevel,
muted,
enforceAudioTrack,
browserExecutable,
ffmpegOverride,
serveUrl: bundleLocation,
codec: videoCodec,
audioBitrate,
videoBitrate,
encodingMaxRate,
encodingBufferSize,
puppeteerInstance,
concurrency: con,
audioCodec: null,
cancelSignal: undefined,
disallowParallelEncoding,
indent: false,
onBrowserLog: null,
onCtrlCExit: () => undefined,
onDownload: () => undefined,
onStart: () => undefined,
preferLossless: false,
server: undefined,
serializedResolvedPropsWithCustomSchema: no_react_1.NoReactInternals.serializeJSONWithSpecialTypes({
data: composition.props,
indent: undefined,
staticBase: null,
}).serializedString,
offthreadVideoThreads: offthreadVideoThreadsOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value,
offthreadVideoCacheSizeInBytes: offthreadVideoCacheSizeInBytesOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value,
colorSpace: colorSpaceOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value,
repro: false,
binariesDirectory: binariesDirectoryOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value,
separateAudioTo: null,
forSeamlessAacConcatenation: forSeamlessAacConcatenationOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value,
compositionStart: 0,
onBrowserDownload,
onArtifact: () => undefined,
metadata,
hardwareAcceleration: hardwareAccelerationOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value,
chromeMode,
mediaCacheSizeInBytes: mediaCacheSizeInBytesOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value,
onLog: renderer_1.RenderInternals.defaultOnLog,
licenseKey: null,
isProduction: null,
}, (run, progress) => {
benchmarkProgress.update(makeBenchmarkProgressBar({
totalRuns: runs,
run,
doneIn: null,
progress,
}), false);
});
benchmarkProgress.update('', false);
benchmarkProgress.update(getResults(timeTaken, runs), false);
benchmark[composition.id][`${con}`] =
timeTaken;
}
}
log_1.Log.info({ indent: false, logLevel });
};
exports.benchmarkCommand = benchmarkCommand;
@@ -0,0 +1,8 @@
import type { LogLevel, OnBrowserDownload } from '@remotion/renderer';
import type { BrowserDownloadState } from '@remotion/studio-shared';
export declare const defaultBrowserDownloadProgress: ({ indent, logLevel, quiet, onProgress, }: {
indent: boolean;
logLevel: LogLevel;
quiet: boolean;
onProgress: (progress: BrowserDownloadState) => void;
}) => OnBrowserDownload;
@@ -0,0 +1,81 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultBrowserDownloadProgress = void 0;
const renderer_1 = require("@remotion/renderer");
const chalk_1 = require("./chalk");
const log_1 = require("./log");
const make_progress_bar_1 = require("./make-progress-bar");
const progress_bar_1 = require("./progress-bar");
const should_use_non_overlaying_logger_1 = require("./should-use-non-overlaying-logger");
const truthy_1 = require("./truthy");
const makeDownloadProgress = ({ bytesDownloaded, totalBytes, doneIn, chromeMode, }) => {
const progress = bytesDownloaded / totalBytes;
return [
`${doneIn ? 'Got' : 'Getting'} ${chromeMode === 'chrome-for-testing'
? 'Chrome for Testing'
: 'Headless Shell'}`.padEnd(progress_bar_1.LABEL_WIDTH, ' '),
(0, make_progress_bar_1.makeProgressBar)(progress, false),
doneIn === null
? (progress * 100).toFixed(0) + '%'
: chalk_1.chalk.gray(`${doneIn}ms`),
]
.filter(truthy_1.truthy)
.join(' ');
};
const defaultBrowserDownloadProgress = ({ indent, logLevel, quiet, onProgress, }) => {
return ({ chromeMode }) => {
if (chromeMode === 'chrome-for-testing') {
log_1.Log.info({ indent, logLevel }, 'Downloading Chrome for Testing https://www.remotion.dev/chrome-for-testing');
}
else {
log_1.Log.info({ indent, logLevel }, chalk_1.chalk.gray('Downloading Chrome Headless Shell https://www.remotion.dev/chrome-headless-shell'));
}
const updatesDontOverwrite = (0, should_use_non_overlaying_logger_1.shouldUseNonOverlayingLogger)({ logLevel });
const productName = chromeMode === 'chrome-for-testing'
? 'Chrome for Testing'
: 'Headless Shell';
if (updatesDontOverwrite) {
let lastProgress = 0;
return {
version: null,
onProgress: (progress) => {
if (progress.downloadedBytes > lastProgress + 10000000) {
lastProgress = progress.downloadedBytes;
log_1.Log.info({ indent, logLevel }, `Getting ${productName} - ${renderer_1.RenderInternals.toMegabytes(progress.downloadedBytes)}/${renderer_1.RenderInternals.toMegabytes(progress.totalSizeInBytes)}`);
}
if (progress.percent === 1) {
log_1.Log.info({ indent, logLevel }, `Got ${productName}`);
}
},
};
}
const cliOutput = (0, progress_bar_1.createOverwriteableCliOutput)({
quiet,
indent,
cancelSignal: null,
updatesDontOverwrite,
});
const startedAt = Date.now();
let doneIn = null;
return {
version: null,
onProgress: (progress) => {
if (progress.percent === 1) {
doneIn = Date.now() - startedAt;
}
onProgress({
alreadyAvailable: progress.alreadyAvailable,
progress: progress.percent,
doneIn,
});
cliOutput.update(makeDownloadProgress({
doneIn,
bytesDownloaded: progress.downloadedBytes,
totalBytes: progress.totalSizeInBytes,
chromeMode,
}), progress.percent === 1);
},
};
};
};
exports.defaultBrowserDownloadProgress = defaultBrowserDownloadProgress;
@@ -0,0 +1,3 @@
import type { LogLevel } from '@remotion/renderer';
export declare const ENSURE_COMMAND = "ensure";
export declare const ensureCommand: (logLevel: LogLevel) => Promise<void>;
@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ensureCommand = exports.ENSURE_COMMAND = void 0;
const renderer_1 = require("@remotion/renderer");
const browser_download_bar_1 = require("../browser-download-bar");
const get_cli_options_1 = require("../get-cli-options");
const log_1 = require("../log");
const parsed_cli_1 = require("../parsed-cli");
exports.ENSURE_COMMAND = 'ensure';
const ensureCommand = async (logLevel) => {
const indent = false;
const { browserExecutable } = (0, get_cli_options_1.getCliOptions)({
isStill: false,
logLevel,
indent,
});
const status = await (0, renderer_1.ensureBrowser)({
browserExecutable,
logLevel,
onBrowserDownload: (0, browser_download_bar_1.defaultBrowserDownloadProgress)({
indent,
logLevel,
quiet: (0, parsed_cli_1.quietFlagProvided)(),
onProgress: () => undefined,
}),
});
if (status.type === 'no-browser') {
throw new Error('should have downloaded browser');
}
if (status.type === 'user-defined-path') {
log_1.Log.info({ indent, logLevel }, `Has browser at ${status.path}`);
return;
}
if (status.type === 'local-puppeteer-browser') {
log_1.Log.info({ indent, logLevel }, `Has browser at ${status.path}`);
}
};
exports.ensureCommand = ensureCommand;
@@ -0,0 +1,3 @@
import type { LogLevel } from '@remotion/renderer';
export declare const BROWSER_COMMAND = "browser";
export declare const browserCommand: (args: string[], logLevel: LogLevel) => Promise<void> | undefined;
@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.browserCommand = exports.BROWSER_COMMAND = void 0;
const chalk_1 = require("../chalk");
const log_1 = require("../log");
const ensure_1 = require("./ensure");
exports.BROWSER_COMMAND = 'browser';
const printHelp = (logLevel) => {
log_1.Log.info({ indent: false, logLevel });
log_1.Log.info({ indent: false, logLevel }, chalk_1.chalk.blue(`remotion ${exports.BROWSER_COMMAND}`));
log_1.Log.info({ indent: false, logLevel });
log_1.Log.info({ indent: false, logLevel }, 'Available commands:');
log_1.Log.info({ indent: false, logLevel }, '');
log_1.Log.info({ indent: false, logLevel }, `remotion ${exports.BROWSER_COMMAND} ${ensure_1.ENSURE_COMMAND}`);
log_1.Log.info({ indent: false, logLevel }, chalk_1.chalk.gray('Ensure Remotion has a browser to render.'));
};
const browserCommand = (args, logLevel) => {
if (args[0] === ensure_1.ENSURE_COMMAND) {
return (0, ensure_1.ensureCommand)(logLevel);
}
printHelp(logLevel);
};
exports.browserCommand = browserCommand;
@@ -0,0 +1,2 @@
import type { LogLevel } from '@remotion/renderer';
export declare const bundleCommand: (remotionRoot: string, args: string[], logLevel: LogLevel) => Promise<void>;
+138
View File
@@ -0,0 +1,138 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.bundleCommand = void 0;
const bundler_1 = require("@remotion/bundler");
const client_1 = require("@remotion/renderer/client");
const studio_server_1 = require("@remotion/studio-server");
const fs_1 = require("fs");
const path_1 = __importDefault(require("path"));
const chalk_1 = require("./chalk");
const entry_point_1 = require("./entry-point");
const get_github_repository_1 = require("./get-github-repository");
const log_1 = require("./log");
const parsed_cli_1 = require("./parsed-cli");
const setup_cache_1 = require("./setup-cache");
const should_use_non_overlaying_logger_1 = require("./should-use-non-overlaying-logger");
const yes_or_no_1 = require("./yes-or-no");
const { publicPathOption, publicDirOption, disableGitSourceOption, audioLatencyHintOption, askAIOption, experimentalClientSideRenderingOption, keyboardShortcutsOption, } = client_1.BrowserSafeApis.options;
const bundleCommand = async (remotionRoot, args, logLevel) => {
const { file, reason } = (0, entry_point_1.findEntryPoint)({
args,
remotionRoot,
logLevel,
allowDirectory: false,
});
const explicitlyPassed = args[0];
if (explicitlyPassed &&
reason !== 'argument passed' &&
reason !== 'argument passed - found in cwd' &&
reason !== 'argument passed - found in root') {
log_1.Log.error({ indent: false, logLevel }, `Entry point was specified as ${chalk_1.chalk.bold(explicitlyPassed)}, but it was not found.`);
process.exit(1);
}
const updatesDontOverwrite = (0, should_use_non_overlaying_logger_1.shouldUseNonOverlayingLogger)({ logLevel });
if (!file) {
log_1.Log.error({ indent: false, logLevel }, 'No entry point found.');
log_1.Log.error({ indent: false, logLevel }, 'Pass another argument to the command specifying the entry point.');
log_1.Log.error({ indent: false, logLevel }, 'See: https://www.remotion.dev/docs/terminology/entry-point');
process.exit(1);
}
const experimentalClientSideRenderingEnabled = experimentalClientSideRenderingOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const askAIEnabled = askAIOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const keyboardShortcutsEnabled = keyboardShortcutsOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
if (experimentalClientSideRenderingEnabled) {
log_1.Log.warn({ indent: false, logLevel }, 'Enabling WIP client-side rendering. Please see caveats on https://www.remotion.dev/docs/client-side-rendering/.');
}
const publicPath = publicPathOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const publicDir = publicDirOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const disableGitSource = disableGitSourceOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const audioLatencyHint = audioLatencyHintOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const outputPath = parsed_cli_1.parsedCli['out-dir']
? path_1.default.resolve(process.cwd(), parsed_cli_1.parsedCli['out-dir'])
: path_1.default.join(remotionRoot, 'build');
const gitignoreFolder = bundler_1.BundlerInternals.findClosestFolderWithItem(outputPath, '.gitignore');
const existed = (0, fs_1.existsSync)(outputPath);
if (existed) {
const existsIndexHtml = (0, fs_1.existsSync)(path_1.default.join(outputPath, 'index.html'));
const isEmpty = (0, fs_1.readdirSync)(outputPath).length === 0;
if (!existsIndexHtml && !isEmpty) {
log_1.Log.error({ indent: false, logLevel }, `The folder at ${outputPath} already exists, and needs to be deleted before a new bundle can be created.`);
log_1.Log.error({ indent: false, logLevel }, 'However, it does not look like the folder was created by `npx remotion bundle` (no index.html).');
log_1.Log.error({ indent: false, logLevel }, 'Aborting to prevent accidental data loss.');
process.exit(1);
}
(0, fs_1.rmSync)(outputPath, { recursive: true });
}
const gitSource = (0, get_github_repository_1.getGitSource)({ remotionRoot, disableGitSource, logLevel });
const output = await (0, setup_cache_1.bundleOnCli)({
fullPath: file,
logLevel,
onDirectoryCreated: () => { },
indent: false,
quietProgress: updatesDontOverwrite,
publicDir,
remotionRoot,
onProgressCallback: ({ bundling, copying }) => {
// Handle floating point inaccuracies
if (bundling.progress < 0.99999) {
if (updatesDontOverwrite) {
log_1.Log.info({ indent: false, logLevel }, `Bundling ${Math.round(bundling.progress * 100)}%`);
}
}
if (copying.doneIn === null) {
if (updatesDontOverwrite) {
return `Copying public dir ${studio_server_1.StudioServerInternals.formatBytes(copying.bytes)}`;
}
}
},
quietFlag: (0, parsed_cli_1.quietFlagProvided)(),
outDir: outputPath,
gitSource,
bufferStateDelayInMilliseconds: null,
maxTimelineTracks: null,
publicPath,
audioLatencyHint,
experimentalClientSideRenderingEnabled,
askAIEnabled,
keyboardShortcutsEnabled,
});
log_1.Log.info({ indent: false, logLevel }, chalk_1.chalk.blue(`${existed ? '○' : '+'} ${output}`));
if (!gitignoreFolder) {
return;
}
// Non-interactive terminal
if (!process.stdout.isTTY) {
return;
}
const gitignorePath = path_1.default.join(gitignoreFolder, '.gitignore');
const gitIgnoreContents = (0, fs_1.readFileSync)(gitignorePath, 'utf-8');
const relativePathToGitIgnore = path_1.default.relative(gitignoreFolder, outputPath);
const isInGitIgnore = gitIgnoreContents
.split('\n')
.includes(relativePathToGitIgnore);
if (isInGitIgnore) {
return;
}
const answer = await (0, yes_or_no_1.yesOrNo)({
defaultValue: true,
question: `Recommended: Add ${chalk_1.chalk.bold(relativePathToGitIgnore)} to your ${chalk_1.chalk.bold('.gitignore')} file? (Y/n)`,
});
if (!answer) {
return;
}
const newGitIgnoreContents = gitIgnoreContents + '\n' + relativePathToGitIgnore;
(0, fs_1.writeFileSync)(gitignorePath, newGitIgnoreContents);
log_1.Log.info({ indent: false, logLevel }, chalk_1.chalk.blue(`Added to .gitignore!`));
};
exports.bundleCommand = bundleCommand;
@@ -0,0 +1,50 @@
export declare const chalk: {
enabled: () => boolean;
visible: boolean;
styles: Record<string, {
codes: [number, number];
name: string;
wrap?: ((input: string, newline: boolean) => string) | undefined;
}>;
keys: Record<string, string[]>;
alias?: ((name: string, col: string) => void) | undefined;
} & {
reset: (str: string) => string;
bold: (str: string) => string;
dim: (str: string) => string;
italic: (str: string) => string;
underline: (str: string) => string;
inverse: (str: string) => string;
hidden: (str: string) => string;
strikethrough: (str: string) => string;
black: (str: string) => string;
red: (str: string) => string;
green: (str: string) => string;
yellow: (str: string) => string;
blue: (str: string) => string;
magenta: (str: string) => string;
cyan: (str: string) => string;
white: (str: string) => string;
gray: (str: string) => string;
bgBlack: (str: string) => string;
bgRed: (str: string) => string;
bgGreen: (str: string) => string;
bgYellow: (str: string) => string;
bgBlue: (str: string) => string;
bgMagenta: (str: string) => string;
bgWhite: (str: string) => string;
blackBright: (str: string) => string;
redBright: (str: string) => string;
greenBright: (str: string) => string;
yellowBright: (str: string) => string;
blueBright: (str: string) => string;
magentaBright: (str: string) => string;
whiteBright: (str: string) => string;
bgBlackBright: (str: string) => string;
bgRedBright: (str: string) => string;
bgGreenBright: (str: string) => string;
bgYellowBright: (str: string) => string;
bgBlueBright: (str: string) => string;
bgMagentaBright: (str: string) => string;
bgWhiteBright: (str: string) => string;
};
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.chalk = void 0;
const renderer_1 = require("@remotion/renderer");
exports.chalk = renderer_1.RenderInternals.chalk;
@@ -0,0 +1,5 @@
import type { LogLevel } from '@remotion/renderer';
export declare const checkForNpmRunFlagPass: ({ indent, logLevel, }: {
indent: boolean;
logLevel: LogLevel;
}) => void;
@@ -0,0 +1,43 @@
"use strict";
// If someone passes --log=verbose to npm run render
// We don't receive it.
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkForNpmRunFlagPass = void 0;
const log_1 = require("./log");
const checkForNpmRunFlagPass = ({ indent, logLevel, }) => {
if (!process.env.npm_config_log) {
return;
}
log_1.Log.error({ indent, logLevel }, `The environment variable "npm_config_log" is set to "${process.env.npm_config_log}".`);
log_1.Log.error({ indent, logLevel }, `This indicates a likely mistake:`);
log_1.Log.error({
indent,
logLevel,
}, `--log gets passed to the npm command, however npm has no "log" configuration option.`);
log_1.Log.error({
indent,
logLevel,
}, `You most likely wanted to pass --log to the Remotion CLI.`);
log_1.Log.error({
indent,
logLevel,
}, `However, arguments passed to "npm run" don't get received by the script, in this case Remotion.`);
log_1.Log.error({
indent,
logLevel,
}, `Edit the npm script and pass Remotion flags to "remotion" command instead. Example:`);
log_1.Log.error({
indent,
logLevel,
});
log_1.Log.error({
indent,
logLevel,
}, ` "render": "remotion render --log=verbose"`);
log_1.Log.error({
indent,
logLevel,
});
process.exit(1);
};
exports.checkForNpmRunFlagPass = checkForNpmRunFlagPass;
@@ -0,0 +1,10 @@
import type { LogLevel } from '@remotion/renderer';
export declare const cleanupBeforeQuit: ({ indent, logLevel, }: {
indent: boolean;
logLevel: LogLevel;
}) => void;
export declare const registerCleanupJob: (label: string, job: () => void) => void;
export declare const handleCtrlC: ({ indent, logLevel, }: {
indent: boolean;
logLevel: LogLevel;
}) => void;
@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleCtrlC = exports.registerCleanupJob = exports.cleanupBeforeQuit = void 0;
const log_1 = require("./log");
const cleanupJobs = [];
const cleanupBeforeQuit = ({ indent, logLevel, }) => {
log_1.Log.verbose({ indent, logLevel }, 'Cleaning up...');
const time = Date.now();
for (const job of cleanupJobs) {
job.job();
log_1.Log.verbose({ indent, logLevel }, `Cleanup job "${job.label}" done`);
}
log_1.Log.verbose({ indent, logLevel }, `Cleanup done in ${Date.now() - time}ms`);
};
exports.cleanupBeforeQuit = cleanupBeforeQuit;
const registerCleanupJob = (label, job) => {
cleanupJobs.push({ job, label });
};
exports.registerCleanupJob = registerCleanupJob;
const handleCtrlC = ({ indent, logLevel, }) => {
process.on('SIGINT', () => {
log_1.Log.info({ indent: false, logLevel });
(0, exports.cleanupBeforeQuit)({ indent, logLevel });
process.exit(0);
});
};
exports.handleCtrlC = handleCtrlC;
@@ -0,0 +1,2 @@
import type { LogLevel } from '@remotion/renderer';
export declare const cloudrunCommand: (remotionRoot: string, args: string[], logLevel: LogLevel) => Promise<never>;
@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cloudrunCommand = void 0;
const studio_server_1 = require("@remotion/studio-server");
const log_1 = require("./log");
const cloudrunCommand = async (remotionRoot, args, logLevel) => {
try {
const path = require.resolve('@remotion/cloudrun', {
paths: [remotionRoot],
});
const { CloudrunInternals } = require(path);
await CloudrunInternals.executeCommand(args, remotionRoot, logLevel);
process.exit(0);
}
catch (err) {
const manager = studio_server_1.StudioServerInternals.getPackageManager({
remotionRoot,
packageManager: undefined,
dirUp: 0,
logLevel,
});
const installCommand = manager === 'unknown' ? 'npm i' : manager.installCommand;
log_1.Log.error({ indent: false, logLevel }, err);
log_1.Log.error({ indent: false, logLevel }, 'Remotion Cloud Run is not installed.');
log_1.Log.info({ indent: false, logLevel }, '');
log_1.Log.info({ indent: false, logLevel }, 'You can install it using:');
log_1.Log.info({ indent: false, logLevel }, `${installCommand} @remotion/cloudrun@${studio_server_1.StudioServerInternals.getRemotionVersion()}`);
process.exit(1);
}
};
exports.cloudrunCommand = cloudrunCommand;
@@ -0,0 +1,5 @@
import type { ErrorWithStackFrame, LogLevel } from '@remotion/renderer';
export declare const printCodeFrameAndStack: ({ symbolicated, logLevel, }: {
symbolicated: ErrorWithStackFrame;
logLevel: LogLevel;
}) => void;
@@ -0,0 +1,87 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.printCodeFrameAndStack = void 0;
const chalk_1 = require("./chalk");
const log_1 = require("./log");
const truthy_1 = require("./truthy");
const makeFileName = (firstFrame) => {
return [
firstFrame.originalFileName,
firstFrame.originalLineNumber,
firstFrame.originalColumnNumber === 0
? null
: firstFrame.originalColumnNumber,
]
.filter(truthy_1.truthy)
.join(':');
};
const printCodeFrame = (frame, logLevel) => {
if (!frame.originalScriptCode) {
return;
}
log_1.Log.info({ indent: false, logLevel });
const longestLineNumber = Math.max(...frame.originalScriptCode.map((script) => script.lineNumber)).toString().length;
log_1.Log.info({ indent: false, logLevel }, 'at', chalk_1.chalk.underline(makeFileName(frame)));
const alignLeftAmount = Math.min(...frame.originalScriptCode.map((c) => c.content.length - c.content.trimStart().length));
log_1.Log.info({ indent: false, logLevel }, `${frame.originalScriptCode
.map((c) => {
const left = String(c.lineNumber).padStart(longestLineNumber, ' ');
const right = c.content.substring(alignLeftAmount);
if (c.highlight) {
return `${left}${right}`;
}
return `${chalk_1.chalk.gray(left)} ${chalk_1.chalk.gray(right)}`;
})
.join('\n')}`);
};
const logLine = (frame, logLevel) => {
const fileName = makeFileName(frame);
if (!fileName) {
return;
}
log_1.Log.info({ indent: false, logLevel }, chalk_1.chalk.gray(['at', frame.originalFunctionName, `${chalk_1.chalk.blueBright(`(${fileName})`)}`]
.filter(truthy_1.truthy)
.join(' ')));
};
const printCodeFrameAndStack = ({ symbolicated, logLevel, }) => {
var _a, _b, _c, _d, _e;
if (!symbolicated.symbolicatedStackFrames ||
symbolicated.symbolicatedStackFrames.length === 0) {
log_1.Log.error({ indent: false, logLevel }, symbolicated.stack);
return;
}
const firstFrame = symbolicated.symbolicatedStackFrames[0];
log_1.Log.error({ indent: false, logLevel }, chalk_1.chalk.bgRed(chalk_1.chalk.white(` ${symbolicated.name} `)), symbolicated.message);
printCodeFrame(firstFrame, logLevel);
log_1.Log.info({ indent: false, logLevel });
for (const frame of symbolicated.symbolicatedStackFrames) {
if (frame === firstFrame) {
continue;
}
const isUserCode = !((_a = frame.originalFileName) === null || _a === void 0 ? void 0 : _a.includes('node_modules')) &&
!((_b = frame.originalFileName) === null || _b === void 0 ? void 0 : _b.startsWith('webpack/'));
if (isUserCode) {
printCodeFrame(frame, logLevel);
}
else {
logLine(frame, logLevel);
}
}
if (symbolicated.delayRenderCall) {
log_1.Log.error({ indent: false, logLevel });
log_1.Log.error({ indent: false, logLevel }, '🕧 The delayRender() call is located at:');
for (const frame of symbolicated.delayRenderCall) {
const showCodeFrame = (!((_c = frame.originalFileName) === null || _c === void 0 ? void 0 : _c.includes('node_modules')) &&
!((_d = frame.originalFileName) === null || _d === void 0 ? void 0 : _d.startsWith('webpack/'))) ||
frame === symbolicated.delayRenderCall[0] ||
((_e = frame.originalScriptCode) === null || _e === void 0 ? void 0 : _e.map((c) => c.content).join('').includes('delayRender'));
if (showCodeFrame) {
printCodeFrame(frame, logLevel);
}
else {
logLine(frame, logLevel);
}
}
}
};
exports.printCodeFrameAndStack = printCodeFrameAndStack;
@@ -0,0 +1,8 @@
import type { LogLevel } from '@remotion/renderer';
import type { PromptObject } from 'prompts';
type Question<V extends string = string> = PromptObject<V> & {
optionsPerPage?: number;
};
type NamelessQuestion = Omit<Question<'value'>, 'name'>;
export declare function selectAsync(question: NamelessQuestion, logLevel: LogLevel): Promise<string | string[]>;
export {};
@@ -0,0 +1,24 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.selectAsync = selectAsync;
const prompts_1 = __importDefault(require("prompts"));
const log_1 = require("./log");
function prompt(questions, logLevel) {
return (0, prompts_1.default)([questions], {
onCancel() {
log_1.Log.error({ indent: false, logLevel }, 'No composition selected.');
process.exit(1);
},
});
}
async function selectAsync(question, logLevel) {
const { value } = await prompt({
...question,
name: 'value',
type: question.type,
}, logLevel);
return value !== null && value !== void 0 ? value : null;
}
@@ -0,0 +1,2 @@
import type { LogLevel } from '@remotion/renderer';
export declare const listCompositionsCommand: (remotionRoot: string, args: string[], logLevel: LogLevel) => Promise<void>;
@@ -0,0 +1,137 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.listCompositionsCommand = void 0;
const renderer_1 = require("@remotion/renderer");
const client_1 = require("@remotion/renderer/client");
const no_react_1 = require("remotion/no-react");
const browser_download_bar_1 = require("./browser-download-bar");
const cleanup_before_quit_1 = require("./cleanup-before-quit");
const preview_server_1 = require("./config/preview-server");
const entry_point_1 = require("./entry-point");
const get_cli_options_1 = require("./get-cli-options");
const log_1 = require("./log");
const parsed_cli_1 = require("./parsed-cli");
const print_compositions_1 = require("./print-compositions");
const setup_cache_1 = require("./setup-cache");
const { enableMultiprocessOnLinuxOption, offthreadVideoCacheSizeInBytesOption, offthreadVideoThreadsOption, glOption, headlessOption, delayRenderTimeoutInMillisecondsOption, binariesDirectoryOption, publicPathOption, publicDirOption, chromeModeOption, audioLatencyHintOption, mediaCacheSizeInBytesOption, darkModeOption, askAIOption, experimentalClientSideRenderingOption, keyboardShortcutsOption, } = client_1.BrowserSafeApis.options;
const listCompositionsCommand = async (remotionRoot, args, logLevel) => {
const { file, reason } = (0, entry_point_1.findEntryPoint)({
args,
remotionRoot,
logLevel,
allowDirectory: true,
});
if (!file) {
log_1.Log.error({ indent: false, logLevel }, 'The `compositions` command requires you to specify a entry point. For example');
log_1.Log.error({ indent: false, logLevel }, ' npx remotion compositions src/index.ts');
log_1.Log.error({ indent: false, logLevel }, 'See https://www.remotion.dev/docs/register-root for more information.');
process.exit(1);
}
log_1.Log.verbose({ indent: false, logLevel }, 'Entry point:', file, 'reason:', reason);
const { browserExecutable, envVariables, inputProps, ignoreCertificateErrors, userAgent, disableWebSecurity, } = (0, get_cli_options_1.getCliOptions)({
isStill: false,
logLevel,
indent: false,
});
const publicPath = publicPathOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const timeoutInMilliseconds = delayRenderTimeoutInMillisecondsOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const binariesDirectory = binariesDirectoryOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const darkMode = darkModeOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const offthreadVideoCacheSizeInBytes = offthreadVideoCacheSizeInBytesOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const offthreadVideoThreads = offthreadVideoThreadsOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const publicDir = publicDirOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const chromeMode = chromeModeOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const audioLatencyHint = audioLatencyHintOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const mediaCacheSizeInBytes = mediaCacheSizeInBytesOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const askAIEnabled = askAIOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value;
const chromiumOptions = {
disableWebSecurity,
enableMultiProcessOnLinux: enableMultiprocessOnLinuxOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value,
gl: glOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value,
headless: headlessOption.getValue({ commandLine: parsed_cli_1.parsedCli }).value,
ignoreCertificateErrors,
userAgent,
darkMode,
};
const experimentalClientSideRenderingEnabled = experimentalClientSideRenderingOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
const keyboardShortcutsEnabled = keyboardShortcutsOption.getValue({
commandLine: parsed_cli_1.parsedCli,
}).value;
if (experimentalClientSideRenderingEnabled) {
log_1.Log.warn({ indent: false, logLevel }, 'Enabling WIP client-side rendering. Please see caveats on https://www.remotion.dev/docs/client-side-rendering/.');
}
const { urlOrBundle: bundled, cleanup: cleanupBundle } = await (0, setup_cache_1.bundleOnCliOrTakeServeUrl)({
remotionRoot,
fullPath: file,
publicDir,
onProgress: () => undefined,
indentOutput: false,
logLevel,
onDirectoryCreated: (dir) => {
(0, cleanup_before_quit_1.registerCleanupJob)(`Delete ${dir}`, () => renderer_1.RenderInternals.deleteDirectory(dir));
},
quietProgress: false,
quietFlag: (0, parsed_cli_1.quietFlagProvided)(),
outDir: null,
// Not needed for compositions
gitSource: null,
bufferStateDelayInMilliseconds: null,
maxTimelineTracks: null,
publicPath,
audioLatencyHint,
experimentalClientSideRenderingEnabled,
askAIEnabled,
keyboardShortcutsEnabled,
});
(0, cleanup_before_quit_1.registerCleanupJob)(`Cleanup bundle`, () => cleanupBundle());
const compositions = await renderer_1.RenderInternals.internalGetCompositions({
serveUrlOrWebpackUrl: bundled,
browserExecutable,
chromiumOptions,
envVariables,
serializedInputPropsWithCustomSchema: no_react_1.NoReactInternals.serializeJSONWithSpecialTypes({
data: inputProps,
staticBase: null,
indent: undefined,
}).serializedString,
timeoutInMilliseconds,
port: (0, preview_server_1.getRendererPortFromConfigFileAndCliFlag)(),
indent: false,
onBrowserLog: null,
puppeteerInstance: undefined,
logLevel,
server: undefined,
offthreadVideoCacheSizeInBytes,
offthreadVideoThreads,
binariesDirectory,
onBrowserDownload: (0, browser_download_bar_1.defaultBrowserDownloadProgress)({
indent: false,
logLevel,
quiet: (0, parsed_cli_1.quietFlagProvided)(),
onProgress: () => undefined,
}),
chromeMode,
mediaCacheSizeInBytes,
onLog: renderer_1.RenderInternals.defaultOnLog,
});
(0, print_compositions_1.printCompositions)(compositions, logLevel);
};
exports.listCompositionsCommand = listCompositionsCommand;
@@ -0,0 +1,3 @@
import type { BrowserExecutable } from '@remotion/renderer';
export declare const setBrowserExecutable: (newBrowserExecutablePath: BrowserExecutable) => void;
export declare const getBrowserExecutable: () => BrowserExecutable;
@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getBrowserExecutable = exports.setBrowserExecutable = void 0;
let currentBrowserExecutablePath = null;
const setBrowserExecutable = (newBrowserExecutablePath) => {
currentBrowserExecutablePath = newBrowserExecutablePath;
};
exports.setBrowserExecutable = setBrowserExecutable;
const getBrowserExecutable = () => {
return currentBrowserExecutablePath;
};
exports.getBrowserExecutable = getBrowserExecutable;
@@ -0,0 +1 @@
export declare const getBrowser: () => null;
@@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getBrowser = void 0;
const currentBrowser = null;
const getBrowser = () => {
return currentBrowser;
};
exports.getBrowser = getBrowser;
@@ -0,0 +1,2 @@
export declare const getBufferStateDelayInMilliseconds: () => number | null;
export declare const setBufferStateDelayInMilliseconds: (val: number | null) => void;
@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setBufferStateDelayInMilliseconds = exports.getBufferStateDelayInMilliseconds = void 0;
let value = null;
const getBufferStateDelayInMilliseconds = () => {
return value;
};
exports.getBufferStateDelayInMilliseconds = getBufferStateDelayInMilliseconds;
const setBufferStateDelayInMilliseconds = (val) => {
value = val;
};
exports.setBufferStateDelayInMilliseconds = setBufferStateDelayInMilliseconds;
@@ -0,0 +1,4 @@
export declare const getChromiumDisableWebSecurity: () => boolean;
export declare const setChromiumDisableWebSecurity: (should: boolean) => void;
export declare const getIgnoreCertificateErrors: () => boolean;
export declare const setChromiumIgnoreCertificateErrors: (should: boolean) => void;
@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setChromiumIgnoreCertificateErrors = exports.getIgnoreCertificateErrors = exports.setChromiumDisableWebSecurity = exports.getChromiumDisableWebSecurity = void 0;
let chromiumDisableWebSecurity = false;
let ignoreCertificateErrors = false;
const getChromiumDisableWebSecurity = () => chromiumDisableWebSecurity;
exports.getChromiumDisableWebSecurity = getChromiumDisableWebSecurity;
const setChromiumDisableWebSecurity = (should) => {
chromiumDisableWebSecurity = should;
};
exports.setChromiumDisableWebSecurity = setChromiumDisableWebSecurity;
const getIgnoreCertificateErrors = () => ignoreCertificateErrors;
exports.getIgnoreCertificateErrors = getIgnoreCertificateErrors;
const setChromiumIgnoreCertificateErrors = (should) => {
ignoreCertificateErrors = should;
};
exports.setChromiumIgnoreCertificateErrors = setChromiumIgnoreCertificateErrors;
@@ -0,0 +1,3 @@
export type Concurrency = number | string | null;
export declare const setConcurrency: (newConcurrency: Concurrency) => void;
export declare const getConcurrency: () => string | number | null;
@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getConcurrency = exports.setConcurrency = void 0;
let currentConcurrency = null;
const setConcurrency = (newConcurrency) => {
currentConcurrency = newConcurrency;
};
exports.setConcurrency = setConcurrency;
const getConcurrency = () => {
return currentConcurrency;
};
exports.getConcurrency = getConcurrency;
@@ -0,0 +1,2 @@
export declare const setEntryPoint: (ep: string) => void;
export declare const getEntryPoint: () => string | null;
@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getEntryPoint = exports.setEntryPoint = void 0;
let entryPoint = null;
const setEntryPoint = (ep) => {
entryPoint = ep;
};
exports.setEntryPoint = setEntryPoint;
const getEntryPoint = () => {
return entryPoint;
};
exports.getEntryPoint = getEntryPoint;
@@ -0,0 +1,2 @@
export declare const setDotEnvLocation: (file: string) => void;
export declare const getDotEnvLocation: () => string | null;
@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDotEnvLocation = exports.setDotEnvLocation = void 0;
let envFile = null;
const setDotEnvLocation = (file) => {
envFile = file;
};
exports.setDotEnvLocation = setDotEnvLocation;
const getDotEnvLocation = () => envFile;
exports.getDotEnvLocation = getDotEnvLocation;
@@ -0,0 +1,2 @@
export declare const setEveryNthFrame: (frame: number) => void;
export declare const getEveryNthFrame: () => number;
@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getEveryNthFrame = exports.setEveryNthFrame = void 0;
let everyNthFrame = 1;
const setEveryNthFrame = (frame) => {
everyNthFrame = frame;
};
exports.setEveryNthFrame = setEveryNthFrame;
const getEveryNthFrame = () => {
return everyNthFrame;
};
exports.getEveryNthFrame = getEveryNthFrame;
@@ -0,0 +1,3 @@
import type { FfmpegOverrideFn } from '@remotion/renderer';
export declare const setFfmpegOverrideFunction: (fn: FfmpegOverrideFn) => void;
export declare const getFfmpegOverrideFunction: () => FfmpegOverrideFn;
@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFfmpegOverrideFunction = exports.setFfmpegOverrideFunction = void 0;
let ffmpegOverrideFn = ({ args }) => args;
const setFfmpegOverrideFunction = (fn) => {
ffmpegOverrideFn = fn;
};
exports.setFfmpegOverrideFunction = setFfmpegOverrideFunction;
const getFfmpegOverrideFunction = () => {
return ffmpegOverrideFn;
};
exports.getFfmpegOverrideFunction = getFfmpegOverrideFunction;
@@ -0,0 +1,4 @@
import type { FrameRange } from '@remotion/renderer';
export declare const setFrameRange: (newFrameRange: FrameRange | null) => void;
export declare const setFrameRangeFromCli: (newFrameRange: string | number) => void;
export declare const getRange: () => FrameRange | null;
@@ -0,0 +1,61 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRange = exports.setFrameRangeFromCli = exports.setFrameRange = void 0;
const renderer_1 = require("@remotion/renderer");
let range = null;
const setFrameRange = (newFrameRange) => {
renderer_1.RenderInternals.validateFrameRange(newFrameRange);
range = newFrameRange;
};
exports.setFrameRange = setFrameRange;
const setFrameRangeFromCli = (newFrameRange) => {
if (typeof newFrameRange === 'number') {
if (newFrameRange < 0) {
(0, exports.setFrameRange)([0, Math.abs(newFrameRange)]);
return;
}
(0, exports.setFrameRange)(newFrameRange);
range = newFrameRange;
return;
}
if (typeof newFrameRange === 'string') {
if (newFrameRange.trim() === '') {
throw new Error('--frames flag must be a single number, or 2 numbers separated by `-`');
}
const parts = newFrameRange.split('-');
if (parts.length > 2 || parts.length <= 0) {
throw new Error(`--frames flag must be a number or 2 numbers separated by '-', instead got ${parts.length} numbers`);
}
if (parts.length === 1) {
const value = Number(parts[0]);
if (isNaN(value)) {
throw new Error('--frames flag must be a single number, or 2 numbers separated by `-`');
}
(0, exports.setFrameRange)(value);
return;
}
const [firstPart, secondPart] = parts;
if (secondPart === '' && firstPart !== '') {
const start = Number(firstPart);
if (isNaN(start)) {
throw new Error('--frames flag must be a single number, or 2 numbers separated by `-`');
}
(0, exports.setFrameRange)([start, null]);
return;
}
const parsed = parts.map((f) => Number(f));
const [first, second] = parsed;
for (const value of parsed) {
if (isNaN(value)) {
throw new Error('--frames flag must be a single number, or 2 numbers separated by `-`');
}
}
if (second < first) {
throw new Error('The second number of the --frames flag number should be greater or equal than first number');
}
(0, exports.setFrameRange)([first, second]);
}
};
exports.setFrameRangeFromCli = setFrameRangeFromCli;
const getRange = () => range;
exports.getRange = getRange;
@@ -0,0 +1,2 @@
export declare const overrideHeight: (newHeight: number) => void;
export declare const getHeight: () => number | null;
@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getHeight = exports.overrideHeight = void 0;
const validate_1 = require("../validate");
let specifiedHeight;
const overrideHeight = (newHeight) => {
(0, validate_1.validateDimension)(newHeight, 'height', 'passed to `overrideHeight()`');
specifiedHeight = newHeight;
};
exports.overrideHeight = overrideHeight;
const getHeight = () => {
return specifiedHeight;
};
exports.getHeight = getHeight;
@@ -0,0 +1,5 @@
import type { StillImageFormat, VideoImageFormat } from '@remotion/renderer';
export declare const setStillImageFormat: (format: StillImageFormat) => void;
export declare const setVideoImageFormat: (format: VideoImageFormat) => void;
export declare const getUserPreferredStillImageFormat: () => "png" | "jpeg" | "pdf" | "webp" | undefined;
export declare const getUserPreferredVideoImageFormat: () => "png" | "jpeg" | "none" | undefined;
@@ -0,0 +1,49 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUserPreferredVideoImageFormat = exports.getUserPreferredStillImageFormat = exports.setVideoImageFormat = exports.setStillImageFormat = void 0;
const renderer_1 = require("@remotion/renderer");
const truthy_1 = require("../truthy");
let currentStillImageFormat;
let currentVideoImageFormat;
const setStillImageFormat = (format) => {
if (typeof format === 'undefined') {
currentStillImageFormat = undefined;
return;
}
if (!renderer_1.RenderInternals.validStillImageFormats.includes(format)) {
throw new TypeError([
`Value ${format} is not valid as an image format.`,
// @ts-expect-error
format === 'jpg' ? 'Did you mean "jpeg"?' : null,
]
.filter(truthy_1.truthy)
.join(' '));
}
currentStillImageFormat = format;
};
exports.setStillImageFormat = setStillImageFormat;
const setVideoImageFormat = (format) => {
if (typeof format === 'undefined') {
currentVideoImageFormat = undefined;
return;
}
if (!renderer_1.RenderInternals.validVideoImageFormats.includes(format)) {
throw new TypeError([
`Value ${format} is not valid as a video image format.`,
// @ts-expect-error
format === 'jpg' ? 'Did you mean "jpeg"?' : null,
]
.filter(truthy_1.truthy)
.join(' '));
}
currentVideoImageFormat = format;
};
exports.setVideoImageFormat = setVideoImageFormat;
const getUserPreferredStillImageFormat = () => {
return currentStillImageFormat;
};
exports.getUserPreferredStillImageFormat = getUserPreferredStillImageFormat;
const getUserPreferredVideoImageFormat = () => {
return currentVideoImageFormat;
};
exports.getUserPreferredVideoImageFormat = getUserPreferredVideoImageFormat;
@@ -0,0 +1,3 @@
import type { FrameRange } from '@remotion/renderer';
export declare const setImageSequence: (newImageSequence: boolean) => void;
export declare const getShouldOutputImageSequence: (frameRange: FrameRange | null) => boolean;
@@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getShouldOutputImageSequence = exports.setImageSequence = void 0;
let imageSequence = false;
const setImageSequence = (newImageSequence) => {
if (typeof newImageSequence !== 'boolean') {
throw new TypeError('setImageSequence accepts a Boolean Value');
}
imageSequence = newImageSequence;
};
exports.setImageSequence = setImageSequence;
const getShouldOutputImageSequence = (frameRange) => {
return imageSequence || typeof frameRange === 'number';
};
exports.getShouldOutputImageSequence = getShouldOutputImageSequence;
@@ -0,0 +1,445 @@
import type { WebpackConfiguration } from '@remotion/bundler';
import type { BrowserExecutable, ChromeMode, CodecOrUndefined, ColorSpace, Crf, DeleteAfter, FrameRange, NumberOfGifLoops, StillImageFormat, VideoImageFormat } from '@remotion/renderer';
import type { HardwareAccelerationOption } from '@remotion/renderer/client';
import type { Concurrency } from './concurrency';
import type { WebpackOverrideFn } from './override-webpack';
export type { Concurrency, WebpackConfiguration, WebpackOverrideFn };
declare global {
interface RemotionBundlingOptions {
/**
* Specify the entry point so you don't have to specify it in the
* CLI command
*/
readonly setEntryPoint: (src: string) => void;
/**
* Whether Webpack bundles should be cached to make
* subsequent renders faster. Default: true
*/
readonly setCachingEnabled: (flag: boolean) => void;
/**
* @deprecated
* Use `setStudioPort()` and `setRendererPort()` instead.
*/
readonly setPort: (port: number | undefined) => void;
/**
* Set the HTTP port used by the Studio.
* By default, Remotion will try to find a free port.
* If you specify a port, but it's not available, Remotion will throw an error.
*/
readonly setStudioPort: (port: number | undefined) => void;
/**
* Set the HTTP port used to host the Webpack bundle.
* By default, Remotion will try to find a free port.
* If you specify a port, but it's not available, Remotion will throw an error.
*/
readonly setRendererPort: (port: number | undefined) => void;
/**
* Define the location of the public/ directory.
* By default it is a folder named "public" inside the current working directory.
* You can set an absolute path or a relative path that will be resolved from the closest package.json location.
*/
readonly setPublicDir: (publicDir: string | null) => void;
readonly overrideWebpackConfig: (f: WebpackOverrideFn) => void;
}
interface RemotionConfigObject {
/**
* Change the maximum amount of tracks that are shown in the timeline.
* @param maxTracks The maximum amount of timeline tracks that you would like to show.
* @default 15
*/
readonly setMaxTimelineTracks: (maxTracks: number) => void;
/**
* Enable Keyboard shortcuts in the Remotion Studio.
* @param enabled Boolean whether to enable the keyboard shortcuts
* @default true
*/
readonly setKeyboardShortcutsEnabled: (enableShortcuts: boolean) => void;
/**
* Enable WIP client-side rendering in the Remotion Studio.
* See https://www.remotion.dev/docs/client-side-rendering/ for notes.
* @param enabled Boolean whether to enable client-side rendering
* @default false
*/
readonly setExperimentalClientSideRenderingEnabled: (enabled: boolean) => void;
/**
* Set number of shared audio tags. https://www.remotion.dev/docs/player/autoplay#using-the-numberofsharedaudiotags-prop
* @param numberOfAudioTags
* @default 0
*/
readonly setNumberOfSharedAudioTags: (numberOfAudioTags: number) => void;
/**
* Enable Webpack polling instead of file system listeners for hot reloading in the Studio.
* This is useful if you are using a remote directory or a virtual machine.
* @param interval
* @default null
*/
readonly setWebpackPollingInMilliseconds: (interval: number | null) => void;
/**
* Whether Remotion should open a browser when starting the Studio.
* @param should
* @default true
*/
readonly setShouldOpenBrowser: (should: boolean) => void;
/**
* Set the log level.
* Acceptable values: 'error' | 'warning' | 'info' | 'verbose' | 'trace'
* Default value: 'info'
*
* Set this to 'verbose' to get browser logs and other IO.
*/
readonly setLevel: (newLogLevel: 'trace' | 'verbose' | 'info' | 'warn' | 'error') => void;
/**
* Specify executable path for the browser to use.
* Default: null, which will make Remotion find or download a version of said browser.
*/
readonly setBrowserExecutable: (newBrowserExecutablePath: BrowserExecutable) => void;
/**
* Set how many milliseconds a frame may take to render before it times out.
* Default: `30000`
*/
readonly setDelayRenderTimeoutInMilliseconds: (newPuppeteerTimeout: number) => void;
/**
* @deprecated Renamed to `setDelayRenderTimeoutInMilliseconds`.
* Set how many milliseconds a frame may take to render before it times out.
* Default: `30000`
*/
readonly setTimeoutInMilliseconds: (newPuppeteerTimeout: number) => void;
/**
* Setting deciding whether to disable CORS and other Chrome security features.
* Default: false
*/
readonly setChromiumDisableWebSecurity: (should: boolean) => void;
/**
* Setting whether to ignore any invalid SSL certificates, such as self-signed ones.
* Default: false
*/
readonly setChromiumIgnoreCertificateErrors: (should: boolean) => void;
/**
* If false, will open an actual browser during rendering to observe progress.
* Default: true
*/
readonly setChromiumHeadlessMode: (should: boolean) => void;
/**
* Set whether to use dark mode for Chrome.
* Default: false
*/
readonly setChromiumDarkMode: (should: boolean) => void;
/**
* Set the OpenGL rendering backend for Chrome. Possible values: 'egl', 'angle', 'swiftshader', 'swangle', 'vulkan' and 'angle-egl'.
* Default: 'swangle' in Lambda, null elsewhere.
*/
readonly setChromiumOpenGlRenderer: (renderer: 'swangle' | 'angle' | 'egl' | 'swiftshader' | 'vulkan' | 'angle-egl') => void;
/**
* Set the user agent for Chrome. Only works during rendering.
* Default is the default user agent for Chrome
*/
readonly setChromiumUserAgent: (userAgent: string | null) => void;
/**
* Set a custom location for a .env file.
* Default: `.env`
*/
readonly setDotEnvLocation: (file: string) => void;
/**
* Sets how many Puppeteer instances will work on rendering your video in parallel.
* Default: `null`, meaning half of the threads available on your CPU.
*/
readonly setConcurrency: (newConcurrency: Concurrency) => void;
/**
* @deprecated Renamed to `setJpegQuality`.
*/
readonly setQuality: (q: never) => void;
/**
* @deprecated Separated into `setStillImageFormat()` and `setVideoImageFormat()`.
*/
readonly setImageFormat: (q: never) => void;
/**
* Set the JPEG quality for the frames.
* Must be between 0 and 100.
* Default: 80
*/
readonly setJpegQuality: (q: number | undefined) => void;
/** Decide the image format for still renders.
*/
readonly setStillImageFormat: (format: StillImageFormat) => void;
/** Decide in which image format to render. Can be either 'jpeg' or 'png'.
* PNG is slower, but supports transparency.
*/
readonly setVideoImageFormat: (format: VideoImageFormat) => void;
/**
* Render only a subset of a video.
* Pass in a tuple [20, 30] to only render frames 20-30 into a video.
* Pass in a single number `20` to only render a single frame as an image.
* The frame count starts at 0.
*/
readonly setFrameRange: (newFrameRange: FrameRange | null) => void;
/**
* Scales the output dimensions by a factor.
* Default: 1.
*/
readonly setScale: (newScale: number) => void;
/**
* Specify which frames should be picked for rendering a GIF
* Default: 1, which means every frame
* https://remotion.dev/docs/render-as-gif
*/
readonly setEveryNthFrame: (frame: number) => void;
/**
* Specify the number of Loop a GIF should have.
* Default: null (means GIF will loop infinite)
*/
readonly setNumberOfGifLoops: (newLoop: NumberOfGifLoops) => void;
/**
* Disable audio output.
* Default: false
*/
readonly setMuted: (muted: boolean) => void;
/**
* Don't render an audio track if it would be silent.
* Default: true
*/
readonly setEnforceAudioTrack: (enforceAudioTrack: boolean) => void;
/**
* Prepare a video for later seamless audio concatenation.
* Default: false
*/
readonly setForSeamlessAacConcatenation: (forSeamlessAacConcatenation: boolean) => void;
/**
* Set the output file location string. Default: `out/{composition}.{codec}`
*/
readonly setOutputLocation: (newOutputLocation: string) => void;
/**
* If the video file already exists, should Remotion overwrite
* the output? Default: true
*/
readonly setOverwriteOutput: (newOverwrite: boolean) => void;
/**
* Sets the pixel format in FFmpeg.
* See https://trac.ffmpeg.org/wiki/Chroma%20Subsampling for an explanation.
* You can override this using the `--pixel-format` Cli flag.
*/
readonly setPixelFormat: (format: 'yuv420p' | 'yuva420p' | 'yuv422p' | 'yuv444p' | 'yuv420p10le' | 'yuv422p10le' | 'yuv444p10le' | 'yuva444p10le') => void;
/**
* Specify the codec for stitching the frames into a video.
* Can be `h264` (default), `h265`, `vp8` or `vp9`
*/
readonly setCodec: (newCodec: CodecOrUndefined) => void;
/**
* Set the Constant Rate Factor to pass to FFmpeg.
* Lower values mean better quality, but be aware that the ranges of
* possible values greatly differs between codecs.
*/
readonly setCrf: (newCrf: Crf) => void;
/**
* Set to true if don't want a video but an image sequence as the output.
*/
readonly setImageSequence: (newImageSequence: boolean) => void;
/**
* Overrides the height of a composition
*/
readonly overrideHeight: (newHeight: number) => void;
/**
* Overrides the width of a composition
*/
readonly overrideWidth: (newWidth: number) => void;
/**
* Set the ProRes profile.
* This method is only valid if the codec has been set to 'prores'.
* Possible values: 4444-xq, 4444, hq, standard, light, proxy. Default: 'hq'
* See https://avpres.net/FFmpeg/im_ProRes.html for meaning of possible values.
*/
readonly setProResProfile: (profile: '4444-xq' | '4444' | 'hq' | 'standard' | 'light' | 'proxy' | undefined) => void;
readonly setX264Preset: (profile: 'ultrafast' | 'superfast' | 'veryfast' | 'faster' | 'fast' | 'medium' | 'slow' | 'slower' | 'veryslow' | 'placebo' | null) => void;
/**
* Override the arguments that Remotion passes to FFmpeg.
* Consult https://remotion.dev/docs/renderer/render-media#ffmpegoverride before using this feature.
*/
readonly overrideFfmpegCommand: (command: (info: {
type: 'pre-stitcher' | 'stitcher';
args: string[];
}) => string[]) => void;
/**
* Set a target audio bitrate to be passed to FFmpeg.
*/
readonly setAudioBitrate: (bitrate: string | null) => void;
/**
* Set a target video bitrate to be passed to FFmpeg.
* Mutually exclusive with setCrf().
*/
readonly setVideoBitrate: (bitrate: string | null) => void;
/**
* Set the audio latency hint that the Studio will
* use when playing back audio
* Default: 'interactive'
*/
readonly setAudioLatencyHint: (audioLatencyHint: AudioContextLatencyCategory | null) => void;
/**
* Set a maximum bitrate to be passed to FFmpeg.
*/
readonly setEncodingMaxRate: (bitrate: string | null) => void;
/**
* Set a buffer size to be passed to FFmpeg.
*/
readonly setEncodingBufferSize: (bitrate: string | null) => void;
/**
* Opt into bt709 rendering.
*/
readonly setColorSpace: (colorSpace: ColorSpace) => void;
/**
* Disallows the renderer from doing rendering frames and encoding at the same time.
* This makes the rendering process more memory-efficient, but possibly slower.
* Default: false
*/
readonly setDisallowParallelEncoding: (disallowParallelEncoding: boolean) => void;
/**
* Enables or disables the Ask AI Modal in Studio
*/
readonly setAskAIEnabled: (askAIEnabled: boolean) => void;
/**
* Removes the --single-process flag that gets passed to
Chromium on Linux by default. This will make the render faster because
multiple processes can be used, but may cause issues with some Linux
distributions or if window server libraries are missing.
*/
readonly setChromiumMultiProcessOnLinux: (multiProcessOnLinux: boolean) => void;
/**
* Whether the Remotion Studio should play a beep sound when a render has finished.
*/
readonly setBeepOnFinish: (beepOnFinish: boolean) => void;
/**
* Enable Cross-Site Isolation in the Studio (Sets Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy HTTP headers)
*/
readonly setEnableCrossSiteIsolation: (enableCrossSiteIsolation: boolean) => void;
/**
* Collect information that you can submit to Remotion if asked for a reproduction.
*/
readonly setRepro: (enableRepro: boolean) => void;
/**
* The directory where the platform-specific binaries and libraries needed
for Remotion are located.
*/
readonly setBinariesDirectory: (directory: string | null) => void;
/**
* Prefer lossless audio encoding. Default: false
*/
readonly setPreferLosslessAudio: (lossless: boolean) => void;
/**
* Prefer lossless audio encoding. Default: false
*/
readonly setPublicPath: (publicPath: string | null) => void;
/**
* Set the pattern for naming image sequence files. Supports [frame] and [ext] replacements.
* @param pattern The pattern string, e.g. 'frame_[frame].[ext]'.
*/
readonly setImageSequencePattern: (pattern: string | null) => void;
/**
* Set the public license key for your company license.
* Obtain it from the "Usage" tab on https://remotion.pro
* Pass "free-license" if you are eligible for the free license.
*/
readonly setPublicLicenseKey: (key: string | null) => void;
}
}
type FlatConfig = RemotionConfigObject & RemotionBundlingOptions & {
/**
* Set the audio codec to use for the output video.
* See the Encoding guide in the docs for defaults and available options.
*/
setAudioCodec: (codec: 'pcm-16' | 'aac' | 'mp3' | 'opus') => void;
setOffthreadVideoCacheSizeInBytes: (size: number | null) => void;
/**
* Forces starting a new Studio instance even if one is already running on the same port for the same project.
* Default: false
*/
setForceNewStudioEnabled: (forceNew: boolean) => void;
setDeleteAfter: (day: DeleteAfter | null) => void;
/**
* Set whether S3 buckets should be allowed to expire.
*/
setEnableFolderExpiry: (value: boolean | null) => void;
/**
* Set whether Lambda Insights should be enabled when deploying a function.
*/
setLambdaInsights: (value: boolean) => void;
/**
* Set the amount of milliseconds after which the Player in the Studio will display a buffering UI after the Player has entered a buffer state.
*/
setBufferStateDelayInMilliseconds: (delay: number | null) => void;
/**
* Metadata to be embedded into the output video file.
*/
setMetadata: (metadata: Record<string, string>) => void;
/**
*
*/
setHardwareAcceleration: (hardwareAccelerationOption: HardwareAccelerationOption) => void;
/**
* Forces Remotion to bind to an IPv4 interface for the Studio server.
* Default: false
*/
setIPv4: (ipv4: boolean) => void;
/**
* Choose between using Chrome Headless Shell or Chrome for Testing
*/
setChromeMode: (chromeMode: ChromeMode) => void;
/**
* @deprecated 'The config format has changed. Change `Config.Bundling.*()` calls to `Config.*()` in your config file.'
*/
Bundling: void;
/**
* @deprecated 'The config format has changed. Change `Config.Preview.*()` calls to `Config.*()` in your config file.'
*/
Preview: void;
/**
* @deprecated 'The config format has changed. Change `Config.Log.*()` calls to `Config.*()` in your config file.'
*/
Log: void;
/**
* @deprecated 'The config format has changed. Change `Config.Puppeteer.*()` calls to `Config.*()` in your config file.'
*/
Puppeteer: void;
/**
* @deprecated 'The config format has changed. Change `Config.Rendering.*()` calls to `Config.*()` in your config file.'
*/
Rendering: void;
/**
* @deprecated 'The config format has changed. Change `Config.Output.*()` calls to `Config.*()` in your config file.'
*/
Output: void;
};
export declare const Config: FlatConfig;
export declare const ConfigInternals: {
getRange: () => FrameRange | null;
getBrowser: () => null;
getPixelFormat: () => "yuv420p" | "yuva420p" | "yuv422p" | "yuv444p" | "yuv420p10le" | "yuv422p10le" | "yuv444p10le" | "yuva444p10le";
getProResProfile: () => import("remotion")._InternalTypes["ProResProfile"] | undefined;
getBrowserExecutable: () => BrowserExecutable;
getStudioPort: () => number | undefined;
getRendererPortFromConfigFile: () => number | null;
getRendererPortFromConfigFileAndCliFlag: () => number | null;
getChromiumDisableWebSecurity: () => boolean;
getIgnoreCertificateErrors: () => boolean;
getEveryNthFrame: () => number;
getConcurrency: () => string | number | null;
getStillFrame: () => number;
getShouldOutputImageSequence: (frameRange: FrameRange | null) => boolean;
getDotEnvLocation: () => string | null;
getUserPreferredStillImageFormat: () => "png" | "jpeg" | "pdf" | "webp" | undefined;
getUserPreferredVideoImageFormat: () => "png" | "jpeg" | "none" | undefined;
getWebpackOverrideFn: () => WebpackOverrideFn;
getWebpackCaching: () => boolean;
getOutputLocation: () => string | null;
setFrameRangeFromCli: (newFrameRange: string | number) => void;
setStillFrame: (frame: number) => void;
getMaxTimelineTracks: () => number;
defaultOverrideFunction: WebpackOverrideFn;
getFfmpegOverrideFunction: () => import("@remotion/renderer").FfmpegOverrideFn;
getHeight: () => number | null;
getWidth: () => number | null;
getMetadata: () => Record<string, string>;
getEntryPoint: () => string | null;
getWebpackPolling: () => number | null;
getShouldOpenBrowser: () => boolean;
getChromiumUserAgent: () => string | null;
getBufferStateDelayInMilliseconds: () => number | null;
getOutputCodecOrUndefined: () => import("@remotion/renderer/dist/codec").CodecOrUndefined;
};
@@ -0,0 +1,181 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConfigInternals = exports.Config = void 0;
const browser_1 = require("./browser");
const browser_executable_1 = require("./browser-executable");
const chromium_flags_1 = require("./chromium-flags");
const concurrency_1 = require("./concurrency");
const env_file_1 = require("./env-file");
const frame_range_1 = require("./frame-range");
const image_format_1 = require("./image-format");
const image_sequence_1 = require("./image-sequence");
const output_location_1 = require("./output-location");
const override_webpack_1 = require("./override-webpack");
const pixel_format_1 = require("./pixel-format");
const preview_server_1 = require("./preview-server");
const prores_profile_1 = require("./prores-profile");
const still_frame_1 = require("./still-frame");
const webpack_caching_1 = require("./webpack-caching");
const client_1 = require("@remotion/renderer/client");
const studio_server_1 = require("@remotion/studio-server");
const browser_executable_2 = require("./browser-executable");
const buffer_state_delay_in_milliseconds_1 = require("./buffer-state-delay-in-milliseconds");
const chromium_flags_2 = require("./chromium-flags");
const concurrency_2 = require("./concurrency");
const entry_point_1 = require("./entry-point");
const env_file_2 = require("./env-file");
const every_nth_frame_1 = require("./every-nth-frame");
const ffmpeg_override_1 = require("./ffmpeg-override");
const frame_range_2 = require("./frame-range");
const height_1 = require("./height");
const image_sequence_2 = require("./image-sequence");
const metadata_1 = require("./metadata");
const open_browser_1 = require("./open-browser");
const output_location_2 = require("./output-location");
const override_webpack_2 = require("./override-webpack");
const pixel_format_2 = require("./pixel-format");
const preview_server_2 = require("./preview-server");
const prores_profile_2 = require("./prores-profile");
const user_agent_1 = require("./user-agent");
const webpack_caching_2 = require("./webpack-caching");
const webpack_poll_1 = require("./webpack-poll");
const width_1 = require("./width");
const { offthreadVideoCacheSizeInBytesOption, x264Option, audioBitrateOption, videoBitrateOption, scaleOption, crfOption, jpegQualityOption, enforceAudioOption, overwriteOption, chromeModeOption, mutedOption, videoCodecOption, colorSpaceOption, disallowParallelEncodingOption, deleteAfterOption, folderExpiryOption, enableMultiprocessOnLinuxOption, glOption, headlessOption, numberOfGifLoopsOption, beepOnFinishOption, encodingMaxRateOption, encodingBufferSizeOption, reproOption, enableLambdaInsights, logLevelOption, delayRenderTimeoutInMillisecondsOption, publicDirOption, binariesDirectoryOption, preferLosslessOption, forSeamlessAacConcatenationOption, audioCodecOption, publicPathOption, hardwareAccelerationOption, audioLatencyHintOption, enableCrossSiteIsolationOption, imageSequencePatternOption, darkModeOption, askAIOption, publicLicenseKeyOption, experimentalClientSideRenderingOption, keyboardShortcutsOption, forceNewStudioOption, numberOfSharedAudioTagsOption, ipv4Option, } = client_1.BrowserSafeApis.options;
exports.Config = {
get Bundling() {
throw new Error('The config format has changed. Change `Config.Bundling.*()` calls to `Config.*()` in your config file.');
},
get Rendering() {
throw new Error('The config format has changed. Change `Config.Rendering.*()` calls to `Config.*()` in your config file.');
},
get Output() {
throw new Error('The config format has changed. Change `Config.Output.*()` calls to `Config.*()` in your config file.');
},
get Log() {
throw new Error('The config format has changed. Change `Config.Log.*()` calls to `Config.*()` in your config file.');
},
get Preview() {
throw new Error('The config format has changed. Change `Config.Preview.*()` calls to `Config.*()` in your config file.');
},
get Puppeteer() {
throw new Error('The config format has changed. Change `Config.Puppeteer.*()` calls to `Config.*()` in your config file.');
},
setMaxTimelineTracks: studio_server_1.StudioServerInternals.setMaxTimelineTracks,
setKeyboardShortcutsEnabled: keyboardShortcutsOption.setConfig,
setExperimentalClientSideRenderingEnabled: experimentalClientSideRenderingOption.setConfig,
setNumberOfSharedAudioTags: numberOfSharedAudioTagsOption.setConfig,
setWebpackPollingInMilliseconds: webpack_poll_1.setWebpackPollingInMilliseconds,
setShouldOpenBrowser: open_browser_1.setShouldOpenBrowser,
setBufferStateDelayInMilliseconds: buffer_state_delay_in_milliseconds_1.setBufferStateDelayInMilliseconds,
overrideWebpackConfig: override_webpack_2.overrideWebpackConfig,
setCachingEnabled: webpack_caching_2.setWebpackCaching,
setPort: preview_server_2.setPort,
setStudioPort: preview_server_2.setStudioPort,
setRendererPort: preview_server_2.setRendererPort,
setPublicDir: publicDirOption.setConfig,
setEntryPoint: entry_point_1.setEntryPoint,
setLevel: logLevelOption.setConfig,
setBrowserExecutable: browser_executable_2.setBrowserExecutable,
setTimeoutInMilliseconds: delayRenderTimeoutInMillisecondsOption.setConfig,
setDelayRenderTimeoutInMilliseconds: delayRenderTimeoutInMillisecondsOption.setConfig,
setChromiumDisableWebSecurity: chromium_flags_2.setChromiumDisableWebSecurity,
setChromiumIgnoreCertificateErrors: chromium_flags_2.setChromiumIgnoreCertificateErrors,
setChromiumHeadlessMode: headlessOption.setConfig,
setChromiumOpenGlRenderer: glOption.setConfig,
setChromiumUserAgent: user_agent_1.setChromiumUserAgent,
setDotEnvLocation: env_file_2.setDotEnvLocation,
setConcurrency: concurrency_2.setConcurrency,
setChromiumMultiProcessOnLinux: enableMultiprocessOnLinuxOption.setConfig,
setChromiumDarkMode: darkModeOption.setConfig,
setQuality: () => {
throw new Error('setQuality() has been renamed - use setJpegQuality() instead.');
},
setImageFormat: () => {
throw new Error('Config.setImageFormat() has been renamed - use Config.setVideoImageFormat() instead (default "jpeg"). For rendering stills, use Config.setStillImageFormat() (default "png")');
},
setJpegQuality: jpegQualityOption.setConfig,
setStillImageFormat: image_format_1.setStillImageFormat,
setVideoImageFormat: image_format_1.setVideoImageFormat,
setMetadata: metadata_1.setMetadata,
setEncodingMaxRate: encodingMaxRateOption.setConfig,
setEncodingBufferSize: encodingBufferSizeOption.setConfig,
setFrameRange: frame_range_2.setFrameRange,
setScale: scaleOption.setConfig,
setEveryNthFrame: every_nth_frame_1.setEveryNthFrame,
setNumberOfGifLoops: numberOfGifLoopsOption.setConfig,
setMuted: mutedOption.setConfig,
setEnforceAudioTrack: enforceAudioOption.setConfig,
setOutputLocation: output_location_2.setOutputLocation,
setOverwriteOutput: overwriteOption.setConfig,
setChromeMode: chromeModeOption.setConfig,
setPixelFormat: pixel_format_2.setPixelFormat,
setCodec: videoCodecOption.setConfig,
setCrf: crfOption.setConfig,
setImageSequence: image_sequence_2.setImageSequence,
setProResProfile: prores_profile_2.setProResProfile,
setX264Preset: x264Option.setConfig,
setAudioBitrate: audioBitrateOption.setConfig,
setVideoBitrate: videoBitrateOption.setConfig,
setAudioLatencyHint: audioLatencyHintOption.setConfig,
setForSeamlessAacConcatenation: forSeamlessAacConcatenationOption.setConfig,
overrideHeight: height_1.overrideHeight,
overrideWidth: width_1.overrideWidth,
overrideFfmpegCommand: ffmpeg_override_1.setFfmpegOverrideFunction,
setAudioCodec: audioCodecOption.setConfig,
setOffthreadVideoCacheSizeInBytes: (size) => {
offthreadVideoCacheSizeInBytesOption.setConfig(size);
},
setDeleteAfter: deleteAfterOption.setConfig,
setColorSpace: colorSpaceOption.setConfig,
setDisallowParallelEncoding: disallowParallelEncodingOption.setConfig,
setBeepOnFinish: beepOnFinishOption.setConfig,
setEnableFolderExpiry: folderExpiryOption.setConfig,
setRepro: reproOption.setConfig,
setLambdaInsights: enableLambdaInsights.setConfig,
setBinariesDirectory: binariesDirectoryOption.setConfig,
setPreferLosslessAudio: preferLosslessOption.setConfig,
setPublicPath: publicPathOption.setConfig,
setImageSequencePattern: imageSequencePatternOption.setConfig,
setHardwareAcceleration: hardwareAccelerationOption.setConfig,
setEnableCrossSiteIsolation: enableCrossSiteIsolationOption.setConfig,
setAskAIEnabled: askAIOption.setConfig,
setPublicLicenseKey: publicLicenseKeyOption.setConfig,
setForceNewStudioEnabled: forceNewStudioOption.setConfig,
setIPv4: ipv4Option.setConfig,
};
exports.ConfigInternals = {
getRange: frame_range_1.getRange,
getBrowser: browser_1.getBrowser,
getPixelFormat: pixel_format_1.getPixelFormat,
getProResProfile: prores_profile_1.getProResProfile,
getBrowserExecutable: browser_executable_1.getBrowserExecutable,
getStudioPort: preview_server_1.getStudioPort,
getRendererPortFromConfigFile: preview_server_1.getRendererPortFromConfigFile,
getRendererPortFromConfigFileAndCliFlag: preview_server_1.getRendererPortFromConfigFileAndCliFlag,
getChromiumDisableWebSecurity: chromium_flags_1.getChromiumDisableWebSecurity,
getIgnoreCertificateErrors: chromium_flags_1.getIgnoreCertificateErrors,
getEveryNthFrame: every_nth_frame_1.getEveryNthFrame,
getConcurrency: concurrency_1.getConcurrency,
getStillFrame: still_frame_1.getStillFrame,
getShouldOutputImageSequence: image_sequence_1.getShouldOutputImageSequence,
getDotEnvLocation: env_file_1.getDotEnvLocation,
getUserPreferredStillImageFormat: image_format_1.getUserPreferredStillImageFormat,
getUserPreferredVideoImageFormat: image_format_1.getUserPreferredVideoImageFormat,
getWebpackOverrideFn: override_webpack_1.getWebpackOverrideFn,
getWebpackCaching: webpack_caching_1.getWebpackCaching,
getOutputLocation: output_location_1.getOutputLocation,
setFrameRangeFromCli: frame_range_1.setFrameRangeFromCli,
setStillFrame: still_frame_1.setStillFrame,
getMaxTimelineTracks: studio_server_1.StudioServerInternals.getMaxTimelineTracks,
defaultOverrideFunction: override_webpack_1.defaultOverrideFunction,
getFfmpegOverrideFunction: ffmpeg_override_1.getFfmpegOverrideFunction,
getHeight: height_1.getHeight,
getWidth: width_1.getWidth,
getMetadata: metadata_1.getMetadata,
getEntryPoint: entry_point_1.getEntryPoint,
getWebpackPolling: webpack_poll_1.getWebpackPolling,
getShouldOpenBrowser: open_browser_1.getShouldOpenBrowser,
getChromiumUserAgent: user_agent_1.getChromiumUserAgent,
getBufferStateDelayInMilliseconds: buffer_state_delay_in_milliseconds_1.getBufferStateDelayInMilliseconds,
getOutputCodecOrUndefined: client_1.BrowserSafeApis.getOutputCodecOrUndefined,
};
@@ -0,0 +1,2 @@
export declare const setMetadata: (metadata: Record<string, string>) => void;
export declare const getMetadata: () => Record<string, string>;

Some files were not shown because too many files have changed in this diff Show More