Further cleanup + make errors copiable

This commit is contained in:
Chad Curtis committed 2025-09-20 03:37:20 +00:00
1 parent fbea142bbb
commit ca2426a800
6 files changed
+164 -134

No files matched your search

@@ -1,114 +0,0 @@
/**
* Early Console Interception Inject Script
* This script runs as early as possible to capture all console messages and errors
*/
class ConsoleInterceptor {
constructor() {
this.originalConsole = {};
this.earlyErrors = [];
this.consoleMethods = [
'log', 'warn', 'error', 'info', 'debug', 'exception', 'assert',
'clear', 'count', 'countReset', 'dir', 'dirxml', 'group',
'groupCollapsed', 'groupEnd', 'table', 'time', 'timeEnd',
'timeLog', 'trace'
];
this.init();
}
init() {
this.storeOriginalConsole();
this.overrideConsoleMethods();
this.setupGlobalErrorHandlers();
this.exposeToWindow();
}
storeOriginalConsole() {
this.consoleMethods.forEach(method => {
if (typeof console[method] === 'function') {
this.originalConsole[method] = console[method];
}
});
}
overrideConsoleMethods() {
this.consoleMethods.forEach(method => {
if (typeof console[method] === 'function') {
console[method] = (...args) => {
this.handleConsoleCall(method, args);
};
}
});
}
handleConsoleCall(method, args) {
// Try to call the original method
try {
this.originalConsole[method](...args);
} catch (e) {
// Original method failed, continue
}
// Store error for later processing
if (method === 'error' || method === 'exception') {
this.earlyErrors.push({
level: method,
message: this.serializeArgs(args),
timestamp: Date.now(),
args: args
});
}
}
serializeArgs(args) {
return args.map(arg => {
if (typeof arg === 'object') {
try {
return JSON.stringify(arg);
} catch {
return String(arg);
}
}
return String(arg);
}).join(' ');
}
setupGlobalErrorHandlers() {
// Handle window errors
window.addEventListener('error', (event) => {
this.earlyErrors.push({
level: 'error',
message: `Global Error: ${event.message}`,
timestamp: Date.now(),
args: [{
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
error: event.error ? event.error.message : 'No error object'
}]
});
});
// Handle unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
this.earlyErrors.push({
level: 'error',
message: 'Unhandled Promise Rejection',
timestamp: Date.now(),
args: [event.reason]
});
});
}
exposeToWindow() {
// Store early errors for the main script to process
window._earlyConsoleErrors = this.earlyErrors;
// Store original console reference for the main script
window._originalConsole = this.originalConsole;
}
}
// Initialize the console interceptor immediately
new ConsoleInterceptor();
File renamed without changes.
@@ -1,13 +1,118 @@
/**
* iframe Fetch Client Main Script
* JSON-RPC based communication with parent page
* iframe Fetch Client Combined Entry Point
* Combines console interception and client initialization
*/
import { overrideConsoleMethods, setupGlobalErrorHandlers, CONSOLE_METHODS } from './console-utils.js';
// Import console interception utilities
import { storeOriginalConsole, overrideConsoleMethods, setupGlobalErrorHandlers, CONSOLE_METHODS } from './console-utils.js';
// Early Console Interception - runs immediately
class EarlyConsoleInterceptor {
constructor() {
this.originalConsole = {};
this.earlyErrors = [];
this.consoleMethods = CONSOLE_METHODS;
this.init();
}
init() {
this.storeOriginalConsole();
this.overrideConsoleMethods();
this.setupGlobalErrorHandlers();
this.exposeToWindow();
}
storeOriginalConsole() {
this.consoleMethods.forEach(method => {
if (typeof console[method] === 'function') {
this.originalConsole[method] = console[method];
}
});
}
overrideConsoleMethods() {
this.consoleMethods.forEach(method => {
if (typeof console[method] === 'function') {
console[method] = (...args) => {
this.handleConsoleCall(method, args);
};
}
});
}
handleConsoleCall(method, args) {
// Try to call the original method
try {
this.originalConsole[method](...args);
} catch (e) {
// Original method failed, continue
}
// Store error for later processing
if (method === 'error' || method === 'exception') {
this.earlyErrors.push({
level: method,
message: this.serializeArgs(args),
timestamp: Date.now(),
args: args
});
}
}
serializeArgs(args) {
return args.map(arg => {
if (typeof arg === 'object') {
try {
return JSON.stringify(arg);
} catch {
return String(arg);
}
}
return String(arg);
}).join(' ');
}
setupGlobalErrorHandlers() {
// Handle window errors
window.addEventListener('error', (event) => {
this.earlyErrors.push({
level: 'error',
message: `Global Error: ${event.message}`,
timestamp: Date.now(),
args: [{
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
error: event.error ? event.error.message : 'No error object'
}]
});
});
// Handle unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
this.earlyErrors.push({
level: 'error',
message: 'Unhandled Promise Rejection',
timestamp: Date.now(),
args: [event.reason]
});
});
}
exposeToWindow() {
// Store early errors for the main script to process
window._earlyConsoleErrors = this.earlyErrors;
// Store original console reference for the main script
window._originalConsole = this.originalConsole;
}
}
// Console Interceptor - handles ongoing console interception
class ConsoleInterceptor {
constructor() {
// Use the original console stored by the inject script
// Use the original console stored by the early interceptor
this.originalConsole = window._originalConsole || console;
overrideConsoleMethods(this.originalConsole, this.sendConsoleMessage.bind(this));
setupGlobalErrorHandlers(this.sendConsoleMessage.bind(this));
@@ -120,6 +225,7 @@ class ConsoleInterceptor {
}
}
// JSON-RPC Client for communication with parent
class JSONRPCClient {
constructor() {
this.requestId = 0;
@@ -189,6 +295,7 @@ class JSONRPCClient {
}
}
// Main Fetch Client
class FetchClient {
constructor() {
this.rpcClient = new JSONRPCClient();
@@ -394,9 +501,12 @@ class FetchClient {
}
}
// Initialize early console interception immediately
new EarlyConsoleInterceptor();
// Initialize when DOM is ready
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => new FetchClient());
} else {
new FetchClient();
}
}
+2 -4
View File
@@ -4,9 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Site Preview</title>
<link rel="stylesheet" href="/_iframe-client.css">
<!-- Early console interception setup -->
<script src="/_iframe-console-intercept.js"></script>
<link rel="stylesheet" href="/core/client.css">
</head>
<body>
<div class="loading">
@@ -14,6 +12,6 @@
<p>Loading preview...</p>
<p><small>Waiting for ServiceWorker and parent communication</small></p>
</div>
<script src="/_iframe-client.js"></script>
<script type="module" src="/core/main.js"></script>
</body>
</html>
+47 -11
View File
@@ -6,7 +6,7 @@ import { useFS } from '@/hooks/useFS';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { FolderOpen, ArrowLeft, X, Bug } from 'lucide-react';
import { FolderOpen, ArrowLeft, X, Bug, Copy, Check } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
@@ -48,7 +48,7 @@ interface JSONRPCResponse {
statusText: string;
headers: Record<string, string>;
body: string | null;
};
}
error?: {
code: number;
message: string;
@@ -77,6 +77,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
const [historyIndex, setHistoryIndex] = useState(0);
const [consoleMessages, setConsoleMessages] = useState<ConsoleMessage[]>([]);
const [copiedMessageId, setCopiedMessageId] = useState<number | null>(null);
const iframeRef = useRef<HTMLIFrameElement>(null);
const { fs } = useFS();
const projectsManager = useProjectsManager();
@@ -436,6 +437,27 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
setConsoleMessages([]);
};
const copyMessageToClipboard = async (msg: ConsoleMessage) => {
try {
// Create a formatted string with all message details
const formattedMessage = `[${formatTimestamp(msg.timestamp)}] [${msg.level.toUpperCase()}] ${msg.message}${
msg.args.length > 0 ? `\nArgs: ${JSON.stringify(msg.args, null, 2)}` : ''
}`;
await navigator.clipboard.writeText(formattedMessage);
setCopiedMessageId(msg.id);
// Reset the copied state after 2 seconds
setTimeout(() => {
setCopiedMessageId(null);
}, 2000);
} catch (error) {
console.error('Failed to copy message to clipboard:', error);
}
};
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -446,15 +468,15 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
)}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-96 max-h-96">
<DropdownMenuContent align="end" className="w-96 max-w-96 max-h-96 overflow-x-hidden">
<div className="flex items-center justify-between p-2 border-b">
<span className="font-medium text-sm">Console Output ({consoleMessages.length})</span>
<Button variant="ghost" size="sm" onClick={clearConsole}>
<X className="h-3 w-3" />
</Button>
</div>
<ScrollArea className="h-80">
<div className="space-y-1 p-2">
<ScrollArea className="h-80 w-full max-w-full overflow-x-hidden">
<div className="space-y-1 p-2 w-full max-w-full overflow-x-hidden">
{consoleMessages.length === 0 ? (
<div className="text-center text-muted-foreground text-sm py-4">
No console messages
@@ -463,15 +485,29 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
consoleMessages.map((msg) => (
<div
key={msg.id}
className={`text-xs font-mono p-2 rounded ${getLevelColor(msg.level)} bg-muted/50`}
className={`text-xs font-mono p-2 rounded ${getLevelColor(msg.level)} bg-muted/50 group relative w-full overflow-hidden`}
>
<div className="flex items-center gap-2 mb-1">
<span>{getLevelIcon(msg.level)}</span>
<span className="opacity-60">{formatTimestamp(msg.timestamp)}</span>
<div className="flex items-center justify-between mb-1">
<div className="flex items-center gap-2">
<span>{getLevelIcon(msg.level)}</span>
<span className="opacity-60">{formatTimestamp(msg.timestamp)}</span>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => copyMessageToClipboard(msg)}
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity duration-200"
>
{copiedMessageId === msg.id ? (
<Check className="h-3 w-3 text-green-500" />
) : (
<Copy className="h-3 w-3" />
)}
</Button>
</div>
<div className="whitespace-pre-wrap break-all">{msg.message}</div>
<div className="whitespace-pre-wrap break-all pr-8 overflow-x-hidden">{msg.message}</div>
{msg.args.length > 0 && (
<div className="mt-1 opacity-70">
<div className="mt-1 opacity-70 break-all overflow-x-hidden">
Args: {JSON.stringify(msg.args)}
</div>
)}