From ba251d57eb592564e6d4988873a6c63bba6ca541 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Tue, 16 Sep 2025 05:30:26 +0000 Subject: [PATCH 01/17] baseline --- iframe-fetch-client/MESSAGING_PROTOCOL.md | 244 +++++++++++++++++++++ iframe-fetch-client/_iframe-client.js | 62 ++++++ iframe-fetch-client/test-console.html | 34 +++ src/components/Shakespeare/PreviewPane.tsx | 145 +++++++++++- 4 files changed, 474 insertions(+), 11 deletions(-) create mode 100644 iframe-fetch-client/test-console.html diff --git a/iframe-fetch-client/MESSAGING_PROTOCOL.md b/iframe-fetch-client/MESSAGING_PROTOCOL.md index a1e4845d..8857a5ee 100644 --- a/iframe-fetch-client/MESSAGING_PROTOCOL.md +++ b/iframe-fetch-client/MESSAGING_PROTOCOL.md @@ -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); ``` + +## 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(); +``` diff --git a/iframe-fetch-client/_iframe-client.js b/iframe-fetch-client/_iframe-client.js index e7281caa..7252fa41 100644 --- a/iframe-fetch-client/_iframe-client.js +++ b/iframe-fetch-client/_iframe-client.js @@ -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(); } diff --git a/iframe-fetch-client/test-console.html b/iframe-fetch-client/test-console.html new file mode 100644 index 00000000..7beb15a0 --- /dev/null +++ b/iframe-fetch-client/test-console.html @@ -0,0 +1,34 @@ + + + + + + Console Test + + +

Console Test Page

+

This page tests console logging functionality.

+ + + + \ No newline at end of file diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index c795e9d8..cca41f01 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -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(null); @@ -60,6 +73,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { const [currentPath, setCurrentPath] = useState('/'); const [navigationHistory, setNavigationHistory] = useState(['/']); const [historyIndex, setHistoryIndex] = useState(0); + const [consoleMessages, setConsoleMessages] = useState([]); const iframeRef = useRef(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 ( + + + + + +
+ Console Output + +
+ +
+ {consoleMessages.length === 0 ? ( +
+ No console messages +
+ ) : ( + consoleMessages.map((msg) => ( +
+
+ {getLevelIcon(msg.level)} + {formatTimestamp(msg.timestamp)} +
+
{msg.message}
+ {msg.args.length > 0 && ( +
+ Args: {JSON.stringify(msg.args)} +
+ )} +
+ )) + )} +
+
+
+
+ ); +}; + return (
{hasBuiltProject ? (
- 0} - canGoForward={historyIndex < navigationHistory.length - 1} - /> +
+ 0} + canGoForward={historyIndex < navigationHistory.length - 1} + /> + +
``` -Implement the JSON-RPC protocol (see `example-parent.html` for a complete -example): +Implement the JSON-RPC protocol: ```javascript class FetchClientParent { @@ -284,9 +284,9 @@ function handleRequest(fetchRequest) { ## Testing -1. Open `example-parent.html` in a browser -2. Click "Load Sample Site" -3. The iframe client should load and display the sample app +1. Create a parent page implementing the JSON-RPC protocol (see example in MESSAGING_PROTOCOL.md) +2. Load the iframe client in an iframe pointing to your deployed client domain +3. The iframe client should load and display the served content 4. Test navigation and functionality within the iframe client ## Browser Support @@ -326,10 +326,10 @@ function handleRequest(fetchRequest) { To modify the system: -1. **iframe Client:** Edit `index.html`, `_iframe-client.js`, - `_iframe-client.css`, `sw.js` +1. **iframe Client:** Edit `index.html`, `_iframe-client/main.js`, + `_iframe-client/client.css`, `sw.js` 2. **Protocol:** Update `MESSAGING_PROTOCOL.md` for any changes -3. **Testing:** Use `example-parent.html` for testing changes +3. **Testing:** Create a parent page implementing the JSON-RPC protocol for testing changes ## License diff --git a/iframe-fetch-client/_iframe-client/main.js b/iframe-fetch-client/_iframe-client/main.js index 4f1b13c2..1edc13b7 100644 --- a/iframe-fetch-client/_iframe-client/main.js +++ b/iframe-fetch-client/_iframe-client/main.js @@ -1,265 +1,8 @@ /** - * iframe Fetch Client Combined Entry Point - * Combines console interception and client initialization + * iframe Fetch Client - Simplified Implementation + * Implements JSON-RPC 2.0 messaging protocol per MESSAGING_PROTOCOL.md */ -// Console interception utilities -const CONSOLE_METHODS = ['log', 'warn', 'error', 'info', 'debug']; - -// Store original console methods -function storeOriginalConsole() { - const original = {}; - CONSOLE_METHODS.forEach(method => { - if (typeof console[method] === 'function') { - original[method] = console[method]; - } - }); - return original; -} - -// Override console methods with custom handler -function overrideConsoleMethods(originalConsole, messageHandler) { - CONSOLE_METHODS.forEach(method => { - if (typeof console[method] === 'function') { - console[method] = (...args) => { - // Call original method first - try { - originalConsole[method](...args); - } catch (e) { - // If original fails, at least send to parent - messageHandler(method, ...args); - return; - } - - // Send to parent - messageHandler(method, ...args); - }; - } - }); -} - -// Set up global error handlers -function setupGlobalErrorHandlers(messageHandler) { - // Override window.onerror to catch unhandled errors - const originalOnError = window.onerror; - window.onerror = (message, source, lineno, colno, error) => { - // Call original handler first - if (originalOnError) { - originalOnError(message, source, lineno, colno, error); - } - - // Send to parent - messageHandler('error', `Uncaught Error: ${message}`, { - source, - lineno, - colno, - error: error ? error.message : 'No error object', - stack: error ? error.stack : 'No stack trace' - }); - - return false; // Don't prevent default - }; - - // Override window.onunhandledrejection for Promise rejections - const originalOnUnhandledRejection = window.onunhandledrejection; - window.onunhandledrejection = (event) => { - // Call original handler first - if (originalOnUnhandledRejection) { - originalOnUnhandledRejection(event); - } - - // Send to parent - messageHandler('error', 'Unhandled Promise Rejection', { - reason: event.reason, - promise: event.promise ? 'Promise object' : 'No promise object' - }); - - event.preventDefault(); // Prevent default console warning - }; -} - -// 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) - }); - } - } - - 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} (${event.filename}:${event.lineno}:${event.colno})` - }); - }); - - // Handle unhandled promise rejections - window.addEventListener('unhandledrejection', (event) => { - this.earlyErrors.push({ - level: 'error', - message: `Unhandled Promise Rejection: ${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 early interceptor - this.originalConsole = window._originalConsole || console; - overrideConsoleMethods(this.originalConsole, this.sendConsoleMessage.bind(this)); - setupGlobalErrorHandlers(this.sendConsoleMessage.bind(this)); - this.overrideWindowError(); - } - - overrideWindowError() { - // Also try to catch errors that might occur during early execution - setTimeout(() => { - // Capture any errors that might have occurred before we were ready - this.sendConsoleMessage('info', 'Console interceptor initialized at:', Date.now()); - }, 0); - } - - sendConsoleMessage(level, ...args) { - try { - const message = args.map(arg => { - if (arg === undefined) return 'undefined'; - if (arg === null) return 'null'; - if (typeof arg === 'object') { - try { - return JSON.stringify(arg, (key, value) => { - if (value instanceof Error) { - return { - name: value.name, - message: value.message, - stack: value.stack - }; - } - return value; - }); - } catch { - return String(arg); - } - } - if (typeof arg === 'function') { - return arg.toString(); - } - return String(arg); - }).join(' '); - - // Try to send to parent, but don't fail if parent isn't ready - try { - window.parent.postMessage({ - jsonrpc: "2.0", - method: "console", - params: { - level, - message - } - }, "*"); - } catch (postMessageError) { - // Parent might not be ready yet, try again later - setTimeout(() => { - try { - window.parent.postMessage({ - jsonrpc: "2.0", - method: "console", - params: { - level: "error", - message: `[DELAYED] ${message}` - } - }, "*"); - } catch { - // Give up - parent isn't available - } - }, 100); - } - } catch (error) { - // If serialization fails, at least try to send a simple message - try { - window.parent.postMessage({ - jsonrpc: "2.0", - method: "console", - params: { - level: "error", - message: `Console interceptor error: ${error.message}` - } - }, "*"); - } catch { - // If even this fails, we can't do anything - } - } - } -} - // JSON-RPC Client for communication with parent class JSONRPCClient { constructor() { @@ -272,19 +15,17 @@ class JSONRPCClient { window.addEventListener("message", (event) => { const message = event.data; if (message.jsonrpc === "2.0" && message.id !== undefined) { - // Check if this is a response to our own request or a ServiceWorker request if (this.pendingRequests.has(message.id)) { this.handleResponse(message); } else { - // This is a response to a ServiceWorker request, relay it back - this.relayJSONRPCToServiceWorker(message); + // Response for ServiceWorker - relay it + this.relayToServiceWorker(message); } } }); } - relayJSONRPCToServiceWorker(response) { - // Forward the JSON-RPC response to ServiceWorker + relayToServiceWorker(response) { if (navigator.serviceWorker.controller) { navigator.serviceWorker.controller.postMessage(response); } @@ -296,7 +37,6 @@ class JSONRPCClient { return new Promise((resolve, reject) => { this.pendingRequests.set(id, { resolve, reject }); - // Send JSON-RPC request to parent window.parent.postMessage({ jsonrpc: "2.0", method: "fetch", @@ -304,7 +44,6 @@ class JSONRPCClient { id, }, "*"); - // Timeout after 10 seconds setTimeout(() => { if (this.pendingRequests.has(id)) { this.pendingRequests.delete(id); @@ -330,71 +69,133 @@ class JSONRPCClient { } } +// Console Interceptor - forwards console messages to parent +class ConsoleInterceptor { + constructor() { + this.originalConsole = {}; + this.methods = ['log', 'warn', 'error', 'info', 'debug']; + this.init(); + } + + init() { + // Store original methods + this.methods.forEach(method => { + if (typeof console[method] === 'function') { + this.originalConsole[method] = console[method]; + } + }); + + // Override console methods + this.methods.forEach(method => { + if (typeof console[method] === 'function') { + console[method] = (...args) => { + // Call original method + try { + this.originalConsole[method](...args); + } catch (e) { + // Continue if original fails + } + + // Send to parent + this.sendConsoleMessage(method, ...args); + }; + } + }); + } + + sendConsoleMessage(level, ...args) { + const message = args.map(arg => { + if (arg === undefined) return 'undefined'; + if (arg === null) return 'null'; + if (typeof arg === 'object') { + try { + return JSON.stringify(arg, (key, value) => { + if (value instanceof Error) { + return { + name: value.name, + message: value.message, + stack: value.stack + }; + } + return value; + }); + } catch { + return String(arg); + } + } + return String(arg); + }).join(' '); + + try { + window.parent.postMessage({ + jsonrpc: "2.0", + method: "console", + params: { level, message } + }, "*"); + } catch (error) { + // Retry once after delay if postMessage fails + setTimeout(() => { + try { + window.parent.postMessage({ + jsonrpc: "2.0", + method: "console", + params: { level: "error", message: `[DELAYED] ${message}` } + }, "*"); + } catch { + // Give up if retry fails + } + }, 100); + } + } +} + // Main Fetch Client class FetchClient { constructor() { this.rpcClient = new JSONRPCClient(); - this.swReady = false; this.consoleInterceptor = new ConsoleInterceptor(); - - // Process any early errors captured by inline script - this.processEarlyErrors(); - this.init(); } - processEarlyErrors() { - // Check for early errors captured before main script loaded - if (window._earlyConsoleErrors && Array.isArray(window._earlyConsoleErrors)) { - window._earlyConsoleErrors.forEach(error => { - console.log(`[EARLY ${error.level.toUpperCase()}] ${error.message}`); - }); - // Clear the early errors - window._earlyConsoleErrors = []; - } - } - async init() { try { - await this.registerServiceWorker(); - this.setupServiceWorkerCommunication(); - await this.waitForServiceWorker(); - await this.fetchSiteIndex(); + await this.setupServiceWorker(); + await this.loadSiteIndex(); } catch (error) { this.showError("Failed to initialize fetch client", error); } } - async registerServiceWorker() { + async setupServiceWorker() { if (!("serviceWorker" in navigator)) { throw new Error("ServiceWorker not supported"); } - // Check if SW is already registered - const existingRegistration = await navigator.serviceWorker - .getRegistration(); - if (existingRegistration) { + // Check if already registered + const existing = await navigator.serviceWorker.getRegistration(); + if (existing) { console.log("ServiceWorker already registered"); - this.swReady = true; + this.setupServiceWorkerCommunication(); return; } - try { - const registration = await navigator.serviceWorker.register("/sw.js", { - scope: "/", - }); + // Register new ServiceWorker + const registration = await navigator.serviceWorker.register("/sw.js", { scope: "/" }); + console.log("ServiceWorker registered:", registration); - console.log("ServiceWorker registered:", registration); + await navigator.serviceWorker.ready; + this.setupServiceWorkerCommunication(); + this.blockFutureRegistrations(); + } - // Wait for SW to be ready - await navigator.serviceWorker.ready; - this.swReady = true; - - // Block future registrations to prevent site from registering its own SW - this.blockFutureRegistrations(); - } catch (error) { - throw new Error(`ServiceWorker registration failed: ${error.message}`); - } + setupServiceWorkerCommunication() { + // Relay JSON-RPC requests from ServiceWorker to parent + navigator.serviceWorker.addEventListener("message", (event) => { + const { data } = event; + if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) { + window.parent.postMessage(data, "*"); + } + }); } blockFutureRegistrations() { @@ -411,71 +212,35 @@ class FetchClient { }; } - setupServiceWorkerCommunication() { - // Listen for JSON-RPC requests from ServiceWorker and relay them to parent - navigator.serviceWorker.addEventListener("message", async (event) => { - const { data } = event; + async loadSiteIndex() { + const serializedRequest = { + url: `${location.origin}/`, + method: "GET", + body: null, + headers: {}, + }; - // Check if this is a JSON-RPC request from ServiceWorker - if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) { - this.relayJSONRPCToParent(data); - } - }); - } + const response = await this.rpcClient.fetch(serializedRequest); - relayJSONRPCToParent(request) { - // Forward the JSON-RPC request directly to parent - window.parent.postMessage(request, "*"); - } - - async waitForServiceWorker() { - const timeout = 10000; // 10 seconds - const start = Date.now(); - - while (!this.swReady) { - if (Date.now() - start > timeout) { - throw new Error("Timeout waiting for ServiceWorker readiness"); - } - await new Promise((resolve) => setTimeout(resolve, 100)); + if (response.status !== 200) { + throw new Error(`Failed to fetch site index: ${response.status} ${response.statusText}`); } - console.log("ServiceWorker is ready"); - } - - async fetchSiteIndex() { - try { - // Request site index from parent via JSON-RPC fetch - const serializedRequest = { - url: `${location.origin}/`, - method: "GET", - body: null, - headers: {}, - }; - - const response = await this.rpcClient.fetch(serializedRequest); - - if (response.status !== 200) { - throw new Error(`Failed to fetch site index: ${response.status} ${response.statusText}`); - } - if (response.headers["Content-Type"] !== "text/html") { - throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`); - } - - const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0))); - const text = new TextDecoder().decode(bytes); - - // Replace current document with the site index content - this.replaceDocument(text); - } catch (error) { - this.showError("Failed to load site index", error); + if (response.headers["Content-Type"] !== "text/html") { + throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`); } + + const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0))); + const text = new TextDecoder().decode(bytes); + + this.replaceDocument(text); } replaceDocument(htmlContent) { - // Create a new document from the HTML content const parser = new DOMParser(); const newDoc = parser.parseFromString(htmlContent, "text/html"); + // Extract scripts for re-execution const scripts = []; newDoc.querySelectorAll("script").forEach((script) => { scripts.push({ @@ -484,14 +249,14 @@ class FetchClient { async: script.hasAttribute("async"), defer: script.hasAttribute("defer"), }); - script.parentNode.removeChild(script); + script.remove(); }); - // Replace the entire document + // Replace document content document.head.innerHTML = newDoc.head.innerHTML; document.body.innerHTML = newDoc.body.innerHTML; - // Re-add scripts (this is necessary to execute them) + // Re-add scripts to execute them scripts.forEach((script) => { const newScript = document.createElement("script"); newScript.src = script.src; @@ -508,38 +273,76 @@ class FetchClient { console.error(message, error); document.body.innerHTML = ` -
-

Fetch Client Error

-

${message}

-

${error.message || error}

-
- Technical Details -
${error.stack || JSON.stringify(error, null, 2)}
-
-
- `; +
+

Fetch Client Error

+

${message}

+

${error.message || error}

+
+ Technical Details +
${error.stack || JSON.stringify(error, null, 2)}
+
+
+ `; } } -// Initialize early console interception immediately -new EarlyConsoleInterceptor(); +// Global error handlers +function setupGlobalErrorHandlers() { + window.addEventListener('error', (event) => { + try { + window.parent.postMessage({ + jsonrpc: "2.0", + method: "console", + params: { + level: "error", + message: `Uncaught Error: ${event.message}`, + source: event.filename, + lineno: event.lineno, + colno: event.colno, + stack: event.error?.stack + } + }, "*"); + } catch { + // Ignore postMessage errors + } + }); + + window.addEventListener('unhandledrejection', (event) => { + try { + window.parent.postMessage({ + jsonrpc: "2.0", + method: "console", + params: { + level: "error", + message: "Unhandled Promise Rejection", + reason: event.reason, + promise: event.promise ? 'Promise object' : 'No promise object' + } + }, "*"); + } catch { + // Ignore postMessage errors + } + }); +} + +// Initialize +setupGlobalErrorHandlers(); -// Initialize when DOM is ready if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", () => new FetchClient()); } else { From 4cd8683e739764e98a8b67df03ea3712e2e3406b Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Sat, 20 Sep 2025 18:09:03 +0000 Subject: [PATCH 14/17] Re-add purged, but informative documentation/comment items. --- iframe-fetch-client/MESSAGING_PROTOCOL.md | 14 +++++++++++++- iframe-fetch-client/_iframe-client/main.js | 9 +++++++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/iframe-fetch-client/MESSAGING_PROTOCOL.md b/iframe-fetch-client/MESSAGING_PROTOCOL.md index ed3186e1..0f1328b5 100644 --- a/iframe-fetch-client/MESSAGING_PROTOCOL.md +++ b/iframe-fetch-client/MESSAGING_PROTOCOL.md @@ -7,7 +7,8 @@ between the parent page and the iframe fetch client. The iframe fetch client uses JSON-RPC 2.0 over `postMessage` for communication. The ServiceWorker makes JSON-RPC calls directly, with the main thread acting as -a relay between the ServiceWorker and parent page. +a relay between the ServiceWorker and parent page. The only required method is +`fetch` for handling HTTP requests. ## Architecture @@ -125,6 +126,17 @@ full request body support - `-32002`: Request processing error - `-32003`: Invalid URL +**Request Body Support:** The system fully supports request bodies, enabling: + +- POST/PUT requests with JSON data +- Form submissions +- API calls with payloads +- File uploads (as base64 strings) +- Any HTTP method with body content + +Request bodies must be base64-encoded strings when not null. This ensures +consistent handling of both text and binary data across the messaging protocol. + ### `console` **Purpose:** Forward console messages from iframe to parent for display diff --git a/iframe-fetch-client/_iframe-client/main.js b/iframe-fetch-client/_iframe-client/main.js index 1edc13b7..83314e24 100644 --- a/iframe-fetch-client/_iframe-client/main.js +++ b/iframe-fetch-client/_iframe-client/main.js @@ -14,11 +14,12 @@ class JSONRPCClient { setupMessageListener() { window.addEventListener("message", (event) => { const message = event.data; + // Check if this is a response to our own request or a ServiceWorker request if (message.jsonrpc === "2.0" && message.id !== undefined) { if (this.pendingRequests.has(message.id)) { this.handleResponse(message); } else { - // Response for ServiceWorker - relay it + // This is a response to a ServiceWorker request, relay it back this.relayToServiceWorker(message); } } @@ -26,6 +27,7 @@ class JSONRPCClient { } relayToServiceWorker(response) { + // Forward the JSON-RPC response to ServiceWorker if (navigator.serviceWorker.controller) { navigator.serviceWorker.controller.postMessage(response); } @@ -37,6 +39,7 @@ class JSONRPCClient { return new Promise((resolve, reject) => { this.pendingRequests.set(id, { resolve, reject }); + // Send JSON-RPC request to parent window.parent.postMessage({ jsonrpc: "2.0", method: "fetch", @@ -44,6 +47,7 @@ class JSONRPCClient { id, }, "*"); + // Timeout after 10 seconds setTimeout(() => { if (this.pendingRequests.has(id)) { this.pendingRequests.delete(id); @@ -185,7 +189,7 @@ class FetchClient { await navigator.serviceWorker.ready; this.setupServiceWorkerCommunication(); - this.blockFutureRegistrations(); + this.blockFutureRegistrations(); // Block future registrations to prevent site from registering its own SW } setupServiceWorkerCommunication() { @@ -237,6 +241,7 @@ class FetchClient { } replaceDocument(htmlContent) { + // Create a new document from the HTML content const parser = new DOMParser(); const newDoc = parser.parseFromString(htmlContent, "text/html"); From a823f81b50ba08a01c7b61be1323da2584b98f65 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Sat, 20 Sep 2025 18:21:55 +0000 Subject: [PATCH 15/17] Function definition consistency + slight deduplication --- iframe-fetch-client/_iframe-client/main.js | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/iframe-fetch-client/_iframe-client/main.js b/iframe-fetch-client/_iframe-client/main.js index 83314e24..c542df60 100644 --- a/iframe-fetch-client/_iframe-client/main.js +++ b/iframe-fetch-client/_iframe-client/main.js @@ -82,16 +82,11 @@ class ConsoleInterceptor { } init() { - // Store original methods - this.methods.forEach(method => { + // Store original methods and override in single pass + this.methods.forEach((method) => { if (typeof console[method] === 'function') { this.originalConsole[method] = console[method]; - } - }); - // Override console methods - this.methods.forEach(method => { - if (typeof console[method] === 'function') { console[method] = (...args) => { // Call original method try { @@ -108,7 +103,7 @@ class ConsoleInterceptor { } sendConsoleMessage(level, ...args) { - const message = args.map(arg => { + const message = args.map((arg) => { if (arg === undefined) return 'undefined'; if (arg === null) return 'null'; if (typeof arg === 'object') { @@ -203,7 +198,7 @@ class FetchClient { } blockFutureRegistrations() { - navigator.serviceWorker.register = function () { + navigator.serviceWorker.register = () => { console.log("Blocked ServiceWorker registration attempt"); return Promise.resolve({ scope: "/", @@ -307,7 +302,7 @@ class FetchClient { } // Global error handlers -function setupGlobalErrorHandlers() { +const setupGlobalErrorHandlers = () => { window.addEventListener('error', (event) => { try { window.parent.postMessage({ @@ -343,7 +338,7 @@ function setupGlobalErrorHandlers() { // Ignore postMessage errors } }); -} +}; // Initialize setupGlobalErrorHandlers(); From 718b2f369b16aea8e516205881c91742d2d61e45 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Sat, 20 Sep 2025 18:24:18 +0000 Subject: [PATCH 16/17] Remove code example from a file path already linked. --- iframe-fetch-client/MESSAGING_PROTOCOL.md | 83 +---------------------- 1 file changed, 1 insertion(+), 82 deletions(-) diff --git a/iframe-fetch-client/MESSAGING_PROTOCOL.md b/iframe-fetch-client/MESSAGING_PROTOCOL.md index 0f1328b5..150486ae 100644 --- a/iframe-fetch-client/MESSAGING_PROTOCOL.md +++ b/iframe-fetch-client/MESSAGING_PROTOCOL.md @@ -371,85 +371,4 @@ const decodedBytes = new Uint8Array(atob(encodedBody).split('').map(c => c.charC ## Console Logging Implementation -The iframe client automatically intercepts console messages and forwards them to the parent. The implementation (in `_iframe-client/main.js`) overrides console methods: - -```javascript -class ConsoleInterceptor { - constructor() { - this.originalConsole = {}; - this.methods = ['log', 'warn', 'error', 'info', 'debug']; - this.init(); - } - - init() { - // Store original methods - this.methods.forEach(method => { - if (typeof console[method] === 'function') { - this.originalConsole[method] = console[method]; - } - }); - - // Override console methods - this.methods.forEach(method => { - if (typeof console[method] === 'function') { - console[method] = (...args) => { - // Call original method - try { - this.originalConsole[method](...args); - } catch (e) { - // Continue if original fails - } - - // Send to parent - this.sendConsoleMessage(method, ...args); - }; - } - }); - } - - sendConsoleMessage(level, ...args) { - const message = args.map(arg => { - if (arg === undefined) return 'undefined'; - if (arg === null) return 'null'; - if (typeof arg === 'object') { - try { - return JSON.stringify(arg, (key, value) => { - if (value instanceof Error) { - return { - name: value.name, - message: value.message, - stack: value.stack - }; - } - return value; - }); - } catch { - return String(arg); - } - } - return String(arg); - }).join(' '); - - try { - window.parent.postMessage({ - jsonrpc: "2.0", - method: "console", - params: { level, message } - }, "*"); - } catch (error) { - // Retry once after delay if postMessage fails - setTimeout(() => { - try { - window.parent.postMessage({ - jsonrpc: "2.0", - method: "console", - params: { level: "error", message: `[DELAYED] ${message}` } - }, "*"); - } catch { - // Give up if retry fails - } - }, 100); - } - } -} -``` \ No newline at end of file +The iframe client automatically intercepts console messages and forwards them to the parent. The implementation (in `_iframe-client/main.js`) overrides console methods. \ No newline at end of file From c6617beb6d92e8498ea45fe7a5df015b68f07416 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Sat, 20 Sep 2025 18:36:52 +0000 Subject: [PATCH 17/17] Gracefully handle total response failure from site - no response at all. --- iframe-fetch-client/_iframe-client/main.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/iframe-fetch-client/_iframe-client/main.js b/iframe-fetch-client/_iframe-client/main.js index c542df60..151c70d0 100644 --- a/iframe-fetch-client/_iframe-client/main.js +++ b/iframe-fetch-client/_iframe-client/main.js @@ -221,8 +221,8 @@ class FetchClient { const response = await this.rpcClient.fetch(serializedRequest); - if (response.status !== 200) { - throw new Error(`Failed to fetch site index: ${response.status} ${response.statusText}`); + if (response?.status !== 200) { + throw new Error(`Failed to fetch site index: ${response?.status || 'Invalid response from site: ' + response} ${response?.statusText || ''}`); } if (response.headers["Content-Type"] !== "text/html") {