🎥 Make videos programmatically with React
inline fast refresh
Jonny Burger26ae0a20b9c1
diff --git a/packages/bundler/src/fast-refresh/helpers.ts b/packages/bundler/src/fast-refresh/helpers.tsnew file mode 100644index 0000000000..c2cbfb209c--- /dev/null+++ b/packages/bundler/src/fast-refresh/helpers.ts@@ -0,0 +1,184 @@+/**+ * 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.+ */++// 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: string) {+ return (+ key === '__esModule' ||+ key === '__N_SSG' ||+ key === '__N_SSP' ||+ key === 'config'+ );+}++function registerExportsForReactRefresh(+ moduleExports: unknown,+ moduleID: unknown+) {+ 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: unknown) {+ 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 shouldInvalidateReactRefreshBoundary(+ prevExports: unknown,+ nextExports: unknown+) {+ 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 getRefreshBoundarySignature(moduleExports: unknown) {+ 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;+}++let isUpdateScheduled = false;+function scheduleUpdate() {+ if (isUpdateScheduled) {+ return;+ }++ function canApplyUpdate() {+ return module.hot?.status() === 'idle';+ }++ isUpdateScheduled = true;+ setTimeout(() => {+ isUpdateScheduled = false;++ // Only trigger refresh if the webpack HMR state is idle+ if (canApplyUpdate()) {+ try {+ RefreshRuntime.performReactRefresh();+ } catch (err) {+ console.warn(+ 'Warning: Failed to re-render. We will retry on the next Fast Refresh event.\n' ++ err+ );+ }++ return;+ }++ return scheduleUpdate();+ }, 30);+}++export default {+ registerExportsForReactRefresh,+ isReactRefreshBoundary,+ shouldInvalidateReactRefreshBoundary,+ getRefreshBoundarySignature,+ scheduleUpdate,+};diff --git a/packages/bundler/src/fast-refresh/index.ts b/packages/bundler/src/fast-refresh/index.tsnew file mode 100644index 0000000000..e70b282f93--- /dev/null+++ b/packages/bundler/src/fast-refresh/index.ts@@ -0,0 +1,106 @@+/**+ * 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.+ */++// This file is copied from the @vercel/next.js, with removed TS annotations+// minor tweaks, and removed all webpack v4-related functionality+//+// https://github.com/vercel/next.js/blob/canary/packages/react-refresh-utils/ReactRefreshWebpackPlugin.ts++import webpack from 'webpack';+import {Template, RuntimeModule, RuntimeGlobals, version} from 'webpack';++class ReactRefreshRuntimeModule extends RuntimeModule {+ constructor() {+ super('react refresh', 5);+ }++ generate() {+ const {runtimeTemplate} = this.compilation;+ return Template.asString([+ `${+ 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 {',+ Template.indent(+ 'originalFactory.call(this, moduleObject, moduleExports, webpackRequire);'+ ),+ '} finally {',+ Template.indent(`cleanup();`),+ '}',+ ]+ )}`,+ ])})`,+ ]);+ }+}++class ReactFreshWebpackPlugin {+ apply(compiler: webpack.Compiler) {+ const webpackMajorVersion = parseInt(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) =>+ Template.asString([+ source,+ '',+ '// noop fns to prevent runtime errors during initialization',+ 'if (typeof self !== "undefined") {',+ Template.indent('self.$RefreshReg$ = function () {};'),+ Template.indent('self.$RefreshSig$ = function () {'),+ Template.indent(Template.indent('return function (type) {')),+ Template.indent(Template.indent(Template.indent('return type;'))),+ Template.indent(Template.indent('};')),+ Template.indent('};'),+ '}',+ ])+ );++ compilation.hooks.additionalTreeRuntimeRequirements.tap(+ this.constructor.name,+ (chunk) => {+ compilation.addRuntimeModule(chunk, new ReactRefreshRuntimeModule());+ }+ );+ });+ }+}++module.exports = ReactFreshWebpackPlugin;diff --git a/packages/bundler/src/fast-refresh/loader.ts b/packages/bundler/src/fast-refresh/loader.tsnew file mode 100644index 0000000000..4efd3a3732--- /dev/null+++ b/packages/bundler/src/fast-refresh/loader.ts@@ -0,0 +1,109 @@+/**+ * 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.+ */++// 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() {+ // 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 = module.__proto__.exports;+ let prevExports = null;++ if (module.hot?.data?.prevExports) {+ prevExports = module.hot.data.prevExports;+ }++ // This cannot happen in MainTemplate because the exports mismatch between+ // templating and execution.+ self.$RefreshHelpers$.registerExportsForReactRefresh(+ currentExports,+ 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.+ 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.+ 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+ )+ ) {+ 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) {+ module.hot?.invalidate();+ }+ }+ }+}++let refreshModuleRuntime = RefreshModuleRuntime.toString();+refreshModuleRuntime = refreshModuleRuntime.slice(+ refreshModuleRuntime.indexOf('{') + 1,+ refreshModuleRuntime.lastIndexOf('}')+);++module.exports = function ReactRefreshLoader(source, inputSourceMap) {+ this.callback(null, `${source}\n\n;${refreshModuleRuntime}`, inputSourceMap);+};diff --git a/packages/bundler/src/fast-refresh/runtime.ts b/packages/bundler/src/fast-refresh/runtime.tsnew file mode 100644index 0000000000..3186988d34--- /dev/null+++ b/packages/bundler/src/fast-refresh/runtime.ts@@ -0,0 +1,68 @@+/**+ * 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.+ */++// 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/runtime.ts++declare global {+ interface Window {+ $RefreshReg$: (type: string, id?: string) => void;+ $RefreshSig$: () => (type: string) => unknown;+ $RefreshHelpers$: typeof RefreshHelpers;+ $RefreshInterceptModuleExecution$: (webpackId: unknown) => () => void;+ }+}++const RefreshRuntime = require('react-refresh/runtime');+import RefreshHelpers from './helpers';++// Hook into ReactDOM initialization+RefreshRuntime.injectIntoGlobalHook(self);++// noop fns to prevent runtime errors during initialization+self.$RefreshReg$ = () => undefined;+self.$RefreshSig$ = () => (type: unknown) => type;++// Register global helpers+self.$RefreshHelpers$ = RefreshHelpers;++// Register a helper for module execution interception+self.$RefreshInterceptModuleExecution$ = function (webpackModuleId: unknown) {+ 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:+ // https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup+ return () => {+ self.$RefreshReg$ = prevRefreshReg;+ self.$RefreshSig$ = prevRefreshSig;+ };+};