diff --git a/iframe-fetch-client/MESSAGING_PROTOCOL.md b/iframe-fetch-client/MESSAGING_PROTOCOL.md index a1e4845d..150486ae 100644 --- a/iframe-fetch-client/MESSAGING_PROTOCOL.md +++ b/iframe-fetch-client/MESSAGING_PROTOCOL.md @@ -65,7 +65,7 @@ All messages follow JSON-RPC 2.0 specification: "headers": { "Content-Type": "application/json" }, - "body": "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9" // base64 of: {"name":"John","age":30} + "body": "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9" // base64 encoded: {"name":"John","age":30} } }, "id": 124 @@ -81,7 +81,7 @@ All messages follow JSON-RPC 2.0 specification: "Content-Type": "application/javascript", "Cache-Control": "no-cache" }, - "body": "Y29uc29sZS5sb2coJ2hlbGxvJyk7" + "body": "Y29uc29sZS5sb2coJ2hlbGxvJyk7" // base64 encoded: console.log('hello'); }, "id": 123 } @@ -137,16 +137,28 @@ full request body support 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 + +**Parameters:** + +- `level` (string): Log level - "log", "warn", "error", "info", "debug" +- `message` (string): The log message + +**Result:** None (notification only, no response expected) + ## Implementation ### Parent Page -In this example, the parent page acts as a static file server. +The parent page acts as a static file server and console log collector: ```javascript class FetchClientParent { constructor(files) { this.files = files; // Map of path -> {content, contentType} + this.consoleLogs = []; // Store console messages this.setupMessageListener(); } @@ -156,12 +168,43 @@ class FetchClientParent { 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 === "console") { + this.handleConsoleMessage(message); + } }); } + handleConsoleMessage(message) { + const { params } = message; + const { level, message: logMessage } = params; + + // Store the log message + this.consoleLogs.push({ + level, + message: logMessage, + timestamp: Date.now(), + id: Date.now() + }); + + // Update UI to show new logs + this.updateConsoleUI(); + + // Also log to parent's console for debugging + console[level](`[IFRAME] ${logMessage}`); + } + + updateConsoleUI() { + // Implementation depends on your UI framework + console.log(`Total console logs: ${this.consoleLogs.length}`); + } + handleFetch(request) { const { params, id } = request; const { request: fetchRequest } = params; @@ -170,9 +213,6 @@ class FetchClientParent { 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) { @@ -186,11 +226,10 @@ class FetchClientParent { "Content-Type": file.contentType, "Cache-Control": "no-cache", }, - body: btoa(file.content), // base64 encode the response body + body: btoa(file.content), }, }); } else { - // Return 404 response (not a JSON-RPC error) this.sendResponse({ id, jsonrpc: "2.0", @@ -200,7 +239,7 @@ class FetchClientParent { headers: { "Content-Type": "text/plain", }, - body: btoa(`File not found: ${path}`), // base64 encode the error message + body: btoa(`File not found: ${path}`), }, }); } @@ -210,22 +249,15 @@ class FetchClientParent { 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"); - } } ``` -### Preview Page +### iframe Client Communication -Below is a simplified RPC client that could be used inside the iframe's main -thread to test functionality of the parent. In practice, requests originate from -the ServiceWorker and the main thread acts as a relay, so multiple steps of -communication are involved. +The iframe client uses a simplified JSON-RPC client for communication. In the actual implementation, the ServiceWorker makes requests and the main thread acts as a relay: ```javascript +// Simplified JSON-RPC client (actual implementation in _iframe-client/main.js) class JSONRPCClient { constructor() { this.requestId = 0; @@ -236,7 +268,7 @@ class JSONRPCClient { setupMessageListener() { window.addEventListener("message", (event) => { const message = event.data; - if (message.jsonrpc === "2.0" && message.id) { + if (message.jsonrpc === "2.0" && message.id !== undefined) { this.handleResponse(message); } }); @@ -248,7 +280,6 @@ class JSONRPCClient { return new Promise((resolve, reject) => { this.pendingRequests.set(id, { resolve, reject }); - // Send request to parent window.parent.postMessage({ jsonrpc: "2.0", method: "fetch", @@ -256,7 +287,6 @@ class JSONRPCClient { id, }, "*"); - // Timeout after 10 seconds setTimeout(() => { if (this.pendingRequests.has(id)) { this.pendingRequests.delete(id); @@ -275,9 +305,8 @@ class JSONRPCClient { this.pendingRequests.delete(id); if (error) { - pending.reject(new Error(error.message)); + pending.reject(new Error(`${error.message} (code: ${error.code})`)); } else { - // Result is a serialized response pending.resolve(result); } } @@ -286,7 +315,7 @@ class JSONRPCClient { ## Base64 Encoding -All request and response bodies must be base64 encoded when not null. This ensures: +All request and response bodies are base64 encoded when not null to ensure proper transmission through JSON-RPC: - **Consistent Data Handling:** Both text and binary data are handled uniformly - **JSON Compatibility:** Avoids issues with special characters in JSON messages @@ -294,11 +323,16 @@ All request and response bodies must be base64 encoded when not null. This ensur **Encoding/Decoding:** ```javascript -// Encoding (before sending) -const encodedBody = btoa(originalBody); +// Encoding text content (parent side) +const encodedBody = btoa(textContent); -// Decoding (after receiving) -const decodedBody = atob(encodedBody); +// Encoding binary content (ServiceWorker side) +const bytes = new Uint8Array(arrayBuffer); +const encodedBody = btoa(String.fromCharCode(...bytes)); + +// Decoding (receiver side) +const decodedText = atob(encodedBody); +const decodedBytes = new Uint8Array(atob(encodedBody).split('').map(c => c.charCodeAt(0))); ``` ## Security @@ -324,9 +358,17 @@ const decodedBody = atob(encodedBody); content: "Hello world!", contentType: "text/html", }], + ["/app.js", { + content: "console.log('App loaded');", + contentType: "application/javascript", + }], ]); - // Example static file server + // Initialize the fetch client parent new FetchClientParent(files); ``` + +## 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. \ No newline at end of file diff --git a/iframe-fetch-client/README.md b/iframe-fetch-client/README.md index 54fe5c5c..a7d2910e 100644 --- a/iframe-fetch-client/README.md +++ b/iframe-fetch-client/README.md @@ -54,30 +54,31 @@ blocked. ``` / -├── index.html # Main iframe client page -├── _iframe-client.js # Main coordination script -├── _iframe-client.css # Styles for the iframe client -├── sw.js # ServiceWorker -├── MESSAGING_PROTOCOL.md # Communication protocol docs -├── example-parent.html # Example parent implementation -└── README.md # This file +├── index.html # Main iframe client page +├── _iframe-client/ +│ ├── main.js # Main coordination script +│ └── client.css # Styles for the iframe client +├── sw.js # ServiceWorker +├── MESSAGING_PROTOCOL.md # Communication protocol docs +└── README.md # This file ``` ## Simplified JSON-RPC Protocol -The system now uses a drastically simplified JSON-RPC 2.0 protocol with only one -method: +The system now uses a simplified JSON-RPC 2.0 protocol with two methods: - **`fetch(request)`** - Handle HTTP requests with serialized fetch request/response +- **`console(level, message)`** - Forward console messages from + iframe to parent for display **Request:** ```javascript { "jsonrpc": "2.0", - "method": "fetch", - "params": { + "method": "fetch", + "params": { "request": { "url": "https://app123.example.com/assets/main.js", "method": "GET", @@ -106,6 +107,19 @@ method: } ``` +**Console Message:** + +```javascript +{ + "jsonrpc": "2.0", + "method": "console", + "params": { + "level": "error", + "message": "Failed to load module" + } +} +``` + ## How It Works 1. **Initialization:** @@ -136,8 +150,9 @@ Deploy these files to your iframe client subdomain: ``` https://*.example.com/ ├── index.html -├── _iframe-client.js -├── _iframe-client.css +├── _iframe-client/ +│ ├── main.js +│ └── client.css └── sw.js ``` @@ -158,8 +173,7 @@ Include the iframe client in your parent page: ``` -Implement the JSON-RPC protocol (see `example-parent.html` for a complete -example): +Implement the JSON-RPC protocol: ```javascript class FetchClientParent { @@ -270,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 @@ -312,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.js b/iframe-fetch-client/_iframe-client.js deleted file mode 100644 index e7281caa..00000000 --- a/iframe-fetch-client/_iframe-client.js +++ /dev/null @@ -1,270 +0,0 @@ -/** - * iframe Fetch Client Main Script - * JSON-RPC based communication with parent page - */ - -class JSONRPCClient { - constructor() { - this.requestId = 0; - this.pendingRequests = new Map(); - this.setupMessageListener(); - } - - setupMessageListener() { - 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); - } - } - }); - } - - relayJSONRPCToServiceWorker(response) { - // Forward the JSON-RPC response to ServiceWorker - if (navigator.serviceWorker.controller) { - navigator.serviceWorker.controller.postMessage(response); - } - } - - async fetch(request) { - const id = ++this.requestId; - - 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", - params: { request }, - id, - }, "*"); - - // Timeout after 10 seconds - setTimeout(() => { - if (this.pendingRequests.has(id)) { - this.pendingRequests.delete(id); - reject(new Error(`Timeout fetching: ${request.url}`)); - } - }, 10000); - }); - } - - handleResponse(message) { - const { id, result, error } = message; - const pending = this.pendingRequests.get(id); - - if (!pending) return; - - this.pendingRequests.delete(id); - - if (error) { - pending.reject(new Error(`${error.message} (code: ${error.code})`)); - } else { - pending.resolve(result); - } - } -} - -class FetchClient { - constructor() { - this.rpcClient = new JSONRPCClient(); - this.swReady = false; - - this.init(); - } - - async init() { - try { - await this.registerServiceWorker(); - this.setupServiceWorkerCommunication(); - await this.waitForServiceWorker(); - await this.fetchSiteIndex(); - } catch (error) { - this.showError("Failed to initialize fetch client", error); - } - } - - async registerServiceWorker() { - if (!("serviceWorker" in navigator)) { - throw new Error("ServiceWorker not supported"); - } - - // Check if SW is already registered - const existingRegistration = await navigator.serviceWorker - .getRegistration(); - if (existingRegistration) { - console.log("ServiceWorker already registered"); - this.swReady = true; - return; - } - - try { - const registration = await navigator.serviceWorker.register("/sw.js", { - scope: "/", - }); - - console.log("ServiceWorker registered:", registration); - - // 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}`); - } - } - - blockFutureRegistrations() { - navigator.serviceWorker.register = function () { - console.log("Blocked ServiceWorker registration attempt"); - return Promise.resolve({ - scope: "/", - active: navigator.serviceWorker.controller, - installing: null, - waiting: null, - addEventListener: () => {}, - removeEventListener: () => {}, - }); - }; - } - - setupServiceWorkerCommunication() { - // Listen for JSON-RPC requests from ServiceWorker and relay them to parent - navigator.serviceWorker.addEventListener("message", async (event) => { - const { data } = event; - - // Check if this is a JSON-RPC request from ServiceWorker - if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) { - this.relayJSONRPCToParent(data); - } - }); - } - - 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)); - } - - 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); - } - } - - replaceDocument(htmlContent) { - // Create a new document from the HTML content - const parser = new DOMParser(); - const newDoc = parser.parseFromString(htmlContent, "text/html"); - - const scripts = []; - newDoc.querySelectorAll("script").forEach((script) => { - scripts.push({ - src: script.src, - type: script.type, - async: script.hasAttribute("async"), - defer: script.hasAttribute("defer"), - }); - script.parentNode.removeChild(script); - }); - - // Replace the entire document - document.head.innerHTML = newDoc.head.innerHTML; - document.body.innerHTML = newDoc.body.innerHTML; - - // Re-add scripts (this is necessary to execute them) - scripts.forEach((script) => { - const newScript = document.createElement("script"); - newScript.src = script.src; - newScript.type = script.type; - if (script.async) newScript.async = true; - if (script.defer) newScript.defer = true; - document.body.appendChild(newScript); - }); - - console.log("Document replaced with site content"); - } - - showError(message, error) { - console.error(message, error); - - document.body.innerHTML = ` -
-

Fetch Client Error

-

${message}

-

${error.message || error}

-
- Technical Details -
${error.stack || JSON.stringify(error, null, 2)}
-
-
- `; - } -} - -// Initialize when DOM is ready -if (document.readyState === "loading") { - document.addEventListener("DOMContentLoaded", () => new FetchClient()); -} else { - new FetchClient(); -} diff --git a/iframe-fetch-client/_iframe-client.css b/iframe-fetch-client/_iframe-client/client.css similarity index 100% rename from iframe-fetch-client/_iframe-client.css rename to iframe-fetch-client/_iframe-client/client.css diff --git a/iframe-fetch-client/_iframe-client/main.js b/iframe-fetch-client/_iframe-client/main.js new file mode 100644 index 00000000..151c70d0 --- /dev/null +++ b/iframe-fetch-client/_iframe-client/main.js @@ -0,0 +1,350 @@ +/** + * iframe Fetch Client - Simplified Implementation + * Implements JSON-RPC 2.0 messaging protocol per MESSAGING_PROTOCOL.md + */ + +// JSON-RPC Client for communication with parent +class JSONRPCClient { + constructor() { + this.requestId = 0; + this.pendingRequests = new Map(); + this.setupMessageListener(); + } + + 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 { + // This is a response to a ServiceWorker request, relay it back + this.relayToServiceWorker(message); + } + } + }); + } + + relayToServiceWorker(response) { + // Forward the JSON-RPC response to ServiceWorker + if (navigator.serviceWorker.controller) { + navigator.serviceWorker.controller.postMessage(response); + } + } + + async fetch(request) { + const id = ++this.requestId; + + 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", + params: { request }, + id, + }, "*"); + + // Timeout after 10 seconds + setTimeout(() => { + if (this.pendingRequests.has(id)) { + this.pendingRequests.delete(id); + reject(new Error(`Timeout fetching: ${request.url}`)); + } + }, 10000); + }); + } + + handleResponse(message) { + const { id, result, error } = message; + const pending = this.pendingRequests.get(id); + + if (!pending) return; + + this.pendingRequests.delete(id); + + if (error) { + pending.reject(new Error(`${error.message} (code: ${error.code})`)); + } else { + pending.resolve(result); + } + } +} + +// 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 and override in single pass + this.methods.forEach((method) => { + if (typeof console[method] === 'function') { + this.originalConsole[method] = console[method]; + + 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.consoleInterceptor = new ConsoleInterceptor(); + this.init(); + } + + async init() { + try { + await this.setupServiceWorker(); + await this.loadSiteIndex(); + } catch (error) { + this.showError("Failed to initialize fetch client", error); + } + } + + async setupServiceWorker() { + if (!("serviceWorker" in navigator)) { + throw new Error("ServiceWorker not supported"); + } + + // Check if already registered + const existing = await navigator.serviceWorker.getRegistration(); + if (existing) { + console.log("ServiceWorker already registered"); + this.setupServiceWorkerCommunication(); + return; + } + + // Register new ServiceWorker + const registration = await navigator.serviceWorker.register("/sw.js", { scope: "/" }); + console.log("ServiceWorker registered:", registration); + + await navigator.serviceWorker.ready; + this.setupServiceWorkerCommunication(); + this.blockFutureRegistrations(); // Block future registrations to prevent site from registering its own SW + } + + 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() { + navigator.serviceWorker.register = () => { + console.log("Blocked ServiceWorker registration attempt"); + return Promise.resolve({ + scope: "/", + active: navigator.serviceWorker.controller, + installing: null, + waiting: null, + addEventListener: () => {}, + removeEventListener: () => {}, + }); + }; + } + + async loadSiteIndex() { + 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 || 'Invalid response from site: ' + response} ${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); + + 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({ + src: script.src, + type: script.type, + async: script.hasAttribute("async"), + defer: script.hasAttribute("defer"), + }); + script.remove(); + }); + + // Replace document content + document.head.innerHTML = newDoc.head.innerHTML; + document.body.innerHTML = newDoc.body.innerHTML; + + // Re-add scripts to execute them + scripts.forEach((script) => { + const newScript = document.createElement("script"); + newScript.src = script.src; + newScript.type = script.type; + if (script.async) newScript.async = true; + if (script.defer) newScript.defer = true; + document.body.appendChild(newScript); + }); + + console.log("Document replaced with site content"); + } + + showError(message, error) { + console.error(message, error); + + document.body.innerHTML = ` +
+

Fetch Client Error

+

${message}

+

${error.message || error}

+
+ Technical Details +
${error.stack || JSON.stringify(error, null, 2)}
+
+
+ `; + } +} + +// Global error handlers +const 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(); + +if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", () => new FetchClient()); +} else { + new FetchClient(); +} \ No newline at end of file diff --git a/iframe-fetch-client/index.html b/iframe-fetch-client/index.html index 001b1ea8..c8a88573 100644 --- a/iframe-fetch-client/index.html +++ b/iframe-fetch-client/index.html @@ -4,7 +4,7 @@ Site Preview - +
@@ -12,6 +12,6 @@

Loading preview...

Waiting for ServiceWorker and parent communication

- + diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index c795e9d8..7d7ed0d7 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -6,14 +6,22 @@ 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, 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'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu'; import { FileTree } from './FileTree'; import { FileEditor } from './FileEditor'; +// Get iframe domain from environment variable +const IFRAME_DOMAIN = import.meta.env.VITE_IFRAME_DOMAIN || 'local-shakespeare.dev'; + interface PreviewPaneProps { projectId: string; activeTab: 'preview' | 'code'; @@ -40,7 +48,7 @@ interface JSONRPCResponse { statusText: string; headers: Record; body: string | null; - }; + } error?: { code: number; message: string; @@ -49,6 +57,12 @@ interface JSONRPCResponse { id: number; } +interface ConsoleMessage { + id: number; + level: 'log' | 'warn' | 'error' | 'info' | 'debug'; + message: string; +} + export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { const { t } = useTranslation(); const [selectedFile, setSelectedFile] = useState(null); @@ -60,6 +74,8 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { const [currentPath, setCurrentPath] = useState('/'); const [navigationHistory, setNavigationHistory] = useState(['/']); const [historyIndex, setHistoryIndex] = useState(0); + const [consoleMessages, setConsoleMessages] = useState([]); + const [copiedMessageId, setCopiedMessageId] = useState(null); const iframeRef = useRef(null); const { fs } = useFS(); const projectsManager = useProjectsManager(); @@ -129,7 +145,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { const navigateToPath = useCallback((path: string) => { if (iframeRef.current) { - const baseUrl = `https://${projectId}.local-shakespeare.dev`; + const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`; const newUrl = `${baseUrl}${path}`; iframeRef.current.src = newUrl; setCurrentPath(path); @@ -150,7 +166,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { setCurrentPath(path); if (iframeRef.current) { - const baseUrl = `https://${projectId}.local-shakespeare.dev`; + const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`; const newUrl = `${baseUrl}${path}`; iframeRef.current.src = newUrl; } @@ -165,7 +181,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { setCurrentPath(path); if (iframeRef.current) { - const baseUrl = `https://${projectId}.local-shakespeare.dev`; + const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`; const newUrl = `${baseUrl}${path}`; iframeRef.current.src = newUrl; } @@ -175,18 +191,46 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { const sendResponse = useCallback((message: JSONRPCResponse) => { if (iframeRef.current?.contentWindow) { console.log(`Sending response to iframe:`, message); - const targetOrigin = `https://${projectId}.local-shakespeare.dev`; + const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`; iframeRef.current.contentWindow.postMessage(message, targetOrigin); } }, [projectId]); const sendError = useCallback((message: JSONRPCResponse) => { if (iframeRef.current?.contentWindow) { - const targetOrigin = `https://${projectId}.local-shakespeare.dev`; + const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`; iframeRef.current.contentWindow.postMessage(message, targetOrigin); } }, [projectId]); + const handleConsoleMessage = useCallback((message: { + jsonrpc: '2.0'; + method: 'console'; + params: { + level: 'log' | 'warn' | 'error' | 'info' | 'debug'; + message: string; + }; + }) => { + const { params } = message; + + // Normalize level to ensure it's one of our supported types + let normalizedLevel: ConsoleMessage['level'] = 'log'; + if (['log', 'warn', 'error', 'info', 'debug'].includes(params.level)) { + normalizedLevel = params.level as ConsoleMessage['level']; + } + + const newConsoleMessage: ConsoleMessage = { + id: Date.now(), + level: normalizedLevel, + message: params.message, + }; + + setConsoleMessages(prev => [...prev, newConsoleMessage]); + + // Log to parent console for debugging with appropriate level + console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`); + }, []); + const handleFetch = useCallback(async (request: JSONRPCRequest) => { const { params, id } = request; const { request: fetchRequest } = params; @@ -196,7 +240,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { try { // Parse the URL and validate origin const url = new URL(fetchRequest.url); - const expectedOrigin = `https://${projectId}.local-shakespeare.dev`; + const expectedOrigin = `https://${projectId}.${IFRAME_DOMAIN}`; if (url.origin !== expectedOrigin) { console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`); @@ -292,7 +336,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { useEffect(() => { const handleMessage = (event: MessageEvent) => { // Verify origin for security - const expectedOrigin = `https://${projectId}.local-shakespeare.dev`; + const expectedOrigin = `https://${projectId}.${IFRAME_DOMAIN}`; if (event.origin !== expectedOrigin) { console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`); return; @@ -302,12 +346,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 === 'console') { + handleConsoleMessage(message); } }; window.addEventListener('message', handleMessage); return () => window.removeEventListener('message', handleMessage); - }, [handleFetch, projectId]); + }, [handleFetch, handleConsoleMessage, projectId]); useEffect(() => { if (selectedFile) { @@ -352,24 +398,123 @@ 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 clearConsole = () => { + setConsoleMessages([]); + }; + + const copyMessageToClipboard = async (msg: ConsoleMessage) => { + try { + // Create a formatted string with all message details + const formattedMessage = `[${msg.level.toUpperCase()}] ${msg.message}`; + + 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 ( + + + + + +
+ Console Output ({consoleMessages.length}) + +
+ +
+ {consoleMessages.length === 0 ? ( +
+ No console messages +
+ ) : ( + consoleMessages.map((msg) => ( +
+
+
{getLevelIcon(msg.level)} {msg.message}
+ +
+
+ )) + )} +
+
+
+
+ ); +}; + return (
{hasBuiltProject ? (
- 0} - canGoForward={historyIndex < navigationHistory.length - 1} - /> +
+ 0} + canGoForward={historyIndex < navigationHistory.length - 1} + extraContent={} + /> +