Unverified Commit dba20c3d authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Turbopack: Add react refresh runtime stubs to workers (#78433)

Analogous to https://github.com/vercel/next.js/pull/15145, this adds
no-op stubs to take the place of the react refresh runtime in workers.

This prevents workers from failing when they use react components, such
as in non-dom react renderers like
[`@react-three/offscreen`](https://github.com/pmndrs/react-three-offscreen).

This code is only added in dev, and the base runtime was parameterized
to allow this.

Test Plan:
- Manually create a worker that uses `@react-three/offscreen` to render
a component and use it in dev.
- [x] Automated test
parent f5054deb
'use client'
import { useEffect } from 'react'
export default function ClientComponent() {
useEffect(() => {
new Worker(new URL('./worker.tsx', import.meta.url))
}, [])
return <p>This is a client component</p>
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import ClientComponent from './client'
export default function Page() {
return <ClientComponent />
}
import { render } from '@react-three/offscreen'
render(<Scene />)
function Scene() {
return (
<mesh>
<boxGeometry />
<meshStandardMaterial color="orange" />
</mesh>
)
}
{
"dependencies": {
"@react-three/offscreen": "^0.0.8"
}
}
import { nextTestSetup } from 'e2e-utils'
describe('worker-react-refresh', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
dependencies: require('./package.json').dependencies,
})
if (skipped) {
return
}
it('does not cause any runtime errors', async () => {
const pageErrors: unknown[] = []
await next.browser('/', {
beforePageLoad: (page) => {
page.on('pageerror', (error: unknown) => {
pageErrors.push(error)
})
},
})
// If the worker runtime does not implement the React Refresh API (i.e.
// `register` and `signature`), transformed React code attempts to call it
// and fails.
expect(pageErrors).toBeEmpty()
})
})
...@@ -131,6 +131,15 @@ const getOrInstantiateModuleFromParent: GetOrInstantiateModuleFromParent<HotModu ...@@ -131,6 +131,15 @@ const getOrInstantiateModuleFromParent: GetOrInstantiateModuleFromParent<HotModu
}); });
}; };
function getDevWorkerBlobURL(chunks) {
return getWorkerBlobURL(
chunks,
`// noop fns to prevent runtime errors during initialization
self.$RefreshReg$ = function() {};
self.$RefreshSig$ = function() {};`
);
}
// @ts-ignore Defined in `runtime-base.ts` // @ts-ignore Defined in `runtime-base.ts`
function instantiateModule(id: ModuleId, source: SourceInfo): Module { function instantiateModule(id: ModuleId, source: SourceInfo): Module {
const moduleFactory = moduleFactories[id]; const moduleFactory = moduleFactories[id];
...@@ -223,7 +232,7 @@ function instantiateModule(id: ModuleId, source: SourceInfo): Module { ...@@ -223,7 +232,7 @@ function instantiateModule(id: ModuleId, source: SourceInfo): Module {
U: relativeURL, U: relativeURL,
k: refresh, k: refresh,
R: createResolvePathFromModule(r), R: createResolvePathFromModule(r),
b: getWorkerBlobURL, b: getDevWorkerBlobURL,
z: requireStub, z: requireStub,
d: typeof module.id === "string" ? module.id.replace(/(^|\/)\/+$/, "") : module.id d: typeof module.id === "string" ? module.id.replace(/(^|\/)\/+$/, "") : module.id
}) })
......
...@@ -252,9 +252,15 @@ function resolveAbsolutePath(modulePath?: string): string { ...@@ -252,9 +252,15 @@ function resolveAbsolutePath(modulePath?: string): string {
return `/ROOT/${modulePath ?? ""}`; return `/ROOT/${modulePath ?? ""}`;
} }
function getWorkerBlobURL(chunks: ChunkPath[]): string { /**
* Returns a blob URL for the worker.
* @param chunks list of chunks to load
* @param beforeLoad code to run before code is loaded. Used in dev for HMR setup.
*/
function getWorkerBlobURL(chunks: ChunkPath[], beforeLoad: string | undefined): string {
let bootstrap = `self.TURBOPACK_WORKER_LOCATION = ${JSON.stringify(location.origin)}; let bootstrap = `self.TURBOPACK_WORKER_LOCATION = ${JSON.stringify(location.origin)};
self.TURBOPACK_NEXT_CHUNK_URLS = ${JSON.stringify(chunks.reverse().map(getChunkRelativeUrl), null, 2)}; self.TURBOPACK_NEXT_CHUNK_URLS = ${JSON.stringify(chunks.reverse().map(getChunkRelativeUrl), null, 2)};
${beforeLoad || ""}
importScripts(...self.TURBOPACK_NEXT_CHUNK_URLS.map(c => self.TURBOPACK_WORKER_LOCATION + c).reverse());`; importScripts(...self.TURBOPACK_NEXT_CHUNK_URLS.map(c => self.TURBOPACK_WORKER_LOCATION + c).reverse());`;
let blob = new Blob([bootstrap], { type: "text/javascript" }); let blob = new Blob([bootstrap], { type: "text/javascript" });
return URL.createObjectURL(blob); return URL.createObjectURL(blob);
......
...@@ -493,9 +493,14 @@ async function loadChunkPath(source, chunkPath) { ...@@ -493,9 +493,14 @@ async function loadChunkPath(source, chunkPath) {
*/ function resolveAbsolutePath(modulePath) { */ function resolveAbsolutePath(modulePath) {
return `/ROOT/${modulePath ?? ""}`; return `/ROOT/${modulePath ?? ""}`;
} }
function getWorkerBlobURL(chunks) { /**
* Returns a blob URL for the worker.
* @param chunks list of chunks to load
* @param beforeLoad code to run before code is loaded. Used in dev for HMR setup.
*/ function getWorkerBlobURL(chunks, beforeLoad) {
let bootstrap = `self.TURBOPACK_WORKER_LOCATION = ${JSON.stringify(location.origin)}; let bootstrap = `self.TURBOPACK_WORKER_LOCATION = ${JSON.stringify(location.origin)};
self.TURBOPACK_NEXT_CHUNK_URLS = ${JSON.stringify(chunks.reverse().map(getChunkRelativeUrl), null, 2)}; self.TURBOPACK_NEXT_CHUNK_URLS = ${JSON.stringify(chunks.reverse().map(getChunkRelativeUrl), null, 2)};
${beforeLoad || ""}
importScripts(...self.TURBOPACK_NEXT_CHUNK_URLS.map(c => self.TURBOPACK_WORKER_LOCATION + c).reverse());`; importScripts(...self.TURBOPACK_NEXT_CHUNK_URLS.map(c => self.TURBOPACK_WORKER_LOCATION + c).reverse());`;
let blob = new Blob([ let blob = new Blob([
bootstrap bootstrap
...@@ -655,6 +660,11 @@ const getOrInstantiateModuleFromParent = (id, sourceModule)=>{ ...@@ -655,6 +660,11 @@ const getOrInstantiateModuleFromParent = (id, sourceModule)=>{
parentId: sourceModule.id parentId: sourceModule.id
}); });
}; };
function getDevWorkerBlobURL(chunks) {
return getWorkerBlobURL(chunks, `// noop fns to prevent runtime errors during initialization
self.$RefreshReg$ = function() {};
self.$RefreshSig$ = function() {};`);
}
// @ts-ignore Defined in `runtime-base.ts` // @ts-ignore Defined in `runtime-base.ts`
function instantiateModule(id, source) { function instantiateModule(id, source) {
const moduleFactory = moduleFactories[id]; const moduleFactory = moduleFactories[id];
...@@ -742,7 +752,7 @@ function instantiateModule(id, source) { ...@@ -742,7 +752,7 @@ function instantiateModule(id, source) {
U: relativeURL, U: relativeURL,
k: refresh, k: refresh,
R: createResolvePathFromModule(r), R: createResolvePathFromModule(r),
b: getWorkerBlobURL, b: getDevWorkerBlobURL,
z: requireStub, z: requireStub,
d: typeof module.id === "string" ? module.id.replace(/(^|\/)\/+$/, "") : module.id d: typeof module.id === "string" ? module.id.replace(/(^|\/)\/+$/, "") : module.id
})); }));
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment