This commit is contained in:
Chad Curtis committed 2025-09-20 02:16:40 +00:00
1 parent efd7c3901b
commit ba251d57eb
4 files changed
+474 -11

No files matched your search

+244
View File
@@ -126,6 +126,71 @@ full request body support
- `-32002`: Request processing error
- `-32003`: Invalid URL
### `console.log`
**Purpose:** Forward console log messages from iframe to parent for display
**Parameters:**
- `level` (string): Log level - "log", "warn", "error", "info", "debug"
- `message` (string): The log message
- `timestamp` (number): Unix timestamp when the log was created
- `args` (array): Additional arguments passed to the console method (optional)
**Result:** None (notification only, no response expected)
### `console.warn`
**Purpose:** Forward console warn messages from iframe to parent for display
**Parameters:**
- `level` (string): Log level - "log", "warn", "error", "info", "debug"
- `message` (string): The log message
- `timestamp` (number): Unix timestamp when the log was created
- `args` (array): Additional arguments passed to the console method (optional)
**Result:** None (notification only, no response expected)
### `console.error`
**Purpose:** Forward console error messages from iframe to parent for display
**Parameters:**
- `level` (string): Log level - "log", "warn", "error", "info", "debug"
- `timestamp` (number): Unix timestamp when the log was created
- `message` (string): The log message
- `args` (array): Additional arguments passed to the console method (optional)
**Result:** None (notification only, no response expected)
### `console.info`
**Purpose:** Forward console info messages from iframe to parent for display
**Parameters:**
- `level` (string): Log level - "log", "warn", "error", "info", "debug"
- `message` (string): The log message
- `timestamp` (number): Unix timestamp when the log was created
- `args` (array): Additional arguments passed to the console method (optional)
**Result:** None (notification only, no response expected)
### `console.debug`
**Purpose:** Forward console debug messages from iframe to parent for display
**Parameters:**
- `level` (string): Log level - "log", "warn", "error", "info", "debug"
- `message` (string): The log message
- `timestamp` (number): Unix timestamp when the log was created
- `args` (array): Additional arguments passed to the console method (optional)
**Result:** None (notification only, no response expected)
**Request Body Support:** The system fully supports request bodies, enabling:
- POST/PUT requests with JSON data
@@ -326,7 +391,186 @@ const decodedBody = atob(encodedBody);
}],
]);
// Example static file server with console logging
class FetchClientParent {
constructor(files) {
this.files = files; // Map of path -> {content, contentType}
this.consoleLogs = []; // Store console messages
this.setupMessageListener();
}
setupMessageListener() {
window.addEventListener("message", (event) => {
// Verify origin for security
if (event.origin !== "https://app123.example.com") return;
const message = event.data;
// Handle fetch requests
if (message.jsonrpc === "2.0" && message.method === "fetch") {
this.handleFetch(message);
}
// Handle console messages
if (message.jsonrpc === "2.0" && message.method && message.method.startsWith("console.")) {
this.handleConsoleMessage(message);
}
});
}
handleConsoleMessage(message) {
const { method, params } = message;
const { level, message: logMessage, timestamp, args = [] } = params;
// Store the log message
this.consoleLogs.push({
level,
message: logMessage,
timestamp,
args,
id: Date.now() // Unique ID for UI purposes
});
// Update UI to show new logs
this.updateConsoleUI();
// Also log to parent's console for debugging
console[level](`[IFRAME] ${logMessage}`, ...args);
}
updateConsoleUI() {
// This would update the parent page UI to show console logs
// Implementation depends on your UI framework
console.log(`Total console logs: ${this.consoleLogs.length}`);
}
handleFetch(request) {
const { params, id } = request;
const { request: fetchRequest } = params;
// Extract path from URL
const url = new URL(fetchRequest.url);
const path = url.pathname;
// Decode request body if present
const requestBody = fetchRequest.body ? atob(fetchRequest.body) : null;
const file = this.files.get(path);
if (file) {
this.sendResponse({
id,
jsonrpc: "2.0",
result: {
status: 200,
statusText: "OK",
headers: {
"Content-Type": file.contentType,
"Cache-Control": "no-cache",
},
body: btoa(file.content), // base64 encode the response body
},
});
} else {
// Return 404 response (not a JSON-RPC error)
this.sendResponse({
id,
jsonrpc: "2.0",
result: {
status: 404,
statusText: "Not Found",
headers: {
"Content-Type": "text/plain",
},
body: btoa(`File not found: ${path}`), // base64 encode the error message
},
});
}
}
sendResponse(message) {
const iframe = document.getElementById("preview-iframe");
iframe.contentWindow.postMessage(message, "https://app123.example.com");
}
sendError(message) {
const iframe = document.getElementById("preview-iframe");
iframe.contentWindow.postMessage(message, "https://app123.example.com");
}
}
// Example static file server
new FetchClientParent(files);
</script>
```
## Console Logging Implementation
To enable console logging from the iframe to the parent page, the iframe's bootstrap script should override the console methods:
```javascript
// In the iframe's bootstrap script
class ConsoleInterceptor {
constructor() {
this.originalConsole = {
log: console.log,
warn: console.warn,
error: console.error,
info: console.info,
debug: console.debug
};
this.overrideConsoleMethods();
}
overrideConsoleMethods() {
const methods = ['log', 'warn', 'error', 'info', 'debug'];
methods.forEach(method => {
console[method] = (...args) => {
// Call original method first
this.originalConsole[method](...args);
// Send to parent via JSON-RPC
this.sendConsoleMessage(method, ...args);
};
});
}
sendConsoleMessage(level, ...args) {
const message = args.map(arg => {
if (typeof arg === 'object') {
try {
return JSON.stringify(arg);
} catch {
return String(arg);
}
}
return String(arg);
}).join(' ');
window.parent.postMessage({
jsonrpc: "2.0",
method: `console.${level}`,
params: {
level,
message,
timestamp: Date.now(),
args: args.map(arg => {
if (typeof arg === 'object') {
try {
return JSON.parse(JSON.stringify(arg));
} catch {
return String(arg);
}
}
return arg;
})
}
}, "*");
}
}
// Initialize console interception
new ConsoleInterceptor();
```
+62
View File
@@ -3,6 +3,67 @@
* JSON-RPC based communication with parent page
*/
class ConsoleInterceptor {
constructor() {
this.originalConsole = {
log: console.log,
warn: console.warn,
error: console.error,
info: console.info,
debug: console.debug
};
this.overrideConsoleMethods();
}
overrideConsoleMethods() {
const methods = ['log', 'warn', 'error', 'info', 'debug'];
methods.forEach(method => {
console[method] = (...args) => {
// Call original method first (for local debugging)
this.originalConsole[method](...args);
// Send to parent via JSON-RPC
this.sendConsoleMessage(method, ...args);
};
});
}
sendConsoleMessage(level, ...args) {
const message = args.map(arg => {
if (typeof arg === 'object') {
try {
return JSON.stringify(arg);
} catch {
return String(arg);
}
}
return String(arg);
}).join(' ');
window.parent.postMessage({
jsonrpc: "2.0",
method: `console.${level}`,
params: {
level,
message,
timestamp: Date.now(),
args: args.map(arg => {
if (typeof arg === 'object') {
try {
return JSON.parse(JSON.stringify(arg));
} catch {
return String(arg);
}
}
return arg;
})
}
}, "*");
}
}
class JSONRPCClient {
constructor() {
this.requestId = 0;
@@ -76,6 +137,7 @@ class FetchClient {
constructor() {
this.rpcClient = new JSONRPCClient();
this.swReady = false;
this.consoleInterceptor = new ConsoleInterceptor();
this.init();
}
+34
View File
@@ -0,0 +1,34 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Console Test</title>
</head>
<body>
<h1>Console Test Page</h1>
<p>This page tests console logging functionality.</p>
<button onclick="testConsole()">Test Console</button>
<script>
function testConsole() {
console.log('This is a log message');
console.warn('This is a warning message');
console.error('This is an error message');
console.info('This is an info message');
console.debug('This is a debug message');
// Test with objects
const testObject = { name: 'Test', value: 42 };
console.log('Test object:', testObject);
// Test with multiple arguments
console.log('Multiple', 'arguments', 'test', 123, true);
}
// Auto-test on load
window.addEventListener('load', () => {
setTimeout(testConsole, 1000);
});
</script>
</body>
</html>
+134 -11
View File
@@ -6,10 +6,15 @@ 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 } from 'lucide-react';
import { FolderOpen, ArrowLeft, Terminal, X } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
@@ -49,6 +54,14 @@ interface JSONRPCResponse {
id: number;
}
interface ConsoleMessage {
id: number;
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
message: string;
timestamp: number;
args: unknown[];
}
export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
const { t } = useTranslation();
const [selectedFile, setSelectedFile] = useState<string | null>(null);
@@ -60,6 +73,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
const [currentPath, setCurrentPath] = useState('/');
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
const [historyIndex, setHistoryIndex] = useState(0);
const [consoleMessages, setConsoleMessages] = useState<ConsoleMessage[]>([]);
const iframeRef = useRef<HTMLIFrameElement>(null);
const { fs } = useFS();
const projectsManager = useProjectsManager();
@@ -187,6 +201,31 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
}
}, [projectId]);
const handleConsoleMessage = useCallback((message: {
jsonrpc: '2.0';
method: string;
params: {
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
message: string;
timestamp: number;
args: unknown[];
};
}) => {
const { params } = message;
const newConsoleMessage: ConsoleMessage = {
id: Date.now(),
level: params.level,
message: params.message,
timestamp: params.timestamp,
args: params.args,
};
setConsoleMessages(prev => [...prev, newConsoleMessage]);
// Log to parent console for debugging
console.log(`[IFRAME ${params.level.toUpperCase()}] ${params.message}`, ...params.args);
}, []);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
const { request: fetchRequest } = params;
@@ -302,12 +341,14 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
console.log('Received message from iframe:', message);
if (message.jsonrpc === '2.0' && message.method === 'fetch') {
handleFetch(message);
} else if (message.jsonrpc === '2.0' && message.method && message.method.startsWith('console.')) {
handleConsoleMessage(message);
}
};
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, [handleFetch, projectId]);
}, [handleFetch, handleConsoleMessage, projectId]);
useEffect(() => {
if (selectedFile) {
@@ -352,21 +393,103 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
}
};
const ConsoleDropdown = () => {
const getLevelColor = (level: ConsoleMessage['level']) => {
switch (level) {
case 'error': return 'text-red-500';
case 'warn': return 'text-yellow-500';
case 'info': return 'text-blue-500';
case 'debug': return 'text-gray-500';
default: return 'text-gray-400';
}
};
const getLevelIcon = (level: ConsoleMessage['level']) => {
switch (level) {
case 'error': return '!';
case 'warn': return '⚠';
case 'info': return 'ℹ';
case 'debug': return '🔍';
default: return '•';
}
};
const formatTimestamp = (timestamp: number) => {
return new Date(timestamp).toLocaleTimeString();
};
const clearConsole = () => {
setConsoleMessages([]);
};
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" className="ml-2">
<Terminal className="h-4 w-4 mr-2" />
Console ({consoleMessages.length})
{consoleMessages.some(msg => msg.level === 'error') && (
<span className="ml-2 h-2 w-2 bg-red-500 rounded-full"></span>
)}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-96 max-h-96">
<div className="flex items-center justify-between p-2 border-b">
<span className="font-medium text-sm">Console Output</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">
{consoleMessages.length === 0 ? (
<div className="text-center text-muted-foreground text-sm py-4">
No console messages
</div>
) : (
consoleMessages.map((msg) => (
<div
key={msg.id}
className={`text-xs font-mono p-2 rounded ${getLevelColor(msg.level)} bg-muted/50`}
>
<div className="flex items-center gap-2 mb-1">
<span>{getLevelIcon(msg.level)}</span>
<span className="opacity-60">{formatTimestamp(msg.timestamp)}</span>
</div>
<div className="whitespace-pre-wrap break-all">{msg.message}</div>
{msg.args.length > 0 && (
<div className="mt-1 opacity-70">
Args: {JSON.stringify(msg.args)}
</div>
)}
</div>
))
)}
</div>
</ScrollArea>
</DropdownMenuContent>
</DropdownMenu>
);
};
return (
<div className="h-full">
<Tabs value={activeTab} className="h-full">
<TabsContent value="preview" className="h-full mt-0">
{hasBuiltProject ? (
<div className="h-full w-full flex flex-col">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={navigateToPath}
onRefresh={refreshIframe}
onBack={goBack}
onForward={goForward}
canGoBack={historyIndex > 0}
canGoForward={historyIndex < navigationHistory.length - 1}
/>
<div className="flex items-center border-b">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={navigateToPath}
onRefresh={refreshIframe}
onBack={goBack}
onForward={goForward}
canGoBack={historyIndex > 0}
canGoForward={historyIndex < navigationHistory.length - 1}
/>
<ConsoleDropdown />
</div>
<iframe
ref={iframeRef}
src={`https://${projectId}.local-shakespeare.dev${currentPath}`}