File size: 8,699 Bytes
94786da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
diff --git a/packages/next/src/server/dev/hot-reloader-turbopack.ts b/packages/next/src/server/dev/hot-reloader-turbopack.ts
index 0fb2cb77bb..6c76ac9af4 100644
--- a/packages/next/src/server/dev/hot-reloader-turbopack.ts
+++ b/packages/next/src/server/dev/hot-reloader-turbopack.ts
@@ -1,7 +1,9 @@
 import type { Socket } from 'net'
 import { mkdir, writeFile } from 'fs/promises'
+import { realpathSync } from 'fs'
 import * as inspector from 'inspector'
-import { join, extname, relative } from 'path'
+import { join, extname, relative, isAbsolute } from 'path'
+import { fileURLToPath, pathToFileURL } from 'url'
 
 import ws from 'next/dist/compiled/ws'
 
@@ -84,6 +86,7 @@ import type { ModernSourceMapPayload } from '../lib/source-maps'
 import { isDeferredEntry } from '../../build/entries'
 import { isMetadataRouteFile } from '../../lib/metadata/is-metadata-route'
 import { setBundlerFindSourceMapImplementation } from '../patch-error-inspect'
+import { setBundlerFindSourceMapURLImplementation } from '../lib/source-maps'
 import { getNextErrorFeedbackMiddleware } from '../../next-devtools/server/get-next-error-feedback-middleware'
 import {
   formatIssue,
@@ -279,6 +282,47 @@ function getSourceMapFromTurbopack(
   }
 }
 
+function getSourceMapURLFromTurbopack(
+  distDir: string,
+  scriptNameOrSourceURL: string
+): string | null {
+  // React invokes this with the raw stack-frame filename, which arrives
+  // either as an absolute filesystem path or as a `file:` URL. Anything else
+  // (`file:` URLs with a query are eval'd server HMR modules carrying inline
+  // source maps, `webpack-internal://`, `node:internal/...`, `<anonymous>`,
+  // ...) is not something we have an emitted source map for.
+  let scriptPath = scriptNameOrSourceURL
+  if (scriptNameOrSourceURL.startsWith('file://')) {
+    if (scriptNameOrSourceURL.includes('?')) {
+      return null
+    }
+    try {
+      scriptPath = fileURLToPath(scriptNameOrSourceURL)
+    } catch {
+      return null
+    }
+  }
+  if (!isAbsolute(scriptPath)) {
+    return null
+  }
+
+  // Only chunks emitted into `distDir` have an on-disk source map to point at.
+  const relativePath = relative(distDir, scriptPath)
+  if (
+    relativePath.startsWith('..') ||
+    // On Windows an absolute path on a different drive is returned unchanged
+    // rather than as a `..`-prefixed relative path.
+    isAbsolute(relativePath)
+  ) {
+    return null
+  }
+
+  // The emitted source map lives next to its chunk with a `.map` suffix (see
+  // `SourceMapAsset::path`). Encode through `pathToFileURL` so any special
+  // characters in the path are escaped into a well-formed `file:` URL.
+  return pathToFileURL(scriptPath + '.map').href
+}
+
 export async function createHotReloaderTurbopack(
   opts: SetupOpts & { isSrcDir: boolean },
   serverFields: ServerFields,
@@ -410,6 +454,14 @@ export async function createHotReloaderTurbopack(
     getSourceMapFromTurbopack.bind(null, project)
   )
 
+  let canonicalDistDir = distDir
+  try {
+    canonicalDistDir = realpathSync(distDir)
+  } catch {}
+  setBundlerFindSourceMapURLImplementation(
+    getSourceMapURLFromTurbopack.bind(null, canonicalDistDir)
+  )
+
   // Set up code frame renderer using native bindings
   const { installCodeFrameSupport } =
     require('../lib/install-code-frame') as typeof import('../lib/install-code-frame')
@@ -417,6 +469,7 @@ export async function createHotReloaderTurbopack(
 
   opts.onDevServerCleanup?.(async () => {
     setBundlerFindSourceMapImplementation(() => undefined)
+    setBundlerFindSourceMapURLImplementation(() => null)
     await project.onExit()
     await lockfile?.unlock()
   })
diff --git a/packages/next/src/server/lib/source-maps.ts b/packages/next/src/server/lib/source-maps.ts
index 40b3a2204c..10f8a4880b 100644
--- a/packages/next/src/server/lib/source-maps.ts
+++ b/packages/next/src/server/lib/source-maps.ts
@@ -158,6 +158,36 @@ export function filterStackFrameDEV(
   }
 }
 
+// `scriptNameOrSourceURL` is what React forwards from the stack frame: the
+// script's `getScriptNameOrSourceURL()`, which for the server chunks we can
+// map is an absolute filesystem path, not a URL. The returned value is the
+// source map's URL (`file:` or `data:`).
+type FindSourceMapURL = (scriptNameOrSourceURL: string) => string | null
+// Find the URL of a source map using the bundler's API.
+// Shared via `globalThis` because this module is compiled both into the server
+// runtime bundles (which call `findSourceMapURLDEV`) and into `next/dist/server`
+// (where the dev server registers the implementation), and each copy has its own
+// module state.
+const bundlerFindSourceMapURLSymbol = Symbol.for(
+  'next.server.bundlerFindSourceMapURL'
+)
+
+export function setBundlerFindSourceMapURLImplementation(
+  findSourceMapURLImplementation: FindSourceMapURL
+): void {
+  ;(globalThis as any)[bundlerFindSourceMapURLSymbol] =
+    findSourceMapURLImplementation
+}
+
+function bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null {
+  const implementation: FindSourceMapURL | undefined = (globalThis as any)[
+    bundlerFindSourceMapURLSymbol
+  ]
+  return implementation === undefined
+    ? null
+    : implementation(scriptNameOrSourceURL)
+}
+
 const invalidSourceMap = Symbol('invalid-source-map')
 const sourceMapURLs = new LRUCache<string | typeof invalidSourceMap>(
   512 * 1024 * 1024,
@@ -172,6 +202,19 @@ const sourceMapURLs = new LRUCache<string | typeof invalidSourceMap>(
 export function findSourceMapURLDEV(
   scriptNameOrSourceURL: string
 ): string | null {
+  try {
+    const bundlerSourceMapURL = bundlerFindSourceMapURL(scriptNameOrSourceURL)
+    if (bundlerSourceMapURL !== null) {
+      return bundlerSourceMapURL
+    }
+  } catch (cause) {
+    console.error(
+      `${scriptNameOrSourceURL}: Failed to find the source map URL. Cause: ${cause}`
+    )
+  }
+
+  // No bundler implementation (e.g. Webpack): inline the source map Node.js
+  // knows as a `data:` URL.
   let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL)
   if (sourceMapURL === undefined) {
     let sourceMapPayload: ModernSourceMapPayload | undefined
diff --git a/packages/next/src/server/patch-error-inspect.ts b/packages/next/src/server/patch-error-inspect.ts
index be16e4727b..2aa0025d1e 100644
--- a/packages/next/src/server/patch-error-inspect.ts
+++ b/packages/next/src/server/patch-error-inspect.ts
@@ -181,7 +181,10 @@ function getSourcemappedFrameIfPossible(
   let sourceMapConsumer: SyncSourceMapConsumer
   let sourceMapPayload: ModernSourceMapPayload
   if (sourceMapCacheEntry === undefined) {
-    let sourceURL = frame.file
+    // Fake frame scripts (`about://React/Server/file:///path/to/chunk.js?42`)
+    // have their positions padded to match the underlying chunk, so they
+    // resolve via the chunk's source map.
+    let sourceURL = devirtualizeReactServerURL(frame.file)
     // e.g. "/Users/foo/APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js"
     // or "C:\Users\foo\APP\.next\server\chunks\ssr\[root-of-the-server]__2934a0._.js"
     // will be keyed by Node.js as "file:///APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js".
@@ -189,8 +192,8 @@ function getSourcemappedFrameIfPossible(
     //
     // But frame.file might also be "webpack-internal:///(rsc)/./app/bad-sourcemap/page.js" or
     // "<anonymous>" or "node:internal/process/task_queues" here
-    if (path.isAbsolute(frame.file)) {
-      sourceURL = url.pathToFileURL(frame.file).toString()
+    if (path.isAbsolute(sourceURL)) {
+      sourceURL = url.pathToFileURL(sourceURL).toString()
     }
     let maybeSourceMapPayload: ModernSourceMapPayload | undefined
     try {
@@ -228,10 +231,9 @@ function getSourcemappedFrameIfPossible(
       // is sufficient to compute relative paths but is actually wrong (the
       // chunk and sourcemap have different content hashes). We are using the
       // node API to read the sourcemap and it doesn't give us access to the
-      // URI. Devirtualize `about://React/Server/file:///path/to/chunk.js?4` to
-      // `file:///path/to/chunk.js` so that relative `sources` in the source map
-      // resolve against the real chunk URL, not the virtual one.
-      const sourceMapURL = devirtualizeReactServerURL(sourceURL) + '.map'
+      // URI. `sourceURL` is already devirtualized so that relative `sources`
+      // resolve against the real chunk URL, not React's virtual one.
+      const sourceMapURL = sourceURL + '.map'
       sourceMapConsumer = new SyncSourceMapConsumer(
         sourceMapPayload,
         // @ts-expect-error: our typings don't include this parameter but it is here.