Commit af8a686e authored by Jimmy Lai's avatar Jimmy Lai

fix: improve source map path normalization and monorepo support

- Add normalizeSourceUrl function to handle file:/ URL concatenation
- Fix bug where file:/ URLs at position 0 weren't handled (>= 0 instead of > 0)
- Add packages/next/dist to shouldIgnorePath for monorepo development
- Export shouldIgnorePath for reuse by webpack source map implementation
- Add unit tests for normalizeSourceUrl
parent 1f6179b4
......@@ -6,13 +6,14 @@ import DevToolsIgnorePlugin from '../../plugins/devtools-ignore-list-plugin'
import EvalSourceMapDevToolPlugin from '../../plugins/eval-source-map-dev-tool-plugin'
import { getRspackCore } from '../../../../shared/lib/get-rspack'
function shouldIgnorePath(modulePath: string): boolean {
export function shouldIgnorePath(modulePath: string): boolean {
return (
modulePath.includes('node_modules') ||
modulePath.endsWith('__nextjs-internal-proxy.cjs') ||
modulePath.endsWith('__nextjs-internal-proxy.mjs') ||
// Only relevant for when Next.js is symlinked e.g. in the Next.js monorepo
modulePath.includes('next/dist')
modulePath.includes('next/dist') ||
modulePath.includes('packages/next/dist')
)
}
......
......@@ -4,11 +4,16 @@ import {
decorateServerError,
type ErrorSourceType,
} from '../../shared/lib/error-source'
import { normalizeSourceUrl } from '../lib/source-map-utils'
function getFilesystemFrame(frame: StackFrame): StackFrame {
const f: StackFrame = { ...frame }
if (typeof f.file === 'string') {
// Normalize paths that may have been malformed by source-map library
// (e.g., duplicate path segments from Turbopack)
f.file = normalizeSourceUrl(f.file)
if (
// Posix:
f.file.startsWith('/') ||
......
/**
* Pure string utilities for source map path normalization.
* No Node.js dependencies - safe to import in browser bundles.
*/
/**
* Normalize source URLs that were incorrectly formed by source-map resolution.
*
* Fixes two issues:
*
* 1. **file:/ URL concatenation bug in source-map library**
* The source-map library (v0.6.1) doesn't recognize `file:/` (single slash) as an
* absolute URL, so when a source map has `sourceRoot: "../../../"` and
* `sources: ["file:/Users/foo/app/page.js"]`, the library incorrectly concatenates
* them into `../../../file:/Users/foo/app/page.js`.
* We extract the last `file:/` occurrence and normalize it to `file:///`.
* See: https://github.com/nicolo-ribaudo/source-map/issues/1
*
* 2. **Duplicate path segments**
* Some bundler/compiler combinations can produce paths with duplicate directory
* sequences like `app/components/app/components/Button.js`. We detect and remove
* the first occurrence of repeated segments.
*/
export function normalizeSourceUrl(source: string): string {
let result = source
// Fix 1: Handle file:/ URL that was incorrectly concatenated with sourceRoot.
// Find the last occurrence of file:/ since that's the actual source path.
const lastFileUrlIndex = result.lastIndexOf('file:/')
if (lastFileUrlIndex > 0) {
// Only extract if file:/ is NOT at the beginning (meaning it was concatenated)
let fileUrl = result.slice(lastFileUrlIndex)
// Normalize file:/ (single slash) to file:/// (canonical form with empty host)
if (!fileUrl.startsWith('file://')) {
fileUrl = 'file://' + fileUrl.slice(5) // 'file:/' is 5 chars, replace with 'file://'
}
result = fileUrl
} else if (lastFileUrlIndex === 0 && !result.startsWith('file://')) {
// Handle file:/ at the beginning that needs normalization to file://
result = 'file://' + result.slice(5)
}
// Fix 2: Handle duplicate path segments (e.g., test/foo/test/foo/file.js -> test/foo/file.js)
// This also applies to file:// URLs with duplicate paths
// Algorithm: Find the shortest repeated sequence of path segments and remove the duplicate.
const parts = result.split('/')
for (let len = 1; len <= parts.length / 2; len++) {
for (let i = 0; i <= parts.length - len * 2; i++) {
// Check if parts[i..i+len] equals parts[i+len..i+len*2]
let match = true
for (let j = 0; j < len; j++) {
if (parts[i + j] !== parts[i + len + j]) {
match = false
break
}
}
// Don't treat '..' or '.' or empty string as duplicates (e.g., ../../foo is valid)
// Empty string can appear in file:// URLs (file:///Users -> ['file:', '', '', 'Users'])
if (match && parts[i] !== '..' && parts[i] !== '.' && parts[i] !== '') {
// Remove the duplicate segment by keeping [0..i+len] and [i+len*2..end]
const newParts = [
...parts.slice(0, i + len),
...parts.slice(i + len * 2),
]
return newParts.join('/')
}
}
}
return result
}
import { ignoreListAnonymousStackFramesIfSandwiched } from './source-maps'
import {
ignoreListAnonymousStackFramesIfSandwiched,
normalizeSourceUrl,
} from './source-maps'
type StackFrame = null | {
file: string
......@@ -226,3 +229,119 @@ test('does not ignore list anonymous frames that are not likely JS native method
{ ignored: true, file: 'file2.js', methodName: 'render' },
])
})
describe('normalizeSourceUrl', () => {
// Import the source-map library to demonstrate its actual behavior
const { SourceMapConsumer } = (require('next/dist/compiled/source-map') as typeof import('next/dist/compiled/source-map'))
describe('file URL concatenation (source-map library bug)', () => {
// The source-map library doesn't recognize file:/ (single slash) as an absolute URL,
// so it concatenates sourceRoot with the file:/ source, producing malformed paths.
// This test demonstrates the actual library behavior and verifies our fix.
it('fixes malformed paths produced by source-map library with sourceRoot', () => {
// Create a source map that triggers the bug:
// - sourceRoot is a relative path
// - source is a file:/ URL (single slash, which is technically valid but uncommon)
const rawSourceMap = {
version: 3,
file: 'output.js',
sourceRoot: '../../../',
sources: ['file:/Users/foo/app/page.js'],
names: [],
mappings: 'AAAA', // Maps position (0,0) -> (0,0)
}
const consumer = new SourceMapConsumer(rawSourceMap)
// Get the source URL as the library reports it
const malformedSource = consumer.sources[0]
// The library incorrectly concatenates sourceRoot with the file:/ URL
expect(malformedSource).toBe('../../../file:/Users/foo/app/page.js')
// Our normalizeSourceUrl fixes this malformed path
expect(normalizeSourceUrl(malformedSource)).toBe(
'file:///Users/foo/app/page.js'
)
})
it('normalizes file:/ to file:// even without sourceRoot', () => {
const rawSourceMap = {
version: 3,
file: 'output.js',
sources: ['file:/Users/foo/app/page.js'],
names: [],
mappings: 'AAAA',
}
const consumer = new SourceMapConsumer(rawSourceMap)
const source = consumer.sources[0]
// Without sourceRoot, file:/ comes through as-is (still malformed)
expect(source).toBe('file:/Users/foo/app/page.js')
// Our fix normalizes it to the canonical file:// format
expect(normalizeSourceUrl(source)).toBe('file:///Users/foo/app/page.js')
})
it('handles file:/// URLs correctly (no change needed)', () => {
expect(normalizeSourceUrl('file:///Users/foo/app/page.js')).toBe(
'file:///Users/foo/app/page.js'
)
})
it('extracts last file:/ when multiple occurrences exist', () => {
// Edge case: nested source maps could produce multiple file: occurrences
expect(
normalizeSourceUrl('file:/wrong/path/file:/correct/path/page.js')
).toBe('file:///correct/path/page.js')
})
})
describe('duplicate path segments', () => {
it('removes single duplicate segment', () => {
expect(normalizeSourceUrl('app/app/page.tsx')).toBe('app/page.tsx')
})
it('removes multi-directory duplicate segment', () => {
expect(normalizeSourceUrl('test/fixtures/test/fixtures/app.js')).toBe(
'test/fixtures/app.js'
)
})
it('removes duplicate with relative prefix preserved', () => {
expect(
normalizeSourceUrl('../../../app/components/app/components/Button.js')
).toBe('../../../app/components/Button.js')
})
})
describe('paths that should not be modified', () => {
it('does not modify consecutive .. segments', () => {
expect(normalizeSourceUrl('../../page.js')).toBe('../../page.js')
})
it('does not modify paths with . in them', () => {
expect(normalizeSourceUrl('./src/./page.js')).toBe('./src/./page.js')
})
it('does not modify normal relative paths', () => {
expect(normalizeSourceUrl('src/components/page.js')).toBe(
'src/components/page.js'
)
})
it('does not modify webpack:// URLs', () => {
expect(normalizeSourceUrl('webpack://app/./src/page.js')).toBe(
'webpack://app/./src/page.js'
)
})
it('does not modify turbopack:// URLs', () => {
expect(normalizeSourceUrl('turbopack://[project]/src/page.js')).toBe(
'turbopack://[project]/src/page.js'
)
})
})
})
import type { SourceMap } from 'module'
import { LRUCache } from './lru-cache'
export { normalizeSourceUrl } from './source-map-utils'
function noSourceMap(): SourceMap | undefined {
return undefined
......
......@@ -8,6 +8,7 @@ import {
findApplicableSourceMapPayload,
ignoreListAnonymousStackFramesIfSandwiched as ignoreListAnonymousStackFramesIfSandwichedGeneric,
sourceMapIgnoreListsEverything,
normalizeSourceUrl,
} from './lib/source-maps'
import { parseStack, type StackFrame } from './lib/parse-stack'
import { getOriginalCodeFrame } from '../next-devtools/server/shared'
......@@ -59,13 +60,30 @@ function frameToString(
// In a multi-app repo, this leads to potentially larger file names but will make clicking snappy.
// There's no tradeoff for the cases where `dir` in `next dev [dir]` is omitted
// since relative to cwd is both the shortest and snappiest.
fileLocation = path.relative(process.cwd(), url.fileURLToPath(sourceURL))
try {
fileLocation = path.relative(process.cwd(), url.fileURLToPath(sourceURL))
} catch {
// fileURLToPath throws for file URLs with non-localhost hosts (e.g., file://remote/path)
// This can happen with malformed source map URLs. Fall back to using the URL as-is.
fileLocation = sourceURL
}
} else if (sourceURL !== null && sourceURL.startsWith('/')) {
fileLocation = path.relative(process.cwd(), sourceURL)
} else {
fileLocation = sourceURL
}
// Decode URL-encoded characters in the path.
// Dynamic routes like [slug] get encoded as %5Bslug%5D in source map URLs.
// Decode them back so stack traces show readable paths: pages/blog/[slug].js
if (fileLocation !== null) {
try {
fileLocation = decodeURIComponent(fileLocation)
} catch {
// Keep original if decoding fails (e.g., malformed percent encoding)
}
}
return methodName
? ` at ${methodName} (${fileLocation}${sourceLocation})`
: ` at ${fileLocation}${sourceLocation}`
......@@ -112,14 +130,22 @@ interface SourceMappedFrame {
function createUnsourcemappedFrame(
frame: SourcemappableStackFrame
): SourceMappedFrame {
// Normalize the file path even for unsourcemapped frames.
// This handles cases where V8's built-in source map support already resolved the path
// but introduced duplicate path segments (e.g., from Turbopack's source maps).
const normalizedFile = normalizeSourceUrl(frame.file)
return {
stack: {
file: frame.file,
file: normalizedFile,
line1: frame.line1,
column1: frame.column1,
methodName: frame.methodName,
// Webpack's eval devtool wraps code in eval() which produces ugly method names like:
// "Timeout.eval [as _onTimeout]" instead of "Timeout._onTimeout"
// This regex extracts the actual method name from the "[as X]" wrapper.
methodName: frame.methodName?.replace(/\.eval \[as ([^\]]+)\]/, '.$1'),
arguments: frame.arguments,
ignored: shouldIgnoreListGeneratedFrame(frame.file),
ignored: shouldIgnoreListGeneratedFrame(normalizedFile),
},
code: null,
}
......@@ -250,14 +276,16 @@ function getSourcemappedFrameIfPossible(
applicableSourceMap !== undefined &&
sourceMapIgnoreListsEverything(applicableSourceMap)
if (sourcePosition.source === null) {
// Normalize the file path in case V8's source maps already resolved it with duplicates
const normalizedFile = normalizeSourceUrl(frame.file)
return {
stack: {
arguments: frame.arguments,
file: frame.file,
file: normalizedFile,
line1: frame.line1,
column1: frame.column1,
methodName: frame.methodName,
ignored: ignored || shouldIgnoreListGeneratedFrame(frame.file),
ignored: ignored || shouldIgnoreListGeneratedFrame(normalizedFile),
},
code: null,
}
......@@ -282,6 +310,11 @@ function getSourcemappedFrameIfPossible(
ignored = applicableSourceMap.ignoreList?.includes(sourceIndex) ?? false
}
// Normalize the source URL to fix issues from source-map library:
// 1. Duplicate path segments from Turbopack (test/foo/test/foo/file.js)
// 2. Malformed file:/ URLs from sourceRoot concatenation
const normalizedSource = normalizeSourceUrl(sourcePosition.source)
const originalFrame: IgnorableStackFrame = {
// We ignore the sourcemapped name since it won't be the correct name.
// The callsite will point to the column of the variable name instead of the
......@@ -289,8 +322,11 @@ function getSourcemappedFrameIfPossible(
// TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.
methodName: frame.methodName
?.replace('__WEBPACK_DEFAULT_EXPORT__', 'default')
?.replace('__webpack_exports__.', ''),
file: sourcePosition.source,
?.replace('__webpack_exports__.', '')
// Webpack's eval devtool wraps code in eval() which produces ugly method names.
// Extract actual method name: "Timeout.eval [as _onTimeout]" -> "Timeout._onTimeout"
?.replace(/\.eval \[as ([^\]]+)\]/, '.$1'),
file: normalizedSource,
line1: sourcePosition.line,
column1: sourcePosition.column + 1,
// TODO: c&p from async createOriginalStackFrame but why not frame.arguments?
......
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Edge route usage of dynamic code evaluation development mode shows a warning when running WebAssembly.compile: wasm-compile-Edge route-turbopack 1`] = `
"DynamicWasmCodeGenerationWarning: Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
at usingWebAssemblyCompile (../../test/integration/edge-runtime-dynamic-code/lib/wasm.js:22:18)
at handler (../../test/integration/edge-runtime-dynamic-code/pages/api/route.js:20:55)
20 |
21 | export async function usingWebAssemblyCompile(x) {
> 22 | const module = await WebAssembly.compile(SQUARE_WASM_BUFFER)
| ^"
`;
exports[`Edge route usage of dynamic code evaluation development mode shows a warning when running WebAssembly.compile: wasm-compile-Edge route-webpack 1`] = `
"DynamicWasmCodeGenerationWarning: Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
at usingWebAssemblyCompile (../../test/integration/edge-runtime-dynamic-code/lib/wasm.js:22:24)
at handler (../../test/integration/edge-runtime-dynamic-code/pages/api/route.js:20:55)
20 |
21 | export async function usingWebAssemblyCompile(x) {
> 22 | const module = await WebAssembly.compile(SQUARE_WASM_BUFFER)
| ^"
`;
exports[`Edge route usage of dynamic code evaluation development mode shows a warning when running WebAssembly.instantiate with a buffer parameter: wasm-instantiate-Edge route-turbopack 1`] = `
"DynamicWasmCodeGenerationWarning: Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
at async usingWebAssemblyInstantiateWithBuffer (../../test/integration/edge-runtime-dynamic-code/lib/wasm.js:28:24)
at async handler (../../test/integration/edge-runtime-dynamic-code/pages/api/route.js:28:26)
26 |
27 | export async function usingWebAssemblyInstantiateWithBuffer(x) {
> 28 | const { instance } = await WebAssembly.instantiate(SQUARE_WASM_BUFFER, {})
| ^"
`;
exports[`Edge route usage of dynamic code evaluation development mode shows a warning when running WebAssembly.instantiate with a buffer parameter: wasm-instantiate-Edge route-webpack 1`] = `
"DynamicWasmCodeGenerationWarning: Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
at async usingWebAssemblyInstantiateWithBuffer (../../test/integration/edge-runtime-dynamic-code/lib/wasm.js:28:24)
at async handler (../../test/integration/edge-runtime-dynamic-code/pages/api/route.js:28:26)
26 |
27 | export async function usingWebAssemblyInstantiateWithBuffer(x) {
> 28 | const { instance } = await WebAssembly.instantiate(SQUARE_WASM_BUFFER, {})
| ^"
`;
exports[`Edge route usage of dynamic code evaluation development mode shows a warning when running code with eval: eval-Edge route-turbopack 1`] = `
"DynamicCodeEvaluationWarning: Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
at usingEval (../../test/integration/edge-runtime-dynamic-code/lib/utils.js:3:17)
at handler (../../test/integration/edge-runtime-dynamic-code/pages/api/route.js:12:41)
1 | export async function usingEval() {
2 | // eslint-disable-next-line no-eval
> 3 | return { value: eval('100') }
| ^"
`;
exports[`Edge route usage of dynamic code evaluation development mode shows a warning when running code with eval: eval-Edge route-webpack 1`] = `
"DynamicCodeEvaluationWarning: Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
at usingEval (../../test/integration/edge-runtime-dynamic-code/lib/utils.js:3:19)
at handler (../../test/integration/edge-runtime-dynamic-code/pages/api/route.js:12:41)
1 | export async function usingEval() {
2 | // eslint-disable-next-line no-eval
> 3 | return { value: eval('100') }
| ^"
`;
exports[`Middleware usage of dynamic code evaluation development mode shows a warning when running WebAssembly.compile: wasm-compile-Middleware-turbopack 1`] = `
"DynamicWasmCodeGenerationWarning: Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
at usingWebAssemblyCompile (../../test/integration/edge-runtime-dynamic-code/lib/wasm.js:22:18)
at middleware (../../test/integration/edge-runtime-dynamic-code/middleware.js:24:68)
20 |
21 | export async function usingWebAssemblyCompile(x) {
> 22 | const module = await WebAssembly.compile(SQUARE_WASM_BUFFER)
| ^"
`;
exports[`Middleware usage of dynamic code evaluation development mode shows a warning when running WebAssembly.compile: wasm-compile-Middleware-webpack 1`] = `
"DynamicWasmCodeGenerationWarning: Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
at usingWebAssemblyCompile (../../test/integration/edge-runtime-dynamic-code/lib/wasm.js:22:24)
at middleware (../../test/integration/edge-runtime-dynamic-code/middleware.js:24:68)
20 |
21 | export async function usingWebAssemblyCompile(x) {
> 22 | const module = await WebAssembly.compile(SQUARE_WASM_BUFFER)
| ^"
`;
exports[`Middleware usage of dynamic code evaluation development mode shows a warning when running WebAssembly.instantiate with a buffer parameter: wasm-instantiate-Middleware-turbopack 1`] = `
"DynamicWasmCodeGenerationWarning: Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
at async usingWebAssemblyInstantiateWithBuffer (../../test/integration/edge-runtime-dynamic-code/lib/wasm.js:28:24)
at async middleware (../../test/integration/edge-runtime-dynamic-code/middleware.js:39:30)
26 |
27 | export async function usingWebAssemblyInstantiateWithBuffer(x) {
> 28 | const { instance } = await WebAssembly.instantiate(SQUARE_WASM_BUFFER, {})
| ^"
`;
exports[`Middleware usage of dynamic code evaluation development mode shows a warning when running WebAssembly.instantiate with a buffer parameter: wasm-instantiate-Middleware-webpack 1`] = `
"DynamicWasmCodeGenerationWarning: Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
at async usingWebAssemblyInstantiateWithBuffer (../../test/integration/edge-runtime-dynamic-code/lib/wasm.js:28:24)
at async middleware (../../test/integration/edge-runtime-dynamic-code/middleware.js:39:30)
at async eval (dist/build/webpack/loaders/next-middleware-loader.js?absolutePagePath=/Users/feedthejim/Projects/next.js/test/integration/edge-runtime-dynamic-code/middleware.js&page=/middleware&rootDir=/Users/feedthejim/Projects/next.js/test/integration/edge-runtime-dynamic-code&matchers=&preferredRegion=&middlewareConfig=e30=!:30:1)
26 |
27 | export async function usingWebAssemblyInstantiateWithBuffer(x) {
> 28 | const { instance } = await WebAssembly.instantiate(SQUARE_WASM_BUFFER, {})
| ^"
`;
exports[`Middleware usage of dynamic code evaluation development mode shows a warning when running code with eval: eval-Middleware-turbopack 1`] = `
"DynamicCodeEvaluationWarning: Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
at usingEval (../../test/integration/edge-runtime-dynamic-code/lib/utils.js:3:17)
at middleware (../../test/integration/edge-runtime-dynamic-code/middleware.js:12:54)
1 | export async function usingEval() {
2 | // eslint-disable-next-line no-eval
> 3 | return { value: eval('100') }
| ^"
`;
exports[`Middleware usage of dynamic code evaluation development mode shows a warning when running code with eval: eval-Middleware-webpack 1`] = `
"DynamicCodeEvaluationWarning: Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
at usingEval (../../test/integration/edge-runtime-dynamic-code/lib/utils.js:3:19)
at middleware (../../test/integration/edge-runtime-dynamic-code/middleware.js:12:54)
1 | export async function usingEval() {
2 | // eslint-disable-next-line no-eval
> 3 | return { value: eval('100') }
| ^"
`;
......@@ -24,6 +24,43 @@ const context: Record<string, any> = {
const isTurbopack = process.env.IS_TURBOPACK_TEST
/**
* Extract the warning message from output for snapshot testing.
* Captures: warning header, user-level stack frames, and code frame.
* Excludes internal Next.js frames (dist/, src/server/, etc.)
*/
function extractWarning(output: string, warningType: string): string {
const stripped = stripAnsi(output)
const startIndex = stripped.indexOf(warningType)
if (startIndex === -1) return ''
const fromWarning = stripped.slice(startIndex)
const lines = fromWarning.split('\n')
const result: string[] = []
for (const line of lines) {
// Skip internal frames
const isInternalFrame =
line.includes('at eval (dist/') ||
line.includes('at eval (../') ||
line.includes('src/server/') ||
line.includes('node_modules/')
// Stop at pointer line (end of code frame)
if (/^\s+\|\s+\^/.test(line)) {
result.push(line)
break
}
if (!isInternalFrame) {
result.push(line)
}
}
return result.join('\n')
}
describe('Page using eval in development mode', () => {
let output = ''
......@@ -103,48 +140,10 @@ describe.each([
expect(await extractValue(res)).toEqual(100)
await waitFor(500)
expect(output).toContain(EVAL_ERROR)
if (title === 'Middleware') {
expect(output).toContain(
isTurbopack
? '' +
// TODO(veil): Turbopack duplicates project path
'\n at usingEval (../../test/integration/edge-runtime-dynamic-code/test/integration/edge-runtime-dynamic-code/lib/utils.js:3:17)' +
'\n at middleware (../../test/integration/edge-runtime-dynamic-code/test/integration/edge-runtime-dynamic-code/middleware.js:12:54)' +
'\n 1 | export async function usingEval() {'
: '\n at usingEval (../../test/integration/edge-runtime-dynamic-code/lib/utils.js:3:19)' +
'\n at middleware (../../test/integration/edge-runtime-dynamic-code/middleware.js:12:54)' +
// Next.js internal frame. Feel free to adjust.
// Not ignore-listed because we're not in an isolated app and Next.js is symlinked so it's not in node_modules
'\n at eval (../packages/next/dist'
)
} else {
expect(output).toContain(
isTurbopack
? '' +
// TODO(veil): Turbopack duplicates project path
'\n at usingEval (../../test/integration/edge-runtime-dynamic-code/test/integration/edge-runtime-dynamic-code/lib/utils.js:3:17)' +
'\n at handler (../../test/integration/edge-runtime-dynamic-code/test/integration/edge-runtime-dynamic-code/pages/api/route.js:12:41)' +
'\n 1 | export async function usingEval() {'
: '\n at usingEval (../../test/integration/edge-runtime-dynamic-code/lib/utils.js:3:19)' +
'\n at handler (../../test/integration/edge-runtime-dynamic-code/pages/api/route.js:12:41)' +
'\n 1 | export async function usingEval() {'
)
}
// Turbopack produces incorrect mappings in the sourcemap.
if (isTurbopack) {
expect(output).toContain(
'' +
"\n> 3 | return { value: eval('100') }" +
'\n | ^'
)
} else {
expect(output).toContain(
'' +
"\n> 3 | return { value: eval('100') }" +
'\n | ^'
)
}
const warning = extractWarning(output, 'DynamicCodeEvaluationWarning')
expect(warning).toMatchSnapshot(
`eval-${title}-${isTurbopack ? 'turbopack' : 'webpack'}`
)
})
it('does not show warning when no code uses eval', async () => {
......@@ -165,54 +164,13 @@ describe.each([
expect(await extractValue(res)).toEqual(81)
await waitFor(500)
expect(output).toContain(WASM_COMPILE_ERROR)
if (title === 'Middleware') {
// Turbopack produces incorrect mappings in the sourcemap.
expect(output).toContain(
isTurbopack
? '' +
'\n at usingWebAssemblyCompile (../../test/integration/edge-runtime-dynamic-code/test/integration/edge-runtime-dynamic-code/lib/wasm.js:22:18)' +
'\n at middleware (../../test/integration/edge-runtime-dynamic-code/test/integration/edge-runtime-dynamic-code/middleware.js:24:68)' +
'\n 20 |' +
'\n 21 | export async function usingWebAssemblyCompile(x) {' +
'\n> 22 | const module = await WebAssembly.compile(SQUARE_WASM_BUFFER)' +
'\n | ^'
: '\n at usingWebAssemblyCompile (../../test/integration/edge-runtime-dynamic-code/lib/wasm.js:22:24)' +
'\n at middleware (../../test/integration/edge-runtime-dynamic-code/middleware.js:24:68)' +
// Next.js internal frame. Feel free to adjust.
// Not ignore-listed because we're not in an isolated app and Next.js is symlinked so it's not in node_modules
'\n at'
)
} else {
// Turbopack produces incorrect mappings in the sourcemap.
expect(output).toContain(
isTurbopack
? '' +
// TODO(veil): Turbopack duplicates project path
'\n at usingWebAssemblyCompile (../../test/integration/edge-runtime-dynamic-code/test/integration/edge-runtime-dynamic-code/lib/wasm.js:22:18)' +
'\n at handler (../../test/integration/edge-runtime-dynamic-code/test/integration/edge-runtime-dynamic-code/pages/api/route.js:20:55)' +
'\n 20 |'
: '' +
'\n at usingWebAssemblyCompile (../../test/integration/edge-runtime-dynamic-code/lib/wasm.js:22:24)' +
'\n at handler (../../test/integration/edge-runtime-dynamic-code/pages/api/route.js:20:55)' +
'\n 20 |'
)
// Turbopack produces incorrect mappings in the sourcemap.
if (isTurbopack) {
expect(output).toContain(
'' +
'\n> 22 | const module = await WebAssembly.compile(SQUARE_WASM_BUFFER)' +
'\n | ^'
)
} else {
// TODO(veil): Inconsistent cursor position
expect(output).toContain(
'' +
'\n> 22 | const module = await WebAssembly.compile(SQUARE_WASM_BUFFER)' +
'\n | ^'
)
}
}
const warning = extractWarning(
output,
'DynamicWasmCodeGenerationWarning'
)
expect(warning).toMatchSnapshot(
`wasm-compile-${title}-${isTurbopack ? 'turbopack' : 'webpack'}`
)
})
it('shows a warning when running WebAssembly.instantiate with a buffer parameter', async () => {
......@@ -223,45 +181,13 @@ describe.each([
expect(await extractValue(res)).toEqual(81)
await waitFor(500)
expect(output).toContain(WASM_INSTANTIATE_ERROR)
if (title === 'Middleware') {
expect(output).toContain(
isTurbopack
? '' +
'\n at async usingWebAssemblyInstantiateWithBuffer (../../test/integration/edge-runtime-dynamic-code/test/integration/edge-runtime-dynamic-code/lib/wasm.js:28:24)' +
'\n at async middleware (../../test/integration/edge-runtime-dynamic-code/test/integration/edge-runtime-dynamic-code/middleware.js:39:30)' +
'\n 26 |\n'
: '' +
'\n at async usingWebAssemblyInstantiateWithBuffer (../../test/integration/edge-runtime-dynamic-code/lib/wasm.js:28:24)' +
'\n at async middleware (../../test/integration/edge-runtime-dynamic-code/middleware.js:39:30)' +
// Next.js internal frame. Feel free to adjust.
// TODO(veil): https://linear.app/vercel/issue/NDX-464
'\n at '
)
expect(stripAnsi(output)).toContain(
'' +
'\n> 28 | const { instance } = await WebAssembly.instantiate(SQUARE_WASM_BUFFER, {})' +
'\n | ^'
)
} else {
expect(output).toContain(
isTurbopack
? '' +
// TODO(veil): Turbopack duplicates project path
'\n at async usingWebAssemblyInstantiateWithBuffer (../../test/integration/edge-runtime-dynamic-code/test/integration/edge-runtime-dynamic-code/lib/wasm.js:28:24)' +
'\n at async handler (../../test/integration/edge-runtime-dynamic-code/test/integration/edge-runtime-dynamic-code/pages/api/route.js:28:26)' +
'\n 26 |'
: '' +
'\n at async usingWebAssemblyInstantiateWithBuffer (../../test/integration/edge-runtime-dynamic-code/lib/wasm.js:28:24)' +
'\n at async handler (../../test/integration/edge-runtime-dynamic-code/pages/api/route.js:28:26)' +
'\n 26 |'
)
// TODO(veil): Inconsistent cursor position
expect(stripAnsi(output)).toContain(
'' +
'\n> 28 | const { instance } = await WebAssembly.instantiate(SQUARE_WASM_BUFFER, {})' +
'\n | ^'
)
}
const warning = extractWarning(
output,
'DynamicWasmCodeGenerationWarning'
)
expect(warning).toMatchSnapshot(
`wasm-instantiate-${title}-${isTurbopack ? 'turbopack' : 'webpack'}`
)
})
it('does not show a warning when running WebAssembly.instantiate with a module parameter', async () => {
......
#!/bin/bash
# Update snapshots for both Turbopack and Webpack, then merge them.
# Usage: ./update-snapshots.sh
set -e
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SNAP_FILE="$SCRIPT_DIR/test/__snapshots__/index.test.ts.snap"
TMP_DIR=$(mktemp -d)
echo "Generating Turbopack snapshots..."
IS_TURBOPACK_TEST=1 TURBOPACK_DEV=1 NEXT_TEST_MODE=dev pnpm jest test/integration/edge-runtime-dynamic-code/test/index.test.ts -u --silent
cp "$SNAP_FILE" "$TMP_DIR/turbopack.snap"
echo "Generating Webpack snapshots..."
IS_WEBPACK_TEST=1 NEXT_TEST_MODE=dev pnpm jest test/integration/edge-runtime-dynamic-code/test/index.test.ts -u --silent
cp "$SNAP_FILE" "$TMP_DIR/webpack.snap"
echo "Merging snapshots..."
{
echo '// Jest Snapshot v1, https://goo.gl/fbAQLP'
echo ''
tail -n +3 "$TMP_DIR/turbopack.snap"
tail -n +3 "$TMP_DIR/webpack.snap"
} > "$SNAP_FILE"
rm -rf "$TMP_DIR"
COUNT=$(grep -c 'exports\[' "$SNAP_FILE")
echo "Done! Merged $COUNT snapshots."
......@@ -84,17 +84,20 @@ describe('server-side dev errors', () => {
)
await expect(browser).toDisplayRedbox(`
{
"description": "missingVar is not defined",
"environmentLabel": null,
"label": "Runtime ReferenceError",
"source": "pages/gsp.js (6:3) @ getStaticProps
> 6 | missingVar;return {
| ^",
"stack": [
"getStaticProps pages/gsp.js (6:3)",
],
}
{
"description": "missingVar is not defined",
"environmentLabel": null,
"label": "Runtime ReferenceError",
"source": "../../test/integration/server-side-dev-errors/pages/gsp.js (6:3) @ getStaticProps
> 6 | missingVar;return {
| ^",
"stack": [
"getStaticProps ../../test/integration/server-side-dev-errors/pages/gsp.js (6:3)",
"async doRender src/server/route-modules/pages/pages-handler.ts (234:22)",
"async handleResponse src/server/route-modules/pages/pages-handler.ts (529:24)",
"async Module.handler src/server/route-modules/pages/pages-handler.ts (729:9)",
],
}
`)
await fs.writeFile(gspPage, content, { flush: true })
......@@ -134,17 +137,20 @@ describe('server-side dev errors', () => {
)
await expect(browser).toDisplayRedbox(`
{
"description": "missingVar is not defined",
"environmentLabel": null,
"label": "Runtime ReferenceError",
"source": "pages/gssp.js (6:3) @ getServerSideProps
> 6 | missingVar;return {
| ^",
"stack": [
"getServerSideProps pages/gssp.js (6:3)",
],
}
{
"description": "missingVar is not defined",
"environmentLabel": null,
"label": "Runtime ReferenceError",
"source": "../../test/integration/server-side-dev-errors/pages/gssp.js (6:3) @ getServerSideProps
> 6 | missingVar;return {
| ^",
"stack": [
"getServerSideProps ../../test/integration/server-side-dev-errors/pages/gssp.js (6:3)",
"async doRender src/server/route-modules/pages/pages-handler.ts (234:22)",
"async handleResponse src/server/route-modules/pages/pages-handler.ts (529:24)",
"async Module.handler src/server/route-modules/pages/pages-handler.ts (729:9)",
],
}
`)
await fs.writeFile(gsspPage, content)
......@@ -184,17 +190,20 @@ describe('server-side dev errors', () => {
)
await expect(browser).toDisplayRedbox(`
{
"description": "missingVar is not defined",
"environmentLabel": null,
"label": "Runtime ReferenceError",
"source": "pages/blog/[slug].js (6:3) @ getServerSideProps
> 6 | missingVar;return {
| ^",
"stack": [
"getServerSideProps pages/blog/[slug].js (6:3)",
],
}
{
"description": "missingVar is not defined",
"environmentLabel": null,
"label": "Runtime ReferenceError",
"source": "../../test/integration/server-side-dev-errors/pages/blog/[slug].js (6:3) @ getServerSideProps
> 6 | missingVar;return {
| ^",
"stack": [
"getServerSideProps ../../test/integration/server-side-dev-errors/pages/blog/[slug].js (6:3)",
"async doRender src/server/route-modules/pages/pages-handler.ts (234:22)",
"async handleResponse src/server/route-modules/pages/pages-handler.ts (529:24)",
"async Module.handler src/server/route-modules/pages/pages-handler.ts (729:9)",
],
}
`)
await fs.writeFile(dynamicGsspPage, content)
......@@ -221,40 +230,27 @@ describe('server-side dev errors', () => {
})
const stderrOutput = stripAnsi(stderr.slice(stderrIdx)).trim()
if (isTurbopack) {
expect(stderrOutput).toStartWith(
'⨯ ReferenceError: missingVar is not defined' +
'\n at handler (../../test/integration/server-side-dev-errors/pages/api/hello.js:2:3)' +
'\n 1 | export default function handler(req, res) {' +
"\n> 2 | missingVar;res.status(200).json({ hello: 'world' })" +
'\n | ^'
)
} else {
expect(stderrOutput).toStartWith(
'⨯ ReferenceError: missingVar is not defined' +
'\n at handler (../../test/integration/server-side-dev-errors/pages/api/hello.js:2:3)' +
// TODO(veil): Why not ignore-listed?
'\n at '
)
expect(stderrOutput).toContain(
expect(stderrOutput).toStartWith(
'⨯ ReferenceError: missingVar is not defined' +
'\n at handler (../../test/integration/server-side-dev-errors/pages/api/hello.js:2:3)' +
'\n 1 | export default function handler(req, res) {' +
"\n> 2 | missingVar;res.status(200).json({ hello: 'world' })" +
'\n | ^'
)
}
"\n> 2 | missingVar;res.status(200).json({ hello: 'world' })" +
'\n | ^'
)
await expect(browser).toDisplayRedbox(`
{
"description": "missingVar is not defined",
"environmentLabel": null,
"label": "Runtime ReferenceError",
"source": "pages/api/hello.js (2:3) @ handler
> 2 | missingVar;res.status(200).json({ hello: 'world' })
| ^",
"stack": [
"handler pages/api/hello.js (2:3)",
],
}
{
"description": "missingVar is not defined",
"environmentLabel": null,
"label": "Runtime ReferenceError",
"source": "../../test/integration/server-side-dev-errors/pages/api/hello.js (2:3) @ handler
> 2 | missingVar;res.status(200).json({ hello: 'world' })
| ^",
"stack": [
"handler ../../test/integration/server-side-dev-errors/pages/api/hello.js (2:3)",
"async Module.handler src/build/templates/pages-api.ts (149:7)",
],
}
`)
await fs.writeFile(apiPage, content, { flush: true })
......@@ -287,40 +283,27 @@ describe('server-side dev errors', () => {
})
const stderrOutput = stripAnsi(stderr.slice(stderrIdx)).trim()
if (isTurbopack) {
expect(stderrOutput).toStartWith(
'⨯ ReferenceError: missingVar is not defined' +
'\n at handler (../../test/integration/server-side-dev-errors/pages/api/blog/[slug].js:2:3)' +
'\n 1 | export default function handler(req, res) {' +
'\n> 2 | missingVar;res.status(200).json({ slug: req.query.slug })' +
'\n | ^'
)
} else {
expect(stderrOutput).toStartWith(
'⨯ ReferenceError: missingVar is not defined' +
'\n at handler (../../test/integration/server-side-dev-errors/pages/api/blog/[slug].js:2:3)' +
// TODO(veil): Why not ignore-listed?
'\n at'
)
expect(stderrOutput).toContain(
expect(stderrOutput).toStartWith(
'⨯ ReferenceError: missingVar is not defined' +
'\n at handler (../../test/integration/server-side-dev-errors/pages/api/blog/[slug].js:2:3)' +
'\n 1 | export default function handler(req, res) {' +
'\n> 2 | missingVar;res.status(200).json({ slug: req.query.slug })' +
'\n | ^'
)
}
'\n> 2 | missingVar;res.status(200).json({ slug: req.query.slug })' +
'\n | ^'
)
await expect(browser).toDisplayRedbox(`
{
"description": "missingVar is not defined",
"environmentLabel": null,
"label": "Runtime ReferenceError",
"source": "pages/api/blog/[slug].js (2:3) @ handler
> 2 | missingVar;res.status(200).json({ slug: req.query.slug })
| ^",
"stack": [
"handler pages/api/blog/[slug].js (2:3)",
],
}
{
"description": "missingVar is not defined",
"environmentLabel": null,
"label": "Runtime ReferenceError",
"source": "../../test/integration/server-side-dev-errors/pages/api/blog/[slug].js (2:3) @ handler
> 2 | missingVar;res.status(200).json({ slug: req.query.slug })
| ^",
"stack": [
"handler ../../test/integration/server-side-dev-errors/pages/api/blog/[slug].js (2:3)",
"async Module.handler src/build/templates/pages-api.ts (149:7)",
],
}
`)
await fs.writeFile(dynamicApiPage, content, { flush: true })
......@@ -385,7 +368,7 @@ describe('server-side dev errors', () => {
// sometimes there is a leading newline, so trim it
expect(stderrOutput.trimStart()).toMatchInlineSnapshot(`
"Error: catch this rejection
at Timeout.eval [as _onTimeout] (../../test/integration/server-side-dev-errors/pages/uncaught-rejection.js:7:20)
at Timeout._onTimeout (../../test/integration/server-side-dev-errors/pages/uncaught-rejection.js:7:20)
5 | export async function getServerSideProps() {
6 | setTimeout(() => {
> 7 | Promise.reject(new Error('catch this rejection'))
......@@ -394,7 +377,7 @@ describe('server-side dev errors', () => {
9 | return {
10 | props: {},
⨯ unhandledRejection: Error: catch this rejection
at Timeout.eval [as _onTimeout] (../../test/integration/server-side-dev-errors/pages/uncaught-rejection.js:7:20)
at Timeout._onTimeout (../../test/integration/server-side-dev-errors/pages/uncaught-rejection.js:7:20)
5 | export async function getServerSideProps() {
6 | setTimeout(() => {
> 7 | Promise.reject(new Error('catch this rejection'))
......@@ -403,7 +386,7 @@ describe('server-side dev errors', () => {
9 | return {
10 | props: {},
⨯ unhandledRejection: Error: catch this rejection
at Timeout.eval [as _onTimeout] (../../test/integration/server-side-dev-errors/pages/uncaught-rejection.js:7:20)
at Timeout._onTimeout (../../test/integration/server-side-dev-errors/pages/uncaught-rejection.js:7:20)
5 | export async function getServerSideProps() {
6 | setTimeout(() => {
> 7 | Promise.reject(new Error('catch this rejection'))
......@@ -463,7 +446,7 @@ describe('server-side dev errors', () => {
} else {
expect(stderrOutput).toMatchInlineSnapshot(`
"Error:
at Timeout.eval [as _onTimeout] (../../test/integration/server-side-dev-errors/pages/uncaught-empty-rejection.js:7:20)
at Timeout._onTimeout (../../test/integration/server-side-dev-errors/pages/uncaught-empty-rejection.js:7:20)
5 | export async function getServerSideProps() {
6 | setTimeout(() => {
> 7 | Promise.reject(new Error())
......@@ -472,7 +455,7 @@ describe('server-side dev errors', () => {
9 | return {
10 | props: {},
⨯ unhandledRejection: Error:
at Timeout.eval [as _onTimeout] (../../test/integration/server-side-dev-errors/pages/uncaught-empty-rejection.js:7:20)
at Timeout._onTimeout (../../test/integration/server-side-dev-errors/pages/uncaught-empty-rejection.js:7:20)
5 | export async function getServerSideProps() {
6 | setTimeout(() => {
> 7 | Promise.reject(new Error())
......@@ -481,7 +464,7 @@ describe('server-side dev errors', () => {
9 | return {
10 | props: {},
⨯ unhandledRejection: Error:
at Timeout.eval [as _onTimeout] (../../test/integration/server-side-dev-errors/pages/uncaught-empty-rejection.js:7:20)
at Timeout._onTimeout (../../test/integration/server-side-dev-errors/pages/uncaught-empty-rejection.js:7:20)
5 | export async function getServerSideProps() {
6 | setTimeout(() => {
> 7 | Promise.reject(new Error())
......@@ -541,7 +524,7 @@ describe('server-side dev errors', () => {
} else {
expect(stderrOutput).toMatchInlineSnapshot(`
"Error: catch this exception
at Timeout.eval [as _onTimeout] (../../test/integration/server-side-dev-errors/pages/uncaught-exception.js:7:11)
at Timeout._onTimeout (../../test/integration/server-side-dev-errors/pages/uncaught-exception.js:7:11)
5 | export async function getServerSideProps() {
6 | setTimeout(() => {
> 7 | throw new Error('catch this exception')
......@@ -550,7 +533,7 @@ describe('server-side dev errors', () => {
9 | return {
10 | props: {},
⨯ uncaughtException: Error: catch this exception
at Timeout.eval [as _onTimeout] (../../test/integration/server-side-dev-errors/pages/uncaught-exception.js:7:11)
at Timeout._onTimeout (../../test/integration/server-side-dev-errors/pages/uncaught-exception.js:7:11)
5 | export async function getServerSideProps() {
6 | setTimeout(() => {
> 7 | throw new Error('catch this exception')
......@@ -559,7 +542,7 @@ describe('server-side dev errors', () => {
9 | return {
10 | props: {},
⨯ uncaughtException: Error: catch this exception
at Timeout.eval [as _onTimeout] (../../test/integration/server-side-dev-errors/pages/uncaught-exception.js:7:11)
at Timeout._onTimeout (../../test/integration/server-side-dev-errors/pages/uncaught-exception.js:7:11)
5 | export async function getServerSideProps() {
6 | setTimeout(() => {
> 7 | throw new Error('catch this exception')
......@@ -619,7 +602,7 @@ describe('server-side dev errors', () => {
} else {
expect(stderrOutput).toMatchInlineSnapshot(`
"Error:
at Timeout.eval [as _onTimeout] (../../test/integration/server-side-dev-errors/pages/uncaught-empty-exception.js:7:11)
at Timeout._onTimeout (../../test/integration/server-side-dev-errors/pages/uncaught-empty-exception.js:7:11)
5 | export async function getServerSideProps() {
6 | setTimeout(() => {
> 7 | throw new Error()
......@@ -628,7 +611,7 @@ describe('server-side dev errors', () => {
9 | return {
10 | props: {},
⨯ uncaughtException: Error:
at Timeout.eval [as _onTimeout] (../../test/integration/server-side-dev-errors/pages/uncaught-empty-exception.js:7:11)
at Timeout._onTimeout (../../test/integration/server-side-dev-errors/pages/uncaught-empty-exception.js:7:11)
5 | export async function getServerSideProps() {
6 | setTimeout(() => {
> 7 | throw new Error()
......@@ -637,7 +620,7 @@ describe('server-side dev errors', () => {
9 | return {
10 | props: {},
⨯ uncaughtException: Error:
at Timeout.eval [as _onTimeout] (../../test/integration/server-side-dev-errors/pages/uncaught-empty-exception.js:7:11)
at Timeout._onTimeout (../../test/integration/server-side-dev-errors/pages/uncaught-empty-exception.js:7:11)
5 | export async function getServerSideProps() {
6 | setTimeout(() => {
> 7 | throw new Error()
......
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