Unverified Commit 7db3bf73 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Fix `unstable_allowDynamic` when used with pnpm (#73732)

When using dependencies in Middleware that make use of dynamic code evaluation, Next.js emits a build error because this is not supported in the Edge runtime.

In rare cases, when the code can not be reached at runtime and can't be removed by tree-shaking, users might opt in to using the `unstable_allowDynamic` config.

When combined with pnpm, the provided glob patterns as documented at https://nextjs.org/docs/messages/edge-dynamic-code-evaluation#possible-ways-to-fix-it did not match correctly because of pnpm's use of the `.pnpm` directory.

To fix the pattern matching, we need to provide the `dot` option to [picomatch](https://github.com/micromatch/picomatch), which enables dotfile matching.

_Side note: Ideally we would detect dynamic code evaluation after tree shaking, to reduce the number of cases where users need to revert to using `unstable_allowDynamic`._

fixes #51401
parent 4fdc2ac6
...@@ -154,7 +154,7 @@ export const config = { ...@@ -154,7 +154,7 @@ export const config = {
// allows a single file // allows a single file
'/lib/utilities.js', '/lib/utilities.js',
// use a glob to allow anything in the function-bind 3rd party module // use a glob to allow anything in the function-bind 3rd party module
'/node_modules/function-bind/**', '**/node_modules/function-bind/**',
], ],
} }
``` ```
......
...@@ -37,7 +37,7 @@ You can relax the check to allow specific files with your Middleware [configurat ...@@ -37,7 +37,7 @@ You can relax the check to allow specific files with your Middleware [configurat
export const config = { export const config = {
unstable_allowDynamic: [ unstable_allowDynamic: [
'/lib/utilities.js', // allows a single file '/lib/utilities.js', // allows a single file
'/node_modules/function-bind/**', // use a glob to allow anything in the function-bind 3rd party module '**/node_modules/function-bind/**', // use a glob to allow anything in the function-bind 3rd party module
], ],
} }
``` ```
......
...@@ -297,7 +297,9 @@ function isDynamicCodeEvaluationAllowed( ...@@ -297,7 +297,9 @@ function isDynamicCodeEvaluationAllowed(
const name = fileName.replace(rootDir ?? '', '') const name = fileName.replace(rootDir ?? '', '')
return picomatch(middlewareConfig?.unstable_allowDynamic ?? [])(name) return picomatch(middlewareConfig?.unstable_allowDynamic ?? [], {
dot: true,
})(name)
} }
function buildUnsupportedApiError({ function buildUnsupportedApiError({
......
{
"name": "lib",
"private": true,
"type": "module",
"exports": {
".": "./index.js"
}
}
.pnpm/test/node_modules/lib
\ No newline at end of file
...@@ -21,7 +21,13 @@ const context = { ...@@ -21,7 +21,13 @@ const context = {
logs: { output: '', stdout: '', stderr: '' }, logs: { output: '', stdout: '', stderr: '' },
api: new File(join(__dirname, '../pages/api/route.js')), api: new File(join(__dirname, '../pages/api/route.js')),
middleware: new File(join(__dirname, '../middleware.js')), middleware: new File(join(__dirname, '../middleware.js')),
lib: new File(join(__dirname, '../lib/index.js')), lib: new File(
join(
__dirname,
// Simulated .pnpm node_modules path:
'../node_modules/.pnpm/test/node_modules/lib/index.js'
)
),
} }
const appOption = { const appOption = {
env: { __NEXT_TEST_WITH_DEVTOOL: 1 }, env: { __NEXT_TEST_WITH_DEVTOOL: 1 },
...@@ -74,7 +80,7 @@ describe('Edge runtime configurable guards', () => { ...@@ -74,7 +80,7 @@ describe('Edge runtime configurable guards', () => {
} }
export const config = { export const config = {
runtime: 'edge', runtime: 'edge',
unstable_allowDynamic: '/lib/**' unstable_allowDynamic: '**/node_modules/lib/**'
} }
`) `)
await waitFor(500) await waitFor(500)
...@@ -167,14 +173,14 @@ describe('Edge runtime configurable guards', () => { ...@@ -167,14 +173,14 @@ describe('Edge runtime configurable guards', () => {
url: routeUrl, url: routeUrl,
init() { init() {
context.api.write(` context.api.write(`
import { hasDynamic } from '../../lib' import { hasDynamic } from 'lib'
export default async function handler(request) { export default async function handler(request) {
await hasDynamic() await hasDynamic()
return Response.json({ result: true }) return Response.json({ result: true })
} }
export const config = { export const config = {
runtime: 'edge', runtime: 'edge',
unstable_allowDynamic: '/lib/**' unstable_allowDynamic: '**/node_modules/lib/**'
} }
`) `)
context.lib.write(` context.lib.write(`
...@@ -190,7 +196,7 @@ describe('Edge runtime configurable guards', () => { ...@@ -190,7 +196,7 @@ describe('Edge runtime configurable guards', () => {
init() { init() {
context.middleware.write(` context.middleware.write(`
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
import { hasDynamic } from './lib' import { hasDynamic } from 'lib'
// populated with tests // populated with tests
export default async function () { export default async function () {
...@@ -198,7 +204,7 @@ describe('Edge runtime configurable guards', () => { ...@@ -198,7 +204,7 @@ describe('Edge runtime configurable guards', () => {
return NextResponse.next() return NextResponse.next()
} }
export const config = { export const config = {
unstable_allowDynamic: '/lib/**' unstable_allowDynamic: '**/node_modules/lib/**'
} }
`) `)
context.lib.write(` context.lib.write(`
...@@ -207,15 +213,19 @@ describe('Edge runtime configurable guards', () => { ...@@ -207,15 +213,19 @@ describe('Edge runtime configurable guards', () => {
} }
`) `)
}, },
// TODO: Re-enable when Turbopack applies the middleware dynamic code
// evaluation transforms also to code in node_modules.
skip: Boolean(process.env.TURBOPACK),
}, },
])('$title with allowed, used dynamic code', ({ init, url }) => { ])('$title with allowed, used dynamic code', ({ init, url, skip }) => {
beforeEach(() => init()) beforeEach(() => init())
;(skip ? it.skip : it)('still warns in dev at runtime', async () => {
it('still warns in dev at runtime', async () => {
context.app = await launchApp(context.appDir, context.appPort, appOption) context.app = await launchApp(context.appDir, context.appPort, appOption)
const res = await fetchViaHTTP(context.appPort, url) const res = await fetchViaHTTP(context.appPort, url)
await waitFor(500) await waitFor(500)
// eslint-disable-next-line jest/no-standalone-expect
expect(res.status).toBe(200) expect(res.status).toBe(200)
// eslint-disable-next-line jest/no-standalone-expect
expect(context.logs.output).toContain( expect(context.logs.output).toContain(
`Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime` `Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime`
) )
...@@ -265,14 +275,14 @@ describe('Edge runtime configurable guards', () => { ...@@ -265,14 +275,14 @@ describe('Edge runtime configurable guards', () => {
url: routeUrl, url: routeUrl,
init() { init() {
context.api.write(` context.api.write(`
import { hasUnusedDynamic } from '../../lib' import { hasUnusedDynamic } from 'lib'
export default async function handler(request) { export default async function handler(request) {
await hasUnusedDynamic() await hasUnusedDynamic()
return Response.json({ result: true }) return Response.json({ result: true })
} }
export const config = { export const config = {
runtime: 'edge', runtime: 'edge',
unstable_allowDynamic: '/lib/**' unstable_allowDynamic: '**/node_modules/lib/**'
} }
`) `)
context.lib.write(` context.lib.write(`
...@@ -290,14 +300,14 @@ describe('Edge runtime configurable guards', () => { ...@@ -290,14 +300,14 @@ describe('Edge runtime configurable guards', () => {
init() { init() {
context.middleware.write(` context.middleware.write(`
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
import { hasUnusedDynamic } from './lib' import { hasUnusedDynamic } from 'lib'
// populated with tests // populated with tests
export default async function () { export default async function () {
await hasUnusedDynamic() await hasUnusedDynamic()
return NextResponse.next() return NextResponse.next()
} }
export const config = { export const config = {
unstable_allowDynamic: '/lib/**' unstable_allowDynamic: '**/node_modules/lib/**'
} }
`) `)
context.lib.write(` context.lib.write(`
...@@ -356,7 +366,7 @@ describe('Edge runtime configurable guards', () => { ...@@ -356,7 +366,7 @@ describe('Edge runtime configurable guards', () => {
url: routeUrl, url: routeUrl,
init() { init() {
context.api.write(` context.api.write(`
import { hasDynamic } from '../../lib' import { hasDynamic } from 'lib'
export default async function handler(request) { export default async function handler(request) {
await hasDynamic() await hasDynamic()
return Response.json({ result: true }) return Response.json({ result: true })
...@@ -372,6 +382,9 @@ describe('Edge runtime configurable guards', () => { ...@@ -372,6 +382,9 @@ describe('Edge runtime configurable guards', () => {
} }
`) `)
}, },
// TODO: Re-enable when Turbopack applies the edge runtime transforms also
// to code in node_modules.
skip: Boolean(process.env.TURBOPACK),
}, },
{ {
title: 'Middleware using lib', title: 'Middleware using lib',
...@@ -379,7 +392,7 @@ describe('Edge runtime configurable guards', () => { ...@@ -379,7 +392,7 @@ describe('Edge runtime configurable guards', () => {
init() { init() {
context.middleware.write(` context.middleware.write(`
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
import { hasDynamic } from './lib' import { hasDynamic } from 'lib'
export default async function () { export default async function () {
await hasDynamic() await hasDynamic()
return NextResponse.next() return NextResponse.next()
...@@ -394,20 +407,24 @@ describe('Edge runtime configurable guards', () => { ...@@ -394,20 +407,24 @@ describe('Edge runtime configurable guards', () => {
} }
`) `)
}, },
// TODO: Re-enable when Turbopack applies the middleware dynamic code
// evaluation transforms also to code in node_modules.
skip: Boolean(process.env.TURBOPACK),
}, },
])('$title with unallowed, used dynamic code', ({ init, url }) => { ])('$title with unallowed, used dynamic code', ({ init, url, skip }) => {
beforeEach(() => init()) beforeEach(() => init())
;(skip ? it.skip : it)('warns in dev at runtime', async () => {
it('warns in dev at runtime', async () => {
context.app = await launchApp(context.appDir, context.appPort, appOption) context.app = await launchApp(context.appDir, context.appPort, appOption)
const res = await fetchViaHTTP(context.appPort, url) const res = await fetchViaHTTP(context.appPort, url)
await waitFor(500) await waitFor(500)
// eslint-disable-next-line jest/no-standalone-expect
expect(res.status).toBe(200) expect(res.status).toBe(200)
// eslint-disable-next-line jest/no-standalone-expect
expect(context.logs.output).toContain( expect(context.logs.output).toContain(
`Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime` `Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime`
) )
}) })
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(skip || process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode', 'production mode',
() => { () => {
it('fails to build because of dynamic code evaluation', async () => { it('fails to build because of dynamic code evaluation', async () => {
...@@ -446,7 +463,7 @@ describe('Edge runtime configurable guards', () => { ...@@ -446,7 +463,7 @@ describe('Edge runtime configurable guards', () => {
init() { init() {
context.middleware.write(` context.middleware.write(`
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
import { returnTrue } from './lib' import { returnTrue } from 'lib'
export default async function () { export default async function () {
(() => {}) instanceof Function (() => {}) instanceof Function
return NextResponse.next() return NextResponse.next()
......
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