Skip to content

🎥 Make videos programmatically with React

inlines

Jonny Burger0e04241bcfd0
diff --git a/packages/bundler/package.json b/packages/bundler/package.json
index 52de2d346b..5a1398cf55 100644
--- a/packages/bundler/package.json
+++ b/packages/bundler/package.json
@@ -32,6 +32,7 @@
"react-error-overlay": "^6.0.10",
"remotion": "2.5.7",
"semver": "7.3.4",
+ "source-map": "^0.5.7",
"source-map-loader": "^3.0.0",
"style-loader": "^2.0.0",
"webpack": "5.60.0",
diff --git a/packages/bundler/src/error-overlay/entry-basic.ts b/packages/bundler/src/error-overlay/entry-basic.ts
index 25cb1a5f4d..df2c2af4f4 100644
--- a/packages/bundler/src/error-overlay/entry-basic.ts
+++ b/packages/bundler/src/error-overlay/entry-basic.ts
@@ -1,36 +1,14 @@
-const {
- setEditorHandler,
- startReportingRuntimeErrors,
- dismissRuntimeErrors,
-} = require('react-error-overlay');
-const launchEditorEndpoint = require('react-dev-utils/launchEditorEndpoint');
-
-type ErrorLocation = {
- fileName: string;
- lineNumber: number;
- colNumber?: number;
-};
-
-setEditorHandler((errorLocation: ErrorLocation) => {
- // Keep this sync with errorOverlayMiddleware.js
- fetch(
- launchEditorEndpoint +
- '?fileName=' +
- window.encodeURIComponent(errorLocation.fileName) +
- '&lineNumber=' +
- window.encodeURIComponent(errorLocation.lineNumber || 1) +
- '&colNumber=' +
- window.encodeURIComponent(errorLocation.colNumber || 1)
- );
-});
+import {startReportingRuntimeErrors} from './react-overlay';
startReportingRuntimeErrors({
onError() {
if (module.hot) {
+ console.log('error occurred');
module.hot.addStatusHandler((status) => {
if (status === 'apply') {
+ console.log('apply');
// window.location.reload();
- dismissRuntimeErrors();
+ // dismissRuntimeErrors();
}
});
}
diff --git a/packages/bundler/src/error-overlay/index.ts b/packages/bundler/src/error-overlay/index.ts
index afb958f300..c90f8aa4db 100644
--- a/packages/bundler/src/error-overlay/index.ts
+++ b/packages/bundler/src/error-overlay/index.ts
@@ -100,6 +100,7 @@ export class ErrorOverlayPlugin {
originalBefore(app, server);
}
+ console.log('use');
app.use(errorOverlayMiddleware());
};
}
diff --git a/packages/bundler/src/error-overlay/react-overlay/effects/format-warning.ts b/packages/bundler/src/error-overlay/react-overlay/effects/format-warning.ts
new file mode 100644
index 0000000000..103a63d7dc
--- /dev/null
+++ b/packages/bundler/src/error-overlay/react-overlay/effects/format-warning.ts
@@ -0,0 +1,59 @@
+/**
+ * Copyright (c) 2015-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+import {ReactFrame} from './proxy-console';
+
+function stripInlineStacktrace(message: string): string {
+ return message
+ .split('\n')
+ .filter((line) => !line.match(/^\s*in/))
+ .join('\n'); // " in Foo"
+}
+
+function massage(
+ warning: string,
+ frames: ReactFrame[]
+): {message: string; stack: string} {
+ const message = stripInlineStacktrace(warning);
+
+ // Reassemble the stack with full filenames provided by React
+ let stack = '';
+ let lastFilename;
+ let lastLineNumber;
+ for (let index = 0; index < frames.length; ++index) {
+ const {fileName, lineNumber} = frames[index];
+ if (
+ fileName === null ||
+ lineNumber === null ||
+ lineNumber === undefined ||
+ fileName === undefined
+ ) {
+ continue;
+ }
+
+ // TODO: instead, collapse them in the UI
+ if (
+ fileName === lastFilename &&
+ typeof lineNumber === 'number' &&
+ typeof lastLineNumber === 'number' &&
+ Math.abs(lineNumber - lastLineNumber) < 3
+ ) {
+ continue;
+ }
+
+ lastFilename = fileName;
+ lastLineNumber = lineNumber;
+
+ let {name} = frames[index];
+ name = name || '(anonymous function)';
+ stack += `in ${name} (at ${fileName}:${lineNumber})\n`;
+ }
+
+ return {message, stack};
+}
+
+export {massage};
diff --git a/packages/bundler/src/error-overlay/react-overlay/effects/proxy-console.ts b/packages/bundler/src/error-overlay/react-overlay/effects/proxy-console.ts
new file mode 100644
index 0000000000..d85ba38107
--- /dev/null
+++ b/packages/bundler/src/error-overlay/react-overlay/effects/proxy-console.ts
@@ -0,0 +1,69 @@
+/**
+ * Copyright (c) 2015-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+type ReactFrame = {
+ fileName: string | null;
+ lineNumber: number | null;
+ name: string | null;
+};
+const reactFrameStack: Array<ReactFrame[]> = [];
+
+export type {ReactFrame};
+
+// This is a stripped down barebones version of this proposal:
+// https://gist.github.com/sebmarkbage/bdefa100f19345229d526d0fdd22830f
+// We're implementing just enough to get the invalid element type warnings
+// to display the component stack in React 15.6+:
+// https://github.com/facebook/react/pull/9679
+/// TODO: a more comprehensive implementation.
+
+const registerReactStack = () => {
+ if (typeof console !== 'undefined') {
+ // @ts-expect-error
+ console.reactStack = (frames) => reactFrameStack.push(frames);
+ // @ts-expect-error
+ console.reactStackEnd = () => reactFrameStack.pop();
+ }
+};
+
+const unregisterReactStack = () => {
+ if (typeof console !== 'undefined') {
+ // @ts-expect-error
+ console.reactStack = undefined;
+ // @ts-expect-error
+ console.reactStackEnd = undefined;
+ }
+};
+
+type ConsoleProxyCallback = (message: string, frames: ReactFrame[]) => void;
+const permanentRegister = function (
+ type: 'error',
+ callback: ConsoleProxyCallback
+) {
+ if (typeof console !== 'undefined') {
+ const orig = console[type];
+ if (typeof orig === 'function') {
+ console[type] = function (...args) {
+ try {
+ const message = args[0];
+ if (typeof message === 'string' && reactFrameStack.length > 0) {
+ callback(message, reactFrameStack[reactFrameStack.length - 1]);
+ }
+ } catch (err) {
+ // Warnings must never crash. Rethrow with a clean stack.
+ setTimeout(() => {
+ throw err;
+ });
+ }
+
+ return orig.apply(this, args);
+ };
+ }
+ }
+};
+
+export {permanentRegister, registerReactStack, unregisterReactStack};
diff --git a/packages/bundler/src/error-overlay/react-overlay/effects/stack-trace-limit.ts b/packages/bundler/src/error-overlay/react-overlay/effects/stack-trace-limit.ts
new file mode 100644
index 0000000000..c5e53b3d89
--- /dev/null
+++ b/packages/bundler/src/error-overlay/react-overlay/effects/stack-trace-limit.ts
@@ -0,0 +1,44 @@
+/**
+ * Copyright (c) 2015-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+let stackTraceRegistered = false;
+// Default: https://docs.microsoft.com/en-us/scripting/javascript/reference/stacktracelimit-property-error-javascript
+let restoreStackTraceValue = 10;
+
+const MAX_STACK_LENGTH = 50;
+
+function registerStackTraceLimit(limit: number = MAX_STACK_LENGTH) {
+ if (stackTraceRegistered) {
+ return;
+ }
+
+ try {
+ restoreStackTraceValue = Error.stackTraceLimit;
+ Error.stackTraceLimit = limit;
+ stackTraceRegistered = true;
+ } catch (e) {
+ // Not all browsers support this so we don't care if it errors
+ }
+}
+
+function unregisterStackTraceLimit() {
+ if (!stackTraceRegistered) {
+ return;
+ }
+
+ try {
+ Error.stackTraceLimit = restoreStackTraceValue;
+ stackTraceRegistered = false;
+ } catch (e) {
+ // Not all browsers support this so we don't care if it errors
+ }
+}
+
+export {
+ registerStackTraceLimit as register,
+ unregisterStackTraceLimit as unregister,
+};
diff --git a/packages/bundler/src/error-overlay/react-overlay/effects/unhandled-error.ts b/packages/bundler/src/error-overlay/react-overlay/effects/unhandled-error.ts
new file mode 100644
index 0000000000..89c01feaa3
--- /dev/null
+++ b/packages/bundler/src/error-overlay/react-overlay/effects/unhandled-error.ts
@@ -0,0 +1,53 @@
+/**
+ * Copyright (c) 2015-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+let boundErrorHandler: EventListenerObject | null = null;
+
+type ErrorCallback = (error: Error) => void;
+
+function errorHandler(callback: ErrorCallback, e: Event): void {
+ // @ts-expect-error
+ if (!e.error) {
+ return;
+ }
+
+ // @ts-expect-error
+ const {error} = e;
+ if (error instanceof Error) {
+ callback(error);
+ } else {
+ // A non-error was thrown, we don't have a trace. :(
+ // Look in your browser's devtools for more information
+ callback(new Error(error));
+ }
+}
+
+function registerUnhandledError(target: EventTarget, callback: ErrorCallback) {
+ if (boundErrorHandler !== null) {
+ return;
+ }
+
+ boundErrorHandler = errorHandler.bind(
+ undefined,
+ callback
+ ) as unknown as EventListenerObject;
+ target.addEventListener('error', boundErrorHandler);
+}
+
+function unregisterUnhandledError(target: EventTarget) {
+ if (boundErrorHandler === null) {
+ return;
+ }
+
+ target.removeEventListener('error', boundErrorHandler);
+ boundErrorHandler = null;
+}
+
+export {
+ registerUnhandledError as register,
+ unregisterUnhandledError as unregister,
+};
diff --git a/packages/bundler/src/error-overlay/react-overlay/effects/unhandled-rejection.ts b/packages/bundler/src/error-overlay/react-overlay/effects/unhandled-rejection.ts
new file mode 100644
index 0000000000..276f0a76f1
--- /dev/null
+++ b/packages/bundler/src/error-overlay/react-overlay/effects/unhandled-rejection.ts
@@ -0,0 +1,57 @@
+/**
+ * Copyright (c) 2015-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+let boundRejectionHandler: EventListener | null = null;
+
+type ErrorCallback = (error: Error) => void;
+
+function rejectionHandler(
+ callback: ErrorCallback,
+ e: PromiseRejectionEvent
+): void {
+ if (!e?.reason) {
+ return callback(new Error('Unknown'));
+ }
+
+ const {reason} = e;
+ if (reason instanceof Error) {
+ return callback(reason);
+ }
+
+ // A non-error was rejected, we don't have a trace :(
+ // Look in your browser's devtools for more information
+ return callback(new Error(reason));
+}
+
+function registerUnhandledRejection(
+ target: EventTarget,
+ callback: ErrorCallback
+) {
+ if (boundRejectionHandler !== null) {
+ return;
+ }
+
+ boundRejectionHandler = rejectionHandler.bind(
+ undefined,
+ callback
+ ) as unknown as EventListener;
+ target.addEventListener('unhandledrejection', boundRejectionHandler);
+}
+
+function unregisterUnhandledRejection(target: EventTarget) {
+ if (boundRejectionHandler === null) {
+ return;
+ }
+
+ target.removeEventListener('unhandledrejection', boundRejectionHandler);
+ boundRejectionHandler = null;
+}
+
+export {
+ registerUnhandledRejection as register,
+ unregisterUnhandledRejection as unregister,
+};
diff --git a/packages/bundler/src/error-overlay/react-overlay/index.ts b/packages/bundler/src/error-overlay/react-overlay/index.ts
new file mode 100644
index 0000000000..9682730a2d
--- /dev/null
+++ b/packages/bundler/src/error-overlay/react-overlay/index.ts
@@ -0,0 +1,47 @@
+import {ErrorRecord, listenToRuntimeErrors} from './listen-to-runtime-errors';
+
+let stopListeningToRuntimeErrors: null | (() => void) = null;
+type RuntimeReportingOptions = {
+ onError: () => void;
+ filename?: string;
+};
+
+let currentRuntimeErrorRecords: Array<ErrorRecord> = [];
+
+export function startReportingRuntimeErrors(options: RuntimeReportingOptions) {
+ if (stopListeningToRuntimeErrors !== null) {
+ throw new Error('Already listening');
+ }
+
+ const handleRuntimeError =
+ (opts: RuntimeReportingOptions) => (errorRecord: ErrorRecord) => {
+ try {
+ if (typeof opts.onError === 'function') {
+ opts.onError.call(null);
+ }
+ } finally {
+ if (
+ currentRuntimeErrorRecords.some(
+ ({error}) => error === errorRecord.error
+ )
+ ) {
+ // Deduplicate identical errors.
+ // This fixes https://github.com/facebook/create-react-app/issues/3011.
+ } else {
+ currentRuntimeErrorRecords = currentRuntimeErrorRecords.concat([
+ errorRecord,
+ ]);
+ update();
+ }
+ }
+ };
+
+ function update() {
+ console.log('do something', currentRuntimeErrorRecords);
+ }
+
+ stopListeningToRuntimeErrors = listenToRuntimeErrors(
+ handleRuntimeError(options),
+ options.filename
+ );
+}
diff --git a/packages/bundler/src/error-overlay/react-overlay/listen-to-runtime-errors.ts b/packages/bundler/src/error-overlay/react-overlay/listen-to-runtime-errors.ts
new file mode 100644
index 0000000000..ec7edce06e
--- /dev/null
+++ b/packages/bundler/src/error-overlay/react-overlay/listen-to-runtime-errors.ts
@@ -0,0 +1,94 @@
+import {StackFrame} from './utils/stack-frame';
+
+export type ErrorRecord = {
+ error: Error;
+ unhandledRejection: boolean;
+ contextSize: number;
+ stackFrames: StackFrame[];
+};
+
+/**
+ * Copyright (c) 2015-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+import {
+ register as registerError,
+ unregister as unregisterError,
+} from './effects/unhandled-error';
+import {
+ register as registerPromise,
+ unregister as unregisterPromise,
+} from './effects/unhandled-rejection';
+import {
+ register as registerStackTraceLimit,
+ unregister as unregisterStackTraceLimit,
+} from './effects/stack-trace-limit';
+import {
+ permanentRegister as permanentRegisterConsole,
+ registerReactStack,
+ unregisterReactStack,
+} from './effects/proxy-console';
+import {massage as massageWarning} from './effects/format-warning';
+import {getStackFrames} from './utils/get-stack-frames';
+
+const CONTEXT_SIZE = 3;
+
+export const crashWithFrames =
+ (crash: (rec: ErrorRecord) => void) =>
+ async (
+ error: Error & {
+ __unmap_source?: string;
+ },
+ unhandledRejection = false
+ ) => {
+ try {
+ const stackFrames = await getStackFrames(error, CONTEXT_SIZE);
+
+ if (stackFrames === null || stackFrames === undefined) {
+ return;
+ }
+
+ crash({
+ error,
+ unhandledRejection,
+ contextSize: CONTEXT_SIZE,
+ stackFrames,
+ });
+ } catch (e) {
+ console.log('Could not get the stack frames of error:', e);
+ }
+ };
+
+export function listenToRuntimeErrors(
+ crash: (rec: ErrorRecord) => void,
+ filename = '/static/js/bundle.js'
+) {
+ const crashWithFramesRunTime = crashWithFrames(crash);
+
+ registerError(window, (error) => crashWithFramesRunTime(error, false));
+ registerPromise(window, (error) => crashWithFramesRunTime(error, true));
+ registerStackTraceLimit();
+ registerReactStack();
+ permanentRegisterConsole('error', (warning, stack) => {
+ const data = massageWarning(warning, stack);
+ crashWithFramesRunTime(
+ {
+ message: data.message,
+ stack: data.stack,
+ __unmap_source: filename,
+ name: '',
+ },
+ false
+ );
+ });
+
+ return function () {
+ unregisterStackTraceLimit();
+ unregisterPromise(window);
+ unregisterError(window);
+ unregisterReactStack();
+ };
+}
diff --git a/packages/bundler/src/error-overlay/react-overlay/utils/get-lines-around.ts b/packages/bundler/src/error-overlay/react-overlay/utils/get-lines-around.ts
new file mode 100644
index 0000000000..51f8f9863b
--- /dev/null
+++ b/packages/bundler/src/error-overlay/react-overlay/utils/get-lines-around.ts
@@ -0,0 +1,35 @@
+/**
+ * Copyright (c) 2015-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+import {ScriptLine} from './stack-frame';
+
+/**
+ *
+ * @param {number} line The line number to provide context around.
+ * @param {number} count The number of lines you'd like for context.
+ * @param {string[] | string} lines The source code.
+ */
+export function getLinesAround(
+ line: number,
+ count: number,
+ lines: string[] | string
+): ScriptLine[] {
+ if (typeof lines === 'string') {
+ lines = lines.split('\n');
+ }
+
+ const result = [];
+ for (
+ let index = Math.max(0, line - 1 - count);
+ index <= Math.min(lines.length - 1, line - 1 + count);
+ ++index
+ ) {
+ result.push(new ScriptLine(index + 1, lines[index], index === line - 1));
+ }
+
+ return result;
+}
diff --git a/packages/bundler/src/error-overlay/react-overlay/utils/get-source-map.ts b/packages/bundler/src/error-overlay/react-overlay/utils/get-source-map.ts
new file mode 100644
index 0000000000..68736284ac
--- /dev/null
+++ b/packages/bundler/src/error-overlay/react-overlay/utils/get-source-map.ts
@@ -0,0 +1,136 @@
+/* eslint-disable no-eq-null */
+/* eslint-disable eqeqeq */
+/**
+ * Copyright (c) 2015-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+import {SourceMapConsumer} from 'source-map';
+
+/**
+ * A wrapped instance of a <code>{@link https://github.com/mozilla/source-map SourceMapConsumer}</code>.
+ *
+ * This exposes methods which will be indifferent to changes made in <code>{@link https://github.com/mozilla/source-map source-map}</code>.
+ */
+class SourceMap {
+ __source_map: SourceMapConsumer;
+
+ constructor(sourceMap: SourceMapConsumer) {
+ this.__source_map = sourceMap;
+ }
+
+ /**
+ * Returns the original code position for a generated code position.
+ * @param {number} line The line of the generated code position.
+ * @param {number} column The column of the generated code position.
+ */
+ getOriginalPosition(
+ line: number,
+ column: number
+ ): {source: string; line: number; column: number} {
+ const {
+ line: l,
+ column: c,
+ source: s,
+ } = this.__source_map.originalPositionFor({
+ line,
+ column,
+ });
+ return {line: l as number, column: c as number, source: s as string};
+ }
+
+ /**
+ * Returns the generated code position for an original position.
+ * @param {string} source The source file of the original code position.
+ * @param {number} line The line of the original code position.
+ * @param {number} column The column of the original code position.
+ */
+ getGeneratedPosition(
+ source: string,
+ line: number,
+ column: number
+ ): {line: number; column: number} {
+ const {line: l, column: c} = this.__source_map.generatedPositionFor({
+ source,
+ line,
+ column,
+ });
+ return {
+ line: l as number,
+ column: c as number,
+ };
+ }
+
+ /**
+ * Returns the code for a given source file name.
+ * @param {string} sourceName The name of the source file.
+ */
+ getSource(sourceName: string): string {
+ return this.__source_map.sourceContentFor(sourceName) as string;
+ }
+
+ getSources(): string[] {
+ // @ts-expect-error
+ return this.__source_map.sources;
+ }
+}
+
+function extractSourceMapUrl(
+ fileUri: string,
+ fileContents: string
+): Promise<string> {
+ const regex = /\/\/[#@] ?sourceMappingURL=([^\s'"]+)\s*$/gm;
+ let match = null;
+ for (;;) {
+ const next = regex.exec(fileContents);
+ if (next == null) {
+ break;
+ }
+
+ match = next;
+ }
+
+ if (!match?.[1]) {
+ return Promise.reject(
+ new Error(`Cannot find a source map directive for ${fileUri}.`)
+ );
+ }
+
+ return Promise.resolve(match[1].toString());
+}
+
+/**
+ * Returns an instance of <code>{@link SourceMap}</code> for a given fileUri and fileContents.
+ * @param {string} fileUri The URI of the source file.
+ * @param {string} fileContents The contents of the source file.
+ */
+async function getSourceMap(
+ fileUri: string,
+ fileContents: string
+): Promise<SourceMap> {
+ let sm = await extractSourceMapUrl(fileUri, fileContents);
+ if (sm.indexOf('data:') === 0) {
+ const base64 = /^data:application\/json;([\w=:"-]+;)*base64,/;
+ const match2 = sm.match(base64);
+ if (!match2) {
+ throw new Error(
+ 'Sorry, non-base64 inline source-map encoding is not supported.'
+ );
+ }
+
+ sm = sm.substring(match2[0].length);
+ sm = window.atob(sm);
+ sm = JSON.parse(sm);
+ return new SourceMap(await new SourceMapConsumer(sm));
+ }
+
+ const index = fileUri.lastIndexOf('/');
+ const url = fileUri.substring(0, index + 1) + sm;
+ const obj = await fetch(url).then((res) => res.json());
+ return new SourceMap(await new SourceMapConsumer(obj));
+}
+
+export {extractSourceMapUrl, getSourceMap};
+export default getSourceMap;
diff --git a/packages/bundler/src/error-overlay/react-overlay/utils/get-stack-frames.ts b/packages/bundler/src/error-overlay/react-overlay/utils/get-stack-frames.ts
new file mode 100644
index 0000000000..3dd4bc50df
--- /dev/null
+++ b/packages/bundler/src/error-overlay/react-overlay/utils/get-stack-frames.ts
@@ -0,0 +1,51 @@
+/**
+ * Copyright (c) 2015-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+import type {StackFrame} from './stack-frame';
+import {parse} from './parser';
+import {map} from './mapper';
+import {unmap} from './unmapper';
+
+function getStackFrames(
+ error: Error & {__unmap_source?: string},
+ contextSize = 3
+): Promise<StackFrame[] | null> {
+ const parsedFrames = parse(error);
+ let enhancedFramesPromise;
+ if (error.__unmap_source) {
+ enhancedFramesPromise = unmap(
+ error.__unmap_source,
+ parsedFrames,
+ contextSize
+ );
+ } else {
+ enhancedFramesPromise = map(parsedFrames, contextSize);
+ }
+
+ return enhancedFramesPromise.then((enhancedFrames) => {
+ if (
+ enhancedFrames
+ .map((f) => f._originalFileName)
+ .filter(
+ (f) =>
+ f !== null && f !== undefined && f.indexOf('node_modules') === -1
+ ).length === 0
+ ) {
+ return null;
+ }
+
+ return enhancedFrames.filter(
+ ({functionName}) =>
+ functionName === null ||
+ functionName === undefined ||
+ functionName.indexOf('__stack_frame_overlay_proxy_console__') === -1
+ );
+ });
+}
+
+export default getStackFrames;
+export {getStackFrames};
diff --git a/packages/bundler/src/error-overlay/react-overlay/utils/mapper.ts b/packages/bundler/src/error-overlay/react-overlay/utils/mapper.ts
new file mode 100644
index 0000000000..9ef1c230b4
--- /dev/null
+++ b/packages/bundler/src/error-overlay/react-overlay/utils/mapper.ts
@@ -0,0 +1,82 @@
+/**
+ * Copyright (c) 2015-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+import {StackFrame} from './stack-frame';
+import {getSourceMap} from './get-source-map';
+import {getLinesAround} from './get-lines-around';
+import {settle} from './settle-promise';
+
+/**
+ * Enhances a set of <code>StackFrame</code>s with their original positions and code (when available).
+ * @param {StackFrame[]} frames A set of <code>StackFrame</code>s which contain (generated) code positions.
+ * @param {number} [contextLines=3] The number of lines to provide before and after the line specified in the <code>StackFrame</code>.
+ */
+async function map(
+ frames: StackFrame[],
+ contextLines = 3
+): Promise<StackFrame[]> {
+ const cache: any = {};
+ const files: string[] = [];
+ frames.forEach((frame) => {
+ const {fileName} = frame;
+ if (fileName === null || fileName === undefined) {
+ return;
+ }
+
+ if (files.indexOf(fileName) !== -1) {
+ return;
+ }
+
+ files.push(fileName);
+ });
+ await settle(
+ files.map(async (fileName) => {
+ const fetchUrl =
+ fileName.indexOf('webpack-internal:') === 0
+ ? `/__get-internal-source?fileName=${encodeURIComponent(fileName)}`
+ : fileName;
+
+ const fileSource = await fetch(fetchUrl).then((r) => r.text());
+ const _map = await getSourceMap(fileName, fileSource);
+ cache[fileName] = {fileSource, map: _map};
+ })
+ );
+ return frames.map((frame) => {
+ const {functionName, fileName, lineNumber, columnNumber} = frame;
+ const {map: _map, fileSource} = cache[fileName as string] || {};
+ if (
+ _map === null ||
+ _map === undefined ||
+ lineNumber === null ||
+ lineNumber === undefined
+ ) {
+ return frame;
+ }
+
+ const {source, line, column} = _map.getOriginalPosition(
+ lineNumber,
+ columnNumber
+ );
+ const originalSource =
+ source === null || source === undefined ? [] : _map.getSource(source);
+ return new StackFrame(
+ functionName,
+ fileName,
+ lineNumber,
+ columnNumber,
+ getLinesAround(lineNumber, contextLines, fileSource),
+ functionName,
+ source,
+ line,
+ column,
+ getLinesAround(line, contextLines, originalSource)
+ );
+ });
+}
+
+export {map};
+export default map;
diff --git a/packages/bundler/src/error-overlay/react-overlay/utils/parser.ts b/packages/bundler/src/error-overlay/react-overlay/utils/parser.ts
new file mode 100644
index 0000000000..2a209bd105
--- /dev/null
+++ b/packages/bundler/src/error-overlay/react-overlay/utils/parser.ts
@@ -0,0 +1,106 @@
+/**
+ * Copyright (c) 2015-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+import {StackFrame} from './stack-frame';
+
+const regexExtractLocation = /\(?(.+?)(?::(\d+))?(?::(\d+))?\)?$/;
+
+function extractLocation(token: string): [string, number, number] {
+ const execed = regexExtractLocation.exec(token);
+ if (!execed) {
+ throw new Error('Could not match in extractLocation');
+ }
+
+ return execed.slice(1).map((v) => {
+ const p = Number(v);
+ if (!isNaN(p)) {
+ return p;
+ }
+
+ return v;
+ }) as [string, number, number];
+}
+
+const regexValidFrame_Chrome = /^\s*(at|in)\s.+(:\d+)/;
+const regexValidFrame_FireFox =
+ /(^|@)\S+:\d+|.+line\s+\d+\s+>\s+(eval|Function).+/;
+
+function parseStack(stack: string[]): StackFrame[] {
+ const frames = stack
+ .filter(
+ (e) => regexValidFrame_Chrome.test(e) || regexValidFrame_FireFox.test(e)
+ )
+ .map((e) => {
+ if (regexValidFrame_FireFox.test(e)) {
+ // Strip eval, we don't care about it
+ let isEval = false;
+ if (/ > (eval|Function)/.test(e)) {
+ e = e.replace(
+ / line (\d+)(?: > eval line \d+)* > (eval|Function):\d+:\d+/g,
+ ':$1'
+ );
+ isEval = true;
+ }
+
+ const _data = e.split(/[@]/g);
+ const _last = _data.pop();
+ if (!_last) {
+ throw new Error('could not get last');
+ }
+
+ return new StackFrame(
+ _data.join('@') || (isEval ? 'eval' : null),
+ ...extractLocation(_last)
+ );
+ }
+
+ // Strip eval, we don't care about it
+ if (e.indexOf('(eval ') !== -1) {
+ e = e.replace(/(\(eval at [^()]*)|(\),.*$)/g, '');
+ }
+
+ if (e.indexOf('(at ') !== -1) {
+ e = e.replace(/\(at /, '(');
+ }
+
+ const data = e.trim().split(/\s+/g).slice(1);
+ const last = data.pop();
+ if (!last) {
+ throw new Error('could not get last');
+ }
+
+ return new StackFrame(data.join(' ') || null, ...extractLocation(last));
+ });
+ return frames;
+}
+
+/**
+ * Turns an <code>Error</code>, or similar object, into a set of <code>StackFrame</code>s.
+ * @alias parse
+ */
+function parseError(error: Error | string | string[]): StackFrame[] {
+ if (error === null) {
+ throw new Error('You cannot pass a null object.');
+ }
+
+ if (typeof error === 'string') {
+ return parseStack(error.split('\n'));
+ }
+
+ if (Array.isArray(error)) {
+ return parseStack(error);
+ }
+
+ if (typeof error.stack === 'string') {
+ return parseStack(error.stack.split('\n'));
+ }
+
+ throw new Error('The error you provided does not contain a stack trace.');
+}
+
+export {parseError as parse};
+export default parseError;
diff --git a/packages/bundler/src/error-overlay/react-overlay/utils/path.ts b/packages/bundler/src/error-overlay/react-overlay/utils/path.ts
new file mode 100644
index 0000000000..8e3f240a54
--- /dev/null
+++ b/packages/bundler/src/error-overlay/react-overlay/utils/path.ts
@@ -0,0 +1,84 @@
+function normalizeStringPosix(path: string, allowAboveRoot: boolean) {
+ let res = '';
+ let lastSegmentLength = 0;
+ let lastSlash = -1;
+ let dots = 0;
+ let code;
+ for (let i = 0; i <= path.length; ++i) {
+ if (i < path.length) code = path.charCodeAt(i);
+ else if (code === 47 /* / */) break;
+ else code = 47 /* / */;
+ if (code === 47 /* / */) {
+ if (lastSlash === i - 1 || dots === 1) {
+ // NOOP
+ } else if (lastSlash !== i - 1 && dots === 2) {
+ if (
+ res.length < 2 ||
+ lastSegmentLength !== 2 ||
+ res.charCodeAt(res.length - 1) !== 46 /* . */ ||
+ res.charCodeAt(res.length - 2) !== 46 /* . */
+ ) {
+ if (res.length > 2) {
+ const lastSlashIndex = res.lastIndexOf('/');
+ // eslint-disable-next-line max-depth
+ if (lastSlashIndex !== res.length - 1) {
+ // eslint-disable-next-line max-depth
+ if (lastSlashIndex === -1) {
+ res = '';
+ lastSegmentLength = 0;
+ } else {
+ res = res.slice(0, lastSlashIndex);
+ lastSegmentLength = res.length - 1 - res.lastIndexOf('/');
+ }
+
+ lastSlash = i;
+ dots = 0;
+ continue;
+ }
+ } else if (res.length === 2 || res.length === 1) {
+ res = '';
+ lastSegmentLength = 0;
+ lastSlash = i;
+ dots = 0;
+ continue;
+ }
+ }
+
+ if (allowAboveRoot) {
+ if (res.length > 0) res += '/..';
+ else res = '..';
+ lastSegmentLength = 2;
+ }
+ } else {
+ if (res.length > 0) res += '/' + path.slice(lastSlash + 1, i);
+ else res = path.slice(lastSlash + 1, i);
+ lastSegmentLength = i - lastSlash - 1;
+ }
+
+ lastSlash = i;
+ dots = 0;
+ } else if (code === 46 /* . */ && dots !== -1) {
+ ++dots;
+ } else {
+ dots = -1;
+ }
+ }
+
+ return res;
+}
+
+export function pathNormalize(path: string) {
+ if (path.length === 0) return '.';
+
+ const isAbsolute = path.charCodeAt(0) === 47; /* / */
+ const trailingSeparator = path.charCodeAt(path.length - 1) === 47; /* / */
+
+ // Normalize the path
+ path = normalizeStringPosix(path, !isAbsolute);
+
+ if (path.length === 0 && !isAbsolute) path = '.';
+ if (path.length > 0 && trailingSeparator) path += '/';
+
+ if (isAbsolute) return '/' + path;
+ return path;
+}
diff --git a/packages/bundler/src/error-overlay/react-overlay/utils/settle-promise.ts b/packages/bundler/src/error-overlay/react-overlay/utils/settle-promise.ts
new file mode 100644
index 0000000000..4b94220e16
--- /dev/null
+++ b/packages/bundler/src/error-overlay/react-overlay/utils/settle-promise.ts
@@ -0,0 +1,22 @@
+function settle(
+ val: Array<Promise<unknown>> | Promise<unknown>
+): Promise<unknown> {
+ if (!Array.isArray(val)) val = [val];
+ return Promise.all(
+ val.map((p) =>
+ p
+ .then((value) => ({
+ isFulfilled: true,
+ isRejected: false,
+ value,
+ }))
+ .catch((reason) => ({
+ isFulfilled: false,
+ isRejected: true,
+ reason,
+ }))
+ )
+ );
+}
+
+export {settle};
diff --git a/packages/bundler/src/error-overlay/react-overlay/utils/stack-frame.ts b/packages/bundler/src/error-overlay/react-overlay/utils/stack-frame.ts
new file mode 100644
index 0000000000..cc3891603c
--- /dev/null
+++ b/packages/bundler/src/error-overlay/react-overlay/utils/stack-frame.ts
@@ -0,0 +1,121 @@
+/**
+ * Copyright (c) 2015-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+/** A container holding a script line. */
+export class ScriptLine {
+ /** The line number of this line of source. */
+ lineNumber: number;
+ /** The content (or value) of this line of source. */
+ content: string;
+ /** Whether or not this line should be highlighted. Particularly useful for error reporting with context. */
+ highlight: boolean;
+
+ constructor(lineNumber: number, content: string, highlight = false) {
+ this.lineNumber = lineNumber;
+ this.content = content;
+ this.highlight = highlight;
+ }
+}
+
+/**
+ * A representation of a stack frame.
+ */
+export class StackFrame {
+ functionName: string | null;
+ fileName: string | null;
+ lineNumber: number | null;
+ columnNumber: number | null;
+
+ _originalFunctionName: string | null;
+ _originalFileName: string | null;
+ _originalLineNumber: number | null;
+ _originalColumnNumber: number | null;
+
+ _scriptCode: ScriptLine[] | null;
+ _originalScriptCode: ScriptLine[] | null;
+
+ // eslint-disable-next-line max-params
+ constructor(
+ functionName: string | null = null,
+ fileName: string | null = null,
+ lineNumber: number | null = null,
+ columnNumber: number | null = null,
+ scriptCode: ScriptLine[] | null = null,
+ sourceFunctionName: string | null = null,
+ sourceFileName: string | null = null,
+ sourceLineNumber: number | null = null,
+ sourceColumnNumber: number | null = null,
+ sourceScriptCode: ScriptLine[] | null = null
+ ) {
+ if (functionName && functionName.indexOf('Object.') === 0) {
+ functionName = functionName.slice('Object.'.length);
+ }
+
+ if (
+ // Chrome has a bug with inferring function.name:
+ // https://github.com/facebook/create-react-app/issues/2097
+ // Let's ignore a meaningless name we get for top-level modules.
+ functionName === 'friendlySyntaxErrorLabel' ||
+ functionName === 'exports.__esModule' ||
+ functionName === '<anonymous>' ||
+ !functionName
+ ) {
+ functionName = null;
+ }
+
+ this.functionName = functionName;
+
+ this.fileName = fileName;
+ this.lineNumber = lineNumber;
+ this.columnNumber = columnNumber;
+
+ this._originalFunctionName = sourceFunctionName;
+ this._originalFileName = sourceFileName;
+ this._originalLineNumber = sourceLineNumber;
+ this._originalColumnNumber = sourceColumnNumber;
+
+ this._scriptCode = scriptCode;
+ this._originalScriptCode = sourceScriptCode;
+ }
+
+ /**
+ * Returns the name of this function.
+ */
+ getFunctionName(): string {
+ return this.functionName || '(anonymous function)';
+ }
+
+ /**
+ * Returns the source of the frame.
+ * This contains the file name, line number, and column number when available.
+ */
+ getSource(): string {
+ let str = '';
+ if (this.fileName !== null) {
+ str += this.fileName + ':';
+ }
+
+ if (this.lineNumber !== null) {
+ str += this.lineNumber + ':';
+ }
+
+ if (this.columnNumber !== null) {
+ str += this.columnNumber + ':';
+ }
+
+ return str.slice(0, -1);
+ }
+
+ /**
+ * Returns a pretty version of this stack frame.
+ */
+ toString(): string {
+ const functionName = this.getFunctionName();
+ const source = this.getSource();
+ return `${functionName}${source ? ` (${source})` : ``}`;
+ }
+}
diff --git a/packages/bundler/src/error-overlay/react-overlay/utils/unmapper.ts b/packages/bundler/src/error-overlay/react-overlay/utils/unmapper.ts
new file mode 100644
index 0000000000..6ee4c26021
--- /dev/null
+++ b/packages/bundler/src/error-overlay/react-overlay/utils/unmapper.ts
@@ -0,0 +1,128 @@
+/* eslint-disable eqeqeq */
+/* eslint-disable no-eq-null */
+/**
+ * Copyright (c) 2015-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+import {getLinesAround} from './get-lines-around';
+import {getSourceMap} from './get-source-map';
+import {pathNormalize} from './path';
+import {StackFrame} from './stack-frame';
+
+function count(search: string, string: string): number {
+ // Count starts at -1 because a do-while loop always runs at least once
+ let _count = -1;
+ let index = -1;
+ do {
+ // First call or the while case evaluated true, meaning we have to make
+ // count 0 or we found a character
+ ++_count;
+ // Find the index of our search string, starting after the previous index
+ index = string.indexOf(search, index + 1);
+ } while (index !== -1);
+
+ return _count;
+}
+
+/**
+ * Turns a set of mapped <code>StackFrame</code>s back into their generated code position and enhances them with code.
+ * @param {string} fileUri The URI of the <code>bundle.js</code> file.
+ * @param {StackFrame[]} frames A set of <code>StackFrame</code>s which are already mapped and missing their generated positions.
+ * @param {number} [fileContents=3] The number of lines to provide before and after the line specified in the <code>StackFrame</code>.
+ */
+async function unmap(
+ _fileUri: string | {uri: string; contents: string},
+ frames: StackFrame[],
+ contextLines = 3
+): Promise<StackFrame[]> {
+ let fileContents = typeof _fileUri === 'object' ? _fileUri.contents : null;
+ const fileUri = typeof _fileUri === 'object' ? _fileUri.uri : _fileUri;
+ if (fileContents == null) {
+ fileContents = await fetch(fileUri).then((res) => res.text());
+ }
+
+ const map = await getSourceMap(fileUri, fileContents as string);
+ return frames.map((frame) => {
+ const {functionName, lineNumber, columnNumber, _originalLineNumber} = frame;
+ if (_originalLineNumber != null) {
+ return frame;
+ }
+
+ let {fileName} = frame;
+ if (fileName) {
+ // The web version of this module only provides POSIX support, so Windows
+ // paths like C:\foo\\baz\..\\bar\ cannot be normalized.
+ // A simple solution to this is to replace all `\` with `/`, then
+ // normalize afterwards.
+ fileName = pathNormalize(fileName.replace(/[\\]+/g, '/'));
+ }
+
+ if (fileName == null) {
+ return frame;
+ }
+
+ const fN: string = fileName;
+ const source = map
+ .getSources()
+ // Prepare path for normalization; see comment above for reasoning.
+ .map((s) => s.replace(/[\\]+/g, '/'))
+ .filter((p) => {
+ p = pathNormalize(p);
+ const i = p.lastIndexOf(fN);
+ return i !== -1 && i === p.length - fN.length;
+ })
+ .map((p) => ({
+ token: p,
+ seps: count('/', pathNormalize(p)),
+ penalties: count('node_modules', p) + count('~', p),
+ }))
+ .sort((a, b) => {
+ const s = Math.sign(a.seps - b.seps);
+ if (s !== 0) {
+ return s;
+ }
+
+ return Math.sign(a.penalties - b.penalties);
+ });
+ if (source.length < 1 || lineNumber == null) {
+ return new StackFrame(
+ null,
+ null,
+ null,
+ null,
+ null,
+ functionName,
+ fN,
+ lineNumber,
+ columnNumber,
+ null
+ );
+ }
+
+ const sourceT = source[0].token;
+ const {line, column} = map.getGeneratedPosition(
+ sourceT,
+ lineNumber,
+ columnNumber as number
+ );
+ const originalSource = map.getSource(sourceT);
+ return new StackFrame(
+ functionName,
+ fileUri,
+ line,
+ column || null,
+ getLinesAround(line, contextLines, fileContents || []),
+ functionName,
+ fN,
+ lineNumber,
+ columnNumber,
+ getLinesAround(lineNumber, contextLines, originalSource)
+ );
+ });
+}
+
+export {unmap};
+export default unmap;
diff --git a/packages/bundler/src/webpack-config.ts b/packages/bundler/src/webpack-config.ts
index 37ed4ba06a..9f9e4d23cc 100644
--- a/packages/bundler/src/webpack-config.ts
+++ b/packages/bundler/src/webpack-config.ts
@@ -55,7 +55,10 @@ export const webpackConfig = ({
name: getWebpackCacheName(environment, inputProps ?? {}),
}
: false,
- devtool: environment === 'development' ? 'eval' : 'cheap-module-source-map',
+ devtool:
+ environment === 'development'
+ ? 'cheap-module-source-map'
+ : 'cheap-module-source-map',
entry: [
require.resolve('./setup-environment'),
environment === 'development'
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8af7cea290..3ee712bef8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -125,6 +125,7 @@ importers:
react-refresh: ^0.9.0-rc.2
remotion: 2.5.7
semver: 7.3.4
+ source-map: ^0.5.7
source-map-loader: ^3.0.0
style-loader: ^2.0.0
typescript: ^4.4.2
@@ -143,6 +144,7 @@ importers:
react-refresh: 0.9.0
remotion: link:../core
semver: 7.3.4
+ source-map: 0.5.7
source-map-loader: [email protected]
style-loader: [email protected]
webpack: 5.60.0