-
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
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
feat(ssr): better DX with sourcemaps, breakpoints, error messages #3928
Closed
+202
−171
Closed
Changes from 14 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
cf4d9a9
fix(ssr): support breakpoints in SSR
aleclarson bd5d6c0
fix(sourcemap): use `moduleGraph` to fix url sources
aleclarson 02ff17a
feat(ssr): use @babel/code-frame in SSR stack traces
aleclarson 19d9027
feat(ssr): use `vm.runInNewContext` in development
aleclarson 06e400a
fix: skip `ssrRewriteStacktrace` if it fails
aleclarson 1732df2
fix(ssr): remove pointless wrapper when using vm.runInNewContext
aleclarson bfa1aa2
fix(ssr): disable `displayErrors` in vm.runInNewContext calls
aleclarson 3cc19f0
fix(ssr): ignore "vm.js" frames in stacktrace
aleclarson f412edb
fix(ssr): print code frames in dev mode
aleclarson 2871e92
fix(ssr): use `vm.runInThisContext` to ensure all instances of built-…
aleclarson 8f1245c
Revert "fix(ssr): ignore "vm.js" frames in stacktrace"
aleclarson 135c903
fix(ssr): breakpoints in modules created with `vm.runInThisContext`
aleclarson 700ba7c
fix: add `columnOffset` back
aleclarson 10d959a
fix: rebase oopsies
aleclarson 294f460
test: update `ssrTransform` tests
aleclarson File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,29 @@ | ||
import { promises as fs } from 'fs' | ||
import path from 'path' | ||
import { ModuleGraph } from './moduleGraph' | ||
|
||
export async function injectSourcesContent( | ||
map: { sources: string[]; sourcesContent?: string[]; sourceRoot?: string }, | ||
file: string | ||
file: string, | ||
moduleGraph?: ModuleGraph | ||
): Promise<void> { | ||
const sourceRoot = await fs.realpath( | ||
path.resolve(path.dirname(file), map.sourceRoot || '') | ||
) | ||
map.sourcesContent = [] | ||
const needsContent = !map.sourcesContent | ||
if (needsContent) { | ||
map.sourcesContent = [] | ||
} | ||
await Promise.all( | ||
map.sources.filter(Boolean).map(async (sourcePath, i) => { | ||
map.sourcesContent![i] = await fs.readFile( | ||
path.resolve(sourceRoot, decodeURI(sourcePath)), | ||
'utf-8' | ||
) | ||
const mod = await moduleGraph?.getModuleByUrl(sourcePath) | ||
sourcePath = mod?.file || path.resolve(sourceRoot, decodeURI(sourcePath)) | ||
if (moduleGraph) { | ||
map.sources[i] = sourcePath | ||
} | ||
if (needsContent) { | ||
map.sourcesContent![i] = await fs.readFile(sourcePath, 'utf-8') | ||
} | ||
}) | ||
) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,6 @@ | ||
import fs from 'fs' | ||
import path from 'path' | ||
import * as convertSourceMap from 'convert-source-map' | ||
import { ViteDevServer } from '..' | ||
import { cleanUrl, resolveFrom, unwrapId } from '../utils' | ||
import { ssrRewriteStacktrace } from './ssrStacktrace' | ||
|
@@ -11,6 +12,7 @@ import { | |
ssrDynamicImportKey | ||
} from './ssrTransform' | ||
import { transformRequest } from '../server/transformRequest' | ||
import { injectSourcesContent } from '../server/sourcemap' | ||
|
||
interface SSRContext { | ||
global: NodeJS.Global | ||
|
@@ -86,19 +88,19 @@ async function instantiateModule( | |
}) | ||
) | ||
|
||
const ssrImportMeta = { url } | ||
const { clearScreen, isProduction, logger, root } = server.config | ||
|
||
const ssrImport = (dep: string) => { | ||
if (isExternal(dep)) { | ||
return nodeRequire(dep, mod.file, server.config.root) | ||
return nodeRequire(dep, mod.file, root) | ||
} else { | ||
return moduleGraph.urlToModuleMap.get(unwrapId(dep))?.ssrModule | ||
} | ||
} | ||
|
||
const ssrDynamicImport = (dep: string) => { | ||
if (isExternal(dep)) { | ||
return Promise.resolve(nodeRequire(dep, mod.file, server.config.root)) | ||
return Promise.resolve(nodeRequire(dep, mod.file, root)) | ||
} else { | ||
// #3087 dynamic import vars is ignored at rewrite import path, | ||
// so here need process relative path | ||
|
@@ -123,32 +125,52 @@ async function instantiateModule( | |
} | ||
} | ||
|
||
const ssrImportMeta = { url } | ||
const ssrArguments: Record<string, any> = { | ||
global: context.global, | ||
[ssrModuleExportsKey]: ssrModule, | ||
[ssrImportMetaKey]: ssrImportMeta, | ||
[ssrImportKey]: ssrImport, | ||
[ssrDynamicImportKey]: ssrDynamicImport, | ||
[ssrExportAllKey]: ssrExportAll | ||
} | ||
|
||
let ssrModuleImpl = isProduction | ||
? result.code + `\n//# sourceURL=${mod.url}` | ||
: `(0,function(${Object.keys(ssrArguments)}){\n${result.code}\n})` | ||
|
||
const { map } = result | ||
if (map?.mappings) { | ||
if (mod.file) { | ||
await injectSourcesContent(map, mod.file, moduleGraph) | ||
} | ||
|
||
ssrModuleImpl += `\n` + convertSourceMap.fromObject(map).toComment() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The inline sourcemap is appended in both production and development, as |
||
} | ||
|
||
try { | ||
new Function( | ||
`global`, | ||
ssrModuleExportsKey, | ||
ssrImportMetaKey, | ||
ssrImportKey, | ||
ssrDynamicImportKey, | ||
ssrExportAllKey, | ||
result.code + `\n//# sourceURL=${mod.url}` | ||
)( | ||
context.global, | ||
ssrModule, | ||
ssrImportMeta, | ||
ssrImport, | ||
ssrDynamicImport, | ||
ssrExportAll | ||
) | ||
let ssrModuleInit: Function | ||
if (isProduction) { | ||
// Use the faster `new Function` in production. | ||
ssrModuleInit = new Function(...Object.keys(ssrArguments), ssrModuleImpl) | ||
} else { | ||
// Use the slower `vm.runInThisContext` for better sourcemap support. | ||
const vm = require('vm') as typeof import('vm') | ||
ssrModuleInit = vm.runInThisContext(ssrModuleImpl, { | ||
filename: mod.file || mod.url, | ||
columnOffset: 1, | ||
displayErrors: false | ||
}) | ||
} | ||
ssrModuleInit(...Object.values(ssrArguments)) | ||
} catch (e) { | ||
e.stack = ssrRewriteStacktrace(e.stack, moduleGraph) | ||
server.config.logger.error( | ||
`Error when evaluating SSR module ${url}:\n${e.stack}`, | ||
{ | ||
timestamp: true, | ||
clear: server.config.clearScreen | ||
} | ||
) | ||
try { | ||
e.stack = ssrRewriteStacktrace(e, moduleGraph) | ||
} catch {} | ||
logger.error(`Error when evaluating SSR module ${url}:\n\n${e.stack}`, { | ||
timestamp: true, | ||
clear: clearScreen | ||
}) | ||
throw e | ||
} | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,58 +1,73 @@ | ||
import { codeFrameColumns, SourceLocation } from '@babel/code-frame' | ||
import { SourceMapConsumer, RawSourceMap } from 'source-map' | ||
import { ModuleGraph } from '../server/moduleGraph' | ||
import fs from 'fs' | ||
|
||
let offset: number | ||
try { | ||
new Function('throw new Error(1)')() | ||
} catch (e) { | ||
// in Node 12, stack traces account for the function wrapper. | ||
// in Node 13 and later, the function wrapper adds two lines, | ||
// which must be subtracted to generate a valid mapping | ||
const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1]) | ||
offset = match ? +match[1] - 1 : 0 | ||
} | ||
const stackFrameRE = /^ {4}at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?)\)?/ | ||
|
||
export function ssrRewriteStacktrace( | ||
stack: string, | ||
error: Error, | ||
moduleGraph: ModuleGraph | ||
): string { | ||
return stack | ||
.split('\n') | ||
.map((line) => { | ||
return line.replace( | ||
/^ {4}at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?)\)?/, | ||
(input, varName, url, line, column) => { | ||
if (!url) return input | ||
|
||
const mod = moduleGraph.urlToModuleMap.get(url) | ||
const rawSourceMap = mod?.ssrTransformResult?.map | ||
|
||
if (!rawSourceMap) { | ||
return input | ||
} | ||
let code!: string | ||
let location: SourceLocation | undefined | ||
|
||
const stackFrames = error | ||
.stack!.split('\n') | ||
.slice(error.message.split('\n').length) | ||
.map((line, i) => { | ||
return line.replace(stackFrameRE, (input, varName, url, line, column) => { | ||
if (!url) return input | ||
|
||
const mod = moduleGraph.urlToModuleMap.get(url) | ||
const rawSourceMap = mod?.ssrTransformResult?.map | ||
|
||
if (rawSourceMap) { | ||
const consumer = new SourceMapConsumer( | ||
rawSourceMap as any as RawSourceMap | ||
) | ||
|
||
const pos = consumer.originalPositionFor({ | ||
line: Number(line) - offset, | ||
line: Number(line), | ||
column: Number(column), | ||
bias: SourceMapConsumer.LEAST_UPPER_BOUND | ||
bias: SourceMapConsumer.GREATEST_LOWER_BOUND | ||
}) | ||
|
||
if (!pos.source) { | ||
return input | ||
if (pos.source) { | ||
url = pos.source | ||
line = pos.line | ||
column = pos.column | ||
} | ||
} | ||
|
||
if (i == 0 && fs.existsSync(url)) { | ||
code = fs.readFileSync(url, 'utf8') | ||
location = { | ||
start: { | ||
line: Number(line), | ||
column: Number(column) | ||
} | ||
} | ||
} | ||
|
||
const source = `${pos.source}:${pos.line || 0}:${pos.column || 0}` | ||
if (rawSourceMap) { | ||
const source = `${url}:${line}:${column}` | ||
if (!varName || varName === 'eval') { | ||
return ` at ${source}` | ||
} else { | ||
return ` at ${varName} (${source})` | ||
} | ||
} | ||
) | ||
return input | ||
}) | ||
}) | ||
.join('\n') | ||
|
||
const message = location | ||
? codeFrameColumns(code, location, { | ||
highlightCode: true, | ||
message: error.message | ||
}) | ||
: error.message | ||
|
||
return message + '\n\n' + stackFrames.join('\n') | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Honestly not sure if this call is needed in production. Someone needs to test with and without to see the difference (as it may affect stack traces?). Otherwise, in development, this ensures that changes to local modules will not appear while debugging an earlier version of a module.