Commit d14db100 authored by devjiwonchoi's avatar devjiwonchoi

wip

parent 521c318e
......@@ -5,7 +5,7 @@ import { useState, useEffect, useRef, createContext, useContext } from 'react'
import { Toast } from '../../toast'
import { NextLogo } from './internal/next-logo'
import { useIsDevBuilding } from '../../../../../../dev/dev-build-indicator/internal/initialize'
import { useIsDevRendering } from './internal/dev-render-indicator'
import { useIsDevRendering } from '../../../../utils/dev-indicator/dev-render-indicator'
import { useDelayedRender } from '../../../hooks/use-delayed-render'
import { noop as css } from '../../../helpers/noop-template'
import { TurbopackInfo } from './dev-tools-info/turbopack-info'
......
import { useMemo, useState } from 'react'
import { CollapseIcon } from '../../icons/collapse-icon'
/**
*
* Format component stack into pseudo HTML
* component stack is an array of strings, e.g.: ['p', 'p', 'Page', ...]
*
* For html tags mismatch, it will render it for the code block
*
* ```
* <pre>
* <code>{`
* <Page>
* <p red>
* <p red>
* `}</code>
* </pre>
* ```
*
* For text mismatch, it will render it for the code block
*
* ```
* <pre>
* <code>{`
* <Page>
* <p>
* "Server Text" (green)
* "Client Text" (red)
* </p>
* </Page>
* `}</code>
* ```
*
* For bad text under a tag it will render it for the code block,
* e.g. "Mismatched Text" under <p>
*
* ```
* <pre>
* <code>{`
* <Page>
* <div>
* <p>
* "Mismatched Text" (red)
* </p>
* </div>
* </Page>
* `}</code>
* ```
*
*/
export function PseudoHtmlDiff({
firstContent,
secondContent,
hydrationMismatchType,
reactOutputComponentDiff,
...props
}: {
firstContent: string
secondContent: string
reactOutputComponentDiff: string
hydrationMismatchType: 'tag' | 'text' | 'text-in-tag'
} & React.HTMLAttributes<HTMLPreElement>) {
const [isDiffCollapsed, toggleCollapseHtml] = useState(true)
const htmlComponents = useMemo(() => {
const componentStacks: React.ReactNode[] = []
const reactComponentDiffLines = reactOutputComponentDiff!.split('\n')
reactComponentDiffLines.forEach((line, index) => {
const isDiffLine = line[0] === '+' || line[0] === '-'
const isHighlightedLine = line[0] === '>'
const hasSign = isDiffLine || isHighlightedLine
const sign = hasSign ? line[0] : ''
const signIndex = hasSign ? line.indexOf(sign) : -1
const [prefix, suffix] = hasSign
? [line.slice(0, signIndex), line.slice(signIndex + 1)]
: [line, '']
if (isDiffLine) {
componentStacks.push(
<span
key={'comp-diff' + index}
data-nextjs-container-errors-pseudo-html-line
data-nextjs-container-errors-pseudo-html--diff={
sign === '+' ? 'add' : 'remove'
}
>
<span>
{/* Slice 2 spaces for the icon */}
{prefix}
<span data-nextjs-container-errors-pseudo-html-line-sign>
{sign}
</span>
{suffix}
{'\n'}
</span>
</span>
)
} else {
// In general, if it's not collapsed, show the whole diff
componentStacks.push(
<span
data-nextjs-container-errors-pseudo-html-line
key={'comp-diff' + index}
{...(isHighlightedLine
? {
'data-nextjs-container-errors-pseudo-html--diff': 'error',
}
: undefined)}
>
{prefix}
<span data-nextjs-container-errors-pseudo-html-line-sign>
{sign}
</span>
{suffix}
{'\n'}
</span>
)
}
})
return componentStacks
}, [reactOutputComponentDiff])
return (
<div
data-nextjs-container-errors-pseudo-html
data-nextjs-container-errors-pseudo-html-collapse={isDiffCollapsed}
>
<button
tabIndex={10} // match CallStackFrame
data-nextjs-container-errors-pseudo-html-collapse-button
onClick={() => toggleCollapseHtml(!isDiffCollapsed)}
>
<CollapseIcon collapsed={isDiffCollapsed} />
</button>
<pre {...props}>
<code>{htmlComponents}</code>
</pre>
</div>
)
}
import { cx } from './cx'
describe('cx', () => {
it('should return an empty string for no arguments', () => {
expect(cx()).toBe('')
})
it('should join multiple string arguments with spaces', () => {
expect(cx('foo', 'bar', 'baz')).toBe('foo bar baz')
})
it('should filter out falsy values', () => {
expect(cx('foo', null, 'bar', undefined, 'baz', false)).toBe('foo bar baz')
})
it('should handle single string argument', () => {
expect(cx('foo')).toBe('foo')
})
it('should not add extra spaces when falsy values are between strings', () => {
expect(cx('foo', null, 'bar')).toBe('foo bar')
})
it('should handle all falsy values', () => {
expect(cx(null, undefined, false)).toBe('')
})
})
/**
* Merge multiple args to a single string with spaces. Useful for merging class names.
* @example
* cx('foo', 'bar') // 'foo bar'
* cx('foo', null, 'bar', undefined, 'baz', false) // 'foo bar baz'
*/
export function cx(...args: (string | undefined | null | false)[]): string {
return args.filter(Boolean).join(' ')
}
const NOOP = (fn: () => void) => fn()
/**
* Returns a transition function that can be used to wrap router actions.
* This allows us to tap into the transition state of the router as an
* approximation of React render time.
*/
export const useSyncDevRenderIndicator = () => {
let syncDevRenderIndicator = NOOP
if (process.env.NODE_ENV === 'development') {
const { useSyncDevRenderIndicatorInternal } =
require('./use-sync-dev-render-indicator-internal') as typeof import('./use-sync-dev-render-indicator-internal')
// eslint-disable-next-line react-hooks/rules-of-hooks
syncDevRenderIndicator = useSyncDevRenderIndicatorInternal()
}
return syncDevRenderIndicator
}
/**
MIT License
Copyright (c) 2015-present, Facebook, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import stripAnsi from 'next/dist/compiled/strip-ansi'
// This file is based on https://github.com/facebook/create-react-app/blob/7b1a32be6ec9f99a6c9a3c66813f3ac09c4736b9/packages/react-dev-utils/formatWebpackMessages.js
// It's been edited to remove chalk and CRA-specific logic
const friendlySyntaxErrorLabel = 'Syntax error:'
const WEBPACK_BREAKING_CHANGE_POLYFILLS =
'\n\nBREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.'
function isLikelyASyntaxError(message: string) {
return stripAnsi(message).includes(friendlySyntaxErrorLabel)
}
let hadMissingSassError = false
// Cleans up webpack error messages.
function formatMessage(
message: any,
verbose?: boolean,
importTraceNote?: boolean
) {
// TODO: Replace this once webpack 5 is stable
if (typeof message === 'object' && message.message) {
const filteredModuleTrace =
message.moduleTrace &&
message.moduleTrace.filter(
(trace: any) =>
!/next-(middleware|client-pages|route|edge-function)-loader\.js/.test(
trace.originName
)
)
let body = message.message
const breakingChangeIndex = body.indexOf(WEBPACK_BREAKING_CHANGE_POLYFILLS)
if (breakingChangeIndex >= 0) {
body = body.slice(0, breakingChangeIndex)
}
message =
(message.moduleName ? stripAnsi(message.moduleName) + '\n' : '') +
(message.file ? stripAnsi(message.file) + '\n' : '') +
body +
(message.details && verbose ? '\n' + message.details : '') +
(filteredModuleTrace && filteredModuleTrace.length
? (importTraceNote || '\n\nImport trace for requested module:') +
filteredModuleTrace
.map((trace: any) => `\n${trace.moduleName}`)
.join('')
: '') +
(message.stack && verbose ? '\n' + message.stack : '')
}
let lines = message.split('\n')
// Strip Webpack-added headers off errors/warnings
// https://github.com/webpack/webpack/blob/master/lib/ModuleError.js
lines = lines.filter((line: string) => !/Module [A-z ]+\(from/.test(line))
// Transform parsing error into syntax error
// TODO: move this to our ESLint formatter?
lines = lines.map((line: string) => {
const parsingError = /Line (\d+):(?:(\d+):)?\s*Parsing error: (.+)$/.exec(
line
)
if (!parsingError) {
return line
}
const [, errorLine, errorColumn, errorMessage] = parsingError
return `${friendlySyntaxErrorLabel} ${errorMessage} (${errorLine}:${errorColumn})`
})
message = lines.join('\n')
// Smoosh syntax errors (commonly found in CSS)
message = message.replace(
/SyntaxError\s+\((\d+):(\d+)\)\s*(.+?)\n/g,
`${friendlySyntaxErrorLabel} $3 ($1:$2)\n`
)
// Clean up export errors
message = message.replace(
/^.*export '(.+?)' was not found in '(.+?)'.*$/gm,
`Attempted import error: '$1' is not exported from '$2'.`
)
message = message.replace(
/^.*export 'default' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm,
`Attempted import error: '$2' does not contain a default export (imported as '$1').`
)
message = message.replace(
/^.*export '(.+?)' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm,
`Attempted import error: '$1' is not exported from '$3' (imported as '$2').`
)
lines = message.split('\n')
// Remove leading newline
if (lines.length > 2 && lines[1].trim() === '') {
lines.splice(1, 1)
}
// Cleans up verbose "module not found" messages for files and packages.
if (lines[1] && lines[1].startsWith('Module not found: ')) {
lines = [
lines[0],
lines[1]
.replace('Error: ', '')
.replace('Module not found: Cannot find file:', 'Cannot find file:'),
...lines.slice(2),
]
}
// Add helpful message for users trying to use Sass for the first time
if (lines[1] && lines[1].match(/Cannot find module.+sass/)) {
// ./file.module.scss (<<loader info>>) => ./file.module.scss
const firstLine = lines[0].split('!')
lines[0] = firstLine[firstLine.length - 1]
lines[1] =
"To use Next.js' built-in Sass support, you first need to install `sass`.\n"
lines[1] += 'Run `npm i sass` or `yarn add sass` inside your workspace.\n'
lines[1] += '\nLearn more: https://nextjs.org/docs/messages/install-sass'
// dispose of unhelpful stack trace
lines = lines.slice(0, 2)
hadMissingSassError = true
} else if (
hadMissingSassError &&
message.match(/(sass-loader|resolve-url-loader: CSS error)/)
) {
// dispose of unhelpful stack trace following missing sass module
lines = []
}
if (!verbose) {
message = lines.join('\n')
// Internal stacks are generally useless so we strip them... with the
// exception of stacks containing `webpack:` because they're normally
// from user code generated by Webpack. For more information see
// https://github.com/facebook/create-react-app/pull/1050
message = message.replace(
/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm,
''
) // at ... ...:x:y
message = message.replace(/^\s*at\s<anonymous>(\n|$)/gm, '') // at <anonymous>
message = message.replace(
/File was processed with these loaders:\n(.+[\\/](next[\\/]dist[\\/].+|@next[\\/]react-refresh-utils[\\/]loader)\.js\n)*You may need an additional loader to handle the result of these loaders.\n/g,
''
)
lines = message.split('\n')
}
// Remove duplicated newlines
lines = (lines as string[]).filter(
(line, index, arr) =>
index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim()
)
// Reassemble the message
message = lines.join('\n')
return message.trim()
}
export default function formatWebpackMessages(json: any, verbose?: boolean) {
const formattedErrors = json.errors.map((message: any) => {
const isUnknownNextFontError = message.message.includes(
'An error occurred in `next/font`.'
)
return formatMessage(message, isUnknownNextFontError || verbose)
})
const formattedWarnings = json.warnings.map((message: any) => {
return formatMessage(message, verbose)
})
// Reorder errors to put the most relevant ones first.
let reactServerComponentsError = -1
for (let i = 0; i < formattedErrors.length; i++) {
const error = formattedErrors[i]
if (error.includes('ReactServerComponentsError')) {
reactServerComponentsError = i
break
}
}
// Move the reactServerComponentsError to the top if it exists
if (reactServerComponentsError !== -1) {
const error = formattedErrors.splice(reactServerComponentsError, 1)
formattedErrors.unshift(error[0])
}
const result = {
...json,
errors: formattedErrors,
warnings: formattedWarnings,
}
if (!verbose && result.errors.some(isLikelyASyntaxError)) {
// If there are any syntax errors, show just them.
result.errors = result.errors.filter(isLikelyASyntaxError)
result.warnings = []
}
return result
}
import { ACTION_UNHANDLED_ERROR, ACTION_UNHANDLED_REJECTION } from '../shared'
import type { SupportedErrorEvent } from '../_internal/container/runtime-error/render-error'
import { getOriginalStackFrames } from './stack-frame'
import type { OriginalStackFrame } from './stack-frame'
import type { ComponentStackFrame } from './parse-component-stack'
import { getErrorSource } from '../../../../shared/lib/error-source'
import React from 'react'
export type ReadyRuntimeError = {
id: number
runtime: true
error: Error & { environmentName?: string }
frames: OriginalStackFrame[] | (() => Promise<OriginalStackFrame[]>)
componentStackFrames?: ComponentStackFrame[]
}
export const useFrames = (error: ReadyRuntimeError): OriginalStackFrame[] => {
if ('use' in React) {
const frames = error.frames
if (typeof frames !== 'function') {
throw new Error(
'Invariant: frames must be a function when the React version has React.use. This is a bug in Next.js.'
)
}
return React.use((frames as () => Promise<OriginalStackFrame[]>)())
} else {
if (!Array.isArray(error.frames)) {
throw new Error(
'Invariant: frames must be an array when the React version does not have React.use. This is a bug in Next.js.'
)
}
return error.frames
}
}
export async function getErrorByType(
ev: SupportedErrorEvent,
isAppDir: boolean
): Promise<ReadyRuntimeError> {
const { id, event } = ev
switch (event.type) {
case ACTION_UNHANDLED_ERROR:
case ACTION_UNHANDLED_REJECTION: {
const baseError = {
id,
runtime: true,
error: event.reason,
} as const
if ('use' in React) {
const readyRuntimeError: ReadyRuntimeError = {
...baseError,
// createMemoizedPromise dedups calls to getOriginalStackFrames
frames: createMemoizedPromise(async () => {
return await getOriginalStackFrames(
event.frames,
getErrorSource(event.reason),
isAppDir
)
}),
}
if (event.type === ACTION_UNHANDLED_ERROR) {
readyRuntimeError.componentStackFrames = event.componentStackFrames
}
return readyRuntimeError
} else {
const readyRuntimeError: ReadyRuntimeError = {
...baseError,
// createMemoizedPromise dedups calls to getOriginalStackFrames
frames: await getOriginalStackFrames(
event.frames,
getErrorSource(event.reason),
isAppDir
),
}
if (event.type === ACTION_UNHANDLED_ERROR) {
readyRuntimeError.componentStackFrames = event.componentStackFrames
}
return readyRuntimeError
}
}
default: {
break
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _: never = event
throw new Error('type system invariant violation')
}
function createMemoizedPromise<T>(
promiseFactory: () => Promise<T>
): () => Promise<T> {
const cachedPromise = promiseFactory()
return function (): Promise<T> {
return cachedPromise
}
}
import { normalizedAssetPrefix } from '../../../../shared/lib/normalized-asset-prefix'
function getSocketProtocol(assetPrefix: string): string {
let protocol = window.location.protocol
try {
// assetPrefix is a url
protocol = new URL(assetPrefix).protocol
} catch {}
return protocol === 'http:' ? 'ws:' : 'wss:'
}
export function getSocketUrl(assetPrefix: string | undefined): string {
const prefix = normalizedAssetPrefix(assetPrefix)
const protocol = getSocketProtocol(assetPrefix || '')
if (URL.canParse(prefix)) {
// since normalized asset prefix is ensured to be a URL format,
// we can safely replace the protocol
return prefix.replace(/^http/, 'ws')
}
const { hostname, port } = window.location
return `${protocol}//${hostname}${port ? `:${port}` : ''}${prefix}`
}
import fs from 'fs/promises'
import path from 'path'
import url from 'url'
import type { RawSourceMap } from 'next/dist/compiled/source-map08'
import dataUriToBuffer from 'next/dist/compiled/data-uri-to-buffer'
import { getSourceMapUrl } from './get-source-map-url'
export async function getSourceMapFromFile(
filename: string
): Promise<RawSourceMap | undefined> {
filename = filename.startsWith('file://')
? url.fileURLToPath(filename)
: filename
let fileContents: string
try {
fileContents = await fs.readFile(filename, 'utf-8')
} catch (error) {
throw new Error(`Failed to read file contents of ${filename}.`, {
cause: error,
})
}
const sourceUrl = getSourceMapUrl(fileContents)
if (!sourceUrl) {
return undefined
}
if (sourceUrl.startsWith('data:')) {
let buffer: dataUriToBuffer.MimeBuffer
try {
buffer = dataUriToBuffer(sourceUrl)
} catch (error) {
throw new Error(`Failed to parse source map URL for ${filename}.`, {
cause: error,
})
}
if (buffer.type !== 'application/json') {
throw new Error(
`Unknown source map type for ${filename}: ${buffer.typeFull}.`
)
}
try {
return JSON.parse(buffer.toString())
} catch (error) {
throw new Error(`Failed to parse source map for ${filename}.`, {
cause: error,
})
}
}
const sourceMapFilename = path.resolve(
path.dirname(filename),
decodeURIComponent(sourceUrl)
)
try {
const sourceMapContents = await fs.readFile(sourceMapFilename, 'utf-8')
return JSON.parse(sourceMapContents.toString())
} catch (error) {
throw new Error(`Failed to parse source map ${sourceMapFilename}.`, {
cause: error,
})
}
}
export function getSourceMapUrl(fileContents: string): string | null {
const regex = /\/\/[#@] ?sourceMappingURL=([^\s'"]+)\s*$/gm
let match = null
for (;;) {
let next = regex.exec(fileContents)
if (next == null) {
break
}
match = next
}
if (!(match && match[1])) {
return null
}
return match[1].toString()
}
import type * as React from 'react'
/**
* A function that merges React refs into one.
* Supports both functions and ref objects created using createRef() and useRef().
*
* Usage:
* ```tsx
* <div ref={mergeRefs(ref1, ref2, ref3)} />
* ```
*
* @param {(React.Ref<T> | undefined)[]} inputRefs Array of refs
* @returns {React.Ref<T> | React.RefCallback<T>} Merged refs
*/
export default function mergeRefs<T>(
...inputRefs: (React.Ref<T> | undefined)[]
): React.Ref<T> | React.RefCallback<T> {
const filteredInputRefs = inputRefs.filter(Boolean)
if (filteredInputRefs.length <= 1) {
const firstRef = filteredInputRefs[0]
return firstRef || null
}
return function mergedRefs(ref) {
for (const inputRef of filteredInputRefs) {
if (typeof inputRef === 'function') {
inputRef(ref)
} else if (inputRef) {
;(inputRef as React.MutableRefObject<T | null>).current = ref
}
}
}
}
import { parse } from 'next/dist/compiled/stacktrace-parser'
import type { StackFrame } from 'next/dist/compiled/stacktrace-parser'
import {
decorateServerError,
type ErrorSourceType,
} from '../../../../shared/lib/error-source'
export function getFilesystemFrame(frame: StackFrame): StackFrame {
const f: StackFrame = { ...frame }
if (typeof f.file === 'string') {
if (
// Posix:
f.file.startsWith('/') ||
// Win32:
/^[a-z]:\\/i.test(f.file) ||
// Win32 UNC:
f.file.startsWith('\\\\')
) {
f.file = `file://${f.file}`
}
}
return f
}
export function getServerError(error: Error, type: ErrorSourceType): Error {
if (error.name === 'TurbopackInternalError') {
// If this is an internal Turbopack error we shouldn't show internal details
// to the user. These are written to a log file instead.
const turbopackInternalError = new Error(
'An unexpected Turbopack error occurred. Please see the output of `next dev` for more details.'
)
decorateServerError(turbopackInternalError, type)
return turbopackInternalError
}
let n: Error
try {
throw new Error(error.message)
} catch (e) {
n = e as Error
}
n.name = error.name
try {
n.stack = `${n.toString()}\n${parse(error.stack!)
.map(getFilesystemFrame)
.map((f) => {
let str = ` at ${f.methodName}`
if (f.file) {
let loc = f.file
if (f.lineNumber) {
loc += `:${f.lineNumber}`
if (f.column) {
loc += `:${f.column}`
}
}
str += ` (${loc})`
}
return str
})
.join('\n')}`
} catch {
n.stack = error.stack
}
decorateServerError(n, type)
return n
}
export function noop(
strings: TemplateStringsArray,
...keys: readonly string[]
) {
const lastIndex = strings.length - 1
return (
strings.slice(0, lastIndex).reduce((p, s, i) => p + s + keys[i], '') +
strings[lastIndex]
)
}
export type ComponentStackFrame = {
canOpenInEditor: boolean
component: string
file?: string
lineNumber?: number
column?: number
}
enum LocationType {
FILE = 'file',
WEBPACK_INTERNAL = 'webpack-internal',
HTTP = 'http',
PROTOCOL_RELATIVE = 'protocol-relative',
UNKNOWN = 'unknown',
}
/**
* Get the type of frame line based on the location
*/
function getLocationType(location: string): LocationType {
if (location.startsWith('file://')) {
return LocationType.FILE
}
if (location.includes('webpack-internal://')) {
return LocationType.WEBPACK_INTERNAL
}
if (location.startsWith('http://') || location.startsWith('https://')) {
return LocationType.HTTP
}
if (location.startsWith('//')) {
return LocationType.PROTOCOL_RELATIVE
}
return LocationType.UNKNOWN
}
function parseStackFrameLocation(
location: string
): Omit<ComponentStackFrame, 'component'> {
const locationType = getLocationType(location)
const modulePath = location?.replace(
/^(webpack-internal:\/\/\/|file:\/\/)(\(.*\)\/)?/,
''
)
const [, file, lineNumber, column] =
modulePath?.match(/^(.+):(\d+):(\d+)/) ?? []
switch (locationType) {
case LocationType.FILE:
case LocationType.WEBPACK_INTERNAL:
return {
canOpenInEditor: true,
file,
lineNumber: lineNumber ? Number(lineNumber) : undefined,
column: column ? Number(column) : undefined,
}
// When the location is a URL we only show the file
// TODO: Resolve http(s) URLs through sourcemaps
case LocationType.HTTP:
case LocationType.PROTOCOL_RELATIVE:
case LocationType.UNKNOWN:
default: {
return {
canOpenInEditor: false,
}
}
}
}
export function parseComponentStack(
componentStack: string
): ComponentStackFrame[] {
const componentStackFrames: ComponentStackFrame[] = []
for (const line of componentStack.trim().split('\n')) {
// TODO: support safari stack trace
// Get component and file from the component stack line
const match = /at ([^ ]+)( \((.*)\))?/.exec(line)
if (match?.[1]) {
const component = match[1]
const location = match[3]
if (!location) {
componentStackFrames.push({
canOpenInEditor: false,
component,
})
continue
}
// Stop parsing the component stack if we reach a Next.js component
if (location?.includes('next/dist')) {
break
}
const frameLocation = parseStackFrameLocation(location)
componentStackFrames.push({
component,
...frameLocation,
})
}
}
return componentStackFrames
}
import { parse } from 'next/dist/compiled/stacktrace-parser'
import type { StackFrame } from 'next/dist/compiled/stacktrace-parser'
import {
getHydrationErrorStackInfo,
isReactHydrationErrorMessage,
} from '../../is-hydration-error'
const regexNextStatic = /\/_next(\/static\/.+)/
export function parseStack(stack: string | undefined): StackFrame[] {
if (!stack) return []
const messageAndStack = stack.replace(/^Error: /, '')
if (isReactHydrationErrorMessage(messageAndStack)) {
const { stack: parsedStack } = getHydrationErrorStackInfo(messageAndStack)
if (parsedStack) {
stack = parsedStack
}
}
// throw away eval information that stacktrace-parser doesn't support
// adapted from https://github.com/stacktracejs/error-stack-parser/blob/9f33c224b5d7b607755eb277f9d51fcdb7287e24/error-stack-parser.js#L59C33-L59C62
stack = stack
.split('\n')
.map((line) => {
if (line.includes('(eval ')) {
line = line
.replace(/eval code/g, 'eval')
.replace(/\(eval at [^()]* \(/, '(file://')
.replace(/\),.*$/g, ')')
}
return line
})
.join('\n')
const frames = parse(stack)
return frames.map((frame) => {
try {
const url = new URL(frame.file!)
const res = regexNextStatic.exec(url.pathname)
if (res) {
const distDir = process.env.__NEXT_DIST_DIR
?.replace(/\\/g, '/')
?.replace(/\/$/, '')
if (distDir) {
frame.file = 'file://' + distDir.concat(res.pop()!) + url.search
}
}
} catch {}
return frame
})
}
import { parseUrlFromText } from './parse-url-from-text'
describe('parseUrlFromText', () => {
it('should extract a URL from text', () => {
const text = 'Check out https://nextjs.org for more info'
expect(parseUrlFromText(text)).toEqual(['https://nextjs.org'])
})
it('should extract multiple URLs from text', () => {
const text = 'Visit https://react.dev and https://vercel.com'
expect(parseUrlFromText(text)).toEqual([
'https://react.dev',
'https://vercel.com',
])
})
it('should handle URLs with paths and query parameters', () => {
const text =
'Link: https://nextjs.org/docs/getting-started?query=123#fragment'
expect(parseUrlFromText(text)).toEqual([
'https://nextjs.org/docs/getting-started?query=123#fragment',
])
})
it('should return empty array when no URLs are found', () => {
const text = 'This text contains no URLs'
expect(parseUrlFromText(text)).toEqual([])
})
it('should handle empty string input', () => {
expect(parseUrlFromText('')).toEqual([])
})
it('should filter URLs using matcherFunc', () => {
const text = 'Visit https://react.dev and https://vercel.com'
const matcherFunc = (url: string) => url.includes('vercel')
expect(parseUrlFromText(text, matcherFunc)).toEqual(['https://vercel.com'])
})
})
export function parseUrlFromText(
text: string,
matcherFunc?: (text: string) => boolean
): string[] {
const linkRegex = /https?:\/\/[^\s/$.?#].[^\s)'"]*/gi
const links = Array.from(text.matchAll(linkRegex), (match) => match[0])
if (matcherFunc) {
return links.filter((link) => matcherFunc(link))
}
return links
}
import type { StackFrame } from 'next/dist/compiled/stacktrace-parser'
import type {
OriginalStackFrameResponse,
OriginalStackFrameResponseResult,
OriginalStackFramesRequest,
} from '../server/shared'
import {
isWebpackInternalResource,
formatFrameSourceFile,
} from './webpack-module-path'
export interface OriginalStackFrame extends OriginalStackFrameResponse {
error: boolean
reason: string | null
external: boolean
ignored: boolean
sourceStackFrame: StackFrame
}
function getOriginalStackFrame(
source: StackFrame,
response: OriginalStackFrameResponseResult
): Promise<OriginalStackFrame> {
async function _getOriginalStackFrame(): Promise<OriginalStackFrame> {
if (response.status === 'rejected') {
return Promise.reject(new Error(response.reason))
}
const body: OriginalStackFrameResponse = response.value
return {
error: false,
reason: null,
external: false,
sourceStackFrame: source,
originalStackFrame: body.originalStackFrame,
originalCodeFrame: body.originalCodeFrame || null,
sourcePackage: body.sourcePackage,
ignored: body.originalStackFrame?.ignored || false,
}
}
// TODO: merge this section into ignoredList handling
if (source.file === 'file://' || source.file?.match(/https?:\/\//)) {
return Promise.resolve({
error: false,
reason: null,
external: true,
sourceStackFrame: source,
originalStackFrame: null,
originalCodeFrame: null,
sourcePackage: null,
ignored: true,
})
}
return _getOriginalStackFrame().catch((err: Error) => ({
error: true,
reason: err?.message ?? err?.toString() ?? 'Unknown Error',
external: false,
sourceStackFrame: source,
originalStackFrame: null,
originalCodeFrame: null,
sourcePackage: null,
ignored: false,
}))
}
export async function getOriginalStackFrames(
frames: StackFrame[],
type: 'server' | 'edge-server' | null,
isAppDir: boolean
): Promise<OriginalStackFrame[]> {
const req: OriginalStackFramesRequest = {
frames,
isServer: type === 'server',
isEdgeServer: type === 'edge-server',
isAppDirectory: isAppDir,
}
let res: Response | undefined = undefined
let reason: string | undefined = undefined
try {
res = await fetch('/__nextjs_original-stack-frames', {
method: 'POST',
body: JSON.stringify(req),
})
} catch (e) {
reason = e + ''
}
// When fails to fetch the original stack frames, we reject here to be
// caught at `_getOriginalStackFrame()` and return the stack frames so
// that the error overlay can render.
if (res && res.ok && res.status !== 204) {
const data = await res.json()
return Promise.all(
frames.map((frame, index) => getOriginalStackFrame(frame, data[index]))
)
} else {
if (res) {
reason = await res.text()
}
}
return Promise.all(
frames.map((frame) =>
getOriginalStackFrame(frame, {
status: 'rejected',
reason: `Failed to fetch the original stack frames ${reason ? `: ${reason}` : ''}`,
})
)
)
}
export function getFrameSource(frame: StackFrame): string {
if (!frame.file) return ''
const isWebpackFrame = isWebpackInternalResource(frame.file)
let str = ''
// Skip URL parsing for webpack internal file paths.
if (isWebpackFrame) {
str = formatFrameSourceFile(frame.file)
} else {
try {
const u = new URL(frame.file)
let parsedPath = ''
// Strip the origin for same-origin scripts.
if (globalThis.location?.origin !== u.origin) {
// URLs can be valid without an `origin`, so long as they have a
// `protocol`. However, `origin` is preferred.
if (u.origin === 'null') {
parsedPath += u.protocol
} else {
parsedPath += u.origin
}
}
// Strip query string information as it's typically too verbose to be
// meaningful.
parsedPath += u.pathname
str = formatFrameSourceFile(parsedPath)
} catch {
str = formatFrameSourceFile(frame.file)
}
}
if (!isWebpackInternalResource(frame.file) && frame.lineNumber != null) {
if (str) {
if (frame.column != null) {
str += ` (${frame.lineNumber}:${frame.column})`
} else {
str += ` (${frame.lineNumber})`
}
}
}
return str
}
import { useCallback } from 'react'
export function useOpenInEditor({
file,
lineNumber,
column,
}: {
file?: string | null
lineNumber?: number | null
column?: number | null
} = {}) {
const openInEditor = useCallback(() => {
if (file == null || lineNumber == null || column == null) return
const params = new URLSearchParams()
params.append('file', file)
params.append('lineNumber', String(lineNumber))
params.append('column', String(column))
self
.fetch(
`${
process.env.__NEXT_ROUTER_BASEPATH || ''
}/__nextjs_launch-editor?${params.toString()}`
)
.then(
() => {},
(cause) => {
console.error(
`Failed to open file "${file} (${lineNumber}:${column})" in your editor. Cause:`,
cause
)
}
)
}, [file, lineNumber, column])
return openInEditor
}
import { useCallback, useContext, useEffect, useRef } from 'react'
import { GlobalLayoutRouterContext } from '../../../../shared/lib/app-router-context.shared-runtime'
import { getSocketUrl } from './get-socket-url'
import type { TurbopackMsgToBrowser } from '../../../../server/dev/hot-reloader-types'
export function useWebsocket(assetPrefix: string) {
const webSocketRef = useRef<WebSocket>(undefined)
useEffect(() => {
if (webSocketRef.current) {
return
}
const url = getSocketUrl(assetPrefix)
webSocketRef.current = new window.WebSocket(`${url}/_next/webpack-hmr`)
}, [assetPrefix])
return webSocketRef
}
export function useSendMessage(webSocketRef: ReturnType<typeof useWebsocket>) {
const sendMessage = useCallback(
(data: string) => {
const socket = webSocketRef.current
if (!socket || socket.readyState !== socket.OPEN) {
return
}
return socket.send(data)
},
[webSocketRef]
)
return sendMessage
}
export function useTurbopack(
sendMessage: ReturnType<typeof useSendMessage>,
onUpdateError: (err: unknown) => void
) {
const turbopackState = useRef<{
init: boolean
queue: Array<TurbopackMsgToBrowser> | undefined
callback: ((msg: TurbopackMsgToBrowser) => void) | undefined
}>({
init: false,
// Until the dynamic import resolves, queue any turbopack messages which will be replayed.
queue: [],
callback: undefined,
})
const processTurbopackMessage = useCallback((msg: TurbopackMsgToBrowser) => {
const { callback, queue } = turbopackState.current
if (callback) {
callback(msg)
} else {
queue!.push(msg)
}
}, [])
useEffect(() => {
const { current: initCurrent } = turbopackState
// TODO(WEB-1589): only install if `process.turbopack` set.
if (initCurrent.init) {
return
}
initCurrent.init = true
import(
// @ts-expect-error requires "moduleResolution": "node16" in tsconfig.json and not .ts extension
'@vercel/turbopack-ecmascript-runtime/browser/dev/hmr-client/hmr-client.ts'
).then(({ connect }) => {
const { current } = turbopackState
connect({
addMessageListener(cb: (msg: TurbopackMsgToBrowser) => void) {
current.callback = cb
// Replay all Turbopack messages before we were able to establish the HMR client.
for (const msg of current.queue!) {
cb(msg)
}
current.queue = undefined
},
sendMessage,
onUpdateError,
})
})
}, [sendMessage, onUpdateError])
return processTurbopackMessage
}
export function useWebsocketPing(
websocketRef: ReturnType<typeof useWebsocket>
) {
const sendMessage = useSendMessage(websocketRef)
const { tree } = useContext(GlobalLayoutRouterContext)
useEffect(() => {
// Never send pings when using Turbopack as it's not used.
// Pings were originally used to keep track of active routes in on-demand-entries with webpack.
if (process.env.TURBOPACK) {
return
}
// Taken from on-demand-entries-client.js
const interval = setInterval(() => {
sendMessage(
JSON.stringify({
event: 'ping',
tree,
appDirRoute: true,
})
)
}, 2500)
return () => clearInterval(interval)
}, [tree, sendMessage])
}
import {
formatFrameSourceFile,
isWebpackInternalResource,
} from './webpack-module-path'
describe('webpack-module-path', () => {
describe('isWebpackInternalResource', () => {
it('should return true for webpack-internal paths', () => {
expect(
isWebpackInternalResource('webpack-internal:///./src/hello.tsx')
).toBe(true)
expect(isWebpackInternalResource('webpack://_N_E/./src/hello.tsx')).toBe(
true
)
expect(isWebpackInternalResource('webpack://./src/hello.tsx')).toBe(true)
expect(isWebpackInternalResource('webpack:///./src/hello.tsx')).toBe(true)
})
it('should return false for non-webpack-internal paths', () => {
expect(isWebpackInternalResource('<anonymous>')).toBe(false)
expect(isWebpackInternalResource('file:///src/hello.tsx')).toBe(false)
})
})
describe('formatFrameSourceFile', () => {
it('should return the original file path', () => {
expect(formatFrameSourceFile('webpack-internal:///./src/hello.tsx')).toBe(
'./src/hello.tsx'
)
expect(formatFrameSourceFile('webpack://_N_E/./src/hello.tsx')).toBe(
'./src/hello.tsx'
)
expect(formatFrameSourceFile('webpack://./src/hello.tsx')).toBe(
'./src/hello.tsx'
)
expect(formatFrameSourceFile('webpack:///./src/hello.tsx')).toBe(
'./src/hello.tsx'
)
})
})
})
const replacementRegExes = [
/^webpack-internal:\/\/\/(\([\w-]+\)\/)?/,
/^(webpack:\/\/\/|webpack:\/\/(_N_E\/)?)(\([\w-]+\)\/)?/,
]
export function isWebpackInternalResource(file: string) {
for (const regex of replacementRegExes) {
if (regex.test(file)) return true
file = file.replace(regex, '')
}
return false
}
/**
* Format the webpack internal id to original file path
*
* webpack-internal:///./src/hello.tsx => ./src/hello.tsx
* webpack://_N_E/./src/hello.tsx => ./src/hello.tsx
* webpack://./src/hello.tsx => ./src/hello.tsx
* webpack:///./src/hello.tsx => ./src/hello.tsx
*/
export function formatFrameSourceFile(file: string) {
for (const regex of replacementRegExes) {
file = file.replace(regex, '')
}
return file
}
......@@ -7,7 +7,7 @@ import type {
ReducerActions,
ReducerState,
} from './router-reducer/router-reducer-types'
import { useSyncDevRenderIndicator } from './react-dev-overlay/utils/use-sync-dev-render-indicator'
import { useSyncDevRenderIndicator } from './react-dev-overlay/utils/dev-indicator/use-sync-dev-render-indicator'
export function useUnwrapState(state: ReducerState): AppRouterState {
// reducer actions can be async, so sometimes we need to suspend until the state is resolved
......
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