Skip to content

fix: add require shims #2050

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions packages/runtime/src/templates/edge/shims.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
// @ts-check
// deno-lint-ignore-file no-var prefer-const no-unused-vars no-explicit-any
// deno-lint-ignore-file prefer-const no-unused-vars
import { decode as _base64Decode } from 'https://deno.land/std@0.175.0/encoding/base64.ts'
import { AsyncLocalStorage as ALSCompat } from 'https://deno.land/std@0.175.0/node/async_hooks.ts'
import BufferCompat from 'https://deno.land/std@0.175.0/node/buffer.ts'
import EventsCompat from 'https://deno.land/std@0.175.0/node/events.ts'
import AsyncHooksCompat from 'https://deno.land/std@0.175.0/node/async_hooks.ts'
import AssertCompat from 'https://deno.land/std@0.175.0/node/assert.ts'
import UtilCompat from 'https://deno.land/std@0.175.0/node/util.ts'

/**
* These are the shims, polyfills and other kludges to make Next.js work in standards-compliant runtime.
Expand All @@ -18,7 +22,7 @@ globalThis.EdgeRuntime = 'netlify-edge'
let _ENTRIES = {}

// Next.js expects this as a global
globalThis.AsyncLocalStorage = ALSCompat
globalThis.AsyncLocalStorage = AsyncHooksCompat.AsyncLocalStorage

// Next.js uses this extension to the Headers API implemented by Cloudflare workerd
if (!('getAll' in Headers.prototype)) {
Expand Down Expand Up @@ -48,6 +52,26 @@ const fetch /* type {typeof globalThis.fetch} */ = async (url, init) => {
}
}

// Shim native modules that Vercel makes available
if (typeof require === 'undefined') {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So many shims. 😅

globalThis.require = (name) => {
switch (name.replace(/^node:/, '')) {
case 'buffer':
return BufferCompat
case 'events':
return EventsCompat
case 'async_hooks':
return AsyncHooksCompat
case 'assert':
return AssertCompat
case 'util':
return UtilCompat
default:
throw new ReferenceError(`Native module not found: ${name}`)
}
}
}

// Next edge runtime uses "self" as a function-scoped global-like object, but some of the older polyfills expect it to equal globalThis
// See https://nextjs.org/docs/basic-features/supported-browsers-features#polyfills
const self = { ...globalThis, fetch }