Initial commit

This commit is contained in:
bilulib
2025-04-13 00:18:57 +02:00
parent cff009bb7c
commit d894249e61
18301 changed files with 2905442 additions and 3845 deletions

View File

@@ -0,0 +1,27 @@
import { PureComponent } from 'react';
import { type GlobalErrorComponent } from '../../error-boundary';
type AppDevOverlayErrorBoundaryProps = {
children: React.ReactNode;
globalError: [GlobalErrorComponent, React.ReactNode];
onError: (value: boolean) => void;
};
type AppDevOverlayErrorBoundaryState = {
isReactError: boolean;
reactError: unknown;
};
export declare class AppDevOverlayErrorBoundary extends PureComponent<AppDevOverlayErrorBoundaryProps, AppDevOverlayErrorBoundaryState> {
state: {
isReactError: boolean;
reactError: null;
};
static getDerivedStateFromError(error: Error): {
isReactError: boolean;
reactError: null;
} | {
isReactError: boolean;
reactError: Error;
};
componentDidCatch(): void;
render(): string | number | bigint | boolean | Iterable<import("react").ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | import("react").ReactPortal | Iterable<import("react").ReactNode> | null | undefined> | import("react/jsx-runtime").JSX.Element | null | undefined;
}
export {};

View File

@@ -0,0 +1,75 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "AppDevOverlayErrorBoundary", {
enumerable: true,
get: function() {
return AppDevOverlayErrorBoundary;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _react = require("react");
const _runtimeerrorhandler = require("../../errors/runtime-error-handler");
const _errorboundary = require("../../error-boundary");
function ErroredHtml(param) {
let { globalError: [GlobalError, globalErrorStyles], error } = param;
if (!error) {
return /*#__PURE__*/ (0, _jsxruntime.jsxs)("html", {
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)("head", {}),
/*#__PURE__*/ (0, _jsxruntime.jsx)("body", {})
]
});
}
return /*#__PURE__*/ (0, _jsxruntime.jsxs)(_errorboundary.ErrorBoundary, {
errorComponent: _errorboundary.GlobalError,
children: [
globalErrorStyles,
/*#__PURE__*/ (0, _jsxruntime.jsx)(GlobalError, {
error: error
})
]
});
}
class AppDevOverlayErrorBoundary extends _react.PureComponent {
static getDerivedStateFromError(error) {
if (!error.stack) {
return {
isReactError: false,
reactError: null
};
}
_runtimeerrorhandler.RuntimeErrorHandler.hadRuntimeError = true;
return {
isReactError: true,
reactError: error
};
}
componentDidCatch() {
this.props.onError(this.state.isReactError);
}
render() {
const { children, globalError } = this.props;
const { isReactError, reactError } = this.state;
const fallback = /*#__PURE__*/ (0, _jsxruntime.jsx)(ErroredHtml, {
globalError: globalError,
error: reactError
});
return isReactError ? fallback : children;
}
constructor(...args){
super(...args), this.state = {
isReactError: false,
reactError: null
};
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=app-dev-overlay-error-boundary.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/app/app-dev-overlay-error-boundary.tsx"],"sourcesContent":["import { PureComponent } from 'react'\nimport { RuntimeErrorHandler } from '../../errors/runtime-error-handler'\nimport {\n ErrorBoundary,\n type GlobalErrorComponent,\n GlobalError as DefaultGlobalError,\n} from '../../error-boundary'\n\ntype AppDevOverlayErrorBoundaryProps = {\n children: React.ReactNode\n globalError: [GlobalErrorComponent, React.ReactNode]\n onError: (value: boolean) => void\n}\n\ntype AppDevOverlayErrorBoundaryState = {\n isReactError: boolean\n reactError: unknown\n}\n\nfunction ErroredHtml({\n globalError: [GlobalError, globalErrorStyles],\n error,\n}: {\n globalError: [GlobalErrorComponent, React.ReactNode]\n error: unknown\n}) {\n if (!error) {\n return (\n <html>\n <head />\n <body />\n </html>\n )\n }\n return (\n <ErrorBoundary errorComponent={DefaultGlobalError}>\n {globalErrorStyles}\n <GlobalError error={error} />\n </ErrorBoundary>\n )\n}\n\nexport class AppDevOverlayErrorBoundary extends PureComponent<\n AppDevOverlayErrorBoundaryProps,\n AppDevOverlayErrorBoundaryState\n> {\n state = { isReactError: false, reactError: null }\n\n static getDerivedStateFromError(error: Error) {\n if (!error.stack) {\n return { isReactError: false, reactError: null }\n }\n\n RuntimeErrorHandler.hadRuntimeError = true\n\n return {\n isReactError: true,\n reactError: error,\n }\n }\n\n componentDidCatch() {\n this.props.onError(this.state.isReactError)\n }\n\n render() {\n const { children, globalError } = this.props\n const { isReactError, reactError } = this.state\n\n const fallback = (\n <ErroredHtml globalError={globalError} error={reactError} />\n )\n\n return isReactError ? fallback : children\n }\n}\n"],"names":["AppDevOverlayErrorBoundary","ErroredHtml","globalError","GlobalError","globalErrorStyles","error","html","head","body","ErrorBoundary","errorComponent","DefaultGlobalError","PureComponent","getDerivedStateFromError","stack","isReactError","reactError","RuntimeErrorHandler","hadRuntimeError","componentDidCatch","props","onError","state","render","children","fallback"],"mappings":";;;;+BA0CaA;;;eAAAA;;;;uBA1CiB;qCACM;+BAK7B;AAaP,SAASC,YAAY,KAMpB;IANoB,IAAA,EACnBC,aAAa,CAACC,aAAaC,kBAAkB,EAC7CC,KAAK,EAIN,GANoB;IAOnB,IAAI,CAACA,OAAO;QACV,qBACE,sBAACC;;8BACC,qBAACC;8BACD,qBAACC;;;IAGP;IACA,qBACE,sBAACC,4BAAa;QAACC,gBAAgBC,0BAAkB;;YAC9CP;0BACD,qBAACD;gBAAYE,OAAOA;;;;AAG1B;AAEO,MAAML,mCAAmCY,oBAAa;IAM3D,OAAOC,yBAAyBR,KAAY,EAAE;QAC5C,IAAI,CAACA,MAAMS,KAAK,EAAE;YAChB,OAAO;gBAAEC,cAAc;gBAAOC,YAAY;YAAK;QACjD;QAEAC,wCAAmB,CAACC,eAAe,GAAG;QAEtC,OAAO;YACLH,cAAc;YACdC,YAAYX;QACd;IACF;IAEAc,oBAAoB;QAClB,IAAI,CAACC,KAAK,CAACC,OAAO,CAAC,IAAI,CAACC,KAAK,CAACP,YAAY;IAC5C;IAEAQ,SAAS;QACP,MAAM,EAAEC,QAAQ,EAAEtB,WAAW,EAAE,GAAG,IAAI,CAACkB,KAAK;QAC5C,MAAM,EAAEL,YAAY,EAAEC,UAAU,EAAE,GAAG,IAAI,CAACM,KAAK;QAE/C,MAAMG,yBACJ,qBAACxB;YAAYC,aAAaA;YAAaG,OAAOW;;QAGhD,OAAOD,eAAeU,WAAWD;IACnC;;QAhCK,qBAILF,QAAQ;YAAEP,cAAc;YAAOC,YAAY;QAAK;;AA6BlD"}

View File

@@ -0,0 +1,7 @@
import type { OverlayState } from '../shared';
import type { GlobalErrorComponent } from '../../error-boundary';
export declare function AppDevOverlay({ state, globalError, children, }: {
state: OverlayState;
globalError: [GlobalErrorComponent, React.ReactNode];
children: React.ReactNode;
}): import("react/jsx-runtime").JSX.Element;

View File

@@ -0,0 +1,111 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "AppDevOverlay", {
enumerable: true,
get: function() {
return AppDevOverlay;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _react = require("react");
const _appdevoverlayerrorboundary = require("./app-dev-overlay-error-boundary");
const _fontstyles = require("../font/font-styles");
const _devoverlay = require("../ui/dev-overlay");
const _useerrorhandler = require("../../errors/use-error-handler");
const _isnextroutererror = require("../../is-next-router-error");
const _constants = require("../../../../shared/lib/errors/constants");
function readSsrError() {
if (typeof document === 'undefined') {
return null;
}
const ssrErrorTemplateTag = document.querySelector('template[data-next-error-message]');
if (ssrErrorTemplateTag) {
const message = ssrErrorTemplateTag.getAttribute('data-next-error-message');
const stack = ssrErrorTemplateTag.getAttribute('data-next-error-stack');
const digest = ssrErrorTemplateTag.getAttribute('data-next-error-digest');
const error = Object.defineProperty(new Error(message), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
if (digest) {
;
error.digest = digest;
}
// Skip Next.js SSR'd internal errors that which will be handled by the error boundaries.
if ((0, _isnextroutererror.isNextRouterError)(error)) {
return null;
}
error.stack = stack || '';
return error;
}
return null;
}
// Needs to be in the same error boundary as the shell.
// If it commits, we know we recovered from an SSR error.
// If it doesn't commit, we errored again and React will take care of error reporting.
function ReplaySsrOnlyErrors(param) {
let { onBlockingError } = param;
if (process.env.NODE_ENV !== 'production') {
// Need to read during render. The attributes will be gone after commit.
const ssrError = readSsrError();
// eslint-disable-next-line react-hooks/rules-of-hooks
(0, _react.useEffect)(()=>{
if (ssrError !== null) {
// TODO(veil): Produces wrong Owner Stack
// TODO(veil): Mark as recoverable error
// TODO(veil): console.error
(0, _useerrorhandler.handleClientError)(ssrError);
// If it's missing root tags, we can't recover, make it blocking.
if (ssrError.digest === _constants.MISSING_ROOT_TAGS_ERROR) {
onBlockingError();
}
}
}, [
ssrError,
onBlockingError
]);
}
return null;
}
function AppDevOverlay(param) {
let { state, globalError, children } = param;
const [isErrorOverlayOpen, setIsErrorOverlayOpen] = (0, _react.useState)(false);
const openOverlay = (0, _react.useCallback)(()=>{
setIsErrorOverlayOpen(true);
}, []);
return /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
/*#__PURE__*/ (0, _jsxruntime.jsxs)(_appdevoverlayerrorboundary.AppDevOverlayErrorBoundary, {
globalError: globalError,
onError: setIsErrorOverlayOpen,
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)(ReplaySsrOnlyErrors, {
onBlockingError: openOverlay
}),
children
]
}),
/*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)(_fontstyles.FontStyles, {}),
/*#__PURE__*/ (0, _jsxruntime.jsx)(_devoverlay.DevOverlay, {
state: state,
isErrorOverlayOpen: isErrorOverlayOpen,
setIsErrorOverlayOpen: setIsErrorOverlayOpen
})
]
})
]
});
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=app-dev-overlay.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
import React from 'react';
export declare function createRootLevelDevOverlayElement(reactEl: React.ReactElement): import("react/jsx-runtime").JSX.Element;

View File

@@ -0,0 +1,52 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "createRootLevelDevOverlayElement", {
enumerable: true,
get: function() {
return createRootLevelDevOverlayElement;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_default._(require("react"));
const _getsocketurl = require("../utils/get-socket-url");
const _hotreloadertypes = require("../../../../server/dev/hot-reloader-types");
const _errorboundary = /*#__PURE__*/ _interop_require_default._(require("../../error-boundary"));
const _appdevoverlayerrorboundary = require("./app-dev-overlay-error-boundary");
const noop = ()=>{};
function createRootLevelDevOverlayElement(reactEl) {
const socketUrl = (0, _getsocketurl.getSocketUrl)(process.env.__NEXT_ASSET_PREFIX || '');
const socket = new window.WebSocket("" + socketUrl + "/_next/webpack-hmr");
// add minimal "hot reload" support for RSC errors
const handler = (event)=>{
let obj;
try {
obj = JSON.parse(event.data);
} catch (e) {}
if (!obj || !('action' in obj)) {
return;
}
if (obj.action === _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES) {
window.location.reload();
}
};
socket.addEventListener('message', handler);
return /*#__PURE__*/ (0, _jsxruntime.jsx)(_appdevoverlayerrorboundary.AppDevOverlayErrorBoundary, {
globalError: [
_errorboundary.default,
null
],
onError: noop,
children: reactEl
});
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=client-entry.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/app/client-entry.tsx"],"sourcesContent":["import React from 'react'\nimport { getSocketUrl } from '../utils/get-socket-url'\nimport { HMR_ACTIONS_SENT_TO_BROWSER } from '../../../../server/dev/hot-reloader-types'\nimport GlobalError from '../../error-boundary'\nimport { AppDevOverlayErrorBoundary } from './app-dev-overlay-error-boundary'\n\nconst noop = () => {}\n\n// if an error is thrown while rendering an RSC stream, this will catch it in dev\n// and show the error overlay\nexport function createRootLevelDevOverlayElement(reactEl: React.ReactElement) {\n const socketUrl = getSocketUrl(process.env.__NEXT_ASSET_PREFIX || '')\n const socket = new window.WebSocket(`${socketUrl}/_next/webpack-hmr`)\n\n // add minimal \"hot reload\" support for RSC errors\n const handler = (event: MessageEvent) => {\n let obj\n try {\n obj = JSON.parse(event.data)\n } catch {}\n\n if (!obj || !('action' in obj)) {\n return\n }\n\n if (obj.action === HMR_ACTIONS_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES) {\n window.location.reload()\n }\n }\n\n socket.addEventListener('message', handler)\n\n return (\n <AppDevOverlayErrorBoundary\n globalError={[GlobalError, null]}\n onError={noop}\n >\n {reactEl}\n </AppDevOverlayErrorBoundary>\n )\n}\n"],"names":["createRootLevelDevOverlayElement","noop","reactEl","socketUrl","getSocketUrl","process","env","__NEXT_ASSET_PREFIX","socket","window","WebSocket","handler","event","obj","JSON","parse","data","action","HMR_ACTIONS_SENT_TO_BROWSER","SERVER_COMPONENT_CHANGES","location","reload","addEventListener","AppDevOverlayErrorBoundary","globalError","GlobalError","onError"],"mappings":";;;;+BAUgBA;;;eAAAA;;;;;gEAVE;8BACW;kCACe;wEACpB;4CACmB;AAE3C,MAAMC,OAAO,KAAO;AAIb,SAASD,iCAAiCE,OAA2B;IAC1E,MAAMC,YAAYC,IAAAA,0BAAY,EAACC,QAAQC,GAAG,CAACC,mBAAmB,IAAI;IAClE,MAAMC,SAAS,IAAIC,OAAOC,SAAS,CAAC,AAAC,KAAEP,YAAU;IAEjD,kDAAkD;IAClD,MAAMQ,UAAU,CAACC;QACf,IAAIC;QACJ,IAAI;YACFA,MAAMC,KAAKC,KAAK,CAACH,MAAMI,IAAI;QAC7B,EAAE,UAAM,CAAC;QAET,IAAI,CAACH,OAAO,CAAE,CAAA,YAAYA,GAAE,GAAI;YAC9B;QACF;QAEA,IAAIA,IAAII,MAAM,KAAKC,6CAA2B,CAACC,wBAAwB,EAAE;YACvEV,OAAOW,QAAQ,CAACC,MAAM;QACxB;IACF;IAEAb,OAAOc,gBAAgB,CAAC,WAAWX;IAEnC,qBACE,qBAACY,sDAA0B;QACzBC,aAAa;YAACC,sBAAW;YAAE;SAAK;QAChCC,SAASzB;kBAERC;;AAGP"}

View File

@@ -0,0 +1,21 @@
import type { ReactNode } from 'react';
import type { VersionInfo } from '../../../../server/dev/parse-version-info';
import type { DebugInfo } from '../types';
import type { GlobalErrorComponent } from '../../error-boundary';
import type { DevIndicatorServerState } from '../../../../server/dev/dev-indicator-server-state';
export interface Dispatcher {
onBuildOk(): void;
onBuildError(message: string): void;
onVersionInfo(versionInfo: VersionInfo): void;
onDebugInfo(debugInfo: DebugInfo): void;
onBeforeRefresh(): void;
onRefresh(): void;
onStaticIndicator(status: boolean): void;
onDevIndicator(devIndicator: DevIndicatorServerState): void;
}
export declare function waitForWebpackRuntimeHotUpdate(): Promise<void>;
export default function HotReload({ assetPrefix, children, globalError, }: {
assetPrefix: string;
children: ReactNode;
globalError: [GlobalErrorComponent, React.ReactNode];
}): import("react/jsx-runtime").JSX.Element;

View File

@@ -0,0 +1,534 @@
/// <reference types="webpack/module.d.ts" />
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
default: null,
waitForWebpackRuntimeHotUpdate: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
default: function() {
return HotReload;
},
waitForWebpackRuntimeHotUpdate: function() {
return waitForWebpackRuntimeHotUpdate;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _jsxruntime = require("react/jsx-runtime");
const _react = require("react");
const _stripansi = /*#__PURE__*/ _interop_require_default._(require("next/dist/compiled/strip-ansi"));
const _formatwebpackmessages = /*#__PURE__*/ _interop_require_default._(require("../utils/format-webpack-messages"));
const _navigation = require("../../navigation");
const _shared = require("../shared");
const _parsestack = require("../utils/parse-stack");
const _appdevoverlay = require("./app-dev-overlay");
const _useerrorhandler = require("../../errors/use-error-handler");
const _runtimeerrorhandler = require("../../errors/runtime-error-handler");
const _usewebsocket = require("../utils/use-websocket");
const _parsecomponentstack = require("../utils/parse-component-stack");
const _hotreloadertypes = require("../../../../server/dev/hot-reloader-types");
const _navigationuntracked = require("../../navigation-untracked");
const _stitchederror = require("../../errors/stitched-error");
const _handledevbuildindicatorhmrevents = require("../../../dev/dev-build-indicator/internal/handle-dev-build-indicator-hmr-events");
const _reporthmrlatency = /*#__PURE__*/ _interop_require_default._(require("../utils/report-hmr-latency"));
const _turbopackhotreloadercommon = require("../utils/turbopack-hot-reloader-common");
const _approuterheaders = require("../../app-router-headers");
let mostRecentCompilationHash = null;
let __nextDevClientId = Math.round(Math.random() * 100 + Date.now());
let reloading = false;
let webpackStartMsSinceEpoch = null;
const turbopackHmr = process.env.TURBOPACK ? new _turbopackhotreloadercommon.TurbopackHmr() : null;
let pendingHotUpdateWebpack = Promise.resolve();
let resolvePendingHotUpdateWebpack = ()=>{};
function setPendingHotUpdateWebpack() {
pendingHotUpdateWebpack = new Promise((resolve)=>{
resolvePendingHotUpdateWebpack = ()=>{
resolve();
};
});
}
function waitForWebpackRuntimeHotUpdate() {
return pendingHotUpdateWebpack;
}
// There is a newer version of the code available.
function handleAvailableHash(hash) {
// Update last known compilation hash.
mostRecentCompilationHash = hash;
}
/**
* Is there a newer version of this code available?
* For webpack: Check if the hash changed compared to __webpack_hash__
* For Turbopack: Always true because it doesn't have __webpack_hash__
*/ function isUpdateAvailable() {
if (process.env.TURBOPACK) {
return true;
}
/* globals __webpack_hash__ */ // __webpack_hash__ is the hash of the current compilation.
// It's a global variable injected by Webpack.
return mostRecentCompilationHash !== __webpack_hash__;
}
// Webpack disallows updates in other states.
function canApplyUpdates() {
return module.hot.status() === 'idle';
}
function afterApplyUpdates(fn) {
if (canApplyUpdates()) {
fn();
} else {
function handler(status) {
if (status === 'idle') {
module.hot.removeStatusHandler(handler);
fn();
}
}
module.hot.addStatusHandler(handler);
}
}
function performFullReload(err, sendMessage) {
const stackTrace = err && (err.stack && err.stack.split('\n').slice(0, 5).join('\n') || err.message || err + '');
sendMessage(JSON.stringify({
event: 'client-full-reload',
stackTrace,
hadRuntimeError: !!_runtimeerrorhandler.RuntimeErrorHandler.hadRuntimeError,
dependencyChain: err ? err.dependencyChain : undefined
}));
if (reloading) return;
reloading = true;
window.location.reload();
}
// Attempt to update code on the fly, fall back to a hard reload.
function tryApplyUpdatesWebpack(sendMessage, dispatcher) {
if (!isUpdateAvailable() || !canApplyUpdates()) {
resolvePendingHotUpdateWebpack();
dispatcher.onBuildOk();
(0, _reporthmrlatency.default)(sendMessage, [], webpackStartMsSinceEpoch, Date.now());
return;
}
function handleApplyUpdates(err, updatedModules) {
if (err || _runtimeerrorhandler.RuntimeErrorHandler.hadRuntimeError || updatedModules == null) {
if (err) {
console.warn(_shared.REACT_REFRESH_FULL_RELOAD);
} else if (_runtimeerrorhandler.RuntimeErrorHandler.hadRuntimeError) {
console.warn(_shared.REACT_REFRESH_FULL_RELOAD_FROM_ERROR);
}
performFullReload(err, sendMessage);
return;
}
dispatcher.onBuildOk();
if (isUpdateAvailable()) {
// While we were updating, there was a new update! Do it again.
tryApplyUpdatesWebpack(sendMessage, dispatcher);
return;
}
dispatcher.onRefresh();
resolvePendingHotUpdateWebpack();
(0, _reporthmrlatency.default)(sendMessage, updatedModules, webpackStartMsSinceEpoch, Date.now());
if (process.env.__NEXT_TEST_MODE) {
afterApplyUpdates(()=>{
if (self.__NEXT_HMR_CB) {
self.__NEXT_HMR_CB();
self.__NEXT_HMR_CB = null;
}
});
}
}
// https://webpack.js.org/api/hot-module-replacement/#check
module.hot.check(/* autoApply */ false).then((updatedModules)=>{
if (updatedModules == null) {
return null;
}
// We should always handle an update, even if updatedModules is empty (but
// non-null) for any reason. That's what webpack would normally do:
// https://github.com/webpack/webpack/blob/3aa6b6bc3a64/lib/hmr/HotModuleReplacement.runtime.js#L296-L298
dispatcher.onBeforeRefresh();
// https://webpack.js.org/api/hot-module-replacement/#apply
return module.hot.apply();
}).then((updatedModules)=>{
handleApplyUpdates(null, updatedModules);
}, (err)=>{
handleApplyUpdates(err, null);
});
}
/** Handles messages from the server for the App Router. */ function processMessage(obj, sendMessage, processTurbopackMessage, router, dispatcher, appIsrManifestRef, pathnameRef) {
if (!('action' in obj)) {
return;
}
function handleErrors(errors) {
// "Massage" webpack messages.
const formatted = (0, _formatwebpackmessages.default)({
errors: errors,
warnings: []
});
// Only show the first error.
dispatcher.onBuildError(formatted.errors[0]);
// Also log them to the console.
for(let i = 0; i < formatted.errors.length; i++){
console.error((0, _stripansi.default)(formatted.errors[i]));
}
// Do not attempt to reload now.
// We will reload on next success instead.
if (process.env.__NEXT_TEST_MODE) {
if (self.__NEXT_HMR_CB) {
self.__NEXT_HMR_CB(formatted.errors[0]);
self.__NEXT_HMR_CB = null;
}
}
}
function handleHotUpdate() {
if (process.env.TURBOPACK) {
const hmrUpdate = turbopackHmr.onBuilt();
if (hmrUpdate != null) {
(0, _reporthmrlatency.default)(sendMessage, [
...hmrUpdate.updatedModules
], hmrUpdate.startMsSinceEpoch, hmrUpdate.endMsSinceEpoch, // suppress the `client-hmr-latency` event if the update was a no-op:
hmrUpdate.hasUpdates);
}
dispatcher.onBuildOk();
} else {
tryApplyUpdatesWebpack(sendMessage, dispatcher);
}
}
switch(obj.action){
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.ISR_MANIFEST:
{
if (process.env.__NEXT_DEV_INDICATOR) {
if (appIsrManifestRef) {
appIsrManifestRef.current = obj.data;
// handle initial status on receiving manifest
// navigation is handled in useEffect for pathname changes
// as we'll receive the updated manifest before usePathname
// triggers for new value
if (pathnameRef.current in obj.data) {
dispatcher.onStaticIndicator(true);
} else {
dispatcher.onStaticIndicator(false);
}
}
}
break;
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.BUILDING:
{
if (process.env.TURBOPACK) {
turbopackHmr.onBuilding();
} else {
webpackStartMsSinceEpoch = Date.now();
setPendingHotUpdateWebpack();
console.log('[Fast Refresh] rebuilding');
}
break;
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.BUILT:
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.SYNC:
{
if (obj.hash) {
handleAvailableHash(obj.hash);
}
const { errors, warnings } = obj;
// Is undefined when it's a 'built' event
if ('versionInfo' in obj) dispatcher.onVersionInfo(obj.versionInfo);
if ('debug' in obj && obj.debug) dispatcher.onDebugInfo(obj.debug);
if ('devIndicator' in obj) dispatcher.onDevIndicator(obj.devIndicator);
const hasErrors = Boolean(errors && errors.length);
// Compilation with errors (e.g. syntax error or missing modules).
if (hasErrors) {
sendMessage(JSON.stringify({
event: 'client-error',
errorCount: errors.length,
clientId: __nextDevClientId
}));
handleErrors(errors);
return;
}
const hasWarnings = Boolean(warnings && warnings.length);
if (hasWarnings) {
sendMessage(JSON.stringify({
event: 'client-warning',
warningCount: warnings.length,
clientId: __nextDevClientId
}));
// Print warnings to the console.
const formattedMessages = (0, _formatwebpackmessages.default)({
warnings: warnings,
errors: []
});
for(let i = 0; i < formattedMessages.warnings.length; i++){
if (i === 5) {
console.warn('There were more warnings in other files.\n' + 'You can find a complete log in the terminal.');
break;
}
console.warn((0, _stripansi.default)(formattedMessages.warnings[i]));
}
// No early return here as we need to apply modules in the same way between warnings only and compiles without warnings
}
sendMessage(JSON.stringify({
event: 'client-success',
clientId: __nextDevClientId
}));
if (obj.action === _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.BUILT) {
handleHotUpdate();
}
return;
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED:
{
processTurbopackMessage({
type: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED,
data: {
sessionId: obj.data.sessionId
}
});
break;
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE:
{
turbopackHmr.onTurbopackMessage(obj);
dispatcher.onBeforeRefresh();
processTurbopackMessage({
type: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE,
data: obj.data
});
if (_runtimeerrorhandler.RuntimeErrorHandler.hadRuntimeError) {
console.warn(_shared.REACT_REFRESH_FULL_RELOAD_FROM_ERROR);
performFullReload(null, sendMessage);
}
dispatcher.onRefresh();
break;
}
// TODO-APP: make server component change more granular
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES:
{
turbopackHmr == null ? void 0 : turbopackHmr.onServerComponentChanges();
sendMessage(JSON.stringify({
event: 'server-component-reload-page',
clientId: __nextDevClientId,
hash: obj.hash
}));
// Store the latest hash in a session cookie so that it's sent back to the
// server with any subsequent requests.
document.cookie = _approuterheaders.NEXT_HMR_REFRESH_HASH_COOKIE + "=" + obj.hash;
if (_runtimeerrorhandler.RuntimeErrorHandler.hadRuntimeError) {
if (reloading) return;
reloading = true;
return window.location.reload();
}
(0, _react.startTransition)(()=>{
router.hmrRefresh();
dispatcher.onRefresh();
});
if (process.env.__NEXT_TEST_MODE) {
if (self.__NEXT_HMR_CB) {
self.__NEXT_HMR_CB();
self.__NEXT_HMR_CB = null;
}
}
return;
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.RELOAD_PAGE:
{
turbopackHmr == null ? void 0 : turbopackHmr.onReloadPage();
sendMessage(JSON.stringify({
event: 'client-reload-page',
clientId: __nextDevClientId
}));
if (reloading) return;
reloading = true;
return window.location.reload();
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.ADDED_PAGE:
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.REMOVED_PAGE:
{
turbopackHmr == null ? void 0 : turbopackHmr.onPageAddRemove();
// TODO-APP: potentially only refresh if the currently viewed page was added/removed.
return router.hmrRefresh();
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.SERVER_ERROR:
{
const { errorJSON } = obj;
if (errorJSON) {
const { message, stack } = JSON.parse(errorJSON);
const error = Object.defineProperty(new Error(message), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
error.stack = stack;
handleErrors([
error
]);
}
return;
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.DEV_PAGES_MANIFEST_UPDATE:
{
return;
}
default:
{}
}
}
function HotReload(param) {
let { assetPrefix, children, globalError } = param;
const [state, dispatch] = (0, _shared.useErrorOverlayReducer)('app');
const dispatcher = (0, _react.useMemo)(()=>{
return {
onBuildOk () {
dispatch({
type: _shared.ACTION_BUILD_OK
});
},
onBuildError (message) {
dispatch({
type: _shared.ACTION_BUILD_ERROR,
message
});
},
onBeforeRefresh () {
dispatch({
type: _shared.ACTION_BEFORE_REFRESH
});
},
onRefresh () {
dispatch({
type: _shared.ACTION_REFRESH
});
},
onVersionInfo (versionInfo) {
dispatch({
type: _shared.ACTION_VERSION_INFO,
versionInfo
});
},
onStaticIndicator (status) {
dispatch({
type: _shared.ACTION_STATIC_INDICATOR,
staticIndicator: status
});
},
onDebugInfo (debugInfo) {
dispatch({
type: _shared.ACTION_DEBUG_INFO,
debugInfo
});
},
onDevIndicator (devIndicator) {
dispatch({
type: _shared.ACTION_DEV_INDICATOR,
devIndicator
});
}
};
}, [
dispatch
]);
const handleOnUnhandledError = (0, _react.useCallback)((error)=>{
// Component stack is added to the error in use-error-handler in case there was a hydration error
const componentStackTrace = error._componentStack;
dispatch({
type: _shared.ACTION_UNHANDLED_ERROR,
reason: error,
frames: (0, _parsestack.parseStack)(error.stack || ''),
componentStackFrames: typeof componentStackTrace === 'string' ? (0, _parsecomponentstack.parseComponentStack)(componentStackTrace) : undefined
});
}, [
dispatch
]);
const handleOnUnhandledRejection = (0, _react.useCallback)((reason)=>{
const stitchedError = (0, _stitchederror.getReactStitchedError)(reason);
dispatch({
type: _shared.ACTION_UNHANDLED_REJECTION,
reason: stitchedError,
frames: (0, _parsestack.parseStack)(stitchedError.stack || '')
});
}, [
dispatch
]);
(0, _useerrorhandler.useErrorHandler)(handleOnUnhandledError, handleOnUnhandledRejection);
const webSocketRef = (0, _usewebsocket.useWebsocket)(assetPrefix);
(0, _usewebsocket.useWebsocketPing)(webSocketRef);
const sendMessage = (0, _usewebsocket.useSendMessage)(webSocketRef);
const processTurbopackMessage = (0, _usewebsocket.useTurbopack)(sendMessage, (err)=>performFullReload(err, sendMessage));
const router = (0, _navigation.useRouter)();
// We don't want access of the pathname for the dev tools to trigger a dynamic
// access (as the dev overlay will never be present in production).
const pathname = (0, _navigationuntracked.useUntrackedPathname)();
const appIsrManifestRef = (0, _react.useRef)({});
const pathnameRef = (0, _react.useRef)(pathname);
if (process.env.__NEXT_DEV_INDICATOR) {
// this conditional is only for dead-code elimination which
// isn't a runtime conditional only build-time so ignore hooks rule
// eslint-disable-next-line react-hooks/rules-of-hooks
(0, _react.useEffect)(()=>{
pathnameRef.current = pathname;
const appIsrManifest = appIsrManifestRef.current;
if (appIsrManifest) {
if (pathname && pathname in appIsrManifest) {
try {
dispatcher.onStaticIndicator(true);
} catch (reason) {
let message = '';
if (reason instanceof DOMException) {
var _reason_stack;
// Most likely a SecurityError, because of an unavailable localStorage
message = (_reason_stack = reason.stack) != null ? _reason_stack : reason.message;
} else if (reason instanceof Error) {
var _reason_stack1;
message = 'Error: ' + reason.message + '\n' + ((_reason_stack1 = reason.stack) != null ? _reason_stack1 : '');
} else {
message = 'Unexpected Exception: ' + reason;
}
console.warn('[HMR] ' + message);
}
} else {
dispatcher.onStaticIndicator(false);
}
}
}, [
pathname,
dispatcher
]);
}
(0, _react.useEffect)(()=>{
const websocket = webSocketRef.current;
if (!websocket) return;
const handler = (event)=>{
try {
const obj = JSON.parse(event.data);
(0, _handledevbuildindicatorhmrevents.handleDevBuildIndicatorHmrEvents)(obj);
processMessage(obj, sendMessage, processTurbopackMessage, router, dispatcher, appIsrManifestRef, pathnameRef);
} catch (err) {
(0, _shared.reportInvalidHmrMessage)(event, err);
}
};
websocket.addEventListener('message', handler);
return ()=>websocket.removeEventListener('message', handler);
}, [
sendMessage,
router,
webSocketRef,
dispatcher,
processTurbopackMessage,
appIsrManifestRef
]);
return /*#__PURE__*/ (0, _jsxruntime.jsx)(_appdevoverlay.AppDevOverlay, {
state: state,
globalError: globalError,
children: children
});
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=hot-reloader-client.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export declare const FontStyles: () => null;

View File

@@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "FontStyles", {
enumerable: true,
get: function() {
return FontStyles;
}
});
const _tagged_template_literal_loose = require("@swc/helpers/_/_tagged_template_literal_loose");
const _css = require("../utils/css");
const _react = require("react");
function _templateObject() {
const data = _tagged_template_literal_loose._([
"\n /* latin-ext */\n @font-face {\n font-family: '__nextjs-Geist';\n font-style: normal;\n font-weight: 400 600;\n font-display: swap;\n src: url(/__nextjs_font/geist-latin-ext.woff2) format('woff2');\n unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7,\n U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F,\n U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F,\n U+A720-A7FF;\n }\n /* latin-ext */\n @font-face {\n font-family: '__nextjs-Geist Mono';\n font-style: normal;\n font-weight: 400 600;\n font-display: swap;\n src: url(/__nextjs_font/geist-mono-latin-ext.woff2) format('woff2');\n unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7,\n U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F,\n U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F,\n U+A720-A7FF;\n }\n /* latin */\n @font-face {\n font-family: '__nextjs-Geist';\n font-style: normal;\n font-weight: 400 600;\n font-display: swap;\n src: url(/__nextjs_font/geist-latin.woff2) format('woff2');\n unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6,\n U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122,\n U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;\n }\n /* latin */\n @font-face {\n font-family: '__nextjs-Geist Mono';\n font-style: normal;\n font-weight: 400 600;\n font-display: swap;\n src: url(/__nextjs_font/geist-mono-latin.woff2) format('woff2');\n unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6,\n U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122,\n U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;\n }\n "
]);
_templateObject = function() {
return data;
};
return data;
}
const FontStyles = ()=>{
(0, _react.useInsertionEffect)(()=>{
const style = document.createElement('style');
style.textContent = (0, _css.css)(_templateObject());
document.head.appendChild(style);
return ()=>{
document.head.removeChild(style);
};
}, []);
return null;
};
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=font-styles.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/font/font-styles.tsx"],"sourcesContent":["import { css } from '../utils/css'\nimport { useInsertionEffect } from 'react'\n\nexport const FontStyles = () => {\n useInsertionEffect(() => {\n const style = document.createElement('style')\n style.textContent = css`\n /* latin-ext */\n @font-face {\n font-family: '__nextjs-Geist';\n font-style: normal;\n font-weight: 400 600;\n font-display: swap;\n src: url(/__nextjs_font/geist-latin-ext.woff2) format('woff2');\n unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7,\n U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F,\n U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F,\n U+A720-A7FF;\n }\n /* latin-ext */\n @font-face {\n font-family: '__nextjs-Geist Mono';\n font-style: normal;\n font-weight: 400 600;\n font-display: swap;\n src: url(/__nextjs_font/geist-mono-latin-ext.woff2) format('woff2');\n unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7,\n U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F,\n U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F,\n U+A720-A7FF;\n }\n /* latin */\n @font-face {\n font-family: '__nextjs-Geist';\n font-style: normal;\n font-weight: 400 600;\n font-display: swap;\n src: url(/__nextjs_font/geist-latin.woff2) format('woff2');\n unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6,\n U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122,\n U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;\n }\n /* latin */\n @font-face {\n font-family: '__nextjs-Geist Mono';\n font-style: normal;\n font-weight: 400 600;\n font-display: swap;\n src: url(/__nextjs_font/geist-mono-latin.woff2) format('woff2');\n unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6,\n U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122,\n U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;\n }\n `\n document.head.appendChild(style)\n\n return () => {\n document.head.removeChild(style)\n }\n }, [])\n\n return null\n}\n"],"names":["FontStyles","useInsertionEffect","style","document","createElement","textContent","css","head","appendChild","removeChild"],"mappings":";;;;+BAGaA;;;eAAAA;;;;qBAHO;uBACe;;;;;;;;;;AAE5B,MAAMA,aAAa;IACxBC,IAAAA,yBAAkB,EAAC;QACjB,MAAMC,QAAQC,SAASC,aAAa,CAAC;QACrCF,MAAMG,WAAW,OAAGC,QAAG;QAgDvBH,SAASI,IAAI,CAACC,WAAW,CAACN;QAE1B,OAAO;YACLC,SAASI,IAAI,CAACE,WAAW,CAACP;QAC5B;IACF,GAAG,EAAE;IAEL,OAAO;AACT"}

View File

@@ -0,0 +1,2 @@
import type { ServerResponse, IncomingMessage } from 'http';
export declare function getDevOverlayFontMiddleware(): (req: IncomingMessage, res: ServerResponse, next: () => void) => Promise<void>;

View File

@@ -0,0 +1,72 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getDevOverlayFontMiddleware", {
enumerable: true,
get: function() {
return getDevOverlayFontMiddleware;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _path = /*#__PURE__*/ _interop_require_default._(require("path"));
const _promises = /*#__PURE__*/ _interop_require_wildcard._(require("fs/promises"));
const _fs = require("fs");
const _log = /*#__PURE__*/ _interop_require_wildcard._(require("../../../../build/output/log"));
const _middlewareresponse = require("../server/middleware-response");
const FONT_PREFIX = '/__nextjs_font/';
const VALID_FONTS = [
'geist-latin-ext.woff2',
'geist-mono-latin-ext.woff2',
'geist-latin.woff2',
'geist-mono-latin.woff2'
];
const FONT_HEADERS = {
'Content-Type': 'font/woff2',
'Cache-Control': 'public, max-age=31536000, immutable'
};
function getDevOverlayFontMiddleware() {
return async function devOverlayFontMiddleware(req, res, next) {
try {
const { pathname } = new URL("http://n" + req.url);
if (!pathname.startsWith(FONT_PREFIX)) {
return next();
}
const fontFile = pathname.replace(FONT_PREFIX, '');
if (!VALID_FONTS.includes(fontFile)) {
return _middlewareresponse.middlewareResponse.notFound(res);
}
const fontPath = _path.default.resolve(__dirname, fontFile);
const fileExists = await checkFileExists(fontPath);
if (!fileExists) {
return _middlewareresponse.middlewareResponse.notFound(res);
}
const fontData = await _promises.readFile(fontPath);
Object.entries(FONT_HEADERS).forEach((param)=>{
let [key, value] = param;
res.setHeader(key, value);
});
res.end(fontData);
} catch (err) {
_log.error('Failed to serve font:', err instanceof Error ? err.message : err);
return _middlewareresponse.middlewareResponse.internalServerError(res);
}
};
}
async function checkFileExists(filePath) {
try {
await _promises.access(filePath, _fs.constants.F_OK);
return true;
} catch (e) {
return false;
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=get-dev-overlay-font-middleware.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/font/get-dev-overlay-font-middleware.ts"],"sourcesContent":["import type { ServerResponse, IncomingMessage } from 'http'\nimport path from 'path'\nimport * as fs from 'fs/promises'\nimport { constants } from 'fs'\nimport * as Log from '../../../../build/output/log'\nimport { middlewareResponse } from '../server/middleware-response'\n\nconst FONT_PREFIX = '/__nextjs_font/'\n\nconst VALID_FONTS = [\n 'geist-latin-ext.woff2',\n 'geist-mono-latin-ext.woff2',\n 'geist-latin.woff2',\n 'geist-mono-latin.woff2',\n]\n\nconst FONT_HEADERS = {\n 'Content-Type': 'font/woff2',\n 'Cache-Control': 'public, max-age=31536000, immutable',\n} as const\n\nexport function getDevOverlayFontMiddleware() {\n return async function devOverlayFontMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void\n ): Promise<void> {\n try {\n const { pathname } = new URL(`http://n${req.url}`)\n\n if (!pathname.startsWith(FONT_PREFIX)) {\n return next()\n }\n\n const fontFile = pathname.replace(FONT_PREFIX, '')\n if (!VALID_FONTS.includes(fontFile)) {\n return middlewareResponse.notFound(res)\n }\n\n const fontPath = path.resolve(__dirname, fontFile)\n const fileExists = await checkFileExists(fontPath)\n\n if (!fileExists) {\n return middlewareResponse.notFound(res)\n }\n\n const fontData = await fs.readFile(fontPath)\n Object.entries(FONT_HEADERS).forEach(([key, value]) => {\n res.setHeader(key, value)\n })\n res.end(fontData)\n } catch (err) {\n Log.error(\n 'Failed to serve font:',\n err instanceof Error ? err.message : err\n )\n return middlewareResponse.internalServerError(res)\n }\n }\n}\n\nasync function checkFileExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath, constants.F_OK)\n return true\n } catch {\n return false\n }\n}\n"],"names":["getDevOverlayFontMiddleware","FONT_PREFIX","VALID_FONTS","FONT_HEADERS","devOverlayFontMiddleware","req","res","next","pathname","URL","url","startsWith","fontFile","replace","includes","middlewareResponse","notFound","fontPath","path","resolve","__dirname","fileExists","checkFileExists","fontData","fs","readFile","Object","entries","forEach","key","value","setHeader","end","err","Log","error","Error","message","internalServerError","filePath","access","constants","F_OK"],"mappings":";;;;+BAqBgBA;;;eAAAA;;;;;+DApBC;oEACG;oBACM;+DACL;oCACc;AAEnC,MAAMC,cAAc;AAEpB,MAAMC,cAAc;IAClB;IACA;IACA;IACA;CACD;AAED,MAAMC,eAAe;IACnB,gBAAgB;IAChB,iBAAiB;AACnB;AAEO,SAASH;IACd,OAAO,eAAeI,yBACpBC,GAAoB,EACpBC,GAAmB,EACnBC,IAAgB;QAEhB,IAAI;YACF,MAAM,EAAEC,QAAQ,EAAE,GAAG,IAAIC,IAAI,AAAC,aAAUJ,IAAIK,GAAG;YAE/C,IAAI,CAACF,SAASG,UAAU,CAACV,cAAc;gBACrC,OAAOM;YACT;YAEA,MAAMK,WAAWJ,SAASK,OAAO,CAACZ,aAAa;YAC/C,IAAI,CAACC,YAAYY,QAAQ,CAACF,WAAW;gBACnC,OAAOG,sCAAkB,CAACC,QAAQ,CAACV;YACrC;YAEA,MAAMW,WAAWC,aAAI,CAACC,OAAO,CAACC,WAAWR;YACzC,MAAMS,aAAa,MAAMC,gBAAgBL;YAEzC,IAAI,CAACI,YAAY;gBACf,OAAON,sCAAkB,CAACC,QAAQ,CAACV;YACrC;YAEA,MAAMiB,WAAW,MAAMC,UAAGC,QAAQ,CAACR;YACnCS,OAAOC,OAAO,CAACxB,cAAcyB,OAAO,CAAC;oBAAC,CAACC,KAAKC,MAAM;gBAChDxB,IAAIyB,SAAS,CAACF,KAAKC;YACrB;YACAxB,IAAI0B,GAAG,CAACT;QACV,EAAE,OAAOU,KAAK;YACZC,KAAIC,KAAK,CACP,yBACAF,eAAeG,QAAQH,IAAII,OAAO,GAAGJ;YAEvC,OAAOlB,sCAAkB,CAACuB,mBAAmB,CAAChC;QAChD;IACF;AACF;AAEA,eAAegB,gBAAgBiB,QAAgB;IAC7C,IAAI;QACF,MAAMf,UAAGgB,MAAM,CAACD,UAAUE,aAAS,CAACC,IAAI;QACxC,OAAO;IACT,EAAE,UAAM;QACN,OAAO;IACT;AACF"}

View File

@@ -0,0 +1,5 @@
import type { BusEvent } from '../shared';
export type BusEventHandler = (ev: BusEvent) => void;
export declare function emit(ev: BusEvent): void;
export declare function on(fn: BusEventHandler): boolean;
export declare function off(fn: BusEventHandler): boolean;

View File

@@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
emit: null,
off: null,
on: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
emit: function() {
return emit;
},
off: function() {
return off;
},
on: function() {
return on;
}
});
let handlers = new Set();
let queue = [];
function drain() {
// Draining should never happen synchronously in case multiple handlers are
// registered.
setTimeout(function() {
while(// Until we are out of events:
Boolean(queue.length) && // Or, if all handlers removed themselves as a result of handling the
// event(s)
Boolean(handlers.size)){
const ev = queue.shift();
handlers.forEach((handler)=>handler(ev));
}
}, 1);
}
function emit(ev) {
queue.push(Object.freeze({
...ev
}));
drain();
}
function on(fn) {
if (handlers.has(fn)) {
return false;
}
handlers.add(fn);
drain();
return true;
}
function off(fn) {
if (handlers.has(fn)) {
handlers.delete(fn);
return true;
}
return false;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=bus.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/pages/bus.ts"],"sourcesContent":["import type { BusEvent } from '../shared'\n\nexport type BusEventHandler = (ev: BusEvent) => void\n\nlet handlers: Set<BusEventHandler> = new Set()\nlet queue: BusEvent[] = []\n\nfunction drain() {\n // Draining should never happen synchronously in case multiple handlers are\n // registered.\n setTimeout(function () {\n while (\n // Until we are out of events:\n Boolean(queue.length) &&\n // Or, if all handlers removed themselves as a result of handling the\n // event(s)\n Boolean(handlers.size)\n ) {\n const ev = queue.shift()!\n handlers.forEach((handler) => handler(ev))\n }\n }, 1)\n}\n\nexport function emit(ev: BusEvent): void {\n queue.push(Object.freeze({ ...ev }))\n drain()\n}\n\nexport function on(fn: BusEventHandler): boolean {\n if (handlers.has(fn)) {\n return false\n }\n\n handlers.add(fn)\n drain()\n return true\n}\n\nexport function off(fn: BusEventHandler): boolean {\n if (handlers.has(fn)) {\n handlers.delete(fn)\n return true\n }\n\n return false\n}\n"],"names":["emit","off","on","handlers","Set","queue","drain","setTimeout","Boolean","length","size","ev","shift","forEach","handler","push","Object","freeze","fn","has","add","delete"],"mappings":";;;;;;;;;;;;;;;;IAwBgBA,IAAI;eAAJA;;IAeAC,GAAG;eAAHA;;IAVAC,EAAE;eAAFA;;;AAzBhB,IAAIC,WAAiC,IAAIC;AACzC,IAAIC,QAAoB,EAAE;AAE1B,SAASC;IACP,2EAA2E;IAC3E,cAAc;IACdC,WAAW;QACT,MACE,8BAA8B;QAC9BC,QAAQH,MAAMI,MAAM,KACpB,qEAAqE;QACrE,WAAW;QACXD,QAAQL,SAASO,IAAI,EACrB;YACA,MAAMC,KAAKN,MAAMO,KAAK;YACtBT,SAASU,OAAO,CAAC,CAACC,UAAYA,QAAQH;QACxC;IACF,GAAG;AACL;AAEO,SAASX,KAAKW,EAAY;IAC/BN,MAAMU,IAAI,CAACC,OAAOC,MAAM,CAAC;QAAE,GAAGN,EAAE;IAAC;IACjCL;AACF;AAEO,SAASJ,GAAGgB,EAAmB;IACpC,IAAIf,SAASgB,GAAG,CAACD,KAAK;QACpB,OAAO;IACT;IAEAf,SAASiB,GAAG,CAACF;IACbZ;IACA,OAAO;AACT;AAEO,SAASL,IAAIiB,EAAmB;IACrC,IAAIf,SAASgB,GAAG,CAACD,KAAK;QACpBf,SAASkB,MAAM,CAACH;QAChB,OAAO;IACT;IAEA,OAAO;AACT"}

View File

@@ -0,0 +1,12 @@
import type { VersionInfo } from '../../../../server/dev/parse-version-info';
import type { DevIndicatorServerState } from '../../../../server/dev/dev-indicator-server-state';
export declare function register(): void;
export declare function onBuildOk(): void;
export declare function onBuildError(message: string): void;
export declare function onRefresh(): void;
export declare function onBeforeRefresh(): void;
export declare function onVersionInfo(versionInfo: VersionInfo): void;
export declare function onStaticIndicator(isStatic: boolean): void;
export declare function onDevIndicator(devIndicatorsState: DevIndicatorServerState): void;
export { getErrorByType } from '../utils/get-error-by-type';
export { getServerError } from '../utils/node-stack-frames';

View File

@@ -0,0 +1,170 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getErrorByType: null,
getServerError: null,
onBeforeRefresh: null,
onBuildError: null,
onBuildOk: null,
onDevIndicator: null,
onRefresh: null,
onStaticIndicator: null,
onVersionInfo: null,
register: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getErrorByType: function() {
return _geterrorbytype.getErrorByType;
},
getServerError: function() {
return _nodestackframes.getServerError;
},
onBeforeRefresh: function() {
return onBeforeRefresh;
},
onBuildError: function() {
return onBuildError;
},
onBuildOk: function() {
return onBuildOk;
},
onDevIndicator: function() {
return onDevIndicator;
},
onRefresh: function() {
return onRefresh;
},
onStaticIndicator: function() {
return onStaticIndicator;
},
onVersionInfo: function() {
return onVersionInfo;
},
register: function() {
return register;
}
});
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _bus = /*#__PURE__*/ _interop_require_wildcard._(require("./bus"));
const _parsestack = require("../utils/parse-stack");
const _parsecomponentstack = require("../utils/parse-component-stack");
const _hydrationerrorinfo = require("../../errors/hydration-error-info");
const _shared = require("../shared");
const _attachhydrationerrorstate = require("../../errors/attach-hydration-error-state");
const _geterrorbytype = require("../utils/get-error-by-type");
const _nodestackframes = require("../utils/node-stack-frames");
let isRegistered = false;
function handleError(error) {
if (!error || !(error instanceof Error) || typeof error.stack !== 'string') {
// A non-error was thrown, we don't have anything to show. :-(
return;
}
(0, _attachhydrationerrorstate.attachHydrationErrorState)(error);
const componentStackTrace = error._componentStack;
const componentStackFrames = typeof componentStackTrace === 'string' ? (0, _parsecomponentstack.parseComponentStack)(componentStackTrace) : undefined;
// Skip ModuleBuildError and ModuleNotFoundError, as it will be sent through onBuildError callback.
// This is to avoid same error as different type showing up on client to cause flashing.
if (error.name !== 'ModuleBuildError' && error.name !== 'ModuleNotFoundError') {
_bus.emit({
type: _shared.ACTION_UNHANDLED_ERROR,
reason: error,
frames: (0, _parsestack.parseStack)(error.stack),
componentStackFrames
});
}
}
let origConsoleError = console.error;
function nextJsHandleConsoleError() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
// See https://github.com/facebook/react/blob/d50323eb845c5fde0d720cae888bf35dedd05506/packages/react-reconciler/src/ReactFiberErrorLogger.js#L78
const error = process.env.NODE_ENV !== 'production' ? args[1] : args[0];
(0, _hydrationerrorinfo.storeHydrationErrorStateFromConsoleArgs)(...args);
handleError(error);
origConsoleError.apply(window.console, args);
}
function onUnhandledError(event) {
const error = event == null ? void 0 : event.error;
handleError(error);
}
function onUnhandledRejection(ev) {
const reason = ev == null ? void 0 : ev.reason;
if (!reason || !(reason instanceof Error) || typeof reason.stack !== 'string') {
// A non-error was thrown, we don't have anything to show. :-(
return;
}
const e = reason;
_bus.emit({
type: _shared.ACTION_UNHANDLED_REJECTION,
reason: reason,
frames: (0, _parsestack.parseStack)(e.stack)
});
}
function register() {
if (isRegistered) {
return;
}
isRegistered = true;
try {
Error.stackTraceLimit = 50;
} catch (e) {}
window.addEventListener('error', onUnhandledError);
window.addEventListener('unhandledrejection', onUnhandledRejection);
window.console.error = nextJsHandleConsoleError;
}
function onBuildOk() {
_bus.emit({
type: _shared.ACTION_BUILD_OK
});
}
function onBuildError(message) {
_bus.emit({
type: _shared.ACTION_BUILD_ERROR,
message
});
}
function onRefresh() {
_bus.emit({
type: _shared.ACTION_REFRESH
});
}
function onBeforeRefresh() {
_bus.emit({
type: _shared.ACTION_BEFORE_REFRESH
});
}
function onVersionInfo(versionInfo) {
_bus.emit({
type: _shared.ACTION_VERSION_INFO,
versionInfo
});
}
function onStaticIndicator(isStatic) {
_bus.emit({
type: _shared.ACTION_STATIC_INDICATOR,
staticIndicator: isStatic
});
}
function onDevIndicator(devIndicatorsState) {
_bus.emit({
type: _shared.ACTION_DEV_INDICATOR,
devIndicator: devIndicatorsState
});
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=client.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
export declare const usePagesDevOverlay: () => {
state: import("../shared").OverlayState & {
routerType: "pages" | "app";
};
onComponentError: (_error: Error, _componentStack: string | null) => void;
};

View File

@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "usePagesDevOverlay", {
enumerable: true,
get: function() {
return usePagesDevOverlay;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _react = /*#__PURE__*/ _interop_require_default._(require("react"));
const _bus = /*#__PURE__*/ _interop_require_wildcard._(require("./bus"));
const _shared = require("../shared");
const _router = require("../../../router");
const usePagesDevOverlay = ()=>{
const [state, dispatch] = (0, _shared.useErrorOverlayReducer)('pages');
_react.default.useEffect(()=>{
_bus.on(dispatch);
const { handleStaticIndicator } = require('./hot-reloader-client');
_router.Router.events.on('routeChangeComplete', handleStaticIndicator);
return function() {
_router.Router.events.off('routeChangeComplete', handleStaticIndicator);
_bus.off(dispatch);
};
}, [
dispatch
]);
const onComponentError = _react.default.useCallback((_error, _componentStack)=>{
// TODO: special handling
}, []);
return {
state,
onComponentError
};
};
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=hooks.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/pages/hooks.ts"],"sourcesContent":["import React from 'react'\nimport * as Bus from './bus'\nimport { useErrorOverlayReducer } from '../shared'\nimport { Router } from '../../../router'\n\nexport const usePagesDevOverlay = () => {\n const [state, dispatch] = useErrorOverlayReducer('pages')\n\n React.useEffect(() => {\n Bus.on(dispatch)\n\n const { handleStaticIndicator } =\n require('./hot-reloader-client') as typeof import('./hot-reloader-client')\n\n Router.events.on('routeChangeComplete', handleStaticIndicator)\n\n return function () {\n Router.events.off('routeChangeComplete', handleStaticIndicator)\n Bus.off(dispatch)\n }\n }, [dispatch])\n\n const onComponentError = React.useCallback(\n (_error: Error, _componentStack: string | null) => {\n // TODO: special handling\n },\n []\n )\n\n return {\n state,\n onComponentError,\n }\n}\n"],"names":["usePagesDevOverlay","state","dispatch","useErrorOverlayReducer","React","useEffect","Bus","on","handleStaticIndicator","require","Router","events","off","onComponentError","useCallback","_error","_componentStack"],"mappings":";;;;+BAKaA;;;eAAAA;;;;;gEALK;+DACG;wBACkB;wBAChB;AAEhB,MAAMA,qBAAqB;IAChC,MAAM,CAACC,OAAOC,SAAS,GAAGC,IAAAA,8BAAsB,EAAC;IAEjDC,cAAK,CAACC,SAAS,CAAC;QACdC,KAAIC,EAAE,CAACL;QAEP,MAAM,EAAEM,qBAAqB,EAAE,GAC7BC,QAAQ;QAEVC,cAAM,CAACC,MAAM,CAACJ,EAAE,CAAC,uBAAuBC;QAExC,OAAO;YACLE,cAAM,CAACC,MAAM,CAACC,GAAG,CAAC,uBAAuBJ;YACzCF,KAAIM,GAAG,CAACV;QACV;IACF,GAAG;QAACA;KAAS;IAEb,MAAMW,mBAAmBT,cAAK,CAACU,WAAW,CACxC,CAACC,QAAeC;IACd,yBAAyB;IAC3B,GACA,EAAE;IAGJ,OAAO;QACLf;QACAY;IACF;AACF"}

View File

@@ -0,0 +1,38 @@
/**
* MIT License
*
* Copyright (c) 2013-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 type { TurbopackMsgToBrowser } from '../../../../server/dev/hot-reloader-types';
declare global {
interface Window {
__nextDevClientId: number;
}
}
export default function connect(): {
subscribeToHmrEvent(handler: any): void;
onUnrecoverableError(): void;
addTurbopackMessageListener(cb: (msg: TurbopackMsgToBrowser) => void): void;
sendTurbopackMessage(msg: string): void;
handleUpdateError(err: unknown): void;
};
export declare function handleStaticIndicator(): void;
export declare function performFullReload(err: any): void;

View File

@@ -0,0 +1,419 @@
// TODO: Remove use of `any` type. Fix no-use-before-define violations.
/* eslint-disable @typescript-eslint/no-use-before-define */ /**
* MIT License
*
* Copyright (c) 2013-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.
*/ /// <reference types="webpack/module.d.ts" />
// This file is a modified version of the Create React App HMR dev client that
// can be found here:
// https://github.com/facebook/create-react-app/blob/v3.4.1/packages/react-dev-utils/webpackHotDevClient.js
/// <reference types="webpack/module.d.ts" />
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
default: null,
handleStaticIndicator: null,
performFullReload: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
default: function() {
return connect;
},
handleStaticIndicator: function() {
return handleStaticIndicator;
},
performFullReload: function() {
return performFullReload;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _client = require("./client");
const _stripansi = /*#__PURE__*/ _interop_require_default._(require("next/dist/compiled/strip-ansi"));
const _websocket = require("./websocket");
const _formatwebpackmessages = /*#__PURE__*/ _interop_require_default._(require("../utils/format-webpack-messages"));
const _hotreloadertypes = require("../../../../server/dev/hot-reloader-types");
const _shared = require("../shared");
const _runtimeerrorhandler = require("../../errors/runtime-error-handler");
const _reporthmrlatency = /*#__PURE__*/ _interop_require_default._(require("../utils/report-hmr-latency"));
const _turbopackhotreloadercommon = require("../utils/turbopack-hot-reloader-common");
window.__nextDevClientId = Math.round(Math.random() * 100 + Date.now());
let customHmrEventHandler;
let turbopackMessageListeners = [];
function connect() {
(0, _client.register)();
(0, _websocket.addMessageListener)((payload)=>{
if (!('action' in payload)) {
return;
}
try {
processMessage(payload);
} catch (err) {
(0, _shared.reportInvalidHmrMessage)(payload, err);
}
});
return {
subscribeToHmrEvent (handler) {
customHmrEventHandler = handler;
},
onUnrecoverableError () {
_runtimeerrorhandler.RuntimeErrorHandler.hadRuntimeError = true;
},
addTurbopackMessageListener (cb) {
turbopackMessageListeners.push(cb);
},
sendTurbopackMessage (msg) {
(0, _websocket.sendMessage)(msg);
},
handleUpdateError (err) {
performFullReload(err);
}
};
}
// Remember some state related to hot module replacement.
var isFirstCompilation = true;
var mostRecentCompilationHash = null;
var hasCompileErrors = false;
function clearOutdatedErrors() {
// Clean up outdated compile errors, if any.
if (typeof console !== 'undefined' && typeof console.clear === 'function') {
if (hasCompileErrors) {
console.clear();
}
}
}
// Successful compilation.
function handleSuccess() {
clearOutdatedErrors();
hasCompileErrors = false;
if (process.env.TURBOPACK) {
const hmrUpdate = turbopackHmr.onBuilt();
if (hmrUpdate != null) {
(0, _reporthmrlatency.default)(_websocket.sendMessage, [
...hmrUpdate.updatedModules
], hmrUpdate.startMsSinceEpoch, hmrUpdate.endMsSinceEpoch, hmrUpdate.hasUpdates);
}
(0, _client.onBuildOk)();
} else {
const isHotUpdate = !isFirstCompilation || window.__NEXT_DATA__.page !== '/_error' && isUpdateAvailable();
// Attempt to apply hot updates or reload.
if (isHotUpdate) {
tryApplyUpdatesWebpack();
}
}
isFirstCompilation = false;
}
// Compilation with warnings (e.g. ESLint).
function handleWarnings(warnings) {
clearOutdatedErrors();
const isHotUpdate = !isFirstCompilation;
isFirstCompilation = false;
hasCompileErrors = false;
function printWarnings() {
// Print warnings to the console.
const formatted = (0, _formatwebpackmessages.default)({
warnings: warnings,
errors: []
});
if (typeof console !== 'undefined' && typeof console.warn === 'function') {
var _formatted_warnings;
for(let i = 0; i < ((_formatted_warnings = formatted.warnings) == null ? void 0 : _formatted_warnings.length); i++){
if (i === 5) {
console.warn('There were more warnings in other files.\n' + 'You can find a complete log in the terminal.');
break;
}
console.warn((0, _stripansi.default)(formatted.warnings[i]));
}
}
}
printWarnings();
// Attempt to apply hot updates or reload.
if (isHotUpdate) {
tryApplyUpdatesWebpack();
}
}
// Compilation with errors (e.g. syntax error or missing modules).
function handleErrors(errors) {
clearOutdatedErrors();
isFirstCompilation = false;
hasCompileErrors = true;
// "Massage" webpack messages.
var formatted = (0, _formatwebpackmessages.default)({
errors: errors,
warnings: []
});
// Only show the first error.
(0, _client.onBuildError)(formatted.errors[0]);
// Also log them to the console.
if (typeof console !== 'undefined' && typeof console.error === 'function') {
for(var i = 0; i < formatted.errors.length; i++){
console.error((0, _stripansi.default)(formatted.errors[i]));
}
}
// Do not attempt to reload now.
// We will reload on next success instead.
if (process.env.__NEXT_TEST_MODE) {
if (self.__NEXT_HMR_CB) {
self.__NEXT_HMR_CB(formatted.errors[0]);
self.__NEXT_HMR_CB = null;
}
}
}
let webpackStartMsSinceEpoch = null;
const turbopackHmr = process.env.TURBOPACK ? new _turbopackhotreloadercommon.TurbopackHmr() : null;
let isrManifest = {};
// There is a newer version of the code available.
function handleAvailableHash(hash) {
// Update last known compilation hash.
mostRecentCompilationHash = hash;
}
function handleStaticIndicator() {
if (process.env.__NEXT_DEV_INDICATOR) {
var _window_next_router_components__app;
const routeInfo = window.next.router.components[window.next.router.pathname];
const pageComponent = routeInfo == null ? void 0 : routeInfo.Component;
const appComponent = (_window_next_router_components__app = window.next.router.components['/_app']) == null ? void 0 : _window_next_router_components__app.Component;
const isDynamicPage = Boolean(pageComponent == null ? void 0 : pageComponent.getInitialProps) || Boolean(routeInfo == null ? void 0 : routeInfo.__N_SSP);
const hasAppGetInitialProps = Boolean(appComponent == null ? void 0 : appComponent.getInitialProps) && (appComponent == null ? void 0 : appComponent.getInitialProps) !== (appComponent == null ? void 0 : appComponent.origGetInitialProps);
const isPageStatic = window.location.pathname in isrManifest || !isDynamicPage && !hasAppGetInitialProps;
(0, _client.onStaticIndicator)(isPageStatic);
}
}
/** Handles messages from the server for the Pages Router. */ function processMessage(obj) {
if (!('action' in obj)) {
return;
}
switch(obj.action){
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.ISR_MANIFEST:
{
isrManifest = obj.data;
handleStaticIndicator();
break;
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.BUILDING:
{
if (process.env.TURBOPACK) {
turbopackHmr.onBuilding();
} else {
webpackStartMsSinceEpoch = Date.now();
console.log('[Fast Refresh] rebuilding');
}
break;
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.BUILT:
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.SYNC:
{
if (obj.hash) handleAvailableHash(obj.hash);
const { errors, warnings } = obj;
// Is undefined when it's a 'built' event
if ('versionInfo' in obj) (0, _client.onVersionInfo)(obj.versionInfo);
if ('devIndicator' in obj) (0, _client.onDevIndicator)(obj.devIndicator);
const hasErrors = Boolean(errors && errors.length);
if (hasErrors) {
(0, _websocket.sendMessage)(JSON.stringify({
event: 'client-error',
errorCount: errors.length,
clientId: window.__nextDevClientId
}));
return handleErrors(errors);
}
// NOTE: Turbopack does not currently send warnings
const hasWarnings = Boolean(warnings && warnings.length);
if (hasWarnings) {
(0, _websocket.sendMessage)(JSON.stringify({
event: 'client-warning',
warningCount: warnings.length,
clientId: window.__nextDevClientId
}));
return handleWarnings(warnings);
}
(0, _websocket.sendMessage)(JSON.stringify({
event: 'client-success',
clientId: window.__nextDevClientId
}));
return handleSuccess();
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES:
{
turbopackHmr == null ? void 0 : turbopackHmr.onServerComponentChanges();
if (hasCompileErrors || _runtimeerrorhandler.RuntimeErrorHandler.hadRuntimeError) {
window.location.reload();
}
return;
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.SERVER_ERROR:
{
const { errorJSON } = obj;
if (errorJSON) {
const { message, stack } = JSON.parse(errorJSON);
const error = Object.defineProperty(new Error(message), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
error.stack = stack;
handleErrors([
error
]);
}
return;
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED:
{
for (const listener of turbopackMessageListeners){
listener({
type: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED,
data: obj.data
});
}
break;
}
case _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE:
{
turbopackHmr.onTurbopackMessage(obj);
(0, _client.onBeforeRefresh)();
for (const listener of turbopackMessageListeners){
listener({
type: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE,
data: obj.data
});
}
if (_runtimeerrorhandler.RuntimeErrorHandler.hadRuntimeError) {
console.warn(_shared.REACT_REFRESH_FULL_RELOAD_FROM_ERROR);
performFullReload(null);
}
(0, _client.onRefresh)();
break;
}
default:
{
if (customHmrEventHandler) {
customHmrEventHandler(obj);
break;
}
break;
}
}
}
// Is there a newer version of this code available?
function isUpdateAvailable() {
/* globals __webpack_hash__ */ // __webpack_hash__ is the hash of the current compilation.
// It's a global variable injected by Webpack.
return mostRecentCompilationHash !== __webpack_hash__;
}
// Webpack disallows updates in other states.
function canApplyUpdates() {
return module.hot.status() === 'idle';
}
function afterApplyUpdates(fn) {
if (canApplyUpdates()) {
fn();
} else {
function handler(status) {
if (status === 'idle') {
module.hot.removeStatusHandler(handler);
fn();
}
}
module.hot.addStatusHandler(handler);
}
}
// Attempt to update code on the fly, fall back to a hard reload.
function tryApplyUpdatesWebpack() {
if (!module.hot) {
// HotModuleReplacementPlugin is not in Webpack configuration.
console.error('HotModuleReplacementPlugin is not in Webpack configuration.');
// window.location.reload();
return;
}
if (!isUpdateAvailable() || !canApplyUpdates()) {
(0, _client.onBuildOk)();
return;
}
function handleApplyUpdates(err, updatedModules) {
if (err || _runtimeerrorhandler.RuntimeErrorHandler.hadRuntimeError || updatedModules == null) {
if (err) {
console.warn(_shared.REACT_REFRESH_FULL_RELOAD);
} else if (_runtimeerrorhandler.RuntimeErrorHandler.hadRuntimeError) {
console.warn(_shared.REACT_REFRESH_FULL_RELOAD_FROM_ERROR);
}
performFullReload(err);
return;
}
(0, _client.onBuildOk)();
if (isUpdateAvailable()) {
// While we were updating, there was a new update! Do it again.
tryApplyUpdatesWebpack();
return;
}
(0, _client.onRefresh)();
(0, _reporthmrlatency.default)(_websocket.sendMessage, updatedModules, webpackStartMsSinceEpoch, Date.now());
if (process.env.__NEXT_TEST_MODE) {
afterApplyUpdates(()=>{
if (self.__NEXT_HMR_CB) {
self.__NEXT_HMR_CB();
self.__NEXT_HMR_CB = null;
}
});
}
}
// https://webpack.js.org/api/hot-module-replacement/#check
module.hot.check(/* autoApply */ false).then((updatedModules)=>{
if (updatedModules == null) {
return null;
}
// We should always handle an update, even if updatedModules is empty (but
// non-null) for any reason. That's what webpack would normally do:
// https://github.com/webpack/webpack/blob/3aa6b6bc3a64/lib/hmr/HotModuleReplacement.runtime.js#L296-L298
(0, _client.onBeforeRefresh)();
// https://webpack.js.org/api/hot-module-replacement/#apply
return module.hot.apply();
}).then((updatedModules)=>{
handleApplyUpdates(null, updatedModules);
}, (err)=>{
handleApplyUpdates(err, null);
});
}
function performFullReload(err) {
const stackTrace = err && (err.stack && err.stack.split('\n').slice(0, 5).join('\n') || err.message || err + '');
(0, _websocket.sendMessage)(JSON.stringify({
event: 'client-full-reload',
stackTrace,
hadRuntimeError: !!_runtimeerrorhandler.RuntimeErrorHandler.hadRuntimeError,
dependencyChain: err ? err.dependencyChain : undefined
}));
window.location.reload();
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=hot-reloader-client.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,21 @@
import React from 'react';
type PagesDevOverlayErrorBoundaryProps = {
children?: React.ReactNode;
onError: (error: Error, componentStack: string | null) => void;
};
type PagesDevOverlayErrorBoundaryState = {
error: Error | null;
};
export declare class PagesDevOverlayErrorBoundary extends React.PureComponent<PagesDevOverlayErrorBoundaryProps, PagesDevOverlayErrorBoundaryState> {
state: {
error: null;
};
static getDerivedStateFromError(error: Error): {
error: Error;
};
componentDidCatch(error: Error, errorInfo?: {
componentStack?: string | null;
}): void;
render(): React.ReactNode;
}
export {};

View File

@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "PagesDevOverlayErrorBoundary", {
enumerable: true,
get: function() {
return PagesDevOverlayErrorBoundary;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _react = /*#__PURE__*/ _interop_require_default._(require("react"));
class PagesDevOverlayErrorBoundary extends _react.default.PureComponent {
static getDerivedStateFromError(error) {
return {
error
};
}
componentDidCatch(error, // Loosely typed because it depends on the React version and was
// accidentally excluded in some versions.
errorInfo) {
this.props.onError(error, (errorInfo == null ? void 0 : errorInfo.componentStack) || null);
this.setState({
error
});
}
// Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version.
render() {
// The component has to be unmounted or else it would continue to error
return this.state.error ? null : this.props.children;
}
constructor(...args){
super(...args), this.state = {
error: null
};
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=pages-dev-overlay-error-boundary.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/pages/pages-dev-overlay-error-boundary.tsx"],"sourcesContent":["import React from 'react'\n\ntype PagesDevOverlayErrorBoundaryProps = {\n children?: React.ReactNode\n onError: (error: Error, componentStack: string | null) => void\n}\ntype PagesDevOverlayErrorBoundaryState = { error: Error | null }\n\nexport class PagesDevOverlayErrorBoundary extends React.PureComponent<\n PagesDevOverlayErrorBoundaryProps,\n PagesDevOverlayErrorBoundaryState\n> {\n state = { error: null }\n\n static getDerivedStateFromError(error: Error) {\n return { error }\n }\n\n componentDidCatch(\n error: Error,\n // Loosely typed because it depends on the React version and was\n // accidentally excluded in some versions.\n errorInfo?: { componentStack?: string | null }\n ) {\n this.props.onError(error, errorInfo?.componentStack || null)\n this.setState({ error })\n }\n\n // Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version.\n render(): React.ReactNode {\n // The component has to be unmounted or else it would continue to error\n return this.state.error ? null : this.props.children\n }\n}\n"],"names":["PagesDevOverlayErrorBoundary","React","PureComponent","getDerivedStateFromError","error","componentDidCatch","errorInfo","props","onError","componentStack","setState","render","state","children"],"mappings":";;;;+BAQaA;;;eAAAA;;;;gEARK;AAQX,MAAMA,qCAAqCC,cAAK,CAACC,aAAa;IAMnE,OAAOC,yBAAyBC,KAAY,EAAE;QAC5C,OAAO;YAAEA;QAAM;IACjB;IAEAC,kBACED,KAAY,EACZ,gEAAgE;IAChE,0CAA0C;IAC1CE,SAA8C,EAC9C;QACA,IAAI,CAACC,KAAK,CAACC,OAAO,CAACJ,OAAOE,CAAAA,6BAAAA,UAAWG,cAAc,KAAI;QACvD,IAAI,CAACC,QAAQ,CAAC;YAAEN;QAAM;IACxB;IAEA,yIAAyI;IACzIO,SAA0B;QACxB,uEAAuE;QACvE,OAAO,IAAI,CAACC,KAAK,CAACR,KAAK,GAAG,OAAO,IAAI,CAACG,KAAK,CAACM,QAAQ;IACtD;;QAxBK,qBAILD,QAAQ;YAAER,OAAO;QAAK;;AAqBxB"}

View File

@@ -0,0 +1,7 @@
export type ErrorType = 'runtime' | 'build';
export type PagesDevOverlayType = typeof PagesDevOverlay;
interface PagesDevOverlayProps {
children?: React.ReactNode;
}
export declare function PagesDevOverlay({ children }: PagesDevOverlayProps): import("react/jsx-runtime").JSX.Element;
export {};

View File

@@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "PagesDevOverlay", {
enumerable: true,
get: function() {
return PagesDevOverlay;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _react = require("react");
const _pagesdevoverlayerrorboundary = require("./pages-dev-overlay-error-boundary");
const _hooks = require("./hooks");
const _fontstyles = require("../font/font-styles");
const _devoverlay = require("../ui/dev-overlay");
function PagesDevOverlay(param) {
let { children } = param;
const { state, onComponentError } = (0, _hooks.usePagesDevOverlay)();
const [isErrorOverlayOpen, setIsErrorOverlayOpen] = (0, _react.useState)(true);
return /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)(_pagesdevoverlayerrorboundary.PagesDevOverlayErrorBoundary, {
onError: onComponentError,
children: children != null ? children : null
}),
/*#__PURE__*/ (0, _jsxruntime.jsx)(_fontstyles.FontStyles, {}),
/*#__PURE__*/ (0, _jsxruntime.jsx)(_devoverlay.DevOverlay, {
state: state,
isErrorOverlayOpen: isErrorOverlayOpen,
setIsErrorOverlayOpen: setIsErrorOverlayOpen
})
]
});
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=pages-dev-overlay.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/pages/pages-dev-overlay.tsx"],"sourcesContent":["import { useState } from 'react'\nimport { PagesDevOverlayErrorBoundary } from './pages-dev-overlay-error-boundary'\nimport { usePagesDevOverlay } from './hooks'\nimport { FontStyles } from '../font/font-styles'\nimport { DevOverlay } from '../ui/dev-overlay'\n\nexport type ErrorType = 'runtime' | 'build'\n\nexport type PagesDevOverlayType = typeof PagesDevOverlay\n\ninterface PagesDevOverlayProps {\n children?: React.ReactNode\n}\n\nexport function PagesDevOverlay({ children }: PagesDevOverlayProps) {\n const { state, onComponentError } = usePagesDevOverlay()\n\n const [isErrorOverlayOpen, setIsErrorOverlayOpen] = useState(true)\n\n return (\n <>\n <PagesDevOverlayErrorBoundary onError={onComponentError}>\n {children ?? null}\n </PagesDevOverlayErrorBoundary>\n\n {/* Fonts can only be loaded outside the Shadow DOM. */}\n <FontStyles />\n <DevOverlay\n state={state}\n isErrorOverlayOpen={isErrorOverlayOpen}\n setIsErrorOverlayOpen={setIsErrorOverlayOpen}\n />\n </>\n )\n}\n"],"names":["PagesDevOverlay","children","state","onComponentError","usePagesDevOverlay","isErrorOverlayOpen","setIsErrorOverlayOpen","useState","PagesDevOverlayErrorBoundary","onError","FontStyles","DevOverlay"],"mappings":";;;;+BAcgBA;;;eAAAA;;;;uBAdS;8CACoB;uBACV;4BACR;4BACA;AAUpB,SAASA,gBAAgB,KAAkC;IAAlC,IAAA,EAAEC,QAAQ,EAAwB,GAAlC;IAC9B,MAAM,EAAEC,KAAK,EAAEC,gBAAgB,EAAE,GAAGC,IAAAA,yBAAkB;IAEtD,MAAM,CAACC,oBAAoBC,sBAAsB,GAAGC,IAAAA,eAAQ,EAAC;IAE7D,qBACE;;0BACE,qBAACC,0DAA4B;gBAACC,SAASN;0BACpCF,mBAAAA,WAAY;;0BAIf,qBAACS,sBAAU;0BACX,qBAACC,sBAAU;gBACTT,OAAOA;gBACPG,oBAAoBA;gBACpBC,uBAAuBA;;;;AAI/B"}

View File

@@ -0,0 +1,9 @@
import { type HMR_ACTION_TYPES } from '../../../../server/dev/hot-reloader-types';
type ActionCallback = (action: HMR_ACTION_TYPES) => void;
export declare function addMessageListener(callback: ActionCallback): void;
export declare function sendMessage(data: string): void;
export declare function connectHMR(options: {
path: string;
assetPrefix: string;
}): void;
export {};

View File

@@ -0,0 +1,104 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
addMessageListener: null,
connectHMR: null,
sendMessage: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
addMessageListener: function() {
return addMessageListener;
},
connectHMR: function() {
return connectHMR;
},
sendMessage: function() {
return sendMessage;
}
});
const _hotreloadertypes = require("../../../../server/dev/hot-reloader-types");
const _getsocketurl = require("../utils/get-socket-url");
let source;
const eventCallbacks = [];
function addMessageListener(callback) {
eventCallbacks.push(callback);
}
function sendMessage(data) {
if (!source || source.readyState !== source.OPEN) return;
return source.send(data);
}
let reconnections = 0;
let reloading = false;
let serverSessionId = null;
function connectHMR(options) {
function init() {
if (source) source.close();
function handleOnline() {
reconnections = 0;
window.console.log('[HMR] connected');
}
function handleMessage(event) {
// While the page is reloading, don't respond to any more messages.
// On reconnect, the server may send an empty list of changes if it was restarted.
if (reloading) {
return;
}
// Coerce into HMR_ACTION_TYPES as that is the format.
const msg = JSON.parse(event.data);
if ('action' in msg && msg.action === _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED) {
if (serverSessionId !== null && serverSessionId !== msg.data.sessionId) {
// Either the server's session id has changed and it's a new server, or
// it's been too long since we disconnected and we should reload the page.
// There could be 1) unhandled server errors and/or 2) stale content.
// Perform a hard reload of the page.
window.location.reload();
reloading = true;
return;
}
serverSessionId = msg.data.sessionId;
}
for (const eventCallback of eventCallbacks){
eventCallback(msg);
}
}
let timer;
function handleDisconnect() {
source.onerror = null;
source.onclose = null;
source.close();
reconnections++;
// After 25 reconnects we'll want to reload the page as it indicates the dev server is no longer running.
if (reconnections > 25) {
reloading = true;
window.location.reload();
return;
}
clearTimeout(timer);
// Try again after 5 seconds
timer = setTimeout(init, reconnections > 5 ? 5000 : 1000);
}
const url = (0, _getsocketurl.getSocketUrl)(options.assetPrefix);
source = new window.WebSocket("" + url + options.path);
source.onopen = handleOnline;
source.onerror = handleDisconnect;
source.onclose = handleDisconnect;
source.onmessage = handleMessage;
}
init();
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=websocket.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
import type { ServerResponse, IncomingMessage } from 'http';
import type { Telemetry } from '../../../../telemetry/storage';
export declare function getNextErrorFeedbackMiddleware(telemetry: Telemetry): (req: IncomingMessage, res: ServerResponse, next: () => void) => Promise<void>;

View File

@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getNextErrorFeedbackMiddleware", {
enumerable: true,
get: function() {
return getNextErrorFeedbackMiddleware;
}
});
const _errorfeedback = require("../../../../telemetry/events/error-feedback");
const _middlewareresponse = require("./middleware-response");
function getNextErrorFeedbackMiddleware(telemetry) {
return async function(req, res, next) {
const { pathname, searchParams } = new URL("http://n" + req.url);
if (pathname !== '/__nextjs_error_feedback') {
return next();
}
try {
const errorCode = searchParams.get('errorCode');
const wasHelpful = searchParams.get('wasHelpful');
if (!errorCode || !wasHelpful) {
return _middlewareresponse.middlewareResponse.badRequest(res);
}
await telemetry.record((0, _errorfeedback.eventErrorFeedback)({
errorCode,
wasHelpful: wasHelpful === 'true'
}));
return _middlewareresponse.middlewareResponse.noContent(res);
} catch (error) {
return _middlewareresponse.middlewareResponse.internalServerError(res);
}
};
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=get-next-error-feedback-middleware.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/server/get-next-error-feedback-middleware.ts"],"sourcesContent":["import { eventErrorFeedback } from '../../../../telemetry/events/error-feedback'\nimport { middlewareResponse } from './middleware-response'\nimport type { ServerResponse, IncomingMessage } from 'http'\nimport type { Telemetry } from '../../../../telemetry/storage'\n\n// Handles HTTP requests to /__nextjs_error_feedback endpoint for collecting user feedback on error messages\nexport function getNextErrorFeedbackMiddleware(telemetry: Telemetry) {\n return async function (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void\n ): Promise<void> {\n const { pathname, searchParams } = new URL(`http://n${req.url}`)\n\n if (pathname !== '/__nextjs_error_feedback') {\n return next()\n }\n\n try {\n const errorCode = searchParams.get('errorCode')\n const wasHelpful = searchParams.get('wasHelpful')\n\n if (!errorCode || !wasHelpful) {\n return middlewareResponse.badRequest(res)\n }\n\n await telemetry.record(\n eventErrorFeedback({\n errorCode,\n wasHelpful: wasHelpful === 'true',\n })\n )\n\n return middlewareResponse.noContent(res)\n } catch (error) {\n return middlewareResponse.internalServerError(res)\n }\n }\n}\n"],"names":["getNextErrorFeedbackMiddleware","telemetry","req","res","next","pathname","searchParams","URL","url","errorCode","get","wasHelpful","middlewareResponse","badRequest","record","eventErrorFeedback","noContent","error","internalServerError"],"mappings":";;;;+BAMgBA;;;eAAAA;;;+BANmB;oCACA;AAK5B,SAASA,+BAA+BC,SAAoB;IACjE,OAAO,eACLC,GAAoB,EACpBC,GAAmB,EACnBC,IAAgB;QAEhB,MAAM,EAAEC,QAAQ,EAAEC,YAAY,EAAE,GAAG,IAAIC,IAAI,AAAC,aAAUL,IAAIM,GAAG;QAE7D,IAAIH,aAAa,4BAA4B;YAC3C,OAAOD;QACT;QAEA,IAAI;YACF,MAAMK,YAAYH,aAAaI,GAAG,CAAC;YACnC,MAAMC,aAAaL,aAAaI,GAAG,CAAC;YAEpC,IAAI,CAACD,aAAa,CAACE,YAAY;gBAC7B,OAAOC,sCAAkB,CAACC,UAAU,CAACV;YACvC;YAEA,MAAMF,UAAUa,MAAM,CACpBC,IAAAA,iCAAkB,EAAC;gBACjBN;gBACAE,YAAYA,eAAe;YAC7B;YAGF,OAAOC,sCAAkB,CAACI,SAAS,CAACb;QACtC,EAAE,OAAOc,OAAO;YACd,OAAOL,sCAAkB,CAACM,mBAAmB,CAACf;QAChD;IACF;AACF"}

View File

@@ -0,0 +1,10 @@
import type { ServerResponse } from 'http';
export declare const middlewareResponse: {
noContent(res: ServerResponse): void;
badRequest(res: ServerResponse): void;
notFound(res: ServerResponse): void;
methodNotAllowed(res: ServerResponse): void;
internalServerError(res: ServerResponse, error?: unknown): void;
json(res: ServerResponse, data: any): void;
jsonString(res: ServerResponse, data: string): void;
};

View File

@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "middlewareResponse", {
enumerable: true,
get: function() {
return middlewareResponse;
}
});
const _util = require("util");
const middlewareResponse = {
noContent (res) {
res.statusCode = 204;
res.end('No Content');
},
badRequest (res) {
res.statusCode = 400;
res.end('Bad Request');
},
notFound (res) {
res.statusCode = 404;
res.end('Not Found');
},
methodNotAllowed (res) {
res.statusCode = 405;
res.end('Method Not Allowed');
},
internalServerError (res, error) {
res.statusCode = 500;
res.setHeader('Content-Type', 'text/plain');
res.end(error !== undefined ? (0, _util.inspect)(error, {
colors: false
}) : 'Internal Server Error');
},
json (res, data) {
res.setHeader('Content-Type', 'application/json').end(Buffer.from(JSON.stringify(data)));
},
jsonString (res, data) {
res.setHeader('Content-Type', 'application/json').end(Buffer.from(data));
}
};
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=middleware-response.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/server/middleware-response.ts"],"sourcesContent":["import type { ServerResponse } from 'http'\nimport { inspect } from 'util'\n\nexport const middlewareResponse = {\n noContent(res: ServerResponse) {\n res.statusCode = 204\n res.end('No Content')\n },\n badRequest(res: ServerResponse) {\n res.statusCode = 400\n res.end('Bad Request')\n },\n notFound(res: ServerResponse) {\n res.statusCode = 404\n res.end('Not Found')\n },\n methodNotAllowed(res: ServerResponse) {\n res.statusCode = 405\n res.end('Method Not Allowed')\n },\n internalServerError(res: ServerResponse, error?: unknown) {\n res.statusCode = 500\n res.setHeader('Content-Type', 'text/plain')\n res.end(\n error !== undefined\n ? inspect(error, { colors: false })\n : 'Internal Server Error'\n )\n },\n json(res: ServerResponse, data: any) {\n res\n .setHeader('Content-Type', 'application/json')\n .end(Buffer.from(JSON.stringify(data)))\n },\n jsonString(res: ServerResponse, data: string) {\n res.setHeader('Content-Type', 'application/json').end(Buffer.from(data))\n },\n}\n"],"names":["middlewareResponse","noContent","res","statusCode","end","badRequest","notFound","methodNotAllowed","internalServerError","error","setHeader","undefined","inspect","colors","json","data","Buffer","from","JSON","stringify","jsonString"],"mappings":";;;;+BAGaA;;;eAAAA;;;sBAFW;AAEjB,MAAMA,qBAAqB;IAChCC,WAAUC,GAAmB;QAC3BA,IAAIC,UAAU,GAAG;QACjBD,IAAIE,GAAG,CAAC;IACV;IACAC,YAAWH,GAAmB;QAC5BA,IAAIC,UAAU,GAAG;QACjBD,IAAIE,GAAG,CAAC;IACV;IACAE,UAASJ,GAAmB;QAC1BA,IAAIC,UAAU,GAAG;QACjBD,IAAIE,GAAG,CAAC;IACV;IACAG,kBAAiBL,GAAmB;QAClCA,IAAIC,UAAU,GAAG;QACjBD,IAAIE,GAAG,CAAC;IACV;IACAI,qBAAoBN,GAAmB,EAAEO,KAAe;QACtDP,IAAIC,UAAU,GAAG;QACjBD,IAAIQ,SAAS,CAAC,gBAAgB;QAC9BR,IAAIE,GAAG,CACLK,UAAUE,YACNC,IAAAA,aAAO,EAACH,OAAO;YAAEI,QAAQ;QAAM,KAC/B;IAER;IACAC,MAAKZ,GAAmB,EAAEa,IAAS;QACjCb,IACGQ,SAAS,CAAC,gBAAgB,oBAC1BN,GAAG,CAACY,OAAOC,IAAI,CAACC,KAAKC,SAAS,CAACJ;IACpC;IACAK,YAAWlB,GAAmB,EAAEa,IAAY;QAC1Cb,IAAIQ,SAAS,CAAC,gBAAgB,oBAAoBN,GAAG,CAACY,OAAOC,IAAI,CAACF;IACpE;AACF"}

View File

@@ -0,0 +1,4 @@
import type { IncomingMessage, ServerResponse } from 'http';
import type { Project } from '../../../../build/swc/types';
export declare function getOverlayMiddleware(project: Project, projectPath: string): (req: IncomingMessage, res: ServerResponse, next: () => void) => Promise<void>;
export declare function getSourceMapMiddleware(project: Project): (req: IncomingMessage, res: ServerResponse, next: () => void) => Promise<void>;

View File

@@ -0,0 +1,391 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getOverlayMiddleware: null,
getSourceMapMiddleware: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getOverlayMiddleware: function() {
return getOverlayMiddleware;
},
getSourceMapMiddleware: function() {
return getSourceMapMiddleware;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _shared = require("./shared");
const _middlewareresponse = require("./middleware-response");
const _promises = /*#__PURE__*/ _interop_require_wildcard._(require("fs/promises"));
const _path = /*#__PURE__*/ _interop_require_default._(require("path"));
const _url = /*#__PURE__*/ _interop_require_default._(require("url"));
const _launcheditor = require("../utils/launch-editor");
const _sourcemap08 = require("next/dist/compiled/source-map08");
const _getsourcemapfromfile = require("../utils/get-source-map-from-file");
const _nodemodule = require("node:module");
const _nodeurl = require("node:url");
const _nodeutil = require("node:util");
function shouldIgnorePath(modulePath) {
return modulePath.includes('node_modules') || // Only relevant for when Next.js is symlinked e.g. in the Next.js monorepo
modulePath.includes('next/dist') || modulePath.startsWith('node:');
}
const currentSourcesByFile = new Map();
async function batchedTraceSource(project, frame) {
const file = frame.file ? decodeURIComponent(frame.file) : undefined;
if (!file) return;
// For node internals they cannot traced the actual source code with project.traceSource,
// we need an early return to indicate it's ignored to avoid the unknown scheme error from `project.traceSource`.
if (file.startsWith('node:')) {
var _frame_line, _frame_column, _frame_methodName;
return {
frame: {
file,
lineNumber: (_frame_line = frame.line) != null ? _frame_line : 0,
column: (_frame_column = frame.column) != null ? _frame_column : 0,
methodName: (_frame_methodName = frame.methodName) != null ? _frame_methodName : '<unknown>',
ignored: true,
arguments: []
},
source: null
};
}
const currentDirectoryFileUrl = (0, _nodeurl.pathToFileURL)(process.cwd()).href;
const sourceFrame = await project.traceSource(frame, currentDirectoryFileUrl);
if (!sourceFrame) {
var _frame_line1, _frame_column1, _frame_methodName1;
return {
frame: {
file,
lineNumber: (_frame_line1 = frame.line) != null ? _frame_line1 : 0,
column: (_frame_column1 = frame.column) != null ? _frame_column1 : 0,
methodName: (_frame_methodName1 = frame.methodName) != null ? _frame_methodName1 : '<unknown>',
ignored: shouldIgnorePath(file),
arguments: []
},
source: null
};
}
let source = null;
const originalFile = sourceFrame.originalFile;
// Don't look up source for node_modules or internals. These can often be large bundled files.
const ignored = shouldIgnorePath(originalFile != null ? originalFile : sourceFrame.file) || // isInternal means resource starts with turbopack:///[turbopack]
!!sourceFrame.isInternal;
if (originalFile && !ignored) {
let sourcePromise = currentSourcesByFile.get(originalFile);
if (!sourcePromise) {
sourcePromise = project.getSourceForAsset(originalFile);
currentSourcesByFile.set(originalFile, sourcePromise);
setTimeout(()=>{
// Cache file reads for 100ms, as frames will often reference the same
// files and can be large.
currentSourcesByFile.delete(originalFile);
}, 100);
}
source = await sourcePromise;
}
var _sourceFrame_line, _sourceFrame_column, // We ignore the sourcemapped name since it won't be the correct name.
// The callsite will point to the column of the variable name instead of the
// name of the enclosing function.
// TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.
_frame_methodName2;
// TODO: get ignoredList from turbopack source map
const ignorableFrame = {
file: sourceFrame.file,
lineNumber: (_sourceFrame_line = sourceFrame.line) != null ? _sourceFrame_line : 0,
column: (_sourceFrame_column = sourceFrame.column) != null ? _sourceFrame_column : 0,
methodName: (_frame_methodName2 = frame.methodName) != null ? _frame_methodName2 : '<unknown>',
ignored,
arguments: []
};
return {
frame: ignorableFrame,
source
};
}
function parseFile(fileParam) {
if (!fileParam) {
return undefined;
}
// rsc://React/Server/file://<filename>?42 => file://<filename>
return fileParam.replace(/^rsc:\/\/React\/[^/]+\//, '').replace(/\?\d+$/, '');
}
function createStackFrames(body) {
const { frames, isServer } = body;
return frames.map((frame)=>{
const file = parseFile(frame.file);
if (!file) {
return undefined;
}
var _frame_methodName, _frame_lineNumber, _frame_column;
return {
file,
methodName: (_frame_methodName = frame.methodName) != null ? _frame_methodName : '<unknown>',
line: (_frame_lineNumber = frame.lineNumber) != null ? _frame_lineNumber : 0,
column: (_frame_column = frame.column) != null ? _frame_column : 0,
isServer
};
}).filter((f)=>f !== undefined);
}
function createStackFrame(searchParams) {
const file = parseFile(searchParams.get('file'));
if (!file) {
return undefined;
}
var _searchParams_get, _searchParams_get1, _searchParams_get2;
return {
file,
methodName: (_searchParams_get = searchParams.get('methodName')) != null ? _searchParams_get : '<unknown>',
line: parseInt((_searchParams_get1 = searchParams.get('lineNumber')) != null ? _searchParams_get1 : '0', 10) || 0,
column: parseInt((_searchParams_get2 = searchParams.get('column')) != null ? _searchParams_get2 : '0', 10) || 0,
isServer: searchParams.get('isServer') === 'true'
};
}
/**
* Finds the sourcemap payload applicable to a given frame.
* Equal to the input unless an Index Source Map is used.
*/ function findApplicableSourceMapPayload(frame, payload) {
if ('sections' in payload) {
var _frame_line;
const frameLine = (_frame_line = frame.line) != null ? _frame_line : 0;
var _frame_column;
const frameColumn = (_frame_column = frame.column) != null ? _frame_column : 0;
// Sections must not overlap and must be sorted: https://tc39.es/source-map/#section-object
// Therefore the last section that has an offset less than or equal to the frame is the applicable one.
// TODO(veil): Binary search
let section = payload.sections[0];
for(let i = 0; i < payload.sections.length && payload.sections[i].offset.line <= frameLine && payload.sections[i].offset.column <= frameColumn; i++){
section = payload.sections[i];
}
return section === undefined ? undefined : section.map;
} else {
return payload;
}
}
/**
* @returns 1-based lines and 0-based columns
*/ async function nativeTraceSource(frame) {
const sourceURL = decodeURIComponent(frame.file);
let sourceMapPayload;
try {
var _findSourceMap;
sourceMapPayload = (_findSourceMap = (0, _nodemodule.findSourceMap)(sourceURL)) == null ? void 0 : _findSourceMap.payload;
} catch (cause) {
throw Object.defineProperty(new Error("" + sourceURL + ": Invalid source map. Only conformant source maps can be used to find the original code.", {
cause
}), "__NEXT_ERROR_CODE", {
value: "E635",
enumerable: false,
configurable: true
});
}
if (sourceMapPayload !== undefined) {
let consumer;
try {
consumer = await new _sourcemap08.SourceMapConsumer(sourceMapPayload);
} catch (cause) {
throw Object.defineProperty(new Error("" + sourceURL + ": Invalid source map. Only conformant source maps can be used to find the original code.", {
cause
}), "__NEXT_ERROR_CODE", {
value: "E635",
enumerable: false,
configurable: true
});
}
let traced;
try {
var _frame_line, _frame_column;
const originalPosition = consumer.originalPositionFor({
line: (_frame_line = frame.line) != null ? _frame_line : 1,
// 0-based columns out requires 0-based columns in.
column: ((_frame_column = frame.column) != null ? _frame_column : 1) - 1
});
if (originalPosition.source === null) {
traced = null;
} else {
var _consumer_sourceContentFor;
const sourceContent = (_consumer_sourceContentFor = consumer.sourceContentFor(originalPosition.source, /* returnNullOnMissing */ true)) != null ? _consumer_sourceContentFor : null;
traced = {
originalPosition,
sourceContent
};
}
} finally{
consumer.destroy();
}
if (traced !== null) {
var // We ignore the sourcemapped name since it won't be the correct name.
// The callsite will point to the column of the variable name instead of the
// name of the enclosing function.
// TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.
_frame_methodName_replace, _frame_methodName;
const { originalPosition, sourceContent } = traced;
const applicableSourceMap = findApplicableSourceMapPayload(frame, sourceMapPayload);
// TODO(veil): Upstream a method to sourcemap consumer that immediately says if a frame is ignored or not.
let ignored = false;
if (applicableSourceMap === undefined) {
console.error('No applicable source map found in sections for frame', frame);
} else {
var _applicableSourceMap_ignoreList;
// TODO: O(n^2). Consider moving `ignoreList` into a Set
const sourceIndex = applicableSourceMap.sources.indexOf(originalPosition.source);
var _applicableSourceMap_ignoreList_includes;
ignored = (_applicableSourceMap_ignoreList_includes = (_applicableSourceMap_ignoreList = applicableSourceMap.ignoreList) == null ? void 0 : _applicableSourceMap_ignoreList.includes(sourceIndex)) != null ? _applicableSourceMap_ignoreList_includes : // When sourcemap is not available, fallback to checking `frame.file`.
// e.g. In pages router, nextjs server code is not bundled into the page.
shouldIgnorePath(frame.file);
}
var _originalPosition_column, _originalPosition_line;
const originalStackFrame = {
methodName: ((_frame_methodName = frame.methodName) == null ? void 0 : (_frame_methodName_replace = _frame_methodName.replace('__WEBPACK_DEFAULT_EXPORT__', 'default')) == null ? void 0 : _frame_methodName_replace.replace('__webpack_exports__.', '')) || '<unknown>',
column: ((_originalPosition_column = originalPosition.column) != null ? _originalPosition_column : 0) + 1,
file: originalPosition.source,
lineNumber: (_originalPosition_line = originalPosition.line) != null ? _originalPosition_line : 0,
// TODO: c&p from async createOriginalStackFrame but why not frame.arguments?
arguments: [],
ignored
};
return {
frame: originalStackFrame,
source: sourceContent
};
}
}
return undefined;
}
async function createOriginalStackFrame(project, projectPath, frame) {
var _ref;
const traced = (_ref = await nativeTraceSource(frame)) != null ? _ref : // TODO(veil): When would the bundler know more than native?
// If it's faster, try the bundler first and fall back to native later.
await batchedTraceSource(project, frame);
if (!traced) {
return null;
}
let normalizedStackFrameLocation = traced.frame.file;
if (normalizedStackFrameLocation !== null && normalizedStackFrameLocation.startsWith('file://')) {
normalizedStackFrameLocation = _path.default.relative(projectPath, _url.default.fileURLToPath(normalizedStackFrameLocation));
}
return {
originalStackFrame: {
arguments: traced.frame.arguments,
column: traced.frame.column,
file: normalizedStackFrameLocation,
ignored: traced.frame.ignored,
lineNumber: traced.frame.lineNumber,
methodName: traced.frame.methodName
},
originalCodeFrame: (0, _shared.getOriginalCodeFrame)(traced.frame, traced.source)
};
}
function getOverlayMiddleware(project, projectPath) {
return async function(req, res, next) {
const { pathname, searchParams } = new URL(req.url, 'http://n');
if (pathname === '/__nextjs_original-stack-frames') {
if (req.method !== 'POST') {
return _middlewareresponse.middlewareResponse.badRequest(res);
}
const body = await new Promise((resolve, reject)=>{
let data = '';
req.on('data', (chunk)=>{
data += chunk;
});
req.on('end', ()=>resolve(data));
req.on('error', reject);
});
const request = JSON.parse(body);
const stackFrames = createStackFrames(request);
const result = await Promise.all(stackFrames.map(async (frame)=>{
try {
const stackFrame = await createOriginalStackFrame(project, projectPath, frame);
if (stackFrame === null) {
return {
status: 'rejected',
reason: 'Failed to create original stack frame'
};
}
return {
status: 'fulfilled',
value: stackFrame
};
} catch (error) {
return {
status: 'rejected',
reason: (0, _nodeutil.inspect)(error, {
colors: false
})
};
}
}));
return _middlewareresponse.middlewareResponse.json(res, result);
} else if (pathname === '/__nextjs_launch-editor') {
const frame = createStackFrame(searchParams);
if (!frame) return _middlewareresponse.middlewareResponse.badRequest(res);
const fileExists = await _promises.default.access(frame.file, _promises.constants.F_OK).then(()=>true, ()=>false);
if (!fileExists) return _middlewareresponse.middlewareResponse.notFound(res);
try {
var _frame_line, _frame_column;
(0, _launcheditor.launchEditor)(frame.file, (_frame_line = frame.line) != null ? _frame_line : 1, (_frame_column = frame.column) != null ? _frame_column : 1);
} catch (err) {
console.log('Failed to launch editor:', err);
return _middlewareresponse.middlewareResponse.internalServerError(res);
}
return _middlewareresponse.middlewareResponse.noContent(res);
}
return next();
};
}
function getSourceMapMiddleware(project) {
return async function(req, res, next) {
const { pathname, searchParams } = new URL(req.url, 'http://n');
if (pathname !== '/__nextjs_source-map') {
return next();
}
let filename = searchParams.get('filename');
if (!filename) {
return _middlewareresponse.middlewareResponse.badRequest(res);
}
// TODO(veil): Always try the native version first.
// Externals could also be files that aren't bundled via Webpack.
if (filename.startsWith('webpack://') || filename.startsWith('webpack-internal:///')) {
const sourceMap = (0, _nodemodule.findSourceMap)(filename);
if (sourceMap) {
return _middlewareresponse.middlewareResponse.json(res, sourceMap.payload);
}
return _middlewareresponse.middlewareResponse.noContent(res);
}
try {
// Turbopack chunk filenames might be URL-encoded.
filename = decodeURI(filename);
if (_path.default.isAbsolute(filename)) {
filename = _url.default.pathToFileURL(filename).href;
}
const sourceMapString = await project.getSourceMap(filename);
if (sourceMapString) {
return _middlewareresponse.middlewareResponse.jsonString(res, sourceMapString);
}
if (filename.startsWith('file:')) {
const sourceMap = await (0, _getsourcemapfromfile.getSourceMapFromFile)(filename);
if (sourceMap) {
return _middlewareresponse.middlewareResponse.json(res, sourceMap);
}
}
} catch (error) {
console.error('Failed to get source map:', error);
}
_middlewareresponse.middlewareResponse.noContent(res);
};
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=middleware-turbopack.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,49 @@
import type { StackFrame } from 'next/dist/compiled/stacktrace-parser';
import { getSourceMapFromFile } from '../utils/get-source-map-from-file';
import { type OriginalStackFrameResponse } from './shared';
export { getServerError } from '../utils/node-stack-frames';
export { parseStack } from '../utils/parse-stack';
export { getSourceMapFromFile };
import type { IncomingMessage, ServerResponse } from 'http';
import type webpack from 'webpack';
import type { RawSourceMap } from 'next/dist/compiled/source-map08';
type IgnoredSources = Array<{
url: string;
ignored: boolean;
}>;
export interface IgnorableStackFrame extends StackFrame {
ignored: boolean;
}
type Source = {
type: 'file';
sourceMap: RawSourceMap;
ignoredSources: IgnoredSources;
moduleURL: string;
} | {
type: 'bundle';
sourceMap: RawSourceMap;
ignoredSources: IgnoredSources;
compilation: webpack.Compilation;
moduleId: string;
moduleURL: string;
};
export declare function getIgnoredSources(sourceMap: RawSourceMap & {
ignoreList?: number[];
}): IgnoredSources;
export declare function createOriginalStackFrame({ source, rootDirectory, frame, errorMessage, }: {
source: Source;
rootDirectory: string;
frame: StackFrame;
errorMessage?: string;
}): Promise<OriginalStackFrameResponse | null>;
export declare function getOverlayMiddleware(options: {
rootDirectory: string;
clientStats: () => webpack.Stats | null;
serverStats: () => webpack.Stats | null;
edgeServerStats: () => webpack.Stats | null;
}): (req: IncomingMessage, res: ServerResponse, next: () => void) => Promise<void>;
export declare function getSourceMapMiddleware(options: {
clientStats: () => webpack.Stats | null;
serverStats: () => webpack.Stats | null;
edgeServerStats: () => webpack.Stats | null;
}): (req: IncomingMessage, res: ServerResponse, next: () => void) => Promise<void>;

View File

@@ -0,0 +1,488 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
createOriginalStackFrame: null,
getIgnoredSources: null,
getOverlayMiddleware: null,
getServerError: null,
getSourceMapFromFile: null,
getSourceMapMiddleware: null,
parseStack: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
createOriginalStackFrame: function() {
return createOriginalStackFrame;
},
getIgnoredSources: function() {
return getIgnoredSources;
},
getOverlayMiddleware: function() {
return getOverlayMiddleware;
},
getServerError: function() {
return _nodestackframes.getServerError;
},
getSourceMapFromFile: function() {
return _getsourcemapfromfile.getSourceMapFromFile;
},
getSourceMapMiddleware: function() {
return getSourceMapMiddleware;
},
parseStack: function() {
return _parsestack.parseStack;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _fs = require("fs");
const _module = require("module");
const _path = /*#__PURE__*/ _interop_require_default._(require("path"));
const _url = require("url");
const _sourcemap08 = require("next/dist/compiled/source-map08");
const _getsourcemapfromfile = require("../utils/get-source-map-from-file");
const _launcheditor = require("../utils/launch-editor");
const _shared = require("./shared");
const _middlewareresponse = require("./middleware-response");
const _nodestackframes = require("../utils/node-stack-frames");
const _parsestack = require("../utils/parse-stack");
const _webpackmodulepath = require("../utils/webpack-module-path");
const _util = require("util");
function shouldIgnoreSource(sourceURL) {
return sourceURL.includes('node_modules') || // Only relevant for when Next.js is symlinked e.g. in the Next.js monorepo
sourceURL.includes('next/dist') || sourceURL.startsWith('node:');
}
function getModuleById(id, compilation) {
const { chunkGraph, modules } = compilation;
return [
...modules
].find((module1)=>chunkGraph.getModuleId(module1) === id);
}
function findModuleNotFoundFromError(errorMessage) {
var _errorMessage_match;
return errorMessage == null ? void 0 : (_errorMessage_match = errorMessage.match(/'([^']+)' module/)) == null ? void 0 : _errorMessage_match[1];
}
function getSourcePath(source) {
if (source.startsWith('file://')) {
return (0, _url.fileURLToPath)(source);
}
return source.replace(/^(webpack:\/\/\/|webpack:\/\/|webpack:\/\/_N_E\/)/, '');
}
/**
* @returns 1-based lines and 0-based columns
*/ async function findOriginalSourcePositionAndContent(sourceMap, position) {
let consumer;
try {
consumer = await new _sourcemap08.SourceMapConsumer(sourceMap);
} catch (cause) {
throw Object.defineProperty(new Error("" + sourceMap.file + ": Invalid source map. Only conformant source maps can be used to find the original code.", {
cause
}), "__NEXT_ERROR_CODE", {
value: "E635",
enumerable: false,
configurable: true
});
}
try {
var _position_lineNumber, _position_column;
const sourcePosition = consumer.originalPositionFor({
line: (_position_lineNumber = position.lineNumber) != null ? _position_lineNumber : 1,
// 0-based columns out requires 0-based columns in.
column: ((_position_column = position.column) != null ? _position_column : 1) - 1
});
if (!sourcePosition.source) {
return null;
}
var _consumer_sourceContentFor;
const sourceContent = (_consumer_sourceContentFor = consumer.sourceContentFor(sourcePosition.source, /* returnNullOnMissing */ true)) != null ? _consumer_sourceContentFor : null;
return {
sourcePosition,
sourceContent
};
} finally{
consumer.destroy();
}
}
function getIgnoredSources(sourceMap) {
var _sourceMap_ignoreList;
const ignoreList = new Set((_sourceMap_ignoreList = sourceMap.ignoreList) != null ? _sourceMap_ignoreList : []);
var _sourceMap_sources;
const moduleFilenames = (_sourceMap_sources = sourceMap == null ? void 0 : sourceMap.sources) != null ? _sourceMap_sources : [];
for(let index = 0; index < moduleFilenames.length; index++){
// bundlerFilePath case: webpack://./app/page.tsx
const webpackSourceURL = moduleFilenames[index];
// Format the path to the normal file path
const formattedFilePath = (0, _webpackmodulepath.formatFrameSourceFile)(webpackSourceURL);
if (shouldIgnoreSource(formattedFilePath)) {
ignoreList.add(index);
}
}
const ignoredSources = sourceMap.sources.map((source, index)=>{
var _sourceMap_sourcesContent;
var _sourceMap_sourcesContent_index;
return {
url: source,
ignored: ignoreList.has(sourceMap.sources.indexOf(source)),
content: (_sourceMap_sourcesContent_index = (_sourceMap_sourcesContent = sourceMap.sourcesContent) == null ? void 0 : _sourceMap_sourcesContent[index]) != null ? _sourceMap_sourcesContent_index : null
};
});
return ignoredSources;
}
function isIgnoredSource(source, sourcePosition) {
if (sourcePosition.source == null) {
return true;
}
for (const ignoredSource of source.ignoredSources){
if (ignoredSource.ignored && ignoredSource.url === sourcePosition.source) {
return true;
}
}
return false;
}
function findOriginalSourcePositionAndContentFromCompilation(moduleId, importedModule, compilation) {
var _module_buildInfo_importLocByPath, _module_buildInfo;
const module1 = getModuleById(moduleId, compilation);
var _module_buildInfo_importLocByPath_get;
return (_module_buildInfo_importLocByPath_get = module1 == null ? void 0 : (_module_buildInfo = module1.buildInfo) == null ? void 0 : (_module_buildInfo_importLocByPath = _module_buildInfo.importLocByPath) == null ? void 0 : _module_buildInfo_importLocByPath.get(importedModule)) != null ? _module_buildInfo_importLocByPath_get : null;
}
async function createOriginalStackFrame(param) {
let { source, rootDirectory, frame, errorMessage } = param;
var // We ignore the sourcemapped name since it won't be the correct name.
// The callsite will point to the column of the variable name instead of the
// name of the enclosing function.
// TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.
// default is not a valid identifier in JS so webpack uses a custom variable when it's an unnamed default export
// Resolve it back to `default` for the method name if the source position didn't have the method.
_frame_methodName_replace, _frame_methodName;
const moduleNotFound = findModuleNotFoundFromError(errorMessage);
const result = await (()=>{
if (moduleNotFound) {
if (source.type === 'file') {
return undefined;
}
return findOriginalSourcePositionAndContentFromCompilation(source.moduleId, moduleNotFound, source.compilation);
}
return findOriginalSourcePositionAndContent(source.sourceMap, frame);
})();
if (!result) {
return null;
}
const { sourcePosition, sourceContent } = result;
if (!sourcePosition.source) {
return null;
}
const ignored = isIgnoredSource(source, sourcePosition) || // If the source file is externals, should be excluded even it's not ignored source.
// e.g. webpack://next/dist/.. needs to be ignored
shouldIgnoreSource(source.moduleURL);
const sourcePath = getSourcePath(// When sourcePosition.source is the loader path the modulePath is generally better.
(sourcePosition.source.includes('|') ? source.moduleURL : sourcePosition.source) || source.moduleURL);
const filePath = _path.default.resolve(rootDirectory, sourcePath);
const resolvedFilePath = _path.default.relative(rootDirectory, filePath);
var _sourcePosition_column;
const traced = {
file: resolvedFilePath,
lineNumber: sourcePosition.line,
column: ((_sourcePosition_column = sourcePosition.column) != null ? _sourcePosition_column : 0) + 1,
methodName: (_frame_methodName = frame.methodName) == null ? void 0 : (_frame_methodName_replace = _frame_methodName.replace('__WEBPACK_DEFAULT_EXPORT__', 'default')) == null ? void 0 : _frame_methodName_replace.replace('__webpack_exports__.', ''),
arguments: [],
ignored
};
return {
originalStackFrame: traced,
originalCodeFrame: (0, _shared.getOriginalCodeFrame)(traced, sourceContent)
};
}
async function getSourceMapFromCompilation(id, compilation) {
try {
const module1 = getModuleById(id, compilation);
if (!module1) {
return undefined;
}
// @ts-expect-error The types for `CodeGenerationResults.get` require a
// runtime to be passed as second argument, but apparently it also works
// without it.
const codeGenerationResult = compilation.codeGenerationResults.get(module1);
const source = codeGenerationResult == null ? void 0 : codeGenerationResult.sources.get('javascript');
var _source_map;
return (_source_map = source == null ? void 0 : source.map()) != null ? _source_map : undefined;
} catch (err) {
console.error('Failed to lookup module by ID ("' + id + '"):', err);
return undefined;
}
}
async function getSource(sourceURL, options) {
const { getCompilations } = options;
// Rspack is now using file:// URLs for source maps. Remove the rsc prefix to produce the file:/// url.
sourceURL = sourceURL.replace(/(.*)\/(?=file:\/\/)/, '');
let nativeSourceMap;
try {
nativeSourceMap = (0, _module.findSourceMap)(sourceURL);
} catch (cause) {
throw Object.defineProperty(new Error("" + sourceURL + ": Invalid source map. Only conformant source maps can be used to find the original code.", {
cause
}), "__NEXT_ERROR_CODE", {
value: "E635",
enumerable: false,
configurable: true
});
}
if (nativeSourceMap !== undefined) {
const sourceMapPayload = nativeSourceMap.payload;
return {
type: 'file',
sourceMap: sourceMapPayload,
ignoredSources: getIgnoredSources(sourceMapPayload),
moduleURL: sourceURL
};
}
if (_path.default.isAbsolute(sourceURL)) {
sourceURL = (0, _url.pathToFileURL)(sourceURL).href;
}
if (sourceURL.startsWith('file:')) {
const sourceMap = await (0, _getsourcemapfromfile.getSourceMapFromFile)(sourceURL);
return sourceMap ? {
type: 'file',
sourceMap,
ignoredSources: getIgnoredSources(sourceMap),
moduleURL: sourceURL
} : undefined;
}
// webpack-internal:///./src/hello.tsx => ./src/hello.tsx
// rsc://React/Server/webpack-internal:///(rsc)/./src/hello.tsx?42 => (rsc)/./src/hello.tsx
// webpack://_N_E/./src/hello.tsx => ./src/hello.tsx
const moduleId = sourceURL.replace(/^(rsc:\/\/React\/[^/]+\/)?(webpack-internal:\/\/\/|webpack:\/\/(_N_E\/)?)/, '').replace(/\?\d+$/, '');
// (rsc)/./src/hello.tsx => ./src/hello.tsx
const moduleURL = moduleId.replace(/^(\(.*\)\/?)/, '');
for (const compilation of getCompilations()){
const sourceMap = await getSourceMapFromCompilation(moduleId, compilation);
if (sourceMap) {
const ignoredSources = getIgnoredSources(sourceMap);
return {
type: 'bundle',
sourceMap,
compilation,
moduleId,
moduleURL,
ignoredSources
};
}
}
return undefined;
}
function getOriginalStackFrames(param) {
let { isServer, isEdgeServer, isAppDirectory, frames, clientStats, serverStats, edgeServerStats, rootDirectory } = param;
return Promise.all(frames.map((frame)=>getOriginalStackFrame({
isServer,
isEdgeServer,
isAppDirectory,
frame,
clientStats,
serverStats,
edgeServerStats,
rootDirectory
}).then((value)=>{
return {
status: 'fulfilled',
value
};
}, (reason)=>{
return {
status: 'rejected',
reason: (0, _util.inspect)(reason, {
colors: false
})
};
})));
}
async function getOriginalStackFrame(param) {
let { isServer, isEdgeServer, isAppDirectory, frame, clientStats, serverStats, edgeServerStats, rootDirectory } = param;
var _frame_file;
const filename = (_frame_file = frame.file) != null ? _frame_file : '';
const source = await getSource(filename, {
getCompilations: ()=>{
const compilations = [];
// Try Client Compilation first. In `pages` we leverage
// `isClientError` to check. In `app` it depends on if it's a server
// / client component and when the code throws. E.g. during HTML
// rendering it's the server/edge compilation.
if (!isEdgeServer && !isServer || isAppDirectory) {
var _clientStats;
const compilation = (_clientStats = clientStats()) == null ? void 0 : _clientStats.compilation;
if (compilation) {
compilations.push(compilation);
}
}
// Try Server Compilation. In `pages` this could be something
// imported in getServerSideProps/getStaticProps as the code for
// those is tree-shaken. In `app` this finds server components and
// code that was imported from a server component. It also covers
// when client component code throws during HTML rendering.
if (isServer || isAppDirectory) {
var _serverStats;
const compilation = (_serverStats = serverStats()) == null ? void 0 : _serverStats.compilation;
if (compilation) {
compilations.push(compilation);
}
}
// Try Edge Server Compilation. Both cases are the same as Server
// Compilation, main difference is that it covers `runtime: 'edge'`
// pages/app routes.
if (isEdgeServer || isAppDirectory) {
var _edgeServerStats;
const compilation = (_edgeServerStats = edgeServerStats()) == null ? void 0 : _edgeServerStats.compilation;
if (compilation) {
compilations.push(compilation);
}
}
return compilations;
}
});
let defaultNormalizedStackFrameLocation = frame.file;
if (defaultNormalizedStackFrameLocation !== null && defaultNormalizedStackFrameLocation.startsWith('file://')) {
defaultNormalizedStackFrameLocation = _path.default.relative(rootDirectory, (0, _url.fileURLToPath)(defaultNormalizedStackFrameLocation));
}
var _frame_column;
// This stack frame is used for the one that couldn't locate the source or source mapped frame
const defaultStackFrame = {
file: defaultNormalizedStackFrameLocation,
lineNumber: frame.lineNumber,
column: (_frame_column = frame.column) != null ? _frame_column : 1,
methodName: frame.methodName,
ignored: shouldIgnoreSource(filename),
arguments: []
};
if (!source) {
// return original stack frame with no source map
return {
originalStackFrame: defaultStackFrame,
originalCodeFrame: null
};
}
const originalStackFrameResponse = await createOriginalStackFrame({
frame,
source,
rootDirectory
});
if (!originalStackFrameResponse) {
return {
originalStackFrame: defaultStackFrame,
originalCodeFrame: null
};
}
return originalStackFrameResponse;
}
function getOverlayMiddleware(options) {
const { rootDirectory, clientStats, serverStats, edgeServerStats } = options;
return async function(req, res, next) {
const { pathname, searchParams } = new URL("http://n" + req.url);
if (pathname === '/__nextjs_original-stack-frames') {
if (req.method !== 'POST') {
return _middlewareresponse.middlewareResponse.badRequest(res);
}
const body = await new Promise((resolve, reject)=>{
let data = '';
req.on('data', (chunk)=>{
data += chunk;
});
req.on('end', ()=>resolve(data));
req.on('error', reject);
});
try {
const { frames, isServer, isEdgeServer, isAppDirectory } = JSON.parse(body);
return _middlewareresponse.middlewareResponse.json(res, await getOriginalStackFrames({
isServer,
isEdgeServer,
isAppDirectory,
frames: frames.map((frame)=>{
var _frame_lineNumber, _frame_column;
return {
...frame,
lineNumber: (_frame_lineNumber = frame.lineNumber) != null ? _frame_lineNumber : 0,
column: (_frame_column = frame.column) != null ? _frame_column : 0
};
}),
clientStats,
serverStats,
edgeServerStats,
rootDirectory
}));
} catch (err) {
return _middlewareresponse.middlewareResponse.badRequest(res);
}
} else if (pathname === '/__nextjs_launch-editor') {
var _searchParams_get, _searchParams_get1;
const frame = {
file: searchParams.get('file'),
methodName: searchParams.get('methodName'),
lineNumber: parseInt((_searchParams_get = searchParams.get('lineNumber')) != null ? _searchParams_get : '0', 10) || 0,
column: parseInt((_searchParams_get1 = searchParams.get('column')) != null ? _searchParams_get1 : '0', 10) || 0,
arguments: searchParams.getAll('arguments').filter(Boolean)
};
if (!frame.file) return _middlewareresponse.middlewareResponse.badRequest(res);
// frame files may start with their webpack layer, like (middleware)/middleware.js
const filePath = _path.default.resolve(rootDirectory, frame.file.replace(/^\([^)]+\)\//, ''));
const fileExists = await _fs.promises.access(filePath, _fs.constants.F_OK).then(()=>true, ()=>false);
if (!fileExists) return _middlewareresponse.middlewareResponse.notFound(res);
try {
var _frame_column;
(0, _launcheditor.launchEditor)(filePath, frame.lineNumber, (_frame_column = frame.column) != null ? _frame_column : 1);
} catch (err) {
console.log('Failed to launch editor:', err);
return _middlewareresponse.middlewareResponse.internalServerError(res);
}
return _middlewareresponse.middlewareResponse.noContent(res);
}
return next();
};
}
function getSourceMapMiddleware(options) {
const { clientStats, serverStats, edgeServerStats } = options;
return async function(req, res, next) {
const { pathname, searchParams } = new URL("http://n" + req.url);
if (pathname !== '/__nextjs_source-map') {
return next();
}
const filename = searchParams.get('filename');
if (!filename) {
return _middlewareresponse.middlewareResponse.badRequest(res);
}
let source;
try {
source = await getSource(filename, {
getCompilations: ()=>{
const compilations = [];
for (const stats of [
clientStats(),
serverStats(),
edgeServerStats()
]){
if (stats == null ? void 0 : stats.compilation) {
compilations.push(stats.compilation);
}
}
return compilations;
}
});
} catch (error) {
return _middlewareresponse.middlewareResponse.internalServerError(res, error);
}
if (!source) {
return _middlewareresponse.middlewareResponse.noContent(res);
}
return _middlewareresponse.middlewareResponse.json(res, source.sourceMap);
};
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=middleware-webpack.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,20 @@
import type { StackFrame } from 'stacktrace-parser';
export interface OriginalStackFramesRequest {
frames: StackFrame[];
isServer: boolean;
isEdgeServer: boolean;
isAppDirectory: boolean;
}
export type OriginalStackFramesResponse = OriginalStackFrameResponseResult[];
export type OriginalStackFrameResponseResult = PromiseSettledResult<OriginalStackFrameResponse>;
export interface OriginalStackFrameResponse {
originalStackFrame?: (StackFrame & {
ignored: boolean;
}) | null;
originalCodeFrame?: string | null;
}
/**
* It looks up the code frame of the traced source.
* @note It ignores Next.js/React internals, as these can often be huge bundled files.
*/
export declare function getOriginalCodeFrame(frame: StackFrame, source: string | null, colors?: boolean): string | null;

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getOriginalCodeFrame", {
enumerable: true,
get: function() {
return getOriginalCodeFrame;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _codeframe = require("next/dist/compiled/babel/code-frame");
const _isinternal = /*#__PURE__*/ _interop_require_default._(require("../../../../shared/lib/is-internal"));
function getOriginalCodeFrame(frame, source, colors) {
if (colors === void 0) colors = process.stdout.isTTY;
if (!source || (0, _isinternal.default)(frame.file)) {
return null;
}
var _frame_lineNumber, _frame_column;
return (0, _codeframe.codeFrameColumns)(source, {
start: {
// 1-based, but -1 means start line without highlighting
line: (_frame_lineNumber = frame.lineNumber) != null ? _frame_lineNumber : -1,
// 1-based, but 0 means whole line without column highlighting
column: (_frame_column = frame.column) != null ? _frame_column : 0
}
}, {
forceColor: colors
});
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=shared.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/server/shared.ts"],"sourcesContent":["import type { StackFrame } from 'stacktrace-parser'\nimport { codeFrameColumns } from 'next/dist/compiled/babel/code-frame'\nimport isInternal from '../../../../shared/lib/is-internal'\n\nexport interface OriginalStackFramesRequest {\n frames: StackFrame[]\n isServer: boolean\n isEdgeServer: boolean\n isAppDirectory: boolean\n}\n\nexport type OriginalStackFramesResponse = OriginalStackFrameResponseResult[]\n\nexport type OriginalStackFrameResponseResult =\n PromiseSettledResult<OriginalStackFrameResponse>\n\nexport interface OriginalStackFrameResponse {\n originalStackFrame?: (StackFrame & { ignored: boolean }) | null\n originalCodeFrame?: string | null\n}\n\n/**\n * It looks up the code frame of the traced source.\n * @note It ignores Next.js/React internals, as these can often be huge bundled files.\n */\nexport function getOriginalCodeFrame(\n frame: StackFrame,\n source: string | null,\n colors: boolean = process.stdout.isTTY\n): string | null {\n if (!source || isInternal(frame.file)) {\n return null\n }\n\n return codeFrameColumns(\n source,\n {\n start: {\n // 1-based, but -1 means start line without highlighting\n line: frame.lineNumber ?? -1,\n // 1-based, but 0 means whole line without column highlighting\n column: frame.column ?? 0,\n },\n },\n { forceColor: colors }\n )\n}\n"],"names":["getOriginalCodeFrame","frame","source","colors","process","stdout","isTTY","isInternal","file","codeFrameColumns","start","line","lineNumber","column","forceColor"],"mappings":";;;;+BAyBgBA;;;eAAAA;;;;2BAxBiB;qEACV;AAuBhB,SAASA,qBACdC,KAAiB,EACjBC,MAAqB,EACrBC,MAAsC;IAAtCA,IAAAA,mBAAAA,SAAkBC,QAAQC,MAAM,CAACC,KAAK;IAEtC,IAAI,CAACJ,UAAUK,IAAAA,mBAAU,EAACN,MAAMO,IAAI,GAAG;QACrC,OAAO;IACT;QAOYP,mBAEEA;IAPd,OAAOQ,IAAAA,2BAAgB,EACrBP,QACA;QACEQ,OAAO;YACL,wDAAwD;YACxDC,MAAMV,CAAAA,oBAAAA,MAAMW,UAAU,YAAhBX,oBAAoB,CAAC;YAC3B,8DAA8D;YAC9DY,QAAQZ,CAAAA,gBAAAA,MAAMY,MAAM,YAAZZ,gBAAgB;QAC1B;IACF,GACA;QAAEa,YAAYX;IAAO;AAEzB"}

View File

@@ -0,0 +1,92 @@
import type { StackFrame } from 'next/dist/compiled/stacktrace-parser';
import type { VersionInfo } from '../../../server/dev/parse-version-info';
import type { SupportedErrorEvent } from './ui/container/runtime-error/render-error';
import type { ComponentStackFrame } from './utils/parse-component-stack';
import type { DebugInfo } from './types';
import type { DevIndicatorServerState } from '../../../server/dev/dev-indicator-server-state';
import type { HMR_ACTION_TYPES } from '../../../server/dev/hot-reloader-types';
type FastRefreshState =
/** No refresh in progress. */
{
type: 'idle';
}
/** The refresh process has been triggered, but the new code has not been executed yet. */
| {
type: 'pending';
errors: SupportedErrorEvent[];
};
export interface OverlayState {
nextId: number;
buildError: string | null;
errors: SupportedErrorEvent[];
refreshState: FastRefreshState;
versionInfo: VersionInfo;
notFound: boolean;
staticIndicator: boolean;
showIndicator: boolean;
disableDevIndicator: boolean;
debugInfo: DebugInfo;
routerType: 'pages' | 'app';
}
export declare const ACTION_STATIC_INDICATOR = "static-indicator";
export declare const ACTION_BUILD_OK = "build-ok";
export declare const ACTION_BUILD_ERROR = "build-error";
export declare const ACTION_BEFORE_REFRESH = "before-fast-refresh";
export declare const ACTION_REFRESH = "fast-refresh";
export declare const ACTION_VERSION_INFO = "version-info";
export declare const ACTION_UNHANDLED_ERROR = "unhandled-error";
export declare const ACTION_UNHANDLED_REJECTION = "unhandled-rejection";
export declare const ACTION_DEBUG_INFO = "debug-info";
export declare const ACTION_DEV_INDICATOR = "dev-indicator";
export declare const STORAGE_KEY_THEME = "__nextjs-dev-tools-theme";
export declare const STORAGE_KEY_POSITION = "__nextjs-dev-tools-position";
export declare const STORAGE_KEY_SCALE = "__nextjs-dev-tools-scale";
interface StaticIndicatorAction {
type: typeof ACTION_STATIC_INDICATOR;
staticIndicator: boolean;
}
interface BuildOkAction {
type: typeof ACTION_BUILD_OK;
}
interface BuildErrorAction {
type: typeof ACTION_BUILD_ERROR;
message: string;
}
interface BeforeFastRefreshAction {
type: typeof ACTION_BEFORE_REFRESH;
}
interface FastRefreshAction {
type: typeof ACTION_REFRESH;
}
export interface UnhandledErrorAction {
type: typeof ACTION_UNHANDLED_ERROR;
reason: Error;
frames: StackFrame[];
componentStackFrames?: ComponentStackFrame[];
}
export interface UnhandledRejectionAction {
type: typeof ACTION_UNHANDLED_REJECTION;
reason: Error;
frames: StackFrame[];
}
export interface DebugInfoAction {
type: typeof ACTION_DEBUG_INFO;
debugInfo: any;
}
interface VersionInfoAction {
type: typeof ACTION_VERSION_INFO;
versionInfo: VersionInfo;
}
interface DevIndicatorAction {
type: typeof ACTION_DEV_INDICATOR;
devIndicator: DevIndicatorServerState;
}
export type BusEvent = BuildOkAction | BuildErrorAction | BeforeFastRefreshAction | FastRefreshAction | UnhandledErrorAction | UnhandledRejectionAction | VersionInfoAction | StaticIndicatorAction | DebugInfoAction | DevIndicatorAction;
export declare const INITIAL_OVERLAY_STATE: Omit<OverlayState, 'routerType'>;
export declare function useErrorOverlayReducer(routerType: 'pages' | 'app'): [OverlayState & {
routerType: "pages" | "app";
}, import("react").ActionDispatch<[action: BusEvent]>];
export declare const REACT_REFRESH_FULL_RELOAD: string;
export declare const REACT_REFRESH_FULL_RELOAD_FROM_ERROR = "[Fast Refresh] performing full reload because your application had an unrecoverable error";
export declare function reportInvalidHmrMessage(message: HMR_ACTION_TYPES | MessageEvent<unknown>, err: unknown): void;
export {};

View File

@@ -0,0 +1,266 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
ACTION_BEFORE_REFRESH: null,
ACTION_BUILD_ERROR: null,
ACTION_BUILD_OK: null,
ACTION_DEBUG_INFO: null,
ACTION_DEV_INDICATOR: null,
ACTION_REFRESH: null,
ACTION_STATIC_INDICATOR: null,
ACTION_UNHANDLED_ERROR: null,
ACTION_UNHANDLED_REJECTION: null,
ACTION_VERSION_INFO: null,
INITIAL_OVERLAY_STATE: null,
REACT_REFRESH_FULL_RELOAD: null,
REACT_REFRESH_FULL_RELOAD_FROM_ERROR: null,
STORAGE_KEY_POSITION: null,
STORAGE_KEY_SCALE: null,
STORAGE_KEY_THEME: null,
reportInvalidHmrMessage: null,
useErrorOverlayReducer: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
ACTION_BEFORE_REFRESH: function() {
return ACTION_BEFORE_REFRESH;
},
ACTION_BUILD_ERROR: function() {
return ACTION_BUILD_ERROR;
},
ACTION_BUILD_OK: function() {
return ACTION_BUILD_OK;
},
ACTION_DEBUG_INFO: function() {
return ACTION_DEBUG_INFO;
},
ACTION_DEV_INDICATOR: function() {
return ACTION_DEV_INDICATOR;
},
ACTION_REFRESH: function() {
return ACTION_REFRESH;
},
ACTION_STATIC_INDICATOR: function() {
return ACTION_STATIC_INDICATOR;
},
ACTION_UNHANDLED_ERROR: function() {
return ACTION_UNHANDLED_ERROR;
},
ACTION_UNHANDLED_REJECTION: function() {
return ACTION_UNHANDLED_REJECTION;
},
ACTION_VERSION_INFO: function() {
return ACTION_VERSION_INFO;
},
INITIAL_OVERLAY_STATE: function() {
return INITIAL_OVERLAY_STATE;
},
REACT_REFRESH_FULL_RELOAD: function() {
return REACT_REFRESH_FULL_RELOAD;
},
REACT_REFRESH_FULL_RELOAD_FROM_ERROR: function() {
return REACT_REFRESH_FULL_RELOAD_FROM_ERROR;
},
STORAGE_KEY_POSITION: function() {
return STORAGE_KEY_POSITION;
},
STORAGE_KEY_SCALE: function() {
return STORAGE_KEY_SCALE;
},
STORAGE_KEY_THEME: function() {
return STORAGE_KEY_THEME;
},
reportInvalidHmrMessage: function() {
return reportInvalidHmrMessage;
},
useErrorOverlayReducer: function() {
return useErrorOverlayReducer;
}
});
const _react = require("react");
var _process_env___NEXT_DEV_INDICATOR;
const ACTION_STATIC_INDICATOR = 'static-indicator';
const ACTION_BUILD_OK = 'build-ok';
const ACTION_BUILD_ERROR = 'build-error';
const ACTION_BEFORE_REFRESH = 'before-fast-refresh';
const ACTION_REFRESH = 'fast-refresh';
const ACTION_VERSION_INFO = 'version-info';
const ACTION_UNHANDLED_ERROR = 'unhandled-error';
const ACTION_UNHANDLED_REJECTION = 'unhandled-rejection';
const ACTION_DEBUG_INFO = 'debug-info';
const ACTION_DEV_INDICATOR = 'dev-indicator';
const STORAGE_KEY_THEME = '__nextjs-dev-tools-theme';
const STORAGE_KEY_POSITION = '__nextjs-dev-tools-position';
const STORAGE_KEY_SCALE = '__nextjs-dev-tools-scale';
function pushErrorFilterDuplicates(errors, err) {
return [
...errors.filter((e)=>{
// Filter out duplicate errors
return e.event.reason.stack !== err.event.reason.stack;
}),
err
];
}
const shouldDisableDevIndicator = ((_process_env___NEXT_DEV_INDICATOR = process.env.__NEXT_DEV_INDICATOR) == null ? void 0 : _process_env___NEXT_DEV_INDICATOR.toString()) === 'false';
const INITIAL_OVERLAY_STATE = {
nextId: 1,
buildError: null,
errors: [],
notFound: false,
staticIndicator: false,
/*
This is set to `true` when we can reliably know
whether the indicator is in disabled state or not.
Otherwise the surface would flicker because the disabled flag loads from the config.
*/ showIndicator: false,
disableDevIndicator: false,
refreshState: {
type: 'idle'
},
versionInfo: {
installed: '0.0.0',
staleness: 'unknown'
},
debugInfo: {
devtoolsFrontendUrl: undefined
}
};
function getInitialState(routerType) {
return {
...INITIAL_OVERLAY_STATE,
routerType
};
}
function useErrorOverlayReducer(routerType) {
return (0, _react.useReducer)((state, action)=>{
switch(action.type){
case ACTION_DEBUG_INFO:
{
return {
...state,
debugInfo: action.debugInfo
};
}
case ACTION_STATIC_INDICATOR:
{
return {
...state,
staticIndicator: action.staticIndicator
};
}
case ACTION_BUILD_OK:
{
return {
...state,
buildError: null
};
}
case ACTION_BUILD_ERROR:
{
return {
...state,
buildError: action.message
};
}
case ACTION_BEFORE_REFRESH:
{
return {
...state,
refreshState: {
type: 'pending',
errors: []
}
};
}
case ACTION_REFRESH:
{
return {
...state,
buildError: null,
errors: // Errors can come in during updates. In this case, UNHANDLED_ERROR
// and UNHANDLED_REJECTION events might be dispatched between the
// BEFORE_REFRESH and the REFRESH event. We want to keep those errors
// around until the next refresh. Otherwise we run into a race
// condition where those errors would be cleared on refresh completion
// before they can be displayed.
state.refreshState.type === 'pending' ? state.refreshState.errors : [],
refreshState: {
type: 'idle'
}
};
}
case ACTION_UNHANDLED_ERROR:
case ACTION_UNHANDLED_REJECTION:
{
switch(state.refreshState.type){
case 'idle':
{
return {
...state,
nextId: state.nextId + 1,
errors: pushErrorFilterDuplicates(state.errors, {
id: state.nextId,
event: action
})
};
}
case 'pending':
{
return {
...state,
nextId: state.nextId + 1,
refreshState: {
...state.refreshState,
errors: pushErrorFilterDuplicates(state.refreshState.errors, {
id: state.nextId,
event: action
})
}
};
}
default:
return state;
}
}
case ACTION_VERSION_INFO:
{
return {
...state,
versionInfo: action.versionInfo
};
}
case ACTION_DEV_INDICATOR:
{
return {
...state,
showIndicator: true,
disableDevIndicator: shouldDisableDevIndicator || !!action.devIndicator.disabledUntil
};
}
default:
{
return state;
}
}
}, getInitialState(routerType));
}
const REACT_REFRESH_FULL_RELOAD = '[Fast Refresh] performing full reload\n\n' + "Fast Refresh will perform a full reload when you edit a file that's imported by modules outside of the React rendering tree.\n" + 'You might have a file which exports a React component but also exports a value that is imported by a non-React component file.\n' + 'Consider migrating the non-React component export to a separate file and importing it into both files.\n\n' + 'It is also possible the parent component of the component you edited is a class component, which disables Fast Refresh.\n' + 'Fast Refresh requires at least one parent function component in your React tree.';
const REACT_REFRESH_FULL_RELOAD_FROM_ERROR = '[Fast Refresh] performing full reload because your application had an unrecoverable error';
function reportInvalidHmrMessage(message, err) {
console.warn('[HMR] Invalid message: ' + JSON.stringify(message) + '\n' + (err instanceof Error && (err == null ? void 0 : err.stack) || ''));
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=shared.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
export type DebugInfo = {
devtoolsFrontendUrl: string | undefined;
};

View File

@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":[],"names":[],"mappings":""}

View File

@@ -0,0 +1,5 @@
import type { OriginalStackFrame } from '../../../utils/stack-frame';
export declare const CallStackFrame: React.FC<{
frame: OriginalStackFrame;
}>;
export declare const CALL_STACK_FRAME_STYLES = "\n [data-nextjs-call-stack-frame-no-source] {\n padding: 6px 8px;\n margin-bottom: 4px;\n\n border-radius: var(--rounded-lg);\n }\n\n [data-nextjs-call-stack-frame-no-source]:last-child {\n margin-bottom: 0;\n }\n\n [data-nextjs-call-stack-frame-ignored=\"true\"] {\n opacity: 0.6;\n }\n\n [data-nextjs-call-stack-frame] {\n user-select: text;\n display: block;\n box-sizing: border-box;\n\n user-select: text;\n -webkit-user-select: text;\n -moz-user-select: text;\n -ms-user-select: text;\n\n padding: 6px 8px;\n\n border-radius: var(--rounded-lg);\n }\n\n .call-stack-frame-method-name {\n display: flex;\n align-items: center;\n gap: 4px;\n\n margin-bottom: 4px;\n font-family: var(--font-stack-monospace);\n\n color: var(--color-gray-1000);\n font-size: var(--size-14);\n font-weight: 500;\n line-height: var(--size-20);\n\n svg {\n width: var(--size-16px);\n height: var(--size-16px);\n }\n }\n\n .open-in-editor-button, .source-mapping-error-button {\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: var(--rounded-full);\n padding: 4px;\n color: var(--color-font);\n\n svg {\n width: var(--size-16);\n height: var(--size-16);\n }\n\n &:focus-visible {\n outline: var(--focus-ring);\n outline-offset: -2px;\n }\n\n &:hover {\n background: var(--color-gray-100);\n }\n }\n\n .call-stack-frame-file-source {\n color: var(--color-gray-900);\n font-size: var(--size-14);\n line-height: var(--size-20);\n }\n";

View File

@@ -0,0 +1,94 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
CALL_STACK_FRAME_STYLES: null,
CallStackFrame: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
CALL_STACK_FRAME_STYLES: function() {
return CALL_STACK_FRAME_STYLES;
},
CallStackFrame: function() {
return CallStackFrame;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _hotlinkedtext = require("../hot-linked-text");
const _external = require("../../icons/external");
const _stackframe = require("../../../utils/stack-frame");
const _useopenineditor = require("../../utils/use-open-in-editor");
const CallStackFrame = function CallStackFrame(param) {
let { frame } = param;
var _frame_originalStackFrame;
// TODO: ability to expand resolved frames
const f = (_frame_originalStackFrame = frame.originalStackFrame) != null ? _frame_originalStackFrame : frame.sourceStackFrame;
const hasSource = Boolean(frame.originalCodeFrame);
const open = (0, _useopenineditor.useOpenInEditor)(hasSource ? {
file: f.file,
lineNumber: f.lineNumber,
column: f.column
} : undefined);
// Format method to strip out the webpack layer prefix.
// e.g. (app-pages-browser)/./app/page.tsx -> ./app/page.tsx
const formattedMethod = f.methodName.replace(/^\([\w-]+\)\//, '');
// Formatted file source could be empty. e.g. <anonymous> will be formatted to empty string,
// we'll skip rendering the frame in this case.
const fileSource = (0, _stackframe.getFrameSource)(f);
if (!fileSource) {
return null;
}
return /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
"data-nextjs-call-stack-frame": true,
"data-nextjs-call-stack-frame-no-source": !hasSource,
"data-nextjs-call-stack-frame-ignored": frame.ignored,
children: [
/*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
className: "call-stack-frame-method-name",
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)(_hotlinkedtext.HotlinkedText, {
text: formattedMethod
}),
hasSource && /*#__PURE__*/ (0, _jsxruntime.jsx)("button", {
onClick: open,
className: "open-in-editor-button",
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_external.ExternalIcon, {
width: 16,
height: 16
})
}),
frame.error ? /*#__PURE__*/ (0, _jsxruntime.jsx)("button", {
className: "source-mapping-error-button",
onClick: ()=>console.error(frame.reason),
title: "Sourcemapping failed. Click to log cause of error.",
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_external.SourceMappingErrorIcon, {
width: 16,
height: 16
})
}) : null
]
}),
/*#__PURE__*/ (0, _jsxruntime.jsx)("span", {
className: "call-stack-frame-file-source",
"data-has-source": hasSource,
children: fileSource
})
]
});
};
const CALL_STACK_FRAME_STYLES = '\n [data-nextjs-call-stack-frame-no-source] {\n padding: 6px 8px;\n margin-bottom: 4px;\n\n border-radius: var(--rounded-lg);\n }\n\n [data-nextjs-call-stack-frame-no-source]:last-child {\n margin-bottom: 0;\n }\n\n [data-nextjs-call-stack-frame-ignored="true"] {\n opacity: 0.6;\n }\n\n [data-nextjs-call-stack-frame] {\n user-select: text;\n display: block;\n box-sizing: border-box;\n\n user-select: text;\n -webkit-user-select: text;\n -moz-user-select: text;\n -ms-user-select: text;\n\n padding: 6px 8px;\n\n border-radius: var(--rounded-lg);\n }\n\n .call-stack-frame-method-name {\n display: flex;\n align-items: center;\n gap: 4px;\n\n margin-bottom: 4px;\n font-family: var(--font-stack-monospace);\n\n color: var(--color-gray-1000);\n font-size: var(--size-14);\n font-weight: 500;\n line-height: var(--size-20);\n\n svg {\n width: var(--size-16px);\n height: var(--size-16px);\n }\n }\n\n .open-in-editor-button, .source-mapping-error-button {\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: var(--rounded-full);\n padding: 4px;\n color: var(--color-font);\n\n svg {\n width: var(--size-16);\n height: var(--size-16);\n }\n\n &:focus-visible {\n outline: var(--focus-ring);\n outline-offset: -2px;\n }\n\n &:hover {\n background: var(--color-gray-100);\n }\n }\n\n .call-stack-frame-file-source {\n color: var(--color-gray-900);\n font-size: var(--size-14);\n line-height: var(--size-20);\n }\n';
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=call-stack-frame.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,7 @@
import type { StackFrame } from 'next/dist/compiled/stacktrace-parser';
export type CodeFrameProps = {
stackFrame: StackFrame;
codeFrame: string;
};
export declare function CodeFrame({ stackFrame, codeFrame }: CodeFrameProps): import("react/jsx-runtime").JSX.Element;
export declare const CODE_FRAME_STYLES = "\n [data-nextjs-codeframe] {\n --code-frame-padding: 12px;\n --code-frame-line-height: var(--size-16);\n background-color: var(--color-background-200);\n overflow: hidden;\n color: var(--color-gray-1000);\n text-overflow: ellipsis;\n border: 1px solid var(--color-gray-400);\n border-radius: 8px;\n font-family: var(--font-stack-monospace);\n font-size: var(--size-12);\n line-height: var(--code-frame-line-height);\n margin: 8px 0;\n\n svg {\n width: var(--size-16);\n height: var(--size-16);\n }\n }\n\n .code-frame-link,\n .code-frame-pre {\n padding: var(--code-frame-padding);\n }\n\n .code-frame-link svg {\n flex-shrink: 0;\n }\n\n .code-frame-link [data-text] {\n display: inline-flex;\n text-align: left;\n margin: auto 6px;\n }\n\n .code-frame-header {\n width: 100%;\n transition: background 100ms ease-out;\n border-radius: 8px 8px 0 0;\n border-bottom: 1px solid var(--color-gray-400);\n }\n\n [data-with-open-in-editor-link-source-file] {\n padding: 4px;\n margin: -4px 0 -4px auto;\n border-radius: var(--rounded-full);\n margin-left: auto;\n\n &:focus-visible {\n outline: var(--focus-ring);\n outline-offset: -2px;\n }\n\n &:hover {\n background: var(--color-gray-100);\n }\n }\n\n [data-nextjs-codeframe]::selection,\n [data-nextjs-codeframe] *::selection {\n background-color: var(--color-ansi-selection);\n }\n\n [data-nextjs-codeframe] *:not(a) {\n color: inherit;\n background-color: transparent;\n font-family: var(--font-stack-monospace);\n }\n\n [data-nextjs-codeframe-line][data-nextjs-codeframe-line--errored=\"true\"] {\n position: relative;\n isolation: isolate;\n\n > span { \n position: relative;\n z-index: 1;\n }\n\n &::after {\n content: \"\";\n width: calc(100% + var(--code-frame-padding) * 2);\n height: var(--code-frame-line-height);\n left: calc(-1 * var(--code-frame-padding));\n background: var(--color-red-200);\n box-shadow: 2px 0 0 0 var(--color-red-900) inset;\n position: absolute;\n }\n }\n\n\n [data-nextjs-codeframe] > * {\n margin: 0;\n }\n\n .code-frame-link {\n display: flex;\n margin: 0;\n outline: 0;\n }\n .code-frame-link [data-icon='right'] {\n margin-left: auto;\n }\n\n [data-nextjs-codeframe] div > pre {\n overflow: hidden;\n display: inline-block;\n }\n\n [data-nextjs-codeframe] svg {\n color: var(--color-gray-900);\n }\n";

View File

@@ -0,0 +1,128 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
CODE_FRAME_STYLES: null,
CodeFrame: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
CODE_FRAME_STYLES: function() {
return CODE_FRAME_STYLES;
},
CodeFrame: function() {
return CodeFrame;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _react = require("react");
const _hotlinkedtext = require("../hot-linked-text");
const _stackframe = require("../../../utils/stack-frame");
const _useopenineditor = require("../../utils/use-open-in-editor");
const _external = require("../../icons/external");
const _file = require("../../icons/file");
const _parsecodeframe = require("./parse-code-frame");
function CodeFrame(param) {
let { stackFrame, codeFrame } = param;
var _stackFrame_file;
const formattedFrame = (0, _react.useMemo)(()=>(0, _parsecodeframe.formatCodeFrame)(codeFrame), [
codeFrame
]);
const decodedLines = (0, _react.useMemo)(()=>(0, _parsecodeframe.groupCodeFrameLines)(formattedFrame), [
formattedFrame
]);
const open = (0, _useopenineditor.useOpenInEditor)({
file: stackFrame.file,
lineNumber: stackFrame.lineNumber,
column: stackFrame.column
});
const fileExtension = stackFrame == null ? void 0 : (_stackFrame_file = stackFrame.file) == null ? void 0 : _stackFrame_file.split('.').pop();
// TODO: make the caret absolute
return /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
"data-nextjs-codeframe": true,
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
className: "code-frame-header",
children: /*#__PURE__*/ (0, _jsxruntime.jsxs)("p", {
className: "code-frame-link",
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)("span", {
className: "code-frame-icon",
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_file.FileIcon, {
lang: fileExtension
})
}),
/*#__PURE__*/ (0, _jsxruntime.jsxs)("span", {
"data-text": true,
children: [
(0, _stackframe.getFrameSource)(stackFrame),
" @",
' ',
/*#__PURE__*/ (0, _jsxruntime.jsx)(_hotlinkedtext.HotlinkedText, {
text: stackFrame.methodName
})
]
}),
/*#__PURE__*/ (0, _jsxruntime.jsx)("button", {
"aria-label": "Open in editor",
"data-with-open-in-editor-link-source-file": true,
onClick: open,
children: /*#__PURE__*/ (0, _jsxruntime.jsx)("span", {
className: "code-frame-icon",
"data-icon": "right",
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_external.ExternalIcon, {
width: 16,
height: 16
})
})
})
]
})
}),
/*#__PURE__*/ (0, _jsxruntime.jsx)("pre", {
className: "code-frame-pre",
children: decodedLines.map((line, lineIndex)=>{
const { lineNumber, isErroredLine } = (0, _parsecodeframe.parseLineNumberFromCodeFrameLine)(line, stackFrame);
const lineNumberProps = {};
if (lineNumber) {
lineNumberProps['data-nextjs-codeframe-line'] = lineNumber;
}
if (isErroredLine) {
lineNumberProps['data-nextjs-codeframe-line--errored'] = true;
}
return /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
...lineNumberProps,
children: line.map((entry, entryIndex)=>/*#__PURE__*/ (0, _jsxruntime.jsx)("span", {
style: {
color: entry.fg ? "var(--color-" + entry.fg + ")" : undefined,
...entry.decoration === 'bold' ? // having longer width than expected on Geist Mono font-weight
// above 600, hence a temporary fix is to use 500 for bold.
{
fontWeight: 500
} : entry.decoration === 'italic' ? {
fontStyle: 'italic'
} : undefined
},
children: entry.content
}, "frame-" + entryIndex))
}, "line-" + lineIndex);
})
})
]
});
}
const CODE_FRAME_STYLES = '\n [data-nextjs-codeframe] {\n --code-frame-padding: 12px;\n --code-frame-line-height: var(--size-16);\n background-color: var(--color-background-200);\n overflow: hidden;\n color: var(--color-gray-1000);\n text-overflow: ellipsis;\n border: 1px solid var(--color-gray-400);\n border-radius: 8px;\n font-family: var(--font-stack-monospace);\n font-size: var(--size-12);\n line-height: var(--code-frame-line-height);\n margin: 8px 0;\n\n svg {\n width: var(--size-16);\n height: var(--size-16);\n }\n }\n\n .code-frame-link,\n .code-frame-pre {\n padding: var(--code-frame-padding);\n }\n\n .code-frame-link svg {\n flex-shrink: 0;\n }\n\n .code-frame-link [data-text] {\n display: inline-flex;\n text-align: left;\n margin: auto 6px;\n }\n\n .code-frame-header {\n width: 100%;\n transition: background 100ms ease-out;\n border-radius: 8px 8px 0 0;\n border-bottom: 1px solid var(--color-gray-400);\n }\n\n [data-with-open-in-editor-link-source-file] {\n padding: 4px;\n margin: -4px 0 -4px auto;\n border-radius: var(--rounded-full);\n margin-left: auto;\n\n &:focus-visible {\n outline: var(--focus-ring);\n outline-offset: -2px;\n }\n\n &:hover {\n background: var(--color-gray-100);\n }\n }\n\n [data-nextjs-codeframe]::selection,\n [data-nextjs-codeframe] *::selection {\n background-color: var(--color-ansi-selection);\n }\n\n [data-nextjs-codeframe] *:not(a) {\n color: inherit;\n background-color: transparent;\n font-family: var(--font-stack-monospace);\n }\n\n [data-nextjs-codeframe-line][data-nextjs-codeframe-line--errored="true"] {\n position: relative;\n isolation: isolate;\n\n > span { \n position: relative;\n z-index: 1;\n }\n\n &::after {\n content: "";\n width: calc(100% + var(--code-frame-padding) * 2);\n height: var(--code-frame-line-height);\n left: calc(-1 * var(--code-frame-padding));\n background: var(--color-red-200);\n box-shadow: 2px 0 0 0 var(--color-red-900) inset;\n position: absolute;\n }\n }\n\n\n [data-nextjs-codeframe] > * {\n margin: 0;\n }\n\n .code-frame-link {\n display: flex;\n margin: 0;\n outline: 0;\n }\n .code-frame-link [data-icon=\'right\'] {\n margin-left: auto;\n }\n\n [data-nextjs-codeframe] div > pre {\n overflow: hidden;\n display: inline-block;\n }\n\n [data-nextjs-codeframe] svg {\n color: var(--color-gray-900);\n }\n';
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=code-frame.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,8 @@
import type { StackFrame } from 'next/dist/compiled/stacktrace-parser';
import { type AnserJsonEntry } from 'next/dist/compiled/anser';
export declare function formatCodeFrame(codeFrame: string): string;
export declare function groupCodeFrameLines(formattedFrame: string): AnserJsonEntry[][];
export declare function parseLineNumberFromCodeFrameLine(line: AnserJsonEntry[], stackFrame: StackFrame): {
lineNumber: string | undefined;
isErroredLine: boolean;
};

View File

@@ -0,0 +1,90 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
formatCodeFrame: null,
groupCodeFrameLines: null,
parseLineNumberFromCodeFrameLine: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
formatCodeFrame: function() {
return formatCodeFrame;
},
groupCodeFrameLines: function() {
return groupCodeFrameLines;
},
parseLineNumberFromCodeFrameLine: function() {
return parseLineNumberFromCodeFrameLine;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _anser = /*#__PURE__*/ _interop_require_default._(require("next/dist/compiled/anser"));
const _stripansi = /*#__PURE__*/ _interop_require_default._(require("next/dist/compiled/strip-ansi"));
function formatCodeFrame(codeFrame) {
const lines = codeFrame.split(/\r?\n/g);
// Find the minimum length of leading spaces after `|` in the code frame
const miniLeadingSpacesLength = lines.map((line)=>/^>? +\d+ +\| [ ]+/.exec((0, _stripansi.default)(line)) === null ? null : /^>? +\d+ +\| ( *)/.exec((0, _stripansi.default)(line))).filter(Boolean).map((v)=>v.pop()).reduce((c, n)=>isNaN(c) ? n.length : Math.min(c, n.length), NaN);
// When the minimum length of leading spaces is greater than 1, remove them
// from the code frame to help the indentation looks better when there's a lot leading spaces.
if (miniLeadingSpacesLength > 1) {
return lines.map((line, a)=>~(a = line.indexOf('|')) ? line.substring(0, a) + line.substring(a).replace("^\\ {" + miniLeadingSpacesLength + "}", '') : line).join('\n');
}
return lines.join('\n');
}
function groupCodeFrameLines(formattedFrame) {
// Map the decoded lines to a format that can be rendered
const decoded = _anser.default.ansiToJson(formattedFrame, {
json: true,
use_classes: true,
remove_empty: true
});
const lines = [];
let line = [];
for (const token of decoded){
if (token.content === '\n') {
lines.push(line);
line = [];
} else {
line.push(token);
}
}
if (line.length > 0) {
lines.push(line);
}
return lines;
}
function parseLineNumberFromCodeFrameLine(line, stackFrame) {
var _line_, _line_1, _stackFrame_lineNumber;
let lineNumberToken;
let lineNumber;
// parse line number from line first 2 tokens
// e.g. ` > 1 | const foo = 'bar'` => `1`, first token is `1 |`
// e.g. ` 2 | const foo = 'bar'` => `2`. first 2 tokens are ' ' and ' 2 |'
// console.log('line', line)
if (((_line_ = line[0]) == null ? void 0 : _line_.content) === '>' || ((_line_1 = line[0]) == null ? void 0 : _line_1.content) === ' ') {
var _lineNumberToken_content_replace, _lineNumberToken_content;
lineNumberToken = line[1];
lineNumber = lineNumberToken == null ? void 0 : (_lineNumberToken_content = lineNumberToken.content) == null ? void 0 : (_lineNumberToken_content_replace = _lineNumberToken_content.replace('|', '')) == null ? void 0 : _lineNumberToken_content_replace.trim();
}
// When the line number is possibly undefined, it can be just the non-source code line
// e.g. the ^ sign can also take a line, we skip rendering line number for it
return {
lineNumber,
isErroredLine: lineNumber === ((_stackFrame_lineNumber = stackFrame.lineNumber) == null ? void 0 : _stackFrame_lineNumber.toString())
};
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=parse-code-frame.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,8 @@
import * as React from 'react';
export declare function CopyButton({ actionLabel, successLabel, content, icon, disabled, ...props }: React.HTMLProps<HTMLButtonElement> & {
actionLabel: string;
successLabel: string;
content: string;
icon?: React.ReactNode;
}): import("react/jsx-runtime").JSX.Element;
export declare const COPY_BUTTON_STYLES = "\n .nextjs-data-copy-button {\n color: inherit;\n\n svg {\n width: var(--size-16);\n height: var(--size-16);\n }\n }\n .nextjs-data-copy-button--initial:hover {\n cursor: pointer;\n }\n .nextjs-data-copy-button--error,\n .nextjs-data-copy-button--error:hover {\n color: var(--color-ansi-red);\n }\n .nextjs-data-copy-button--success {\n color: var(--color-ansi-green);\n }\n";

View File

@@ -0,0 +1,242 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
COPY_BUTTON_STYLES: null,
CopyButton: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
COPY_BUTTON_STYLES: function() {
return COPY_BUTTON_STYLES;
},
CopyButton: function() {
return CopyButton;
}
});
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
const _cx = require("../../utils/cx");
function useCopyLegacy(content) {
// This would be simpler with useActionState but we need to support React 18 here.
// React 18 also doesn't have async transitions.
const [copyState, dispatch] = _react.useReducer((state, action)=>{
if (action.type === 'reset') {
return {
state: 'initial'
};
}
if (action.type === 'copied') {
return {
state: 'success'
};
}
if (action.type === 'copying') {
return {
state: 'pending'
};
}
if (action.type === 'error') {
return {
state: 'error',
error: action.error
};
}
return state;
}, {
state: 'initial'
});
function copy() {
if (isPending) {
return;
}
if (!navigator.clipboard) {
dispatch({
type: 'error',
error: Object.defineProperty(new Error('Copy to clipboard is not supported in this browser'), "__NEXT_ERROR_CODE", {
value: "E376",
enumerable: false,
configurable: true
})
});
} else {
dispatch({
type: 'copying'
});
navigator.clipboard.writeText(content).then(()=>{
dispatch({
type: 'copied'
});
}, (error)=>{
dispatch({
type: 'error',
error
});
});
}
}
const reset = _react.useCallback(()=>{
dispatch({
type: 'reset'
});
}, []);
const isPending = copyState.state === 'pending';
return [
copyState,
copy,
reset,
isPending
];
}
function useCopyModern(content) {
const [copyState, dispatch, isPending] = _react.useActionState((state, action)=>{
if (action === 'reset') {
return {
state: 'initial'
};
}
if (action === 'copy') {
if (!navigator.clipboard) {
return {
state: 'error',
error: Object.defineProperty(new Error('Copy to clipboard is not supported in this browser'), "__NEXT_ERROR_CODE", {
value: "E376",
enumerable: false,
configurable: true
})
};
}
return navigator.clipboard.writeText(content).then(()=>{
return {
state: 'success'
};
}, (error)=>{
return {
state: 'error',
error
};
});
}
return state;
}, {
state: 'initial'
});
function copy() {
_react.startTransition(()=>{
dispatch('copy');
});
}
const reset = _react.useCallback(()=>{
dispatch('reset');
}, [
// TODO: `dispatch` from `useActionState` is not reactive.
// Remove from dependencies once https://github.com/facebook/react/pull/29665 is released.
dispatch
]);
return [
copyState,
copy,
reset,
isPending
];
}
const useCopy = typeof _react.useActionState === 'function' ? useCopyModern : useCopyLegacy;
function CopyButton(param) {
let { actionLabel, successLabel, content, icon, disabled, ...props } = param;
const [copyState, copy, reset, isPending] = useCopy(content);
const error = copyState.state === 'error' ? copyState.error : null;
_react.useEffect(()=>{
if (error !== null) {
// Additional console.error to get the stack.
console.error(error);
}
}, [
error
]);
_react.useEffect(()=>{
if (copyState.state === 'success') {
const timeoutId = setTimeout(()=>{
reset();
}, 2000);
return ()=>{
clearTimeout(timeoutId);
};
}
}, [
isPending,
copyState.state,
reset
]);
const isDisabled = isPending || disabled;
const label = copyState.state === 'success' ? successLabel : actionLabel;
// Assign default icon
const renderedIcon = copyState.state === 'success' ? /*#__PURE__*/ (0, _jsxruntime.jsx)(CopySuccessIcon, {}) : icon || /*#__PURE__*/ (0, _jsxruntime.jsx)(CopyIcon, {
width: 14,
height: 14,
className: "error-overlay-toolbar-button-icon"
});
return /*#__PURE__*/ (0, _jsxruntime.jsxs)("button", {
...props,
type: "button",
title: label,
"aria-label": label,
"aria-disabled": isDisabled,
disabled: isDisabled,
"data-nextjs-copy-button": true,
className: (0, _cx.cx)(props.className, 'nextjs-data-copy-button', "nextjs-data-copy-button--" + copyState.state),
onClick: ()=>{
if (!isDisabled) {
copy();
}
},
children: [
renderedIcon,
copyState.state === 'error' ? " " + copyState.error : null
]
});
}
function CopyIcon(props) {
return /*#__PURE__*/ (0, _jsxruntime.jsx)("svg", {
width: "14",
height: "14",
viewBox: "0 0 14 14",
fill: "none",
xmlns: "http://www.w3.org/2000/svg",
...props,
children: /*#__PURE__*/ (0, _jsxruntime.jsx)("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M2.406.438c-.845 0-1.531.685-1.531 1.53v6.563c0 .846.686 1.531 1.531 1.531H3.937V8.75H2.406a.219.219 0 0 1-.219-.219V1.97c0-.121.098-.219.22-.219h4.812c.12 0 .218.098.218.219v.656H8.75v-.656c0-.846-.686-1.532-1.531-1.532H2.406zm4.375 3.5c-.845 0-1.531.685-1.531 1.53v6.563c0 .846.686 1.531 1.531 1.531h4.813c.845 0 1.531-.685 1.531-1.53V5.468c0-.846-.686-1.532-1.531-1.532H6.78zm-.218 1.53c0-.12.097-.218.218-.218h4.813c.12 0 .219.098.219.219v6.562c0 .121-.098.219-.22.219H6.782a.219.219 0 0 1-.218-.219V5.47z",
fill: "currentColor"
})
});
}
function CopySuccessIcon() {
return /*#__PURE__*/ (0, _jsxruntime.jsx)("svg", {
height: "16",
xlinkTitle: "copied",
viewBox: "0 0 16 16",
width: "16",
stroke: "currentColor",
fill: "currentColor",
children: /*#__PURE__*/ (0, _jsxruntime.jsx)("path", {
d: "M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"
})
});
}
const COPY_BUTTON_STYLES = "\n .nextjs-data-copy-button {\n color: inherit;\n\n svg {\n width: var(--size-16);\n height: var(--size-16);\n }\n }\n .nextjs-data-copy-button--initial:hover {\n cursor: pointer;\n }\n .nextjs-data-copy-button--error,\n .nextjs-data-copy-button--error:hover {\n color: var(--color-ansi-red);\n }\n .nextjs-data-copy-button--success {\n color: var(--color-ansi-green);\n }\n";
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,7 @@
import * as React from 'react';
export type DialogBodyProps = {
children?: React.ReactNode;
className?: string;
};
declare const DialogBody: React.FC<DialogBodyProps>;
export { DialogBody };

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "DialogBody", {
enumerable: true,
get: function() {
return DialogBody;
}
});
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
const DialogBody = function DialogBody(param) {
let { children, className } = param;
return /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
"data-nextjs-dialog-body": true,
className: className,
children: children
});
};
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=dialog-body.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../src/client/components/react-dev-overlay/ui/components/dialog/dialog-body.tsx"],"sourcesContent":["import * as React from 'react'\n\nexport type DialogBodyProps = {\n children?: React.ReactNode\n className?: string\n}\n\nconst DialogBody: React.FC<DialogBodyProps> = function DialogBody({\n children,\n className,\n}) {\n return (\n <div data-nextjs-dialog-body className={className}>\n {children}\n </div>\n )\n}\n\nexport { DialogBody }\n"],"names":["DialogBody","children","className","div","data-nextjs-dialog-body"],"mappings":";;;;+BAkBSA;;;eAAAA;;;;;iEAlBc;AAOvB,MAAMA,aAAwC,SAASA,WAAW,KAGjE;IAHiE,IAAA,EAChEC,QAAQ,EACRC,SAAS,EACV,GAHiE;IAIhE,qBACE,qBAACC;QAAIC,yBAAuB;QAACF,WAAWA;kBACrCD;;AAGP"}

View File

@@ -0,0 +1,7 @@
import * as React from 'react';
export type DialogContentProps = {
children?: React.ReactNode;
className?: string;
};
declare const DialogContent: React.FC<DialogContentProps>;
export { DialogContent };

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "DialogContent", {
enumerable: true,
get: function() {
return DialogContent;
}
});
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
const DialogContent = function DialogContent(param) {
let { children, className } = param;
return /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
"data-nextjs-dialog-content": true,
className: className,
children: children
});
};
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=dialog-content.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../src/client/components/react-dev-overlay/ui/components/dialog/dialog-content.tsx"],"sourcesContent":["import * as React from 'react'\n\nexport type DialogContentProps = {\n children?: React.ReactNode\n className?: string\n}\n\nconst DialogContent: React.FC<DialogContentProps> = function DialogContent({\n children,\n className,\n}) {\n return (\n <div data-nextjs-dialog-content className={className}>\n {children}\n </div>\n )\n}\n\nexport { DialogContent }\n"],"names":["DialogContent","children","className","div","data-nextjs-dialog-content"],"mappings":";;;;+BAkBSA;;;eAAAA;;;;;iEAlBc;AAOvB,MAAMA,gBAA8C,SAASA,cAAc,KAG1E;IAH0E,IAAA,EACzEC,QAAQ,EACRC,SAAS,EACV,GAH0E;IAIzE,qBACE,qBAACC;QAAIC,4BAA0B;QAACF,WAAWA;kBACxCD;;AAGP"}

View File

@@ -0,0 +1,7 @@
import * as React from 'react';
export type DialogHeaderProps = {
children?: React.ReactNode;
className?: string;
};
declare const DialogHeader: React.FC<DialogHeaderProps>;
export { DialogHeader };

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "DialogHeader", {
enumerable: true,
get: function() {
return DialogHeader;
}
});
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
const DialogHeader = function DialogHeader(param) {
let { children, className } = param;
return /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
"data-nextjs-dialog-header": true,
className: className,
children: children
});
};
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=dialog-header.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../src/client/components/react-dev-overlay/ui/components/dialog/dialog-header.tsx"],"sourcesContent":["import * as React from 'react'\n\nexport type DialogHeaderProps = {\n children?: React.ReactNode\n className?: string\n}\n\nconst DialogHeader: React.FC<DialogHeaderProps> = function DialogHeader({\n children,\n className,\n}) {\n return (\n <div data-nextjs-dialog-header className={className}>\n {children}\n </div>\n )\n}\n\nexport { DialogHeader }\n"],"names":["DialogHeader","children","className","div","data-nextjs-dialog-header"],"mappings":";;;;+BAkBSA;;;eAAAA;;;;;iEAlBc;AAOvB,MAAMA,eAA4C,SAASA,aAAa,KAGvE;IAHuE,IAAA,EACtEC,QAAQ,EACRC,SAAS,EACV,GAHuE;IAItE,qBACE,qBAACC;QAAIC,2BAAyB;QAACF,WAAWA;kBACvCD;;AAGP"}

View File

@@ -0,0 +1,12 @@
import * as React from 'react';
export type DialogProps = {
children?: React.ReactNode;
type: 'error' | 'warning';
'aria-labelledby': string;
'aria-describedby': string;
className?: string;
onClose?: () => void;
dialogResizerRef?: React.RefObject<HTMLDivElement | null>;
} & React.HTMLAttributes<HTMLDivElement>;
declare const Dialog: React.FC<DialogProps>;
export { Dialog };

View File

@@ -0,0 +1,101 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "Dialog", {
enumerable: true,
get: function() {
return Dialog;
}
});
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
const _useonclickoutside = require("../../hooks/use-on-click-outside");
const _usemeasureheight = require("../../hooks/use-measure-height");
const CSS_SELECTORS_TO_EXCLUDE_ON_CLICK_OUTSIDE = [
'[data-next-mark]',
'[data-issues-open]',
'#nextjs-dev-tools-menu',
'[data-nextjs-error-overlay-nav]',
'[data-info-popover]'
];
const Dialog = function Dialog(param) {
let { children, type, className, onClose, 'aria-labelledby': ariaLabelledBy, 'aria-describedby': ariaDescribedBy, dialogResizerRef, ...props } = param;
const dialogRef = _react.useRef(null);
const [role, setRole] = _react.useState(typeof document !== 'undefined' && document.hasFocus() ? 'dialog' : undefined);
const ref = _react.useRef(null);
const [height, pristine] = (0, _usemeasureheight.useMeasureHeight)(ref);
(0, _useonclickoutside.useOnClickOutside)(dialogRef.current, CSS_SELECTORS_TO_EXCLUDE_ON_CLICK_OUTSIDE, (e)=>{
e.preventDefault();
return onClose == null ? void 0 : onClose();
});
_react.useEffect(()=>{
if (dialogRef.current == null) {
return;
}
function handleFocus() {
// safari will force itself as the active application when a background page triggers any sort of autofocus
// this is a workaround to only set the dialog role if the document has focus
setRole(document.hasFocus() ? 'dialog' : undefined);
}
window.addEventListener('focus', handleFocus);
window.addEventListener('blur', handleFocus);
return ()=>{
window.removeEventListener('focus', handleFocus);
window.removeEventListener('blur', handleFocus);
};
}, []);
_react.useEffect(()=>{
const dialog = dialogRef.current;
const root = dialog == null ? void 0 : dialog.getRootNode();
const initialActiveElement = root instanceof ShadowRoot ? root == null ? void 0 : root.activeElement : null;
// Trap focus within the dialog
dialog == null ? void 0 : dialog.focus();
return ()=>{
// Blur first to avoid getting stuck, in case `activeElement` is missing
dialog == null ? void 0 : dialog.blur();
// Restore focus to the previously active element
initialActiveElement == null ? void 0 : initialActiveElement.focus();
};
}, []);
return /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
ref: dialogRef,
tabIndex: -1,
"data-nextjs-dialog": true,
role: role,
"aria-labelledby": ariaLabelledBy,
"aria-describedby": ariaDescribedBy,
"aria-modal": "true",
className: className,
onKeyDown: (e)=>{
if (e.key === 'Escape') {
onClose == null ? void 0 : onClose();
}
},
...props,
children: /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
ref: dialogResizerRef,
"data-nextjs-dialog-sizer": true,
// [x] Don't animate on initial load
// [x] No duplicate elements
// [x] Responds to content growth
style: {
height,
transition: pristine ? undefined : 'height 250ms var(--timing-swift)'
},
children: /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
ref: ref,
children: children
})
})
});
};
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=dialog.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
export { Dialog } from './dialog';
export { DialogBody } from './dialog-body';
export { DialogContent } from './dialog-content';
export { DialogHeader } from './dialog-header';
export { styles } from './styles';

View File

@@ -0,0 +1,47 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
Dialog: null,
DialogBody: null,
DialogContent: null,
DialogHeader: null,
styles: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
Dialog: function() {
return _dialog.Dialog;
},
DialogBody: function() {
return _dialogbody.DialogBody;
},
DialogContent: function() {
return _dialogcontent.DialogContent;
},
DialogHeader: function() {
return _dialogheader.DialogHeader;
},
styles: function() {
return _styles.styles;
}
});
const _dialog = require("./dialog");
const _dialogbody = require("./dialog-body");
const _dialogcontent = require("./dialog-content");
const _dialogheader = require("./dialog-header");
const _styles = require("./styles");
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../src/client/components/react-dev-overlay/ui/components/dialog/index.ts"],"sourcesContent":["export { Dialog } from './dialog'\nexport { DialogBody } from './dialog-body'\nexport { DialogContent } from './dialog-content'\nexport { DialogHeader } from './dialog-header'\nexport { styles } from './styles'\n"],"names":["Dialog","DialogBody","DialogContent","DialogHeader","styles"],"mappings":";;;;;;;;;;;;;;;;;;IAASA,MAAM;eAANA,cAAM;;IACNC,UAAU;eAAVA,sBAAU;;IACVC,aAAa;eAAbA,4BAAa;;IACbC,YAAY;eAAZA,0BAAY;;IACZC,MAAM;eAANA,cAAM;;;wBAJQ;4BACI;+BACG;8BACD;wBACN"}

View File

@@ -0,0 +1,2 @@
declare const styles = "\n [data-nextjs-dialog-root] {\n --next-dialog-radius: var(--rounded-xl);\n --next-dialog-max-width: 960px;\n --next-dialog-row-padding: 16px;\n --next-dialog-padding-x: 12px;\n --next-dialog-notch-height: 42px;\n --next-dialog-border-width: 1px;\n\n display: flex;\n flex-direction: column;\n width: 100%;\n max-height: calc(100% - 56px);\n max-width: var(--next-dialog-max-width);\n margin-right: auto;\n margin-left: auto;\n scale: 0.98;\n opacity: 0;\n transition-property: scale, opacity;\n transition-duration: var(--transition-duration);\n transition-timing-function: var(--timing-overlay);\n\n &[data-rendered='true'] {\n opacity: 1;\n scale: 1;\n }\n\n [data-nextjs-scroll-fader][data-side=\"top\"] {\n left: 1px;\n top: calc(var(--next-dialog-notch-height) + var(--next-dialog-border-width));\n width: calc(100% - var(--next-dialog-padding-x));\n opacity: 0;\n }\n }\n\n [data-nextjs-dialog] {\n outline: 0;\n }\n\n [data-nextjs-dialog], [data-nextjs-dialog] * {\n &::-webkit-scrollbar {\n width: 6px;\n height: 6px;\n border-radius: 0 0 1rem 1rem;\n margin-bottom: 1rem;\n }\n\n &::-webkit-scrollbar-button {\n display: none;\n }\n\n &::-webkit-scrollbar-track {\n border-radius: 0 0 1rem 1rem;\n background-color: var(--color-background-100);\n }\n \n &::-webkit-scrollbar-thumb {\n border-radius: 1rem;\n background-color: var(--color-gray-500);\n }\n }\n\n /* Place overflow: hidden on this so we can break out from [data-nextjs-dialog] */\n [data-nextjs-dialog-sizer] {\n overflow: hidden;\n border-radius: inherit;\n }\n\n [data-nextjs-dialog-backdrop] {\n opacity: 0;\n transition: opacity var(--transition-duration) var(--timing-overlay);\n }\n\n [data-nextjs-dialog-overlay][data-rendered='true']\n [data-nextjs-dialog-backdrop] {\n opacity: 1;\n }\n\n [data-nextjs-dialog-content] {\n border: none;\n margin: 0;\n display: flex;\n flex-direction: column;\n position: relative;\n padding: 16px var(--next-dialog-padding-x);\n }\n\n [data-nextjs-dialog-content] > [data-nextjs-dialog-header] {\n flex-shrink: 0;\n margin-bottom: 8px;\n }\n\n [data-nextjs-dialog-content] > [data-nextjs-dialog-body] {\n position: relative;\n flex: 1 1 auto;\n }\n\n @media (max-height: 812px) {\n [data-nextjs-dialog-overlay] {\n max-height: calc(100% - 15px);\n }\n }\n\n @media (min-width: 576px) {\n [data-nextjs-dialog-root] {\n --next-dialog-max-width: 540px;\n }\n }\n\n @media (min-width: 768px) {\n [data-nextjs-dialog-root] {\n --next-dialog-max-width: 720px;\n }\n }\n\n @media (min-width: 992px) {\n [data-nextjs-dialog-root] {\n --next-dialog-max-width: 960px;\n }\n }\n";
export { styles };

View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "styles", {
enumerable: true,
get: function() {
return styles;
}
});
const styles = "\n [data-nextjs-dialog-root] {\n --next-dialog-radius: var(--rounded-xl);\n --next-dialog-max-width: 960px;\n --next-dialog-row-padding: 16px;\n --next-dialog-padding-x: 12px;\n --next-dialog-notch-height: 42px;\n --next-dialog-border-width: 1px;\n\n display: flex;\n flex-direction: column;\n width: 100%;\n max-height: calc(100% - 56px);\n max-width: var(--next-dialog-max-width);\n margin-right: auto;\n margin-left: auto;\n scale: 0.98;\n opacity: 0;\n transition-property: scale, opacity;\n transition-duration: var(--transition-duration);\n transition-timing-function: var(--timing-overlay);\n\n &[data-rendered='true'] {\n opacity: 1;\n scale: 1;\n }\n\n [data-nextjs-scroll-fader][data-side=\"top\"] {\n left: 1px;\n top: calc(var(--next-dialog-notch-height) + var(--next-dialog-border-width));\n width: calc(100% - var(--next-dialog-padding-x));\n opacity: 0;\n }\n }\n\n [data-nextjs-dialog] {\n outline: 0;\n }\n\n [data-nextjs-dialog], [data-nextjs-dialog] * {\n &::-webkit-scrollbar {\n width: 6px;\n height: 6px;\n border-radius: 0 0 1rem 1rem;\n margin-bottom: 1rem;\n }\n\n &::-webkit-scrollbar-button {\n display: none;\n }\n\n &::-webkit-scrollbar-track {\n border-radius: 0 0 1rem 1rem;\n background-color: var(--color-background-100);\n }\n \n &::-webkit-scrollbar-thumb {\n border-radius: 1rem;\n background-color: var(--color-gray-500);\n }\n }\n\n /* Place overflow: hidden on this so we can break out from [data-nextjs-dialog] */\n [data-nextjs-dialog-sizer] {\n overflow: hidden;\n border-radius: inherit;\n }\n\n [data-nextjs-dialog-backdrop] {\n opacity: 0;\n transition: opacity var(--transition-duration) var(--timing-overlay);\n }\n\n [data-nextjs-dialog-overlay][data-rendered='true']\n [data-nextjs-dialog-backdrop] {\n opacity: 1;\n }\n\n [data-nextjs-dialog-content] {\n border: none;\n margin: 0;\n display: flex;\n flex-direction: column;\n position: relative;\n padding: 16px var(--next-dialog-padding-x);\n }\n\n [data-nextjs-dialog-content] > [data-nextjs-dialog-header] {\n flex-shrink: 0;\n margin-bottom: 8px;\n }\n\n [data-nextjs-dialog-content] > [data-nextjs-dialog-body] {\n position: relative;\n flex: 1 1 auto;\n }\n\n @media (max-height: 812px) {\n [data-nextjs-dialog-overlay] {\n max-height: calc(100% - 15px);\n }\n }\n\n @media (min-width: 576px) {\n [data-nextjs-dialog-root] {\n --next-dialog-max-width: 540px;\n }\n }\n\n @media (min-width: 768px) {\n [data-nextjs-dialog-root] {\n --next-dialog-max-width: 720px;\n }\n }\n\n @media (min-width: 992px) {\n [data-nextjs-dialog-root] {\n --next-dialog-max-width: 960px;\n }\n }\n";
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=styles.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../src/client/components/react-dev-overlay/ui/components/dialog/styles.ts"],"sourcesContent":["const styles = `\n [data-nextjs-dialog-root] {\n --next-dialog-radius: var(--rounded-xl);\n --next-dialog-max-width: 960px;\n --next-dialog-row-padding: 16px;\n --next-dialog-padding-x: 12px;\n --next-dialog-notch-height: 42px;\n --next-dialog-border-width: 1px;\n\n display: flex;\n flex-direction: column;\n width: 100%;\n max-height: calc(100% - 56px);\n max-width: var(--next-dialog-max-width);\n margin-right: auto;\n margin-left: auto;\n scale: 0.98;\n opacity: 0;\n transition-property: scale, opacity;\n transition-duration: var(--transition-duration);\n transition-timing-function: var(--timing-overlay);\n\n &[data-rendered='true'] {\n opacity: 1;\n scale: 1;\n }\n\n [data-nextjs-scroll-fader][data-side=\"top\"] {\n left: 1px;\n top: calc(var(--next-dialog-notch-height) + var(--next-dialog-border-width));\n width: calc(100% - var(--next-dialog-padding-x));\n opacity: 0;\n }\n }\n\n [data-nextjs-dialog] {\n outline: 0;\n }\n\n [data-nextjs-dialog], [data-nextjs-dialog] * {\n &::-webkit-scrollbar {\n width: 6px;\n height: 6px;\n border-radius: 0 0 1rem 1rem;\n margin-bottom: 1rem;\n }\n\n &::-webkit-scrollbar-button {\n display: none;\n }\n\n &::-webkit-scrollbar-track {\n border-radius: 0 0 1rem 1rem;\n background-color: var(--color-background-100);\n }\n \n &::-webkit-scrollbar-thumb {\n border-radius: 1rem;\n background-color: var(--color-gray-500);\n }\n }\n\n /* Place overflow: hidden on this so we can break out from [data-nextjs-dialog] */\n [data-nextjs-dialog-sizer] {\n overflow: hidden;\n border-radius: inherit;\n }\n\n [data-nextjs-dialog-backdrop] {\n opacity: 0;\n transition: opacity var(--transition-duration) var(--timing-overlay);\n }\n\n [data-nextjs-dialog-overlay][data-rendered='true']\n [data-nextjs-dialog-backdrop] {\n opacity: 1;\n }\n\n [data-nextjs-dialog-content] {\n border: none;\n margin: 0;\n display: flex;\n flex-direction: column;\n position: relative;\n padding: 16px var(--next-dialog-padding-x);\n }\n\n [data-nextjs-dialog-content] > [data-nextjs-dialog-header] {\n flex-shrink: 0;\n margin-bottom: 8px;\n }\n\n [data-nextjs-dialog-content] > [data-nextjs-dialog-body] {\n position: relative;\n flex: 1 1 auto;\n }\n\n @media (max-height: 812px) {\n [data-nextjs-dialog-overlay] {\n max-height: calc(100% - 15px);\n }\n }\n\n @media (min-width: 576px) {\n [data-nextjs-dialog-root] {\n --next-dialog-max-width: 540px;\n }\n }\n\n @media (min-width: 768px) {\n [data-nextjs-dialog-root] {\n --next-dialog-max-width: 720px;\n }\n }\n\n @media (min-width: 992px) {\n [data-nextjs-dialog-root] {\n --next-dialog-max-width: 960px;\n }\n }\n`\n\nexport { styles }\n"],"names":["styles"],"mappings":";;;;+BA0HSA;;;eAAAA;;;AA1HT,MAAMA,SAAU"}

View File

@@ -0,0 +1,8 @@
import type { OriginalStackFrame } from '../../../../utils/stack-frame';
interface CallStackProps {
frames: OriginalStackFrame[];
dialogResizerRef: React.RefObject<HTMLDivElement | null>;
}
export declare function CallStack({ frames, dialogResizerRef }: CallStackProps): import("react/jsx-runtime").JSX.Element;
export declare const CALL_STACK_STYLES = "\n .error-overlay-call-stack-container {\n position: relative;\n margin-top: 8px;\n }\n\n .error-overlay-call-stack-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n min-height: var(--size-28);\n padding: 8px 8px 12px 4px;\n width: 100%;\n }\n\n .error-overlay-call-stack-title {\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n\n margin: 0;\n\n color: var(--color-gray-1000);\n font-size: var(--size-16);\n font-weight: 500;\n }\n\n .error-overlay-call-stack-count {\n display: flex;\n justify-content: center;\n align-items: center;\n\n width: var(--size-20);\n height: var(--size-20);\n gap: 4px;\n\n color: var(--color-gray-1000);\n text-align: center;\n font-size: var(--size-11);\n font-weight: 500;\n line-height: var(--size-16);\n\n border-radius: var(--rounded-full);\n background: var(--color-gray-300);\n }\n\n .error-overlay-call-stack-ignored-list-toggle-button {\n all: unset;\n display: flex;\n align-items: center;\n gap: 6px;\n color: var(--color-gray-900);\n font-size: var(--size-14);\n line-height: var(--size-20);\n border-radius: 6px;\n padding: 4px 6px;\n margin-right: -6px;\n transition: background 150ms ease;\n\n &:hover {\n background: var(--color-gray-100);\n }\n\n &:focus {\n outline: var(--focus-ring);\n }\n\n svg {\n width: var(--size-16);\n height: var(--size-16);\n }\n }\n";
export {};

View File

@@ -0,0 +1,114 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
CALL_STACK_STYLES: null,
CallStack: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
CALL_STACK_STYLES: function() {
return CALL_STACK_STYLES;
},
CallStack: function() {
return CallStack;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _react = require("react");
const _callstackframe = require("../../call-stack-frame/call-stack-frame");
function CallStack(param) {
let { frames, dialogResizerRef } = param;
const initialDialogHeight = (0, _react.useRef)(NaN);
const [isIgnoreListOpen, setIsIgnoreListOpen] = (0, _react.useState)(false);
const ignoredFramesTally = (0, _react.useMemo)(()=>{
return frames.reduce((tally, frame)=>tally + (frame.ignored ? 1 : 0), 0);
}, [
frames
]);
function onToggleIgnoreList() {
const dialog = dialogResizerRef == null ? void 0 : dialogResizerRef.current;
if (!dialog) {
return;
}
const { height: currentHeight } = dialog == null ? void 0 : dialog.getBoundingClientRect();
if (!initialDialogHeight.current) {
initialDialogHeight.current = currentHeight;
}
if (isIgnoreListOpen) {
function onTransitionEnd() {
dialog.removeEventListener('transitionend', onTransitionEnd);
setIsIgnoreListOpen(false);
}
dialog.style.height = "" + initialDialogHeight.current + "px";
dialog.addEventListener('transitionend', onTransitionEnd);
} else {
setIsIgnoreListOpen(true);
}
}
return /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
className: "error-overlay-call-stack-container",
children: [
/*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
className: "error-overlay-call-stack-header",
children: [
/*#__PURE__*/ (0, _jsxruntime.jsxs)("p", {
className: "error-overlay-call-stack-title",
children: [
"Call Stack",
' ',
/*#__PURE__*/ (0, _jsxruntime.jsx)("span", {
className: "error-overlay-call-stack-count",
children: frames.length
})
]
}),
ignoredFramesTally > 0 && /*#__PURE__*/ (0, _jsxruntime.jsxs)("button", {
"data-expand-ignore-button": isIgnoreListOpen,
className: "error-overlay-call-stack-ignored-list-toggle-button",
onClick: onToggleIgnoreList,
children: [
(isIgnoreListOpen ? 'Hide' : 'Show') + " " + ignoredFramesTally + " ignore-listed frame(s)",
/*#__PURE__*/ (0, _jsxruntime.jsx)(ChevronUpDown, {})
]
})
]
}),
frames.map((frame, frameIndex)=>{
return !frame.ignored || isIgnoreListOpen ? /*#__PURE__*/ (0, _jsxruntime.jsx)(_callstackframe.CallStackFrame, {
frame: frame
}, frameIndex) : null;
})
]
});
}
function ChevronUpDown() {
return /*#__PURE__*/ (0, _jsxruntime.jsx)("svg", {
width: "16",
height: "16",
viewBox: "0 0 16 16",
fill: "none",
xmlns: "http://www.w3.org/2000/svg",
children: /*#__PURE__*/ (0, _jsxruntime.jsx)("path", {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M8.70722 2.39641C8.3167 2.00588 7.68353 2.00588 7.29301 2.39641L4.46978 5.21963L3.93945 5.74996L5.00011 6.81062L5.53044 6.28029L8.00011 3.81062L10.4698 6.28029L11.0001 6.81062L12.0608 5.74996L11.5304 5.21963L8.70722 2.39641ZM5.53044 9.71963L5.00011 9.1893L3.93945 10.25L4.46978 10.7803L7.29301 13.6035C7.68353 13.994 8.3167 13.994 8.70722 13.6035L11.5304 10.7803L12.0608 10.25L11.0001 9.1893L10.4698 9.71963L8.00011 12.1893L5.53044 9.71963Z",
fill: "currentColor"
})
});
}
const CALL_STACK_STYLES = "\n .error-overlay-call-stack-container {\n position: relative;\n margin-top: 8px;\n }\n\n .error-overlay-call-stack-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n min-height: var(--size-28);\n padding: 8px 8px 12px 4px;\n width: 100%;\n }\n\n .error-overlay-call-stack-title {\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n\n margin: 0;\n\n color: var(--color-gray-1000);\n font-size: var(--size-16);\n font-weight: 500;\n }\n\n .error-overlay-call-stack-count {\n display: flex;\n justify-content: center;\n align-items: center;\n\n width: var(--size-20);\n height: var(--size-20);\n gap: 4px;\n\n color: var(--color-gray-1000);\n text-align: center;\n font-size: var(--size-11);\n font-weight: 500;\n line-height: var(--size-16);\n\n border-radius: var(--rounded-full);\n background: var(--color-gray-300);\n }\n\n .error-overlay-call-stack-ignored-list-toggle-button {\n all: unset;\n display: flex;\n align-items: center;\n gap: 6px;\n color: var(--color-gray-900);\n font-size: var(--size-14);\n line-height: var(--size-20);\n border-radius: 6px;\n padding: 4px 6px;\n margin-right: -6px;\n transition: background 150ms ease;\n\n &:hover {\n background: var(--color-gray-100);\n }\n\n &:focus {\n outline: var(--focus-ring);\n }\n\n svg {\n width: var(--size-16);\n height: var(--size-16);\n }\n }\n";
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=call-stack.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,19 @@
import type { OverlayState } from '../../../../shared';
import { type DevToolsScale } from './dev-tools-info/preferences';
export declare function DevToolsIndicator({ state, errorCount, isBuildError, setIsErrorOverlayOpen, ...props }: {
state: OverlayState;
errorCount: number;
isBuildError: boolean;
setIsErrorOverlayOpen: (isErrorOverlayOpen: boolean | ((prev: boolean) => boolean)) => void;
scale: DevToolsScale;
setScale: (value: DevToolsScale) => void;
}): import("react/jsx-runtime").JSX.Element;
declare const OVERLAYS: {
readonly Root: "root";
readonly Turbo: "turbo";
readonly Route: "route";
readonly Preferences: "preferences";
};
export type Overlays = (typeof OVERLAYS)[keyof typeof OVERLAYS];
export declare const DEV_TOOLS_INDICATOR_STYLES = "\n .dev-tools-indicator-menu {\n -webkit-font-smoothing: antialiased;\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n background: var(--color-background-100);\n border: 1px solid var(--color-gray-alpha-400);\n background-clip: padding-box;\n box-shadow: var(--shadow-menu);\n border-radius: var(--rounded-xl);\n position: absolute;\n font-family: var(--font-stack-sans);\n z-index: 1000;\n overflow: hidden;\n opacity: 0;\n outline: 0;\n min-width: 248px;\n transition: opacity var(--animate-out-duration-ms)\n var(--animate-out-timing-function);\n\n &[data-rendered='true'] {\n opacity: 1;\n scale: 1;\n }\n }\n\n .dev-tools-indicator-inner {\n padding: 6px;\n width: 100%;\n }\n\n .dev-tools-indicator-item {\n display: flex;\n align-items: center;\n padding: 8px 6px;\n height: var(--size-36);\n border-radius: 6px;\n text-decoration: none !important;\n user-select: none;\n white-space: nowrap;\n\n svg {\n width: var(--size-16);\n height: var(--size-16);\n }\n\n &:focus-visible {\n outline: 0;\n }\n }\n\n .dev-tools-indicator-footer {\n background: var(--color-background-200);\n padding: 6px;\n border-top: 1px solid var(--color-gray-400);\n width: 100%;\n }\n\n .dev-tools-indicator-item[data-selected='true'] {\n cursor: pointer;\n background-color: var(--color-gray-200);\n }\n\n .dev-tools-indicator-label {\n font-size: var(--size-14);\n line-height: var(--size-20);\n color: var(--color-gray-1000);\n }\n\n .dev-tools-indicator-value {\n font-size: var(--size-14);\n line-height: var(--size-20);\n color: var(--color-gray-900);\n margin-left: auto;\n }\n\n .dev-tools-indicator-issue-count {\n --color-primary: var(--color-gray-800);\n --color-secondary: var(--color-gray-100);\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: center;\n gap: 8px;\n min-width: var(--size-40);\n height: var(--size-24);\n background: var(--color-background-100);\n border: 1px solid var(--color-gray-alpha-400);\n background-clip: padding-box;\n box-shadow: var(--shadow-small);\n padding: 2px;\n color: var(--color-gray-1000);\n border-radius: 128px;\n font-weight: 500;\n font-size: var(--size-13);\n font-variant-numeric: tabular-nums;\n\n &[data-has-issues='true'] {\n --color-primary: var(--color-red-800);\n --color-secondary: var(--color-red-100);\n }\n\n .dev-tools-indicator-issue-count-indicator {\n width: var(--size-8);\n height: var(--size-8);\n background: var(--color-primary);\n box-shadow: 0 0 0 2px var(--color-secondary);\n border-radius: 50%;\n }\n }\n\n .dev-tools-indicator-shortcut {\n display: flex;\n gap: 4px;\n\n kbd {\n width: var(--size-20);\n height: var(--size-20);\n display: flex;\n justify-content: center;\n align-items: center;\n border-radius: var(--rounded-md);\n border: 1px solid var(--color-gray-400);\n font-family: var(--font-stack-sans);\n background: var(--color-background-100);\n color: var(--color-gray-1000);\n text-align: center;\n font-size: var(--size-12);\n line-height: var(--size-16);\n }\n }\n";
export {};

View File

@@ -0,0 +1,397 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
DEV_TOOLS_INDICATOR_STYLES: null,
DevToolsIndicator: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
DEV_TOOLS_INDICATOR_STYLES: function() {
return DEV_TOOLS_INDICATOR_STYLES;
},
DevToolsIndicator: function() {
return DevToolsIndicator;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _jsxruntime = require("react/jsx-runtime");
const _react = require("react");
const _toast = require("../../toast");
const _nextlogo = require("./next-logo");
const _initialize = require("../../../../../../dev/dev-build-indicator/internal/initialize");
const _devrenderindicator = require("../../../../utils/dev-indicator/dev-render-indicator");
const _usedelayedrender = require("../../../hooks/use-delayed-render");
const _turbopackinfo = require("./dev-tools-info/turbopack-info");
const _routeinfo = require("./dev-tools-info/route-info");
const _gearicon = /*#__PURE__*/ _interop_require_default._(require("../../../icons/gear-icon"));
const _userpreferences = require("./dev-tools-info/user-preferences");
const _utils = require("./utils");
const _preferences = require("./dev-tools-info/preferences");
function DevToolsIndicator(param) {
let { state, errorCount, isBuildError, setIsErrorOverlayOpen, ...props } = param;
const [isDevToolsIndicatorVisible, setIsDevToolsIndicatorVisible] = (0, _react.useState)(true);
return /*#__PURE__*/ (0, _jsxruntime.jsx)(DevToolsPopover, {
routerType: state.routerType,
semver: state.versionInfo.installed,
issueCount: errorCount,
isStaticRoute: state.staticIndicator,
hide: ()=>{
setIsDevToolsIndicatorVisible(false);
fetch('/__nextjs_disable_dev_indicator', {
method: 'POST'
});
},
setIsErrorOverlayOpen: setIsErrorOverlayOpen,
isTurbopack: !!process.env.TURBOPACK,
disabled: state.disableDevIndicator || !isDevToolsIndicatorVisible,
isBuildError: isBuildError,
...props
});
}
const Context = /*#__PURE__*/ (0, _react.createContext)({});
const OVERLAYS = {
Root: 'root',
Turbo: 'turbo',
Route: 'route',
Preferences: 'preferences'
};
function DevToolsPopover(param) {
let { routerType, disabled, issueCount, isStaticRoute, isTurbopack, isBuildError, hide, setIsErrorOverlayOpen, scale, setScale } = param;
const menuRef = (0, _react.useRef)(null);
const triggerRef = (0, _react.useRef)(null);
const [open, setOpen] = (0, _react.useState)(null);
const [position, setPosition] = (0, _react.useState)((0, _preferences.getInitialPosition)());
const [selectedIndex, setSelectedIndex] = (0, _react.useState)(-1);
const isMenuOpen = open === OVERLAYS.Root;
const isTurbopackInfoOpen = open === OVERLAYS.Turbo;
const isRouteInfoOpen = open === OVERLAYS.Route;
const isPreferencesOpen = open === OVERLAYS.Preferences;
const { mounted: menuMounted, rendered: menuRendered } = (0, _usedelayedrender.useDelayedRender)(isMenuOpen, {
// Intentionally no fade in, makes the UI feel more immediate
enterDelay: 0,
// Graceful fade out to confirm that the UI did not break
exitDelay: _utils.MENU_DURATION_MS
});
// Features to make the menu accessible
(0, _utils.useFocusTrap)(menuRef, triggerRef, isMenuOpen);
(0, _utils.useClickOutside)(menuRef, triggerRef, isMenuOpen, closeMenu);
(0, _react.useEffect)(()=>{
if (open === null) {
// Avoid flashing selected state
const id = setTimeout(()=>{
setSelectedIndex(-1);
}, _utils.MENU_DURATION_MS);
return ()=>clearTimeout(id);
}
}, [
open
]);
function select(index) {
var _menuRef_current;
if (index === 'first') {
setTimeout(()=>{
var _menuRef_current;
const all = (_menuRef_current = menuRef.current) == null ? void 0 : _menuRef_current.querySelectorAll('[role="menuitem"]');
if (all) {
const firstIndex = all[0].getAttribute('data-index');
select(Number(firstIndex));
}
});
return;
}
if (index === 'last') {
setTimeout(()=>{
var _menuRef_current;
const all = (_menuRef_current = menuRef.current) == null ? void 0 : _menuRef_current.querySelectorAll('[role="menuitem"]');
if (all) {
const lastIndex = all.length - 1;
select(lastIndex);
}
});
return;
}
const el = (_menuRef_current = menuRef.current) == null ? void 0 : _menuRef_current.querySelector('[data-index="' + index + '"]');
if (el) {
setSelectedIndex(index);
el == null ? void 0 : el.focus();
}
}
function onMenuKeydown(e) {
e.preventDefault();
switch(e.key){
case 'ArrowDown':
const next = selectedIndex + 1;
select(next);
break;
case 'ArrowUp':
const prev = selectedIndex - 1;
select(prev);
break;
case 'Home':
select('first');
break;
case 'End':
select('last');
break;
default:
break;
}
}
function openErrorOverlay() {
setOpen(null);
if (issueCount > 0) {
setIsErrorOverlayOpen(true);
}
}
function toggleErrorOverlay() {
setIsErrorOverlayOpen((prev)=>!prev);
}
function openRootMenu() {
setOpen((prevOpen)=>{
if (prevOpen === null) select('first');
return OVERLAYS.Root;
});
}
function onTriggerClick() {
if (open === OVERLAYS.Root) {
setOpen(null);
} else {
openRootMenu();
setTimeout(()=>{
select('first');
});
}
}
function closeMenu() {
// Only close when we were on `Root`,
// otherwise it will close other overlays
setOpen((prevOpen)=>{
if (prevOpen === OVERLAYS.Root) {
return null;
}
return prevOpen;
});
}
function handleHideDevtools() {
setOpen(null);
hide();
}
const [vertical, horizontal] = position.split('-', 2);
const popover = {
[vertical]: 'calc(100% + 8px)',
[horizontal]: 0
};
return /*#__PURE__*/ (0, _jsxruntime.jsxs)(_toast.Toast, {
"data-nextjs-toast": true,
style: {
'--animate-out-duration-ms': "" + _utils.MENU_DURATION_MS + "ms",
'--animate-out-timing-function': _utils.MENU_CURVE,
boxShadow: 'none',
zIndex: 2147483647,
// Reset the toast component's default positions.
bottom: 'initial',
left: 'initial',
[vertical]: '20px',
[horizontal]: '20px'
},
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)(_nextlogo.NextLogo, {
ref: triggerRef,
"aria-haspopup": "menu",
"aria-expanded": isMenuOpen,
"aria-controls": "nextjs-dev-tools-menu",
"aria-label": "" + (isMenuOpen ? 'Close' : 'Open') + " Next.js Dev Tools",
"data-nextjs-dev-tools-button": true,
disabled: disabled,
issueCount: issueCount,
onTriggerClick: onTriggerClick,
toggleErrorOverlay: toggleErrorOverlay,
isDevBuilding: (0, _initialize.useIsDevBuilding)(),
isDevRendering: (0, _devrenderindicator.useIsDevRendering)(),
isBuildError: isBuildError,
scale: scale
}),
/*#__PURE__*/ (0, _jsxruntime.jsx)(_routeinfo.RouteInfo, {
isOpen: isRouteInfoOpen,
close: openRootMenu,
triggerRef: triggerRef,
style: popover,
routerType: routerType,
routeType: isStaticRoute ? 'Static' : 'Dynamic'
}),
/*#__PURE__*/ (0, _jsxruntime.jsx)(_turbopackinfo.TurbopackInfo, {
isOpen: isTurbopackInfoOpen,
close: openRootMenu,
triggerRef: triggerRef,
style: popover
}),
/*#__PURE__*/ (0, _jsxruntime.jsx)(_userpreferences.UserPreferences, {
isOpen: isPreferencesOpen,
close: openRootMenu,
triggerRef: triggerRef,
style: popover,
hide: handleHideDevtools,
setPosition: setPosition,
position: position,
scale: scale,
setScale: setScale
}),
menuMounted && /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
ref: menuRef,
id: "nextjs-dev-tools-menu",
role: "menu",
dir: "ltr",
"aria-orientation": "vertical",
"aria-label": "Next.js Dev Tools Items",
tabIndex: -1,
className: "dev-tools-indicator-menu",
onKeyDown: onMenuKeydown,
"data-rendered": menuRendered,
style: popover,
children: /*#__PURE__*/ (0, _jsxruntime.jsxs)(Context.Provider, {
value: {
closeMenu,
selectedIndex,
setSelectedIndex
},
children: [
/*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
className: "dev-tools-indicator-inner",
children: [
issueCount > 0 && /*#__PURE__*/ (0, _jsxruntime.jsx)(MenuItem, {
title: issueCount + " " + (issueCount === 1 ? 'issue' : 'issues') + " found. Click to view details in the dev overlay.",
index: 0,
label: "Issues",
value: /*#__PURE__*/ (0, _jsxruntime.jsx)(IssueCount, {
children: issueCount
}),
onClick: openErrorOverlay
}),
/*#__PURE__*/ (0, _jsxruntime.jsx)(MenuItem, {
title: "Current route is " + (isStaticRoute ? 'static' : 'dynamic') + ".",
label: "Route",
index: 1,
value: isStaticRoute ? 'Static' : 'Dynamic',
onClick: ()=>setOpen(OVERLAYS.Route),
"data-nextjs-route-type": isStaticRoute ? 'static' : 'dynamic'
}),
isTurbopack ? /*#__PURE__*/ (0, _jsxruntime.jsx)(MenuItem, {
title: "Turbopack is enabled.",
label: "Turbopack",
value: "Enabled"
}) : /*#__PURE__*/ (0, _jsxruntime.jsx)(MenuItem, {
index: 2,
title: "Learn about Turbopack and how to enable it in your application.",
label: "Try Turbopack",
value: /*#__PURE__*/ (0, _jsxruntime.jsx)(ChevronRight, {}),
onClick: ()=>setOpen(OVERLAYS.Turbo)
})
]
}),
/*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
className: "dev-tools-indicator-footer",
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(MenuItem, {
"data-preferences": true,
label: "Preferences",
value: /*#__PURE__*/ (0, _jsxruntime.jsx)(_gearicon.default, {}),
onClick: ()=>setOpen(OVERLAYS.Preferences),
index: isTurbopack ? 2 : 3
})
})
]
})
})
]
});
}
function ChevronRight() {
return /*#__PURE__*/ (0, _jsxruntime.jsx)("svg", {
xmlns: "http://www.w3.org/2000/svg",
width: "16",
height: "16",
viewBox: "0 0 16 16",
fill: "none",
children: /*#__PURE__*/ (0, _jsxruntime.jsx)("path", {
fill: "#666",
fillRule: "evenodd",
clipRule: "evenodd",
d: "M5.50011 1.93945L6.03044 2.46978L10.8537 7.293C11.2442 7.68353 11.2442 8.31669 10.8537 8.70722L6.03044 13.5304L5.50011 14.0608L4.43945 13.0001L4.96978 12.4698L9.43945 8.00011L4.96978 3.53044L4.43945 3.00011L5.50011 1.93945Z"
})
});
}
function MenuItem(param) {
let { index, label, value, onClick, href, ...props } = param;
const isInteractive = typeof onClick === 'function' || typeof href === 'string';
const { closeMenu, selectedIndex, setSelectedIndex } = (0, _react.useContext)(Context);
const selected = selectedIndex === index;
function click() {
if (isInteractive) {
onClick == null ? void 0 : onClick();
closeMenu();
if (href) {
window.open(href, '_blank', 'noopener, noreferrer');
}
}
}
return /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
className: "dev-tools-indicator-item",
"data-index": index,
"data-selected": selected,
onClick: click,
// Needs `onMouseMove` instead of enter to work together
// with keyboard and mouse input
onMouseMove: ()=>{
if (isInteractive && index !== undefined && selectedIndex !== index) {
setSelectedIndex(index);
}
},
onMouseLeave: ()=>setSelectedIndex(-1),
onKeyDown: (e)=>{
if (e.key === 'Enter' || e.key === ' ') {
click();
}
},
role: isInteractive ? 'menuitem' : undefined,
tabIndex: selected ? 0 : -1,
...props,
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)("span", {
className: "dev-tools-indicator-label",
children: label
}),
/*#__PURE__*/ (0, _jsxruntime.jsx)("span", {
className: "dev-tools-indicator-value",
children: value
})
]
});
}
function IssueCount(param) {
let { children } = param;
return /*#__PURE__*/ (0, _jsxruntime.jsxs)("span", {
className: "dev-tools-indicator-issue-count",
"data-has-issues": children > 0,
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)("span", {
className: "dev-tools-indicator-issue-count-indicator"
}),
children
]
});
}
const DEV_TOOLS_INDICATOR_STYLES = "\n .dev-tools-indicator-menu {\n -webkit-font-smoothing: antialiased;\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n background: var(--color-background-100);\n border: 1px solid var(--color-gray-alpha-400);\n background-clip: padding-box;\n box-shadow: var(--shadow-menu);\n border-radius: var(--rounded-xl);\n position: absolute;\n font-family: var(--font-stack-sans);\n z-index: 1000;\n overflow: hidden;\n opacity: 0;\n outline: 0;\n min-width: 248px;\n transition: opacity var(--animate-out-duration-ms)\n var(--animate-out-timing-function);\n\n &[data-rendered='true'] {\n opacity: 1;\n scale: 1;\n }\n }\n\n .dev-tools-indicator-inner {\n padding: 6px;\n width: 100%;\n }\n\n .dev-tools-indicator-item {\n display: flex;\n align-items: center;\n padding: 8px 6px;\n height: var(--size-36);\n border-radius: 6px;\n text-decoration: none !important;\n user-select: none;\n white-space: nowrap;\n\n svg {\n width: var(--size-16);\n height: var(--size-16);\n }\n\n &:focus-visible {\n outline: 0;\n }\n }\n\n .dev-tools-indicator-footer {\n background: var(--color-background-200);\n padding: 6px;\n border-top: 1px solid var(--color-gray-400);\n width: 100%;\n }\n\n .dev-tools-indicator-item[data-selected='true'] {\n cursor: pointer;\n background-color: var(--color-gray-200);\n }\n\n .dev-tools-indicator-label {\n font-size: var(--size-14);\n line-height: var(--size-20);\n color: var(--color-gray-1000);\n }\n\n .dev-tools-indicator-value {\n font-size: var(--size-14);\n line-height: var(--size-20);\n color: var(--color-gray-900);\n margin-left: auto;\n }\n\n .dev-tools-indicator-issue-count {\n --color-primary: var(--color-gray-800);\n --color-secondary: var(--color-gray-100);\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: center;\n gap: 8px;\n min-width: var(--size-40);\n height: var(--size-24);\n background: var(--color-background-100);\n border: 1px solid var(--color-gray-alpha-400);\n background-clip: padding-box;\n box-shadow: var(--shadow-small);\n padding: 2px;\n color: var(--color-gray-1000);\n border-radius: 128px;\n font-weight: 500;\n font-size: var(--size-13);\n font-variant-numeric: tabular-nums;\n\n &[data-has-issues='true'] {\n --color-primary: var(--color-red-800);\n --color-secondary: var(--color-red-100);\n }\n\n .dev-tools-indicator-issue-count-indicator {\n width: var(--size-8);\n height: var(--size-8);\n background: var(--color-primary);\n box-shadow: 0 0 0 2px var(--color-secondary);\n border-radius: 50%;\n }\n }\n\n .dev-tools-indicator-shortcut {\n display: flex;\n gap: 4px;\n\n kbd {\n width: var(--size-20);\n height: var(--size-20);\n display: flex;\n justify-content: center;\n align-items: center;\n border-radius: var(--rounded-md);\n border: 1px solid var(--color-gray-400);\n font-family: var(--font-stack-sans);\n background: var(--color-background-100);\n color: var(--color-gray-1000);\n text-align: center;\n font-size: var(--size-12);\n line-height: var(--size-16);\n }\n }\n";
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=dev-tools-indicator.js.map

Some files were not shown because too many files have changed in this diff Show More