diff --git a/.changeset/slow-news-tease.md b/.changeset/slow-news-tease.md new file mode 100644 index 000000000000..d1dfb4f12b98 --- /dev/null +++ b/.changeset/slow-news-tease.md @@ -0,0 +1,9 @@ +--- +"wrangler": patch +--- + +fix: add `fetch()` dev helper correctly for pnp style package managers + +In https://github.com/cloudflare/wrangler2/pull/992, we added a dev-only helper that would warn when using `fetch()` in a manner that wouldn't work as expected (because of a bug we currently have in the runtime). We did this by injecting a file that would override usages of `fetch()`. When using pnp style package managers like yarn, this file can't be resolved correctly. So to fix that, we extract it into the temporary destination directory that we use to build the worker (much like a similar fix we did in https://github.com/cloudflare/wrangler2/pull/1154) + +Reported at https://github.com/cloudflare/wrangler2/issues/1320#issuecomment-1188804668 diff --git a/packages/wrangler/src/bundle.ts b/packages/wrangler/src/bundle.ts index 5c26df8b6c70..455ab846c590 100644 --- a/packages/wrangler/src/bundle.ts +++ b/packages/wrangler/src/bundle.ts @@ -92,14 +92,37 @@ export async function bundleWorker( rules, }); + // In dev, we want to patch `fetch()` with a special version that looks + // for bad usages and can warn the user about them; so we inject + // `checked-fetch.js` to do so. However, with yarn 3 style pnp, + // we need to extract that file to an accessbile place before injecting + // it in, hence this code here. + let checkedFetchFileToInject: string | undefined; + if (checkFetch) { + fs.mkdirSync(path.join(destination, "--temp-wrangler-files--"), { + recursive: true, + }); + checkedFetchFileToInject = path.join( + destination, + "--temp-wrangler-files--", + "checked-fetch.js" + ); + fs.writeFileSync( + checkedFetchFileToInject, + fs.readFileSync(path.resolve(__dirname, "../templates/checked-fetch.js")) + ); + } + // TODO: we need to have similar logic like above for other files + // like the static asset facade, and other middleware that we + // plan on injecting/referencing. + const result = await esbuild.build({ ...getEntryPoint(entry.file, serveAssetsFromWorker), bundle: true, absWorkingDir: entry.directory, outdir: destination, - inject: checkFetch - ? [path.resolve(__dirname, "../templates/checked-fetch.js")] - : [], + inject: + checkFetch && checkedFetchFileToInject ? [checkedFetchFileToInject] : [], external: ["__STATIC_CONTENT_MANIFEST"], format: entry.format === "modules" ? "esm" : "iife", target: "es2020",