Skip to content
Draft
Show file tree
Hide file tree
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
10 changes: 10 additions & 0 deletions packages/vite/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,16 @@ if (typeof window !== 'undefined') {
window.addEventListener?.('beforeunload', () => {
willUnload = true
})
window.addEventListener('error', (error) => {
transport.send({
type: 'browser-error',
stack: error.error.stack,
filename: error.filename,
message: error.message,
colno: error.colno,
lineno: error.lineno,
})
})
}

function cleanUrl(pathname: string): string {
Expand Down
1 change: 1 addition & 0 deletions packages/vite/src/node/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ export const SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/
export const FS_PREFIX = `/@fs/`

export const CLIENT_PUBLIC_PATH = `/@vite/client`
export const CLIENT_ERROR_RELAY_PATH = '/@vite/errors'
export const ENV_PUBLIC_PATH = `/@vite/env`
export const VITE_PACKAGE_DIR = resolve(
fileURLToPath(import.meta.url),
Expand Down
53 changes: 53 additions & 0 deletions packages/vite/src/node/server/errorIngestion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import path from 'node:path'
import repl from 'node:repl'
import { readFileSync } from 'fs';

import { stripVTControlCharacters as strip } from 'node:util'
import colors from 'picocolors'
import type { RollupError } from 'rollup'
import bodyParser from 'body-parser'
import type { Connect } from 'dep-types/connect'
import type { ErrorPayload } from 'types/hmrPayload'
import { pad } from '../../utils'
import type { ResolvedConfig } from '../..'
import { CLIENT_ERROR_RELAY_PATH } from '../../constants'

export interface BrowserErrorInfo {
type: 'browser-error'
stack: string
lineno: number
colno: number
message: string
}

export async function logBrowserError(
source: string,
error: BrowserErrorInfo,
stack: string,
config: ResolvedConfig
) {
const fragment = await getErrorFragment(error, source)
const msg = `${colors.magenta('[browser]')} ${colors.red(stack)}`
config.logger.error(`${msg}\n\n${fragment}`, {
clear: true,
timestamp: true,
})
}

async function getErrorFragment (error, source) {
const filtered = source.split(/\r?\n/g)
.map((line, i) => [i, line])
.slice(Math.max(1, error.lineno - 2), error.lineno + 3)
let fragment = ""
let padding = String(error.lineno).length
for (const [lineno, line] of filtered) {
fragment += `${
lineno === (error.lineno - 1) ? colors.red('>') : ' '
}${String(lineno).padStart(padding)} | ${line}\n`
if (lineno === (error.lineno - 1)) {
const leftPadding = Math.max(0, (error.colno - 1) + padding + 5)
fragment += `${new Array(leftPadding).fill('').join(' ')}${colors.red('^')}\n`
}
}
return fragment
}
14 changes: 8 additions & 6 deletions packages/vite/src/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,14 @@ export async function _createServer(
? null
: await resolveHttpServer(serverConfig, middlewares, httpsOptions)

const ws = createWebSocketServer(httpServer, config, httpsOptions)
const environments: Record<string, DevEnvironment> = {}

let moduleGraph = new ModuleGraph({
client: () => environments.client.moduleGraph,
ssr: () => environments.ssr.moduleGraph,
})

const ws = createWebSocketServer(httpServer, config, httpsOptions, moduleGraph)

const publicFiles = await initPublicFilesPromise
const { publicDir } = config
Expand All @@ -509,7 +516,6 @@ export async function _createServer(
) as FSWatcher)
: createNoopWatcher(resolvedWatchOptions)

const environments: Record<string, DevEnvironment> = {}

for (const [name, environmentOptions] of Object.entries(
config.environments,
Expand All @@ -530,10 +536,6 @@ export async function _createServer(

// Backward compatibility

let moduleGraph = new ModuleGraph({
client: () => environments.client.moduleGraph,
ssr: () => environments.ssr.moduleGraph,
})
let pluginContainer = createPluginContainer(environments)

const closeHttpServer = createServerCloseFn(httpServer)
Expand Down
80 changes: 80 additions & 0 deletions packages/vite/src/node/server/stacktrace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import path from 'node:path'
import { TraceMap, originalPositionFor } from '@jridgewell/trace-mapping'
import type { EnvironmentModuleGraph } from './server'

let offset: number

function calculateOffsetOnce() {
if (offset !== undefined) {
return
}

try {
new Function('throw new Error(1)')()
} catch (e) {
// in Node 12, stack traces account for the function wrapper.
Copy link
Contributor

Choose a reason for hiding this comment

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

i don't think we have to support node12 here, our engine field asks for 20.19+

// 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
}
}


export function browserRewriteStacktrace(
stack: string,
moduleGraph: EnvironmentModuleGraph,
): [string, string] {
let firstSource
const processedStack = stack
.split('\n')
.map((line) => {
return line.replace(
/^ {4}at (?:(\S.*?)\s\()?(.*?)\)$/,
(input, varName, url) => {
const { pathname } = new URL(url)
const [,id, line, column] = pathname.match(/^(.*?):(\d+):(\d+)$/)
if (!id) return input

const mod = moduleGraph.urlToModuleMap.get(id)
const rawSource = mod?._clientModule.transformResult.code
if (!firstSource) {
firstSource = rawSource
}
const rawSourceMap = mod?._clientModule.transformResult?.map
const trimmedVarName = varName?.trim()

if (!rawSourceMap) {
if (!trimmedVarName || trimmedVarName === 'eval') {
return ` at (${pathname})`
} else {
return ` at ${trimmedVarName} (${pathname})`
}
}

const traced = new TraceMap(rawSourceMap as any)

const pos = originalPositionFor(traced, {
line: Number(line) - offset,
// stacktrace's column is 1-indexed, but sourcemap's one is 0-indexed
column: Number(column) - 1,
})

if (!pos.source) {
return input
}

const sourceFile = path.resolve(path.dirname(id), pos.source)
// stacktrace's column is 1-indexed, but sourcemap's one is 0-indexed
const source = `${sourceFile}:${pos.line}:${pos.column + 1}`
if (!trimmedVarName || trimmedVarName === 'eval') {
return ` at ${source}`
} else {
return ` at ${trimmedVarName} (${source})`
}
},
)
})
.join('\n')
return [firstSource, processedStack]
}
10 changes: 9 additions & 1 deletion packages/vite/src/node/server/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ import { isObject } from '../utils'
import type { NormalizedHotChannel, NormalizedHotChannelClient } from './hmr'
import { normalizeHotChannel } from './hmr'
import type { HttpServer } from '.'
import type { EnvironmentModuleGraph } from '..'
import { browserRewriteStacktrace } from './stacktrace'
import { logBrowserError } from './errorIngestion'

/* In Bun, the `ws` module is overridden to hook into the native code. Using the bundled `js` version
* of `ws` will not work as Bun's req.socket does not allow reading/writing to the underlying socket.
Expand Down Expand Up @@ -116,6 +119,7 @@ export function createWebSocketServer(
server: HttpServer | null,
config: ResolvedConfig,
httpsOptions?: HttpsServerOptions,
moduleGraph: EnvironmentModuleGraph,
): WebSocketServer {
if (config.server.ws === false) {
return {
Expand Down Expand Up @@ -283,11 +287,15 @@ export function createWebSocketServer(

wss.on('connection', (socket) => {
socket.on('message', (raw) => {
if (!customListeners.size) return
let parsed: any
try {
parsed = JSON.parse(String(raw))
} catch {}
if (parsed.type === 'browser-error') {
const [source, stack] = browserRewriteStacktrace(parsed.stack, moduleGraph)
logBrowserError(source, parsed, stack, config)
}
if (!customListeners.size) return
if (!parsed || parsed.type !== 'custom' || !parsed.event) return
const listeners = customListeners.get(parsed.event)
if (!listeners?.size) return
Expand Down
Empty file.
2 changes: 2 additions & 0 deletions packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { VALID_ID_PREFIX } from '../shared/constants'
import {
CLIENT_ENTRY,
CLIENT_PUBLIC_PATH,
CLIENT_ERROR_RELAY_PATH,
CSS_LANGS_RE,
ENV_PUBLIC_PATH,
FS_PREFIX,
Expand Down Expand Up @@ -326,6 +327,7 @@ const internalPrefixes = [
FS_PREFIX,
VALID_ID_PREFIX,
CLIENT_PUBLIC_PATH,
CLIENT_ERROR_RELAY_PATH,
ENV_PUBLIC_PATH,
]
const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join('|')})`)
Expand Down
5 changes: 5 additions & 0 deletions playground/client-errors/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<body>
<h4>Test Client Error Ingestion</h4>
<input type="button" value="Create error">
<script type="module" src="/index.js"></script>
</body>
8 changes: 8 additions & 0 deletions playground/client-errors/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@

const input = document.querySelector('input')

input.addEventListener('click', handleClick)

function handleClick () {
throw new Error('Something went wrong')
}
15 changes: 15 additions & 0 deletions playground/client-errors/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "@vitejs/test-client-errors",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"debug": "node --inspect-brk ../../packages/vite/bin/vite",
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"devDependencies": {
"vite": "workspace:^"
}
}
5 changes: 5 additions & 0 deletions playground/client-errors/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { defineConfig } from 'vite'

export default defineConfig({
server: {},
})
46 changes: 26 additions & 20 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.