diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 14b7efa7..4cc9481a 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -11,6 +11,8 @@ stages: test: stage: test script: + - npm run typecheck + - npm run build - npm run test pages: 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 = ` -${message}
-${error.message || error}
-${error.stack || JSON.stringify(error, null, 2)}
- ${message}
+${error.message || error}
+${error.stack || JSON.stringify(error, null, 2)}
+ Loading preview...
Waiting for ServiceWorker and parent communication