inital commit

This commit is contained in:
2026-01-01 15:25:19 +05:30
commit f0ae49465a
36361 changed files with 4894111 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
export function css(strings) {
for(var _len = arguments.length, keys = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
keys[_key - 1] = arguments[_key];
}
const lastIndex = strings.length - 1;
const str = // Convert template literal into a single line string
strings.slice(0, lastIndex).reduce((p, s, i)=>p + s + keys[i], '') + strings[lastIndex];
return str// Remove comments
.replace(/\/\*[\s\S]*?\*\//g, '')// Remove whitespace, tabs, and newlines
.replace(/\s+/g, ' ')// Remove spaces before and after semicolons, and spaces after commas
.replace(/\s*([:;,{}])\s*/g, '$1')// Remove extra semicolons
.replace(/;+}/g, '}')// Trim leading and trailing whitespaces
.trim();
}
//# sourceMappingURL=css.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/utils/css.ts"],"sourcesContent":["export function css(\n strings: TemplateStringsArray,\n ...keys: readonly string[]\n): string {\n const lastIndex = strings.length - 1\n const str =\n // Convert template literal into a single line string\n strings.slice(0, lastIndex).reduce((p, s, i) => p + s + keys[i], '') +\n strings[lastIndex]\n\n return (\n str\n // Remove comments\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n // Remove whitespace, tabs, and newlines\n .replace(/\\s+/g, ' ')\n // Remove spaces before and after semicolons, and spaces after commas\n .replace(/\\s*([:;,{}])\\s*/g, '$1')\n // Remove extra semicolons\n .replace(/;+}/g, '}')\n // Trim leading and trailing whitespaces\n .trim()\n )\n}\n"],"names":["css","strings","keys","lastIndex","length","str","slice","reduce","p","s","i","replace","trim"],"mappings":"AAAA,OAAO,SAASA,IACdC,OAA6B;IAC7B,IAAA,IAAA,OAAA,UAAA,QAAA,AAAGC,OAAH,UAAA,OAAA,IAAA,OAAA,QAAA,OAAA,GAAA,OAAA,MAAA;QAAGA,KAAH,OAAA,KAAA,SAAA,CAAA,KAA0B;;IAE1B,MAAMC,YAAYF,QAAQG,MAAM,GAAG;IACnC,MAAMC,MACJ,qDAAqD;IACrDJ,QAAQK,KAAK,CAAC,GAAGH,WAAWI,MAAM,CAAC,CAACC,GAAGC,GAAGC,IAAMF,IAAIC,IAAIP,IAAI,CAACQ,EAAE,EAAE,MACjET,OAAO,CAACE,UAAU;IAEpB,OACEE,GACE,kBAAkB;KACjBM,OAAO,CAAC,qBAAqB,GAC9B,wCAAwC;KACvCA,OAAO,CAAC,QAAQ,IACjB,qEAAqE;KACpEA,OAAO,CAAC,oBAAoB,KAC7B,0BAA0B;KACzBA,OAAO,CAAC,QAAQ,IACjB,wCAAwC;KACvCC,IAAI;AAEX"}

View File

@@ -0,0 +1,30 @@
/*
* Singleton store to track whether the app is currently being rendered
* Used by the dev tools indicator to show render status
*/ import { useSyncExternalStore } from 'react';
let isVisible = false;
let listeners = [];
const subscribe = (listener)=>{
listeners.push(listener);
return ()=>{
listeners = listeners.filter((l)=>l !== listener);
};
};
const getSnapshot = ()=>isVisible;
const show = ()=>{
isVisible = true;
listeners.forEach((listener)=>listener());
};
const hide = ()=>{
isVisible = false;
listeners.forEach((listener)=>listener());
};
export function useIsDevRendering() {
return useSyncExternalStore(subscribe, getSnapshot);
}
export const devRenderIndicator = {
show,
hide
};
//# sourceMappingURL=dev-render-indicator.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/client/components/react-dev-overlay/utils/dev-indicator/dev-render-indicator.tsx"],"sourcesContent":["/*\n * Singleton store to track whether the app is currently being rendered\n * Used by the dev tools indicator to show render status\n */\n\nimport { useSyncExternalStore } from 'react'\n\nlet isVisible = false\nlet listeners: Array<() => void> = []\n\nconst subscribe = (listener: () => void) => {\n listeners.push(listener)\n return () => {\n listeners = listeners.filter((l) => l !== listener)\n }\n}\n\nconst getSnapshot = () => isVisible\n\nconst show = () => {\n isVisible = true\n listeners.forEach((listener) => listener())\n}\n\nconst hide = () => {\n isVisible = false\n listeners.forEach((listener) => listener())\n}\n\nexport function useIsDevRendering() {\n return useSyncExternalStore(subscribe, getSnapshot)\n}\n\nexport const devRenderIndicator = {\n show,\n hide,\n}\n"],"names":["useSyncExternalStore","isVisible","listeners","subscribe","listener","push","filter","l","getSnapshot","show","forEach","hide","useIsDevRendering","devRenderIndicator"],"mappings":"AAAA;;;CAGC,GAED,SAASA,oBAAoB,QAAQ,QAAO;AAE5C,IAAIC,YAAY;AAChB,IAAIC,YAA+B,EAAE;AAErC,MAAMC,YAAY,CAACC;IACjBF,UAAUG,IAAI,CAACD;IACf,OAAO;QACLF,YAAYA,UAAUI,MAAM,CAAC,CAACC,IAAMA,MAAMH;IAC5C;AACF;AAEA,MAAMI,cAAc,IAAMP;AAE1B,MAAMQ,OAAO;IACXR,YAAY;IACZC,UAAUQ,OAAO,CAAC,CAACN,WAAaA;AAClC;AAEA,MAAMO,OAAO;IACXV,YAAY;IACZC,UAAUQ,OAAO,CAAC,CAACN,WAAaA;AAClC;AAEA,OAAO,SAASQ;IACd,OAAOZ,qBAAqBG,WAAWK;AACzC;AAEA,OAAO,MAAMK,qBAAqB;IAChCJ;IACAE;AACF,EAAC"}

View File

@@ -0,0 +1,17 @@
import { useEffect, useTransition } from 'react';
import { devRenderIndicator } from './dev-render-indicator';
export const useSyncDevRenderIndicatorInternal = ()=>{
const [isPending, startTransition] = useTransition();
useEffect(()=>{
if (isPending) {
devRenderIndicator.show();
} else {
devRenderIndicator.hide();
}
}, [
isPending
]);
return startTransition;
};
//# sourceMappingURL=use-sync-dev-render-indicator-internal.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/client/components/react-dev-overlay/utils/dev-indicator/use-sync-dev-render-indicator-internal.tsx"],"sourcesContent":["import { useEffect, useTransition } from 'react'\nimport { devRenderIndicator } from './dev-render-indicator'\n\nexport const useSyncDevRenderIndicatorInternal = () => {\n const [isPending, startTransition] = useTransition()\n\n useEffect(() => {\n if (isPending) {\n devRenderIndicator.show()\n } else {\n devRenderIndicator.hide()\n }\n }, [isPending])\n\n return startTransition\n}\n"],"names":["useEffect","useTransition","devRenderIndicator","useSyncDevRenderIndicatorInternal","isPending","startTransition","show","hide"],"mappings":"AAAA,SAASA,SAAS,EAAEC,aAAa,QAAQ,QAAO;AAChD,SAASC,kBAAkB,QAAQ,yBAAwB;AAE3D,OAAO,MAAMC,oCAAoC;IAC/C,MAAM,CAACC,WAAWC,gBAAgB,GAAGJ;IAErCD,UAAU;QACR,IAAII,WAAW;YACbF,mBAAmBI,IAAI;QACzB,OAAO;YACLJ,mBAAmBK,IAAI;QACzB;IACF,GAAG;QAACH;KAAU;IAEd,OAAOC;AACT,EAAC"}

View File

@@ -0,0 +1,16 @@
const NOOP = (fn)=>fn();
/**
* Returns a transition function that can be used to wrap router actions.
* This allows us to tap into the transition state of the router as an
* approximation of React render time.
*/ export const useSyncDevRenderIndicator = ()=>{
let syncDevRenderIndicator = NOOP;
if (process.env.NODE_ENV === 'development') {
const { useSyncDevRenderIndicatorInternal } = require('./use-sync-dev-render-indicator-internal');
// eslint-disable-next-line react-hooks/rules-of-hooks
syncDevRenderIndicator = useSyncDevRenderIndicatorInternal();
}
return syncDevRenderIndicator;
};
//# sourceMappingURL=use-sync-dev-render-indicator.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../src/client/components/react-dev-overlay/utils/dev-indicator/use-sync-dev-render-indicator.tsx"],"sourcesContent":["const NOOP = (fn: () => void) => fn()\n\n/**\n * Returns a transition function that can be used to wrap router actions.\n * This allows us to tap into the transition state of the router as an\n * approximation of React render time.\n */\nexport const useSyncDevRenderIndicator = () => {\n let syncDevRenderIndicator = NOOP\n\n if (process.env.NODE_ENV === 'development') {\n const { useSyncDevRenderIndicatorInternal } =\n require('./use-sync-dev-render-indicator-internal') as typeof import('./use-sync-dev-render-indicator-internal')\n\n // eslint-disable-next-line react-hooks/rules-of-hooks\n syncDevRenderIndicator = useSyncDevRenderIndicatorInternal()\n }\n\n return syncDevRenderIndicator\n}\n"],"names":["NOOP","fn","useSyncDevRenderIndicator","syncDevRenderIndicator","process","env","NODE_ENV","useSyncDevRenderIndicatorInternal","require"],"mappings":"AAAA,MAAMA,OAAO,CAACC,KAAmBA;AAEjC;;;;CAIC,GACD,OAAO,MAAMC,4BAA4B;IACvC,IAAIC,yBAAyBH;IAE7B,IAAII,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;QAC1C,MAAM,EAAEC,iCAAiC,EAAE,GACzCC,QAAQ;QAEV,sDAAsD;QACtDL,yBAAyBI;IAC3B;IAEA,OAAOJ;AACT,EAAC"}

View File

@@ -0,0 +1,147 @@
/**
MIT License
Copyright (c) 2015-present, Facebook, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/ import stripAnsi from 'next/dist/compiled/strip-ansi';
// This file is based on https://github.com/facebook/create-react-app/blob/7b1a32be6ec9f99a6c9a3c66813f3ac09c4736b9/packages/react-dev-utils/formatWebpackMessages.js
// It's been edited to remove chalk and CRA-specific logic
const friendlySyntaxErrorLabel = 'Syntax error:';
const WEBPACK_BREAKING_CHANGE_POLYFILLS = '\n\nBREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.';
function isLikelyASyntaxError(message) {
return stripAnsi(message).includes(friendlySyntaxErrorLabel);
}
let hadMissingSassError = false;
// Cleans up webpack error messages.
function formatMessage(message, verbose, importTraceNote) {
// TODO: Replace this once webpack 5 is stable
if (typeof message === 'object' && message.message) {
const filteredModuleTrace = message.moduleTrace && message.moduleTrace.filter((trace)=>!/next-(middleware|client-pages|route|edge-function)-loader\.js/.test(trace.originName));
let body = message.message;
const breakingChangeIndex = body.indexOf(WEBPACK_BREAKING_CHANGE_POLYFILLS);
if (breakingChangeIndex >= 0) {
body = body.slice(0, breakingChangeIndex);
}
message = (message.moduleName ? stripAnsi(message.moduleName) + '\n' : '') + (message.file ? stripAnsi(message.file) + '\n' : '') + body + (message.details && verbose ? '\n' + message.details : '') + (filteredModuleTrace && filteredModuleTrace.length ? (importTraceNote || '\n\nImport trace for requested module:') + filteredModuleTrace.map((trace)=>"\n" + trace.moduleName).join('') : '') + (message.stack && verbose ? '\n' + message.stack : '');
}
let lines = message.split('\n');
// Strip Webpack-added headers off errors/warnings
// https://github.com/webpack/webpack/blob/master/lib/ModuleError.js
lines = lines.filter((line)=>!/Module [A-z ]+\(from/.test(line));
// Transform parsing error into syntax error
// TODO: move this to our ESLint formatter?
lines = lines.map((line)=>{
const parsingError = /Line (\d+):(?:(\d+):)?\s*Parsing error: (.+)$/.exec(line);
if (!parsingError) {
return line;
}
const [, errorLine, errorColumn, errorMessage] = parsingError;
return friendlySyntaxErrorLabel + " " + errorMessage + " (" + errorLine + ":" + errorColumn + ")";
});
message = lines.join('\n');
// Smoosh syntax errors (commonly found in CSS)
message = message.replace(/SyntaxError\s+\((\d+):(\d+)\)\s*(.+?)\n/g, "" + friendlySyntaxErrorLabel + " $3 ($1:$2)\n");
// Clean up export errors
message = message.replace(/^.*export '(.+?)' was not found in '(.+?)'.*$/gm, "Attempted import error: '$1' is not exported from '$2'.");
message = message.replace(/^.*export 'default' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm, "Attempted import error: '$2' does not contain a default export (imported as '$1').");
message = message.replace(/^.*export '(.+?)' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm, "Attempted import error: '$1' is not exported from '$3' (imported as '$2').");
lines = message.split('\n');
// Remove leading newline
if (lines.length > 2 && lines[1].trim() === '') {
lines.splice(1, 1);
}
// Cleans up verbose "module not found" messages for files and packages.
if (lines[1] && lines[1].startsWith('Module not found: ')) {
lines = [
lines[0],
lines[1].replace('Error: ', '').replace('Module not found: Cannot find file:', 'Cannot find file:'),
...lines.slice(2)
];
}
// Add helpful message for users trying to use Sass for the first time
if (lines[1] && lines[1].match(/Cannot find module.+sass/)) {
// ./file.module.scss (<<loader info>>) => ./file.module.scss
const firstLine = lines[0].split('!');
lines[0] = firstLine[firstLine.length - 1];
lines[1] = "To use Next.js' built-in Sass support, you first need to install `sass`.\n";
lines[1] += 'Run `npm i sass` or `yarn add sass` inside your workspace.\n';
lines[1] += '\nLearn more: https://nextjs.org/docs/messages/install-sass';
// dispose of unhelpful stack trace
lines = lines.slice(0, 2);
hadMissingSassError = true;
} else if (hadMissingSassError && message.match(/(sass-loader|resolve-url-loader: CSS error)/)) {
// dispose of unhelpful stack trace following missing sass module
lines = [];
}
if (!verbose) {
message = lines.join('\n');
// Internal stacks are generally useless so we strip them... with the
// exception of stacks containing `webpack:` because they're normally
// from user code generated by Webpack. For more information see
// https://github.com/facebook/create-react-app/pull/1050
message = message.replace(/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm, '') // at ... ...:x:y
;
message = message.replace(/^\s*at\s<anonymous>(\n|$)/gm, '') // at <anonymous>
;
message = message.replace(/File was processed with these loaders:\n(.+[\\/](next[\\/]dist[\\/].+|@next[\\/]react-refresh-utils[\\/]loader)\.js\n)*You may need an additional loader to handle the result of these loaders.\n/g, '');
lines = message.split('\n');
}
// Remove duplicated newlines
lines = lines.filter((line, index, arr)=>index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim());
// Reassemble the message
message = lines.join('\n');
return message.trim();
}
export default function formatWebpackMessages(json, verbose) {
const formattedErrors = json.errors.map((message)=>{
const isUnknownNextFontError = message.message.includes('An error occurred in `next/font`.');
return formatMessage(message, isUnknownNextFontError || verbose);
});
const formattedWarnings = json.warnings.map((message)=>{
return formatMessage(message, verbose);
});
// Reorder errors to put the most relevant ones first.
let reactServerComponentsError = -1;
for(let i = 0; i < formattedErrors.length; i++){
const error = formattedErrors[i];
if (error.includes('ReactServerComponentsError')) {
reactServerComponentsError = i;
break;
}
}
// Move the reactServerComponentsError to the top if it exists
if (reactServerComponentsError !== -1) {
const error = formattedErrors.splice(reactServerComponentsError, 1);
formattedErrors.unshift(error[0]);
}
const result = {
...json,
errors: formattedErrors,
warnings: formattedWarnings
};
if (!verbose && result.errors.some(isLikelyASyntaxError)) {
// If there are any syntax errors, show just them.
result.errors = result.errors.filter(isLikelyASyntaxError);
result.warnings = [];
}
return result;
}
//# sourceMappingURL=format-webpack-messages.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,82 @@
import { ACTION_UNHANDLED_ERROR, ACTION_UNHANDLED_REJECTION } from '../shared';
import { getOriginalStackFrames } from './stack-frame';
import { getErrorSource } from '../../../../shared/lib/error-source';
import React from 'react';
export const useFrames = (error)=>{
if ('use' in React) {
const frames = error.frames;
if (typeof frames !== 'function') {
throw Object.defineProperty(new Error('Invariant: frames must be a function when the React version has React.use. This is a bug in Next.js.'), "__NEXT_ERROR_CODE", {
value: "E636",
enumerable: false,
configurable: true
});
}
return React.use(frames());
} else {
if (!Array.isArray(error.frames)) {
throw Object.defineProperty(new Error('Invariant: frames must be an array when the React version does not have React.use. This is a bug in Next.js.'), "__NEXT_ERROR_CODE", {
value: "E637",
enumerable: false,
configurable: true
});
}
return error.frames;
}
};
export async function getErrorByType(ev, isAppDir) {
const { id, event } = ev;
switch(event.type){
case ACTION_UNHANDLED_ERROR:
case ACTION_UNHANDLED_REJECTION:
{
const baseError = {
id,
runtime: true,
error: event.reason
};
if ('use' in React) {
const readyRuntimeError = {
...baseError,
// createMemoizedPromise dedups calls to getOriginalStackFrames
frames: createMemoizedPromise(async ()=>{
return await getOriginalStackFrames(event.frames, getErrorSource(event.reason), isAppDir);
})
};
if (event.type === ACTION_UNHANDLED_ERROR) {
readyRuntimeError.componentStackFrames = event.componentStackFrames;
}
return readyRuntimeError;
} else {
const readyRuntimeError = {
...baseError,
// createMemoizedPromise dedups calls to getOriginalStackFrames
frames: await getOriginalStackFrames(event.frames, getErrorSource(event.reason), isAppDir)
};
if (event.type === ACTION_UNHANDLED_ERROR) {
readyRuntimeError.componentStackFrames = event.componentStackFrames;
}
return readyRuntimeError;
}
}
default:
{
break;
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _ = event;
throw Object.defineProperty(new Error('type system invariant violation'), "__NEXT_ERROR_CODE", {
value: "E335",
enumerable: false,
configurable: true
});
}
function createMemoizedPromise(promiseFactory) {
const cachedPromise = promiseFactory();
return function() {
return cachedPromise;
};
}
//# sourceMappingURL=get-error-by-type.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,22 @@
import { normalizedAssetPrefix } from '../../../../shared/lib/normalized-asset-prefix';
function getSocketProtocol(assetPrefix) {
let protocol = window.location.protocol;
try {
// assetPrefix is a url
protocol = new URL(assetPrefix).protocol;
} catch (e) {}
return protocol === 'http:' ? 'ws:' : 'wss:';
}
export function getSocketUrl(assetPrefix) {
const prefix = normalizedAssetPrefix(assetPrefix);
const protocol = getSocketProtocol(assetPrefix || '');
if (URL.canParse(prefix)) {
// since normalized asset prefix is ensured to be a URL format,
// we can safely replace the protocol
return prefix.replace(/^http/, 'ws');
}
const { hostname, port } = window.location;
return protocol + "//" + hostname + (port ? ":" + port : '') + prefix;
}
//# sourceMappingURL=get-socket-url.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/utils/get-socket-url.ts"],"sourcesContent":["import { normalizedAssetPrefix } from '../../../../shared/lib/normalized-asset-prefix'\n\nfunction getSocketProtocol(assetPrefix: string): string {\n let protocol = window.location.protocol\n\n try {\n // assetPrefix is a url\n protocol = new URL(assetPrefix).protocol\n } catch {}\n\n return protocol === 'http:' ? 'ws:' : 'wss:'\n}\n\nexport function getSocketUrl(assetPrefix: string | undefined): string {\n const prefix = normalizedAssetPrefix(assetPrefix)\n const protocol = getSocketProtocol(assetPrefix || '')\n\n if (URL.canParse(prefix)) {\n // since normalized asset prefix is ensured to be a URL format,\n // we can safely replace the protocol\n return prefix.replace(/^http/, 'ws')\n }\n\n const { hostname, port } = window.location\n return `${protocol}//${hostname}${port ? `:${port}` : ''}${prefix}`\n}\n"],"names":["normalizedAssetPrefix","getSocketProtocol","assetPrefix","protocol","window","location","URL","getSocketUrl","prefix","canParse","replace","hostname","port"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,iDAAgD;AAEtF,SAASC,kBAAkBC,WAAmB;IAC5C,IAAIC,WAAWC,OAAOC,QAAQ,CAACF,QAAQ;IAEvC,IAAI;QACF,uBAAuB;QACvBA,WAAW,IAAIG,IAAIJ,aAAaC,QAAQ;IAC1C,EAAE,UAAM,CAAC;IAET,OAAOA,aAAa,UAAU,QAAQ;AACxC;AAEA,OAAO,SAASI,aAAaL,WAA+B;IAC1D,MAAMM,SAASR,sBAAsBE;IACrC,MAAMC,WAAWF,kBAAkBC,eAAe;IAElD,IAAII,IAAIG,QAAQ,CAACD,SAAS;QACxB,+DAA+D;QAC/D,qCAAqC;QACrC,OAAOA,OAAOE,OAAO,CAAC,SAAS;IACjC;IAEA,MAAM,EAAEC,QAAQ,EAAEC,IAAI,EAAE,GAAGR,OAAOC,QAAQ;IAC1C,OAAO,AAAGF,WAAS,OAAIQ,WAAWC,CAAAA,OAAO,AAAC,MAAGA,OAAS,EAAC,IAAIJ;AAC7D"}

View File

@@ -0,0 +1,71 @@
import fs from 'fs/promises';
import path from 'path';
import url from 'url';
import dataUriToBuffer from 'next/dist/compiled/data-uri-to-buffer';
import { getSourceMapUrl } from './get-source-map-url';
export async function getSourceMapFromFile(filename) {
filename = filename.startsWith('file://') ? url.fileURLToPath(filename) : filename;
let fileContents;
try {
fileContents = await fs.readFile(filename, 'utf-8');
} catch (error) {
throw Object.defineProperty(new Error("Failed to read file contents of " + filename + ".", {
cause: error
}), "__NEXT_ERROR_CODE", {
value: "E466",
enumerable: false,
configurable: true
});
}
const sourceUrl = getSourceMapUrl(fileContents);
if (!sourceUrl) {
return undefined;
}
if (sourceUrl.startsWith('data:')) {
let buffer;
try {
buffer = dataUriToBuffer(sourceUrl);
} catch (error) {
throw Object.defineProperty(new Error("Failed to parse source map URL for " + filename + ".", {
cause: error
}), "__NEXT_ERROR_CODE", {
value: "E199",
enumerable: false,
configurable: true
});
}
if (buffer.type !== 'application/json') {
throw Object.defineProperty(new Error("Unknown source map type for " + filename + ": " + buffer.typeFull + "."), "__NEXT_ERROR_CODE", {
value: "E113",
enumerable: false,
configurable: true
});
}
try {
return JSON.parse(buffer.toString());
} catch (error) {
throw Object.defineProperty(new Error("Failed to parse source map for " + filename + ".", {
cause: error
}), "__NEXT_ERROR_CODE", {
value: "E318",
enumerable: false,
configurable: true
});
}
}
const sourceMapFilename = path.resolve(path.dirname(filename), decodeURIComponent(sourceUrl));
try {
const sourceMapContents = await fs.readFile(sourceMapFilename, 'utf-8');
return JSON.parse(sourceMapContents.toString());
} catch (error) {
throw Object.defineProperty(new Error("Failed to parse source map " + sourceMapFilename + ".", {
cause: error
}), "__NEXT_ERROR_CODE", {
value: "E220",
enumerable: false,
configurable: true
});
}
}
//# sourceMappingURL=get-source-map-from-file.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/utils/get-source-map-from-file.ts"],"sourcesContent":["import fs from 'fs/promises'\nimport path from 'path'\nimport url from 'url'\nimport type { RawSourceMap } from 'next/dist/compiled/source-map08'\nimport dataUriToBuffer from 'next/dist/compiled/data-uri-to-buffer'\nimport { getSourceMapUrl } from './get-source-map-url'\n\nexport async function getSourceMapFromFile(\n filename: string\n): Promise<RawSourceMap | undefined> {\n filename = filename.startsWith('file://')\n ? url.fileURLToPath(filename)\n : filename\n\n let fileContents: string\n\n try {\n fileContents = await fs.readFile(filename, 'utf-8')\n } catch (error) {\n throw new Error(`Failed to read file contents of ${filename}.`, {\n cause: error,\n })\n }\n\n const sourceUrl = getSourceMapUrl(fileContents)\n\n if (!sourceUrl) {\n return undefined\n }\n\n if (sourceUrl.startsWith('data:')) {\n let buffer: dataUriToBuffer.MimeBuffer\n\n try {\n buffer = dataUriToBuffer(sourceUrl)\n } catch (error) {\n throw new Error(`Failed to parse source map URL for ${filename}.`, {\n cause: error,\n })\n }\n\n if (buffer.type !== 'application/json') {\n throw new Error(\n `Unknown source map type for ${filename}: ${buffer.typeFull}.`\n )\n }\n\n try {\n return JSON.parse(buffer.toString())\n } catch (error) {\n throw new Error(`Failed to parse source map for ${filename}.`, {\n cause: error,\n })\n }\n }\n\n const sourceMapFilename = path.resolve(\n path.dirname(filename),\n decodeURIComponent(sourceUrl)\n )\n\n try {\n const sourceMapContents = await fs.readFile(sourceMapFilename, 'utf-8')\n\n return JSON.parse(sourceMapContents.toString())\n } catch (error) {\n throw new Error(`Failed to parse source map ${sourceMapFilename}.`, {\n cause: error,\n })\n }\n}\n"],"names":["fs","path","url","dataUriToBuffer","getSourceMapUrl","getSourceMapFromFile","filename","startsWith","fileURLToPath","fileContents","readFile","error","Error","cause","sourceUrl","undefined","buffer","type","typeFull","JSON","parse","toString","sourceMapFilename","resolve","dirname","decodeURIComponent","sourceMapContents"],"mappings":"AAAA,OAAOA,QAAQ,cAAa;AAC5B,OAAOC,UAAU,OAAM;AACvB,OAAOC,SAAS,MAAK;AAErB,OAAOC,qBAAqB,wCAAuC;AACnE,SAASC,eAAe,QAAQ,uBAAsB;AAEtD,OAAO,eAAeC,qBACpBC,QAAgB;IAEhBA,WAAWA,SAASC,UAAU,CAAC,aAC3BL,IAAIM,aAAa,CAACF,YAClBA;IAEJ,IAAIG;IAEJ,IAAI;QACFA,eAAe,MAAMT,GAAGU,QAAQ,CAACJ,UAAU;IAC7C,EAAE,OAAOK,OAAO;QACd,MAAM,qBAEJ,CAFI,IAAIC,MAAM,AAAC,qCAAkCN,WAAS,KAAI;YAC9DO,OAAOF;QACT,IAFM,qBAAA;mBAAA;wBAAA;0BAAA;QAEL;IACH;IAEA,MAAMG,YAAYV,gBAAgBK;IAElC,IAAI,CAACK,WAAW;QACd,OAAOC;IACT;IAEA,IAAID,UAAUP,UAAU,CAAC,UAAU;QACjC,IAAIS;QAEJ,IAAI;YACFA,SAASb,gBAAgBW;QAC3B,EAAE,OAAOH,OAAO;YACd,MAAM,qBAEJ,CAFI,IAAIC,MAAM,AAAC,wCAAqCN,WAAS,KAAI;gBACjEO,OAAOF;YACT,IAFM,qBAAA;uBAAA;4BAAA;8BAAA;YAEL;QACH;QAEA,IAAIK,OAAOC,IAAI,KAAK,oBAAoB;YACtC,MAAM,qBAEL,CAFK,IAAIL,MACR,AAAC,iCAA8BN,WAAS,OAAIU,OAAOE,QAAQ,GAAC,MADxD,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAI;YACF,OAAOC,KAAKC,KAAK,CAACJ,OAAOK,QAAQ;QACnC,EAAE,OAAOV,OAAO;YACd,MAAM,qBAEJ,CAFI,IAAIC,MAAM,AAAC,oCAAiCN,WAAS,KAAI;gBAC7DO,OAAOF;YACT,IAFM,qBAAA;uBAAA;4BAAA;8BAAA;YAEL;QACH;IACF;IAEA,MAAMW,oBAAoBrB,KAAKsB,OAAO,CACpCtB,KAAKuB,OAAO,CAAClB,WACbmB,mBAAmBX;IAGrB,IAAI;QACF,MAAMY,oBAAoB,MAAM1B,GAAGU,QAAQ,CAACY,mBAAmB;QAE/D,OAAOH,KAAKC,KAAK,CAACM,kBAAkBL,QAAQ;IAC9C,EAAE,OAAOV,OAAO;QACd,MAAM,qBAEJ,CAFI,IAAIC,MAAM,AAAC,gCAA6BU,oBAAkB,KAAI;YAClET,OAAOF;QACT,IAFM,qBAAA;mBAAA;wBAAA;0BAAA;QAEL;IACH;AACF"}

View File

@@ -0,0 +1,17 @@
export function getSourceMapUrl(fileContents) {
const regex = /\/\/[#@] ?sourceMappingURL=([^\s'"]+)\s*$/gm;
let match = null;
for(;;){
let next = regex.exec(fileContents);
if (next == null) {
break;
}
match = next;
}
if (!(match && match[1])) {
return null;
}
return match[1].toString();
}
//# sourceMappingURL=get-source-map-url.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/utils/get-source-map-url.ts"],"sourcesContent":["export function getSourceMapUrl(fileContents: string): string | null {\n const regex = /\\/\\/[#@] ?sourceMappingURL=([^\\s'\"]+)\\s*$/gm\n let match = null\n for (;;) {\n let next = regex.exec(fileContents)\n if (next == null) {\n break\n }\n match = next\n }\n if (!(match && match[1])) {\n return null\n }\n return match[1].toString()\n}\n"],"names":["getSourceMapUrl","fileContents","regex","match","next","exec","toString"],"mappings":"AAAA,OAAO,SAASA,gBAAgBC,YAAoB;IAClD,MAAMC,QAAQ;IACd,IAAIC,QAAQ;IACZ,OAAS;QACP,IAAIC,OAAOF,MAAMG,IAAI,CAACJ;QACtB,IAAIG,QAAQ,MAAM;YAChB;QACF;QACAD,QAAQC;IACV;IACA,IAAI,CAAED,CAAAA,SAASA,KAAK,CAAC,EAAE,AAAD,GAAI;QACxB,OAAO;IACT;IACA,OAAOA,KAAK,CAAC,EAAE,CAACG,QAAQ;AAC1B"}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,62 @@
import { parse } from 'next/dist/compiled/stacktrace-parser';
import { decorateServerError } from '../../../../shared/lib/error-source';
export function getFilesystemFrame(frame) {
const f = {
...frame
};
if (typeof f.file === 'string') {
if (// Posix:
f.file.startsWith('/') || // Win32:
/^[a-z]:\\/i.test(f.file) || // Win32 UNC:
f.file.startsWith('\\\\')) {
f.file = "file://" + f.file;
}
}
return f;
}
export function getServerError(error, type) {
if (error.name === 'TurbopackInternalError') {
// If this is an internal Turbopack error we shouldn't show internal details
// to the user. These are written to a log file instead.
const turbopackInternalError = Object.defineProperty(new Error('An unexpected Turbopack error occurred. Please see the output of `next dev` for more details.'), "__NEXT_ERROR_CODE", {
value: "E167",
enumerable: false,
configurable: true
});
decorateServerError(turbopackInternalError, type);
return turbopackInternalError;
}
let n;
try {
throw Object.defineProperty(new Error(error.message), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
} catch (e) {
n = e;
}
n.name = error.name;
try {
n.stack = n.toString() + "\n" + parse(error.stack).map(getFilesystemFrame).map((f)=>{
let str = " at " + f.methodName;
if (f.file) {
let loc = f.file;
if (f.lineNumber) {
loc += ":" + f.lineNumber;
if (f.column) {
loc += ":" + f.column;
}
}
str += " (" + loc + ")";
}
return str;
}).join('\n');
} catch (e) {
n.stack = error.stack;
}
decorateServerError(n, type);
return n;
}
//# sourceMappingURL=node-stack-frames.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/utils/node-stack-frames.ts"],"sourcesContent":["import { parse } from 'next/dist/compiled/stacktrace-parser'\nimport type { StackFrame } from 'next/dist/compiled/stacktrace-parser'\nimport {\n decorateServerError,\n type ErrorSourceType,\n} from '../../../../shared/lib/error-source'\n\nexport function getFilesystemFrame(frame: StackFrame): StackFrame {\n const f: StackFrame = { ...frame }\n\n if (typeof f.file === 'string') {\n if (\n // Posix:\n f.file.startsWith('/') ||\n // Win32:\n /^[a-z]:\\\\/i.test(f.file) ||\n // Win32 UNC:\n f.file.startsWith('\\\\\\\\')\n ) {\n f.file = `file://${f.file}`\n }\n }\n\n return f\n}\n\nexport function getServerError(error: Error, type: ErrorSourceType): Error {\n if (error.name === 'TurbopackInternalError') {\n // If this is an internal Turbopack error we shouldn't show internal details\n // to the user. These are written to a log file instead.\n const turbopackInternalError = new Error(\n 'An unexpected Turbopack error occurred. Please see the output of `next dev` for more details.'\n )\n decorateServerError(turbopackInternalError, type)\n return turbopackInternalError\n }\n\n let n: Error\n try {\n throw new Error(error.message)\n } catch (e) {\n n = e as Error\n }\n\n n.name = error.name\n try {\n n.stack = `${n.toString()}\\n${parse(error.stack!)\n .map(getFilesystemFrame)\n .map((f) => {\n let str = ` at ${f.methodName}`\n if (f.file) {\n let loc = f.file\n if (f.lineNumber) {\n loc += `:${f.lineNumber}`\n if (f.column) {\n loc += `:${f.column}`\n }\n }\n str += ` (${loc})`\n }\n return str\n })\n .join('\\n')}`\n } catch {\n n.stack = error.stack\n }\n\n decorateServerError(n, type)\n return n\n}\n"],"names":["parse","decorateServerError","getFilesystemFrame","frame","f","file","startsWith","test","getServerError","error","type","name","turbopackInternalError","Error","n","message","e","stack","toString","map","str","methodName","loc","lineNumber","column","join"],"mappings":"AAAA,SAASA,KAAK,QAAQ,uCAAsC;AAE5D,SACEC,mBAAmB,QAEd,sCAAqC;AAE5C,OAAO,SAASC,mBAAmBC,KAAiB;IAClD,MAAMC,IAAgB;QAAE,GAAGD,KAAK;IAAC;IAEjC,IAAI,OAAOC,EAAEC,IAAI,KAAK,UAAU;QAC9B,IACE,SAAS;QACTD,EAAEC,IAAI,CAACC,UAAU,CAAC,QAClB,SAAS;QACT,aAAaC,IAAI,CAACH,EAAEC,IAAI,KACxB,aAAa;QACbD,EAAEC,IAAI,CAACC,UAAU,CAAC,SAClB;YACAF,EAAEC,IAAI,GAAG,AAAC,YAASD,EAAEC,IAAI;QAC3B;IACF;IAEA,OAAOD;AACT;AAEA,OAAO,SAASI,eAAeC,KAAY,EAAEC,IAAqB;IAChE,IAAID,MAAME,IAAI,KAAK,0BAA0B;QAC3C,4EAA4E;QAC5E,wDAAwD;QACxD,MAAMC,yBAAyB,qBAE9B,CAF8B,IAAIC,MACjC,kGAD6B,qBAAA;mBAAA;wBAAA;0BAAA;QAE/B;QACAZ,oBAAoBW,wBAAwBF;QAC5C,OAAOE;IACT;IAEA,IAAIE;IACJ,IAAI;QACF,MAAM,qBAAwB,CAAxB,IAAID,MAAMJ,MAAMM,OAAO,GAAvB,qBAAA;mBAAA;wBAAA;0BAAA;QAAuB;IAC/B,EAAE,OAAOC,GAAG;QACVF,IAAIE;IACN;IAEAF,EAAEH,IAAI,GAAGF,MAAME,IAAI;IACnB,IAAI;QACFG,EAAEG,KAAK,GAAG,AAAGH,EAAEI,QAAQ,KAAG,OAAIlB,MAAMS,MAAMQ,KAAK,EAC5CE,GAAG,CAACjB,oBACJiB,GAAG,CAAC,CAACf;YACJ,IAAIgB,MAAM,AAAC,YAAShB,EAAEiB,UAAU;YAChC,IAAIjB,EAAEC,IAAI,EAAE;gBACV,IAAIiB,MAAMlB,EAAEC,IAAI;gBAChB,IAAID,EAAEmB,UAAU,EAAE;oBAChBD,OAAO,AAAC,MAAGlB,EAAEmB,UAAU;oBACvB,IAAInB,EAAEoB,MAAM,EAAE;wBACZF,OAAO,AAAC,MAAGlB,EAAEoB,MAAM;oBACrB;gBACF;gBACAJ,OAAO,AAAC,OAAIE,MAAI;YAClB;YACA,OAAOF;QACT,GACCK,IAAI,CAAC;IACV,EAAE,UAAM;QACNX,EAAEG,KAAK,GAAGR,MAAMQ,KAAK;IACvB;IAEAhB,oBAAoBa,GAAGJ;IACvB,OAAOI;AACT"}

View File

@@ -0,0 +1,83 @@
var LocationType = /*#__PURE__*/ function(LocationType) {
LocationType["FILE"] = "file";
LocationType["WEBPACK_INTERNAL"] = "webpack-internal";
LocationType["HTTP"] = "http";
LocationType["PROTOCOL_RELATIVE"] = "protocol-relative";
LocationType["UNKNOWN"] = "unknown";
return LocationType;
}(LocationType || {});
/**
* Get the type of frame line based on the location
*/ function getLocationType(location) {
if (location.startsWith('file://')) {
return "file";
}
if (location.includes('webpack-internal://')) {
return "webpack-internal";
}
if (location.startsWith('http://') || location.startsWith('https://')) {
return "http";
}
if (location.startsWith('//')) {
return "protocol-relative";
}
return "unknown";
}
function parseStackFrameLocation(location) {
const locationType = getLocationType(location);
const modulePath = location == null ? void 0 : location.replace(/^(webpack-internal:\/\/\/|file:\/\/)(\(.*\)\/)?/, '');
var _modulePath_match;
const [, file, lineNumber, column] = (_modulePath_match = modulePath == null ? void 0 : modulePath.match(/^(.+):(\d+):(\d+)/)) != null ? _modulePath_match : [];
switch(locationType){
case "file":
case "webpack-internal":
return {
canOpenInEditor: true,
file,
lineNumber: lineNumber ? Number(lineNumber) : undefined,
column: column ? Number(column) : undefined
};
// When the location is a URL we only show the file
// TODO: Resolve http(s) URLs through sourcemaps
case "http":
case "protocol-relative":
case "unknown":
default:
{
return {
canOpenInEditor: false
};
}
}
}
export function parseComponentStack(componentStack) {
const componentStackFrames = [];
for (const line of componentStack.trim().split('\n')){
// TODO: support safari stack trace
// Get component and file from the component stack line
const match = /at ([^ ]+)( \((.*)\))?/.exec(line);
if (match == null ? void 0 : match[1]) {
const component = match[1];
const location = match[3];
if (!location) {
componentStackFrames.push({
canOpenInEditor: false,
component
});
continue;
}
// Stop parsing the component stack if we reach a Next.js component
if (location == null ? void 0 : location.includes('next/dist')) {
break;
}
const frameLocation = parseStackFrameLocation(location);
componentStackFrames.push({
component,
...frameLocation
});
}
}
return componentStackFrames;
}
//# sourceMappingURL=parse-component-stack.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/utils/parse-component-stack.ts"],"sourcesContent":["export type ComponentStackFrame = {\n canOpenInEditor: boolean\n component: string\n file?: string\n lineNumber?: number\n column?: number\n}\n\nenum LocationType {\n FILE = 'file',\n WEBPACK_INTERNAL = 'webpack-internal',\n HTTP = 'http',\n PROTOCOL_RELATIVE = 'protocol-relative',\n UNKNOWN = 'unknown',\n}\n\n/**\n * Get the type of frame line based on the location\n */\nfunction getLocationType(location: string): LocationType {\n if (location.startsWith('file://')) {\n return LocationType.FILE\n }\n if (location.includes('webpack-internal://')) {\n return LocationType.WEBPACK_INTERNAL\n }\n if (location.startsWith('http://') || location.startsWith('https://')) {\n return LocationType.HTTP\n }\n if (location.startsWith('//')) {\n return LocationType.PROTOCOL_RELATIVE\n }\n return LocationType.UNKNOWN\n}\n\nfunction parseStackFrameLocation(\n location: string\n): Omit<ComponentStackFrame, 'component'> {\n const locationType = getLocationType(location)\n\n const modulePath = location?.replace(\n /^(webpack-internal:\\/\\/\\/|file:\\/\\/)(\\(.*\\)\\/)?/,\n ''\n )\n const [, file, lineNumber, column] =\n modulePath?.match(/^(.+):(\\d+):(\\d+)/) ?? []\n\n switch (locationType) {\n case LocationType.FILE:\n case LocationType.WEBPACK_INTERNAL:\n return {\n canOpenInEditor: true,\n file,\n lineNumber: lineNumber ? Number(lineNumber) : undefined,\n column: column ? Number(column) : undefined,\n }\n // When the location is a URL we only show the file\n // TODO: Resolve http(s) URLs through sourcemaps\n case LocationType.HTTP:\n case LocationType.PROTOCOL_RELATIVE:\n case LocationType.UNKNOWN:\n default: {\n return {\n canOpenInEditor: false,\n }\n }\n }\n}\n\nexport function parseComponentStack(\n componentStack: string\n): ComponentStackFrame[] {\n const componentStackFrames: ComponentStackFrame[] = []\n for (const line of componentStack.trim().split('\\n')) {\n // TODO: support safari stack trace\n // Get component and file from the component stack line\n const match = /at ([^ ]+)( \\((.*)\\))?/.exec(line)\n if (match?.[1]) {\n const component = match[1]\n const location = match[3]\n\n if (!location) {\n componentStackFrames.push({\n canOpenInEditor: false,\n component,\n })\n continue\n }\n\n // Stop parsing the component stack if we reach a Next.js component\n if (location?.includes('next/dist')) {\n break\n }\n\n const frameLocation = parseStackFrameLocation(location)\n componentStackFrames.push({\n component,\n ...frameLocation,\n })\n }\n }\n\n return componentStackFrames\n}\n"],"names":["LocationType","getLocationType","location","startsWith","includes","parseStackFrameLocation","locationType","modulePath","replace","file","lineNumber","column","match","canOpenInEditor","Number","undefined","parseComponentStack","componentStack","componentStackFrames","line","trim","split","exec","component","push","frameLocation"],"mappings":"AAQA,IAAA,AAAKA,sCAAAA;;;;;;WAAAA;EAAAA;AAQL;;CAEC,GACD,SAASC,gBAAgBC,QAAgB;IACvC,IAAIA,SAASC,UAAU,CAAC,YAAY;QAClC;IACF;IACA,IAAID,SAASE,QAAQ,CAAC,wBAAwB;QAC5C;IACF;IACA,IAAIF,SAASC,UAAU,CAAC,cAAcD,SAASC,UAAU,CAAC,aAAa;QACrE;IACF;IACA,IAAID,SAASC,UAAU,CAAC,OAAO;QAC7B;IACF;IACA;AACF;AAEA,SAASE,wBACPH,QAAgB;IAEhB,MAAMI,eAAeL,gBAAgBC;IAErC,MAAMK,aAAaL,4BAAAA,SAAUM,OAAO,CAClC,mDACA;QAGAD;IADF,MAAM,GAAGE,MAAMC,YAAYC,OAAO,GAChCJ,CAAAA,oBAAAA,8BAAAA,WAAYK,KAAK,CAAC,gCAAlBL,oBAA0C,EAAE;IAE9C,OAAQD;QACN;QACA;YACE,OAAO;gBACLO,iBAAiB;gBACjBJ;gBACAC,YAAYA,aAAaI,OAAOJ,cAAcK;gBAC9CJ,QAAQA,SAASG,OAAOH,UAAUI;YACpC;QACF,mDAAmD;QACnD,gDAAgD;QAChD;QACA;QACA;QACA;YAAS;gBACP,OAAO;oBACLF,iBAAiB;gBACnB;YACF;IACF;AACF;AAEA,OAAO,SAASG,oBACdC,cAAsB;IAEtB,MAAMC,uBAA8C,EAAE;IACtD,KAAK,MAAMC,QAAQF,eAAeG,IAAI,GAAGC,KAAK,CAAC,MAAO;QACpD,mCAAmC;QACnC,uDAAuD;QACvD,MAAMT,QAAQ,yBAAyBU,IAAI,CAACH;QAC5C,IAAIP,yBAAAA,KAAO,CAAC,EAAE,EAAE;YACd,MAAMW,YAAYX,KAAK,CAAC,EAAE;YAC1B,MAAMV,WAAWU,KAAK,CAAC,EAAE;YAEzB,IAAI,CAACV,UAAU;gBACbgB,qBAAqBM,IAAI,CAAC;oBACxBX,iBAAiB;oBACjBU;gBACF;gBACA;YACF;YAEA,mEAAmE;YACnE,IAAIrB,4BAAAA,SAAUE,QAAQ,CAAC,cAAc;gBACnC;YACF;YAEA,MAAMqB,gBAAgBpB,wBAAwBH;YAC9CgB,qBAAqBM,IAAI,CAAC;gBACxBD;gBACA,GAAGE,aAAa;YAClB;QACF;IACF;IAEA,OAAOP;AACT"}

View File

@@ -0,0 +1,38 @@
import { parse } from 'next/dist/compiled/stacktrace-parser';
import { getHydrationErrorStackInfo, isReactHydrationErrorMessage } from '../../is-hydration-error';
const regexNextStatic = /\/_next(\/static\/.+)/;
export function parseStack(stack) {
if (!stack) return [];
const messageAndStack = stack.replace(/^Error: /, '');
if (isReactHydrationErrorMessage(messageAndStack)) {
const { stack: parsedStack } = getHydrationErrorStackInfo(messageAndStack);
if (parsedStack) {
stack = parsedStack;
}
}
// throw away eval information that stacktrace-parser doesn't support
// adapted from https://github.com/stacktracejs/error-stack-parser/blob/9f33c224b5d7b607755eb277f9d51fcdb7287e24/error-stack-parser.js#L59C33-L59C62
stack = stack.split('\n').map((line)=>{
if (line.includes('(eval ')) {
line = line.replace(/eval code/g, 'eval').replace(/\(eval at [^()]* \(/, '(file://').replace(/\),.*$/g, ')');
}
return line;
}).join('\n');
const frames = parse(stack);
return frames.map((frame)=>{
try {
const url = new URL(frame.file);
const res = regexNextStatic.exec(url.pathname);
if (res) {
var _process_env___NEXT_DIST_DIR_replace, _process_env___NEXT_DIST_DIR;
const distDir = (_process_env___NEXT_DIST_DIR = process.env.__NEXT_DIST_DIR) == null ? void 0 : (_process_env___NEXT_DIST_DIR_replace = _process_env___NEXT_DIST_DIR.replace(/\\/g, '/')) == null ? void 0 : _process_env___NEXT_DIST_DIR_replace.replace(/\/$/, '');
if (distDir) {
frame.file = 'file://' + distDir.concat(res.pop()) + url.search;
}
}
} catch (e) {}
return frame;
});
}
//# sourceMappingURL=parse-stack.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/utils/parse-stack.ts"],"sourcesContent":["import { parse } from 'next/dist/compiled/stacktrace-parser'\nimport type { StackFrame } from 'next/dist/compiled/stacktrace-parser'\nimport {\n getHydrationErrorStackInfo,\n isReactHydrationErrorMessage,\n} from '../../is-hydration-error'\n\nconst regexNextStatic = /\\/_next(\\/static\\/.+)/\n\nexport function parseStack(stack: string | undefined): StackFrame[] {\n if (!stack) return []\n const messageAndStack = stack.replace(/^Error: /, '')\n if (isReactHydrationErrorMessage(messageAndStack)) {\n const { stack: parsedStack } = getHydrationErrorStackInfo(messageAndStack)\n if (parsedStack) {\n stack = parsedStack\n }\n }\n\n // throw away eval information that stacktrace-parser doesn't support\n // adapted from https://github.com/stacktracejs/error-stack-parser/blob/9f33c224b5d7b607755eb277f9d51fcdb7287e24/error-stack-parser.js#L59C33-L59C62\n stack = stack\n .split('\\n')\n .map((line) => {\n if (line.includes('(eval ')) {\n line = line\n .replace(/eval code/g, 'eval')\n .replace(/\\(eval at [^()]* \\(/, '(file://')\n .replace(/\\),.*$/g, ')')\n }\n\n return line\n })\n .join('\\n')\n\n const frames = parse(stack)\n return frames.map((frame) => {\n try {\n const url = new URL(frame.file!)\n const res = regexNextStatic.exec(url.pathname)\n if (res) {\n const distDir = process.env.__NEXT_DIST_DIR\n ?.replace(/\\\\/g, '/')\n ?.replace(/\\/$/, '')\n if (distDir) {\n frame.file = 'file://' + distDir.concat(res.pop()!) + url.search\n }\n }\n } catch {}\n return frame\n })\n}\n"],"names":["parse","getHydrationErrorStackInfo","isReactHydrationErrorMessage","regexNextStatic","parseStack","stack","messageAndStack","replace","parsedStack","split","map","line","includes","join","frames","frame","url","URL","file","res","exec","pathname","process","distDir","env","__NEXT_DIST_DIR","concat","pop","search"],"mappings":"AAAA,SAASA,KAAK,QAAQ,uCAAsC;AAE5D,SACEC,0BAA0B,EAC1BC,4BAA4B,QACvB,2BAA0B;AAEjC,MAAMC,kBAAkB;AAExB,OAAO,SAASC,WAAWC,KAAyB;IAClD,IAAI,CAACA,OAAO,OAAO,EAAE;IACrB,MAAMC,kBAAkBD,MAAME,OAAO,CAAC,YAAY;IAClD,IAAIL,6BAA6BI,kBAAkB;QACjD,MAAM,EAAED,OAAOG,WAAW,EAAE,GAAGP,2BAA2BK;QAC1D,IAAIE,aAAa;YACfH,QAAQG;QACV;IACF;IAEA,qEAAqE;IACrE,oJAAoJ;IACpJH,QAAQA,MACLI,KAAK,CAAC,MACNC,GAAG,CAAC,CAACC;QACJ,IAAIA,KAAKC,QAAQ,CAAC,WAAW;YAC3BD,OAAOA,KACJJ,OAAO,CAAC,cAAc,QACtBA,OAAO,CAAC,uBAAuB,YAC/BA,OAAO,CAAC,WAAW;QACxB;QAEA,OAAOI;IACT,GACCE,IAAI,CAAC;IAER,MAAMC,SAASd,MAAMK;IACrB,OAAOS,OAAOJ,GAAG,CAAC,CAACK;QACjB,IAAI;YACF,MAAMC,MAAM,IAAIC,IAAIF,MAAMG,IAAI;YAC9B,MAAMC,MAAMhB,gBAAgBiB,IAAI,CAACJ,IAAIK,QAAQ;YAC7C,IAAIF,KAAK;oBACSG,sCAAAA;gBAAhB,MAAMC,WAAUD,+BAAAA,QAAQE,GAAG,CAACC,eAAe,sBAA3BH,uCAAAA,6BACZf,OAAO,CAAC,OAAO,yBADHe,qCAEZf,OAAO,CAAC,OAAO;gBACnB,IAAIgB,SAAS;oBACXR,MAAMG,IAAI,GAAG,YAAYK,QAAQG,MAAM,CAACP,IAAIQ,GAAG,MAAOX,IAAIY,MAAM;gBAClE;YACF;QACF,EAAE,UAAM,CAAC;QACT,OAAOb;IACT;AACF"}

View File

@@ -0,0 +1,124 @@
import { isWebpackInternalResource, formatFrameSourceFile } from './webpack-module-path';
function getOriginalStackFrame(source, response) {
var _source_file;
async function _getOriginalStackFrame() {
var _body_originalStackFrame;
if (response.status === 'rejected') {
throw Object.defineProperty(new Error(response.reason), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
const body = response.value;
return {
error: false,
reason: null,
external: false,
sourceStackFrame: source,
originalStackFrame: body.originalStackFrame,
originalCodeFrame: body.originalCodeFrame || null,
ignored: ((_body_originalStackFrame = body.originalStackFrame) == null ? void 0 : _body_originalStackFrame.ignored) || false
};
}
// TODO: merge this section into ignoredList handling
if (source.file === 'file://' || ((_source_file = source.file) == null ? void 0 : _source_file.match(/https?:\/\//))) {
return Promise.resolve({
error: false,
reason: null,
external: true,
sourceStackFrame: source,
originalStackFrame: null,
originalCodeFrame: null,
ignored: true
});
}
return _getOriginalStackFrame().catch((err)=>{
var _err_message, _ref;
return {
error: true,
reason: (_ref = (_err_message = err == null ? void 0 : err.message) != null ? _err_message : err == null ? void 0 : err.toString()) != null ? _ref : 'Unknown Error',
external: false,
sourceStackFrame: source,
originalStackFrame: null,
originalCodeFrame: null,
ignored: false
};
});
}
export async function getOriginalStackFrames(frames, type, isAppDir) {
const req = {
frames,
isServer: type === 'server',
isEdgeServer: type === 'edge-server',
isAppDirectory: isAppDir
};
let res = undefined;
let reason = undefined;
try {
res = await fetch('/__nextjs_original-stack-frames', {
method: 'POST',
body: JSON.stringify(req)
});
} catch (e) {
reason = e + '';
}
// When fails to fetch the original stack frames, we reject here to be
// caught at `_getOriginalStackFrame()` and return the stack frames so
// that the error overlay can render.
if (res && res.ok && res.status !== 204) {
const data = await res.json();
return Promise.all(frames.map((frame, index)=>getOriginalStackFrame(frame, data[index])));
} else {
if (res) {
reason = await res.text();
}
}
return Promise.all(frames.map((frame)=>getOriginalStackFrame(frame, {
status: 'rejected',
reason: "Failed to fetch the original stack frames " + (reason ? ": " + reason : '')
})));
}
export function getFrameSource(frame) {
if (!frame.file) return '';
const isWebpackFrame = isWebpackInternalResource(frame.file);
let str = '';
// Skip URL parsing for webpack internal file paths.
if (isWebpackFrame) {
str = formatFrameSourceFile(frame.file);
} else {
try {
var _globalThis_location;
const u = new URL(frame.file);
let parsedPath = '';
// Strip the origin for same-origin scripts.
if (((_globalThis_location = globalThis.location) == null ? void 0 : _globalThis_location.origin) !== u.origin) {
// URLs can be valid without an `origin`, so long as they have a
// `protocol`. However, `origin` is preferred.
if (u.origin === 'null') {
parsedPath += u.protocol;
} else {
parsedPath += u.origin;
}
}
// Strip query string information as it's typically too verbose to be
// meaningful.
parsedPath += u.pathname;
str = formatFrameSourceFile(parsedPath);
} catch (e) {
str = formatFrameSourceFile(frame.file);
}
}
if (!isWebpackInternalResource(frame.file) && frame.lineNumber != null) {
if (str) {
if (frame.column != null) {
str += " (" + frame.lineNumber + ":" + frame.column + ")";
} else {
str += " (" + frame.lineNumber + ")";
}
}
}
return str;
}
//# sourceMappingURL=stack-frame.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,98 @@
import { useCallback, useContext, useEffect, useRef } from 'react';
import { GlobalLayoutRouterContext } from '../../../../shared/lib/app-router-context.shared-runtime';
import { getSocketUrl } from './get-socket-url';
export function useWebsocket(assetPrefix) {
const webSocketRef = useRef(undefined);
useEffect(()=>{
if (webSocketRef.current) {
return;
}
const url = getSocketUrl(assetPrefix);
webSocketRef.current = new window.WebSocket("" + url + "/_next/webpack-hmr");
}, [
assetPrefix
]);
return webSocketRef;
}
export function useSendMessage(webSocketRef) {
const sendMessage = useCallback((data)=>{
const socket = webSocketRef.current;
if (!socket || socket.readyState !== socket.OPEN) {
return;
}
return socket.send(data);
}, [
webSocketRef
]);
return sendMessage;
}
export function useTurbopack(sendMessage, onUpdateError) {
const turbopackState = useRef({
init: false,
// Until the dynamic import resolves, queue any turbopack messages which will be replayed.
queue: [],
callback: undefined
});
const processTurbopackMessage = useCallback((msg)=>{
const { callback, queue } = turbopackState.current;
if (callback) {
callback(msg);
} else {
queue.push(msg);
}
}, []);
useEffect(()=>{
const { current: initCurrent } = turbopackState;
// TODO(WEB-1589): only install if `process.turbopack` set.
if (initCurrent.init) {
return;
}
initCurrent.init = true;
import(// @ts-expect-error requires "moduleResolution": "node16" in tsconfig.json and not .ts extension
'@vercel/turbopack-ecmascript-runtime/browser/dev/hmr-client/hmr-client.ts').then((param)=>{
let { connect } = param;
const { current } = turbopackState;
connect({
addMessageListener (cb) {
current.callback = cb;
// Replay all Turbopack messages before we were able to establish the HMR client.
for (const msg of current.queue){
cb(msg);
}
current.queue = undefined;
},
sendMessage,
onUpdateError
});
});
}, [
sendMessage,
onUpdateError
]);
return processTurbopackMessage;
}
export function useWebsocketPing(websocketRef) {
const sendMessage = useSendMessage(websocketRef);
const { tree } = useContext(GlobalLayoutRouterContext);
useEffect(()=>{
// Never send pings when using Turbopack as it's not used.
// Pings were originally used to keep track of active routes in on-demand-entries with webpack.
if (process.env.TURBOPACK) {
return;
}
// Taken from on-demand-entries-client.js
const interval = setInterval(()=>{
sendMessage(JSON.stringify({
event: 'ping',
tree,
appDirRoute: true
}));
}, 2500);
return ()=>clearInterval(interval);
}, [
tree,
sendMessage
]);
}
//# sourceMappingURL=use-websocket.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,26 @@
const replacementRegExes = [
/^webpack-internal:\/\/\/(\([\w-]+\)\/)?/,
/^(webpack:\/\/\/|webpack:\/\/(_N_E\/)?)(\([\w-]+\)\/)?/
];
export function isWebpackInternalResource(file) {
for (const regex of replacementRegExes){
if (regex.test(file)) return true;
file = file.replace(regex, '');
}
return false;
}
/**
* Format the webpack internal id to original file path
*
* webpack-internal:///./src/hello.tsx => ./src/hello.tsx
* webpack://_N_E/./src/hello.tsx => ./src/hello.tsx
* webpack://./src/hello.tsx => ./src/hello.tsx
* webpack:///./src/hello.tsx => ./src/hello.tsx
*/ export function formatFrameSourceFile(file) {
for (const regex of replacementRegExes){
file = file.replace(regex, '');
}
return file;
}
//# sourceMappingURL=webpack-module-path.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/utils/webpack-module-path.ts"],"sourcesContent":["const replacementRegExes = [\n /^webpack-internal:\\/\\/\\/(\\([\\w-]+\\)\\/)?/,\n /^(webpack:\\/\\/\\/|webpack:\\/\\/(_N_E\\/)?)(\\([\\w-]+\\)\\/)?/,\n]\n\nexport function isWebpackInternalResource(file: string) {\n for (const regex of replacementRegExes) {\n if (regex.test(file)) return true\n\n file = file.replace(regex, '')\n }\n\n return false\n}\n\n/**\n * Format the webpack internal id to original file path\n *\n * webpack-internal:///./src/hello.tsx => ./src/hello.tsx\n * webpack://_N_E/./src/hello.tsx => ./src/hello.tsx\n * webpack://./src/hello.tsx => ./src/hello.tsx\n * webpack:///./src/hello.tsx => ./src/hello.tsx\n */\nexport function formatFrameSourceFile(file: string) {\n for (const regex of replacementRegExes) {\n file = file.replace(regex, '')\n }\n\n return file\n}\n"],"names":["replacementRegExes","isWebpackInternalResource","file","regex","test","replace","formatFrameSourceFile"],"mappings":"AAAA,MAAMA,qBAAqB;IACzB;IACA;CACD;AAED,OAAO,SAASC,0BAA0BC,IAAY;IACpD,KAAK,MAAMC,SAASH,mBAAoB;QACtC,IAAIG,MAAMC,IAAI,CAACF,OAAO,OAAO;QAE7BA,OAAOA,KAAKG,OAAO,CAACF,OAAO;IAC7B;IAEA,OAAO;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,SAASG,sBAAsBJ,IAAY;IAChD,KAAK,MAAMC,SAASH,mBAAoB;QACtCE,OAAOA,KAAKG,OAAO,CAACF,OAAO;IAC7B;IAEA,OAAOD;AACT"}