Unverified Commit dcb69ee9 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Strictly type `react-dev-overlay` (#15669)

Fixes #15668
parent 3caa9960
...@@ -15,7 +15,7 @@ function onUnhandledError(ev: ErrorEvent) { ...@@ -15,7 +15,7 @@ function onUnhandledError(ev: ErrorEvent) {
Bus.emit({ Bus.emit({
type: Bus.TYPE_UNHANDLED_ERROR, type: Bus.TYPE_UNHANDLED_ERROR,
reason: error, reason: error,
frames: parseStack(e.stack), frames: parseStack(e.stack!),
}) })
} }
...@@ -34,7 +34,7 @@ function onUnhandledRejection(ev: PromiseRejectionEvent) { ...@@ -34,7 +34,7 @@ function onUnhandledRejection(ev: PromiseRejectionEvent) {
Bus.emit({ Bus.emit({
type: Bus.TYPE_UNHANDLED_REJECTION, type: Bus.TYPE_UNHANDLED_REJECTION,
reason: reason, reason: reason,
frames: parseStack(e.stack), frames: parseStack(e.stack!),
}) })
} }
......
...@@ -41,7 +41,9 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState { ...@@ -41,7 +41,9 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
} }
} }
function ReactDevOverlay({ children }) { const ReactDevOverlay: React.FunctionComponent = function ReactDevOverlay({
children,
}) {
const [state, dispatch] = React.useReducer< const [state, dispatch] = React.useReducer<
React.Reducer<OverlayState, Bus.BusEvent> React.Reducer<OverlayState, Bus.BusEvent>
>(reducer, { nextId: 1, buildError: null, errors: [] }) >(reducer, { nextId: 1, buildError: null, errors: [] })
...@@ -76,7 +78,7 @@ function ReactDevOverlay({ children }) { ...@@ -76,7 +78,7 @@ function ReactDevOverlay({ children }) {
<ComponentStyles /> <ComponentStyles />
{hasBuildError ? ( {hasBuildError ? (
<BuildError message={state.buildError} /> <BuildError message={state.buildError!} />
) : hasRuntimeErrors ? ( ) : hasRuntimeErrors ? (
<Errors errors={state.errors} /> <Errors errors={state.errors} />
) : undefined} ) : undefined}
......
...@@ -45,7 +45,7 @@ function drain() { ...@@ -45,7 +45,7 @@ function drain() {
// event(s) // event(s)
Boolean(handlers.size) Boolean(handlers.size)
) { ) {
const ev = queue.shift() const ev = queue.shift()!
handlers.forEach((handler) => handler(ev)) handlers.forEach((handler) => handler(ev))
} }
}, 1) }, 1)
......
...@@ -16,7 +16,7 @@ export const CodeFrame: React.FC<CodeFrameProps> = function CodeFrame({ ...@@ -16,7 +16,7 @@ export const CodeFrame: React.FC<CodeFrameProps> = function CodeFrame({
const prefixLength = lines const prefixLength = lines
.map((line) => /^>? +\d+ +\| ( *)/.exec(stripAnsi(line))) .map((line) => /^>? +\d+ +\| ( *)/.exec(stripAnsi(line)))
.filter(Boolean) .filter(Boolean)
.map((v) => v.pop()) .map((v) => v!.pop()!)
.reduce((c, n) => (isNaN(c) ? n.length : Math.min(c, n.length)), NaN) .reduce((c, n) => (isNaN(c) ? n.length : Math.min(c, n.length)), NaN)
if (prefixLength > 1) { if (prefixLength > 1) {
...@@ -43,7 +43,7 @@ export const CodeFrame: React.FC<CodeFrameProps> = function CodeFrame({ ...@@ -43,7 +43,7 @@ export const CodeFrame: React.FC<CodeFrameProps> = function CodeFrame({
const open = React.useCallback(() => { const open = React.useCallback(() => {
const params = new URLSearchParams() const params = new URLSearchParams()
for (const key in stackFrame) { for (const key in stackFrame) {
params.append(key, (stackFrame[key] ?? '').toString()) params.append(key, ((stackFrame as any)[key] ?? '').toString())
} }
self self
......
...@@ -14,7 +14,7 @@ const Dialog: React.FC<DialogProps> = function Dialog({ ...@@ -14,7 +14,7 @@ const Dialog: React.FC<DialogProps> = function Dialog({
onClose, onClose,
...props ...props
}) { }) {
const [dialog, setDialog] = React.useState<HTMLDivElement>(null) const [dialog, setDialog] = React.useState<HTMLDivElement | null>(null)
const onDialog = React.useCallback((node) => { const onDialog = React.useCallback((node) => {
setDialog(node) setDialog(node)
}, []) }, [])
...@@ -47,8 +47,9 @@ const Dialog: React.FC<DialogProps> = function Dialog({ ...@@ -47,8 +47,9 @@ const Dialog: React.FC<DialogProps> = function Dialog({
} }
} }
shadowRoot.addEventListener('keydown', handler) shadowRoot.addEventListener('keydown', handler as EventListener)
return () => shadowRoot.removeEventListener('keydown', handler) return () =>
shadowRoot.removeEventListener('keydown', handler as EventListener)
}, [dialog]) }, [dialog])
return ( return (
......
...@@ -14,9 +14,9 @@ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function Lef ...@@ -14,9 +14,9 @@ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function Lef
next, next,
close, close,
}) { }) {
const buttonLeft = React.useRef<HTMLButtonElement>() const buttonLeft = React.useRef<HTMLButtonElement | null>(null)
const buttonRight = React.useRef<HTMLButtonElement>() const buttonRight = React.useRef<HTMLButtonElement | null>(null)
const buttonClose = React.useRef<HTMLButtonElement>() const buttonClose = React.useRef<HTMLButtonElement | null>(null)
const [nav, setNav] = React.useState<HTMLElement | null>(null) const [nav, setNav] = React.useState<HTMLElement | null>(null)
const onNav = React.useCallback((el: HTMLElement) => { const onNav = React.useCallback((el: HTMLElement) => {
...@@ -54,16 +54,18 @@ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function Lef ...@@ -54,16 +54,18 @@ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function Lef
} }
} }
close() if (close) {
close()
}
} }
} }
root.addEventListener('keydown', handler) root.addEventListener('keydown', handler as EventListener)
if (root !== d) { if (root !== d) {
d.addEventListener('keydown', handler) d.addEventListener('keydown', handler)
} }
return function () { return function () {
root.removeEventListener('keydown', handler) root.removeEventListener('keydown', handler as EventListener)
if (root !== d) { if (root !== d) {
d.removeEventListener('keydown', handler) d.removeEventListener('keydown', handler)
} }
...@@ -83,11 +85,11 @@ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function Lef ...@@ -83,11 +85,11 @@ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function Lef
const a = root.activeElement const a = root.activeElement
if (previous == null) { if (previous == null) {
if (a === buttonLeft.current) { if (buttonLeft.current && a === buttonLeft.current) {
buttonLeft.current.blur() buttonLeft.current.blur()
} }
} else if (next == null) { } else if (next == null) {
if (a === buttonRight.current) { if (buttonRight.current && a === buttonRight.current) {
buttonRight.current.blur() buttonRight.current.blur()
} }
} }
...@@ -142,7 +144,7 @@ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function Lef ...@@ -142,7 +144,7 @@ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function Lef
&nbsp; &nbsp;
{children} {children}
</nav> </nav>
{close && ( {close ? (
<button <button
ref={buttonClose} ref={buttonClose}
type="button" type="button"
...@@ -174,7 +176,7 @@ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function Lef ...@@ -174,7 +176,7 @@ const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function Lef
</svg> </svg>
</span> </span>
</button> </button>
)} ) : null}
</div> </div>
) )
} }
......
// @ts-ignore
import allyDisable from 'ally.js/maintain/disabled' import allyDisable from 'ally.js/maintain/disabled'
// @ts-ignore
import allyTrap from 'ally.js/maintain/tab-focus' import allyTrap from 'ally.js/maintain/tab-focus'
import * as React from 'react' import * as React from 'react'
import { lock, unlock } from './body-locker' import { lock, unlock } from './body-locker'
...@@ -17,8 +19,8 @@ const Overlay: React.FC<OverlayProps> = function Overlay({ ...@@ -17,8 +19,8 @@ const Overlay: React.FC<OverlayProps> = function Overlay({
} }
}, []) }, [])
const [overlay, setOverlay] = React.useState<HTMLElement | null>(null) const [overlay, setOverlay] = React.useState<HTMLDivElement | null>(null)
const onOverlay = React.useCallback((el: HTMLElement) => { const onOverlay = React.useCallback((el: HTMLDivElement) => {
setOverlay(el) setOverlay(el)
}, []) }, [])
......
...@@ -14,7 +14,7 @@ export const ShadowPortal: React.FC<ShadowPortalProps> = function Portal({ ...@@ -14,7 +14,7 @@ export const ShadowPortal: React.FC<ShadowPortalProps> = function Portal({
let [, forceUpdate] = React.useState() let [, forceUpdate] = React.useState()
React.useLayoutEffect(() => { React.useLayoutEffect(() => {
const ownerDocument = mountNode.current.ownerDocument const ownerDocument = mountNode.current!.ownerDocument!
portalNode.current = ownerDocument.createElement('nextjs-portal') portalNode.current = ownerDocument.createElement('nextjs-portal')
shadowNode.current = portalNode.current.attachShadow({ mode: 'open' }) shadowNode.current = portalNode.current.attachShadow({ mode: 'open' })
ownerDocument.body.appendChild(portalNode.current) ownerDocument.body.appendChild(portalNode.current)
......
...@@ -209,7 +209,7 @@ export const Errors: React.FC<ErrorsProps> = function Errors({ errors }) { ...@@ -209,7 +209,7 @@ export const Errors: React.FC<ErrorsProps> = function Errors({ errors }) {
// This component shouldn't be rendered with no errors, but if it is, let's // This component shouldn't be rendered with no errors, but if it is, let's
// handle it gracefully by rendering nothing. // handle it gracefully by rendering nothing.
if (errors.length < 1) { if (errors.length < 1 || activeError == null) {
return null return null
} }
...@@ -252,14 +252,14 @@ export const Errors: React.FC<ErrorsProps> = function Errors({ errors }) { ...@@ -252,14 +252,14 @@ export const Errors: React.FC<ErrorsProps> = function Errors({ errors }) {
type="error" type="error"
aria-labelledby="nextjs__container_errors_label" aria-labelledby="nextjs__container_errors_label"
aria-describedby="nextjs__container_errors_desc" aria-describedby="nextjs__container_errors_desc"
onClose={!isServerError && minimize} onClose={isServerError ? undefined : minimize}
> >
<DialogContent> <DialogContent>
<DialogHeader className="nextjs-container-errors-header"> <DialogHeader className="nextjs-container-errors-header">
<LeftRightDialogHeader <LeftRightDialogHeader
previous={activeIdx > 0 ? previous : null} previous={activeIdx > 0 ? previous : null}
next={activeIdx < readyErrors.length - 1 ? next : null} next={activeIdx < readyErrors.length - 1 ? next : null}
close={!isServerError && minimize} close={isServerError ? undefined : minimize}
> >
<small> <small>
<span>{activeIdx + 1}</span> of{' '} <span>{activeIdx + 1}</span> of{' '}
......
...@@ -21,7 +21,7 @@ const CallStackFrame: React.FC<{ ...@@ -21,7 +21,7 @@ const CallStackFrame: React.FC<{
const params = new URLSearchParams() const params = new URLSearchParams()
for (const key in f) { for (const key in f) {
params.append(key, (f[key] ?? '').toString()) params.append(key, ((f as any)[key] ?? '').toString())
} }
self self
...@@ -134,8 +134,8 @@ const RuntimeError: React.FC<RuntimeErrorProps> = function RuntimeError({ ...@@ -134,8 +134,8 @@ const RuntimeError: React.FC<RuntimeErrorProps> = function RuntimeError({
/> />
))} ))}
<CodeFrame <CodeFrame
stackFrame={firstFrame.originalStackFrame} stackFrame={firstFrame.originalStackFrame!}
codeFrame={firstFrame.originalCodeFrame} codeFrame={firstFrame.originalCodeFrame!}
/> />
</React.Fragment> </React.Fragment>
) : undefined} ) : undefined}
......
...@@ -35,7 +35,7 @@ export function getNodeError(error: Error): Error { ...@@ -35,7 +35,7 @@ export function getNodeError(error: Error): Error {
n.name = error.name n.name = error.name
try { try {
n.stack = parse(error.stack) n.stack = parse(error.stack!)
.map(getFilesystemFrame) .map(getFilesystemFrame)
.map((f) => { .map((f) => {
let str = ` at ${f.methodName}` let str = ` at ${f.methodName}`
......
...@@ -6,14 +6,14 @@ export function parseStack(stack: string): StackFrame[] { ...@@ -6,14 +6,14 @@ export function parseStack(stack: string): StackFrame[] {
const frames = parse(stack) const frames = parse(stack)
return frames.map((frame) => { return frames.map((frame) => {
try { try {
const url = new URL(frame.file) const url = new URL(frame.file!)
const res = regexNextStatic.exec(url.pathname) const res = regexNextStatic.exec(url.pathname)
if (res) { if (res) {
const distDir = process.env.__NEXT_DIST_DIR const distDir = process.env.__NEXT_DIST_DIR
?.replace(/\\/g, '/') ?.replace(/\\/g, '/')
?.replace(/\/$/, '') ?.replace(/\/$/, '')
if (distDir) { if (distDir) {
frame.file = 'file://' + distDir.concat(res.pop()) frame.file = 'file://' + distDir.concat(res.pop()!)
} }
} }
} catch {} } catch {}
......
...@@ -47,7 +47,7 @@ export function getOriginalStackFrame( ...@@ -47,7 +47,7 @@ export function getOriginalStackFrame(
const params = new URLSearchParams() const params = new URLSearchParams()
params.append('isServerSide', String(isServerSide)) params.append('isServerSide', String(isServerSide))
for (const key in source) { for (const key in source) {
params.append(key, (source[key] ?? '').toString()) params.append(key, ((source as any)[key] ?? '').toString())
} }
const controller = new AbortController() const controller = new AbortController()
...@@ -114,7 +114,7 @@ export function getOriginalStackFrame( ...@@ -114,7 +114,7 @@ export function getOriginalStackFrame(
export function getFrameSource(frame: StackFrame): string { export function getFrameSource(frame: StackFrame): string {
let str = '' let str = ''
try { try {
const u = new URL(frame.file) const u = new URL(frame.file!)
// Strip the origin for same-origin scripts. // Strip the origin for same-origin scripts.
if ( if (
......
...@@ -2,10 +2,10 @@ import * as React from 'react' ...@@ -2,10 +2,10 @@ import * as React from 'react'
export function useOnClickOutside( export function useOnClickOutside(
el: Node | null, el: Node | null,
handler: (e: MouseEvent | TouchEvent) => void handler: ((e: MouseEvent | TouchEvent) => void) | undefined
) { ) {
React.useEffect(() => { React.useEffect(() => {
if (el == null) { if (el == null || handler == null) {
return return
} }
...@@ -19,11 +19,11 @@ export function useOnClickOutside( ...@@ -19,11 +19,11 @@ export function useOnClickOutside(
} }
const root = el.getRootNode() const root = el.getRootNode()
root.addEventListener('mousedown', listener) root.addEventListener('mousedown', listener as EventListener)
root.addEventListener('touchstart', listener) root.addEventListener('touchstart', listener as EventListener)
return function () { return function () {
root.removeEventListener('mousedown', listener) root.removeEventListener('mousedown', listener as EventListener)
root.removeEventListener('touchstart', listener) root.removeEventListener('touchstart', listener as EventListener)
} }
}, [handler, el]) }, [handler, el])
} }
...@@ -10,6 +10,7 @@ import { ...@@ -10,6 +10,7 @@ import {
import { StackFrame } from 'stacktrace-parser' import { StackFrame } from 'stacktrace-parser'
import url from 'url' import url from 'url'
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
// @ts-ignore
import webpack from 'webpack' import webpack from 'webpack'
import { getRawSourceMap } from './internal/helpers/getRawSourceMap' import { getRawSourceMap } from './internal/helpers/getRawSourceMap'
import { launchEditor } from './internal/helpers/launchEditor' import { launchEditor } from './internal/helpers/launchEditor'
...@@ -97,6 +98,10 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) { ...@@ -97,6 +98,10 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
const compilation = isServerSide const compilation = isServerSide
? options.serverStats()?.compilation ? options.serverStats()?.compilation
: options.stats()?.compilation : options.stats()?.compilation
if (compilation == null) {
return null
}
const module = [...compilation.modules].find( const module = [...compilation.modules].find(
(searchModule) => searchModule.id === id (searchModule) => searchModule.id === id
) )
...@@ -112,7 +117,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) { ...@@ -112,7 +117,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
res: ServerResponse, res: ServerResponse,
next: Function next: Function
) { ) {
const { pathname, query } = url.parse(req.url, true) const { pathname, query } = url.parse(req.url!, true)
if (pathname === '/__nextjs_original-stack-frame') { if (pathname === '/__nextjs_original-stack-frame') {
const frame = (query as unknown) as StackFrame & { const frame = (query as unknown) as StackFrame & {
...@@ -171,7 +176,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) { ...@@ -171,7 +176,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
const consumer = await new SourceMapConsumer(source.map()) const consumer = await new SourceMapConsumer(source.map())
pos = consumer.originalPositionFor({ pos = consumer.originalPositionFor({
line: frameLine, line: frameLine,
column: frameColumn, column: frameColumn ?? 0,
}) })
if (pos.source) { if (pos.source) {
posSourceContent = posSourceContent =
...@@ -215,7 +220,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) { ...@@ -215,7 +220,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
pos.line pos.line
? (codeFrameColumns( ? (codeFrameColumns(
posSourceContent, posSourceContent,
{ start: { line: pos.line, column: pos.column } }, { start: { line: pos.line, column: pos.column ?? 0 } },
{ forceColor: true } { forceColor: true }
) as string) ) as string)
: null : null
......
{ {
"compilerOptions": { "compilerOptions": {
"sourceMap": true, "sourceMap": true,
"strict": true,
"esModuleInterop": true, "esModuleInterop": true,
"target": "es3", "target": "es3",
"lib": ["dom"], "lib": ["dom"],
......
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