From 5011ddb1bd21c335feff93ee6aedeace95acfa55 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 20 Jul 2025 13:15:33 -0500 Subject: [PATCH] Add iframe-fetch-client code --- iframe-fetch-client/MESSAGING_PROTOCOL.md | 295 ++++++++++++++++++++ iframe-fetch-client/README.md | 323 ++++++++++++++++++++++ iframe-fetch-client/_iframe-client.css | 39 +++ iframe-fetch-client/_iframe-client.js | 260 +++++++++++++++++ iframe-fetch-client/index.html | 17 ++ iframe-fetch-client/sw.js | 151 ++++++++++ 6 files changed, 1085 insertions(+) create mode 100644 iframe-fetch-client/MESSAGING_PROTOCOL.md create mode 100644 iframe-fetch-client/README.md create mode 100644 iframe-fetch-client/_iframe-client.css create mode 100644 iframe-fetch-client/_iframe-client.js create mode 100644 iframe-fetch-client/index.html create mode 100644 iframe-fetch-client/sw.js diff --git a/iframe-fetch-client/MESSAGING_PROTOCOL.md b/iframe-fetch-client/MESSAGING_PROTOCOL.md new file mode 100644 index 00000000..1be19ab2 --- /dev/null +++ b/iframe-fetch-client/MESSAGING_PROTOCOL.md @@ -0,0 +1,295 @@ +# iframe Fetch Client Messaging Protocol (JSON-RPC) + +This document describes the simplified JSON-RPC based communication protocol +between the parent page and the iframe fetch client. + +## Overview + +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. The only required method is +`fetch` for handling HTTP requests. + +## Architecture + +``` +┌─────────────────┐ JSON-RPC over ┌──────────────────────┐ +│ Parent Page │ postMessage │ Main Thread │ +│ │ ←─────────────────→ │ (relay only) │ +│ - Request │ │ │ +│ handling │ │ ↕ │ +└─────────────────┘ │ JSON-RPC over │ + │ postMessage │ + │ │ + │ ┌──────────────────┐ │ + │ │ ServiceWorker │ │ + │ │ │ │ + │ │ - Makes JSON-RPC │ │ + │ │ calls directly │ │ + │ │ - Handles │ │ + │ │ requests │ │ + │ └──────────────────┘ │ + └──────────────────────┘ +``` + +## JSON-RPC Structure + +All messages follow JSON-RPC 2.0 specification: + +```javascript +// GET Request +{ + "jsonrpc": "2.0", + "method": "fetch", + "params": { + "request": { + "url": "https://app123.example.com/assets/main.js", + "method": "GET", + "headers": { + "Accept": "application/javascript" + }, + "body": null + } + }, + "id": 123 +} + +// Success Response +{ + "jsonrpc": "2.0", + "result": { + "status": 200, + "statusText": "OK", + "headers": { + "Content-Type": "application/javascript", + "Cache-Control": "no-cache" + }, + "body": "console.log('hello');" + }, + "id": 123 +} + +// Error Response (still uses JSON-RPC error format for protocol errors) +{ + "jsonrpc": "2.0", + "error": { + "code": -32001, + "message": "Invalid request format", + "data": { "url": "/assets/main.js" } + }, + "id": 123 +} +``` + +## Methods + +### `fetch` + +**Purpose:** Handle HTTP requests, including GET, POST, PUT, DELETE, etc. with +full request body support + +**Parameters:** + +- `request` (object): Serialized fetch request + - `url` (string): Full URL of the request + - `method` (string): HTTP method (GET, POST, etc.) + - `headers` (object): Request headers as key-value pairs + - `body` (string|null): Request body as string, or null if no body + +**Result:** + +- `status` (number): HTTP status code (200, 404, etc.) +- `statusText` (string): HTTP status text ("OK", "Not Found", etc.) +- `headers` (object): Response headers as key-value pairs +- `body` (string|null): Response body content (null if status is 204) + +**Error Codes:** + +- `-32001`: Invalid request format +- `-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 are serialized as strings, so binary data should be +base64-encoded. + +## Implementation + +### Parent Page + +In this example, the parent page acts as a static file server. + +```javascript +class FetchClientParent { + constructor(files) { + this.files = files; // Map of path -> {content, contentType} + this.setupMessageListener(); + } + + setupMessageListener() { + window.addEventListener("message", (event) => { + // Verify origin for security + if (event.origin !== "https://app123.example.com") return; + + const message = event.data; + if (message.jsonrpc === "2.0" && message.method === "fetch") { + this.handleFetch(message); + } + }); + } + + handleFetch(request) { + const { params, id } = request; + const { request: fetchRequest } = params; + + // Extract path from URL + const url = new URL(fetchRequest.url); + const path = url.pathname; + + 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: file.content, + }, + }); + } 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: `File not found: ${path}`, + }, + }); + } + } + + 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"); + } +} +``` + +### Preview Page + +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. + +```javascript +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) { + this.handleResponse(message); + } + }); + } + + async fetch(request) { + const id = ++this.requestId; + + return new Promise((resolve, reject) => { + this.pendingRequests.set(id, { resolve, reject }); + + // Send 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)); + } else { + // Result is a serialized response + pending.resolve(result); + } + } +} +``` + +## Security + +- **Origin Validation:** Always verify message origin +- **Path Validation:** Validate file paths to prevent directory traversal +- **Timeout:** Requests timeout after 10 seconds +- **Error Handling:** Proper JSON-RPC error responses + +## Example Usage + +```html + + + +``` diff --git a/iframe-fetch-client/README.md b/iframe-fetch-client/README.md new file mode 100644 index 00000000..54fe5c5c --- /dev/null +++ b/iframe-fetch-client/README.md @@ -0,0 +1,323 @@ +# iframe Fetch Client + +An iframe preview system for **Single Page Applications (SPAs)**. + +## Why? + +We want to display a preview of a project built with Vite, Webpack, etc in an +iframe, but the SPA uses root-relative paths (like `/assets/main.js`). This +means we can't just load it directly from a file system or a local server +without deploying it to a web server. + +To work around this, we can instead deploy this "iframe Fetch Client" to a +subdomain, embed it in an iframe, and then respond to its `postMessage` requests +from the parent to serve it the files it needs. + +This "iframe Fetch Client" is entirely static files, and only needs to be +deployed once. As long as the parent page implements its JSON-RPC protocol, it +can serve any web application. + +## Architecture + +``` +┌─────────────────┐ JSON-RPC over ┌──────────────────────┐ +│ Parent Page │ postMessage │ iframe Client │ +│ (example.com) │ ←─────────────────→ │ (*.example.com) │ +│ │ fetch() │ │ +│ - Request │ │ ┌──────────────────┐ │ +│ handling │ │ │ Main Thread │ │ +└─────────────────┘ │ │ (relay only) │ │ + │ │ ↕ │ │ + │ │ JSON-RPC over │ │ + │ │ postMessage │ │ + │ │ ↕ │ │ + │ │ ┌──────────────┐ │ │ + │ │ │ServiceWorker │ │ │ + │ │ │ │ │ │ + │ │ │- Makes │ │ │ + │ │ │ JSON-RPC │ │ │ + │ │ │ calls │ │ │ + │ │ │- Handles │ │ │ + │ │ │ requests │ │ │ + │ │ └──────────────┘ │ │ + │ └──────────────────┘ │ + └──────────────────────┘ +``` + +## Limitations + +This system uses a ServiceWorker to serve requests, which means the preview site +cannot itself register a ServiceWorker. If it tries, the attempt will be +blocked. + +## Files Structure + +``` +/ +├── 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 +``` + +## Simplified JSON-RPC Protocol + +The system now uses a drastically simplified JSON-RPC 2.0 protocol with only one +method: + +- **`fetch(request)`** - Handle HTTP requests with serialized fetch + request/response + +**Request:** + +```javascript +{ + "jsonrpc": "2.0", + "method": "fetch", + "params": { + "request": { + "url": "https://app123.example.com/assets/main.js", + "method": "GET", + "headers": {}, + "body": null + } + }, + "id": 123 +} +``` + +**Response:** + +```javascript +{ + "jsonrpc": "2.0", + "result": { + "status": 200, + "statusText": "OK", + "headers": { + "Content-Type": "application/javascript" + }, + "body": "console.log('hello');" + }, + "id": 123 +} +``` + +## How It Works + +1. **Initialization:** + - iframe client loads at `app123.example.com` + - Registers ServiceWorker at `/sw.js` with scope `/` + - Blocks future ServiceWorker registrations + - Main thread sets up relay between ServiceWorker and parent + +2. **Request Handling:** + - ServiceWorker intercepts all requests (except iframe client system files) + - ServiceWorker makes JSON-RPC `fetch()` calls directly with serialized + requests + - Main thread relays JSON-RPC messages between ServiceWorker and parent + - Parent responds with serialized HTTP responses + - ServiceWorker creates Response objects and returns them to the client app + +3. **Content Replacement:** + - Main thread requests `/` from parent via JSON-RPC fetch + - Replaces its own content with the site index + - Site runs normally, with all requests handled by SW via JSON-RPC + +## Deployment + +### iframe Client Domain (`*.example.com`) + +Deploy these files to your iframe client subdomain: + +``` +https://*.example.com/ +├── index.html +├── _iframe-client.js +├── _iframe-client.css +└── sw.js +``` + +**Security Note:** It is recommended to serve the client on a wildcard subdomain +(like `*.example.com`) if you wish to support multiple projects. That way +projects won't share the same localStorage and IndexedDB. + +### Parent Page Integration + +Include the iframe client in your parent page: + +```html + +``` + +Implement the JSON-RPC protocol (see `example-parent.html` for a complete +example): + +```javascript +class FetchClientParent { + constructor(files) { + this.files = files; // Map of path -> {content, contentType} + this.setupMessageListener(); + } + + setupMessageListener() { + window.addEventListener("message", (event) => { + if (event.origin !== "https://example.com") return; + + const message = event.data; + if (message.jsonrpc === "2.0" && message.method === "fetch") { + this.handleFetch(message); + } + }); + } + + handleFetch(request) { + const { params, id } = request; + const { request: fetchRequest } = params; + + // Extract path from URL + const url = new URL(fetchRequest.url); + const path = url.pathname; + 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: file.content, + }, + }); + } else { + // Return 404 response + this.sendResponse({ + id, + jsonrpc: "2.0", + result: { + status: 404, + statusText: "Not Found", + headers: { + "Content-Type": "text/plain", + }, + body: `File not found: ${path}`, + }, + }); + } + } + + sendResponse(message) { + const iframe = document.getElementById("preview-iframe"); + iframe.contentWindow.postMessage(message, "https://app123.example.com"); + } +} +``` + +## Request Handling + +Handle requests by providing responses as a Map or object for static files, or +implement custom logic for dynamic requests: + +```javascript +const staticFiles = new Map([ + ["/", { + content: "...", + contentType: "text/html", + }], + ["/assets/main.js", { + content: 'console.log("app");', + contentType: "application/javascript", + }], + ["/assets/style.css", { + content: "body { margin: 0; }", + contentType: "text/css", + }], +]); + +// Or handle dynamic requests like APIs +function handleRequest(fetchRequest) { + const url = new URL(fetchRequest.url); + + if (url.pathname.startsWith("/api/")) { + // Handle API requests + return handleAPIRequest(fetchRequest); + } else { + // Serve static files + return serveStaticFile(url.pathname); + } +} +``` + +## Security Features + +- **Origin Validation:** Messages are validated by origin +- **Sandboxed Iframe:** Client runs in a sandboxed environment +- **Isolated ServiceWorker:** SW only affects the iframe client domain +- **No Direct Access:** Parent controls all request handling + +## 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 +4. Test navigation and functionality within the iframe client + +## Browser Support + +- **ServiceWorker:** Required (supported in all modern browsers) +- **postMessage:** Required (universal support) +- **iframe sandbox:** Recommended (modern browsers) + +## Limitations + +- Request/response bodies must be JSON-serializable strings (no binary support) +- All requests go through the parent page (potential performance impact) +- Requires HTTPS for ServiceWorker (except localhost) +- Limited to same-origin communication patterns within the iframe + +## Troubleshooting + +### iframe client doesn't load + +- Check browser console for ServiceWorker errors +- Verify HTTPS is used (required for ServiceWorker) +- Ensure parent page implements the messaging protocol + +### Requests fail + +- Check that request paths match your handling logic (case-sensitive) +- Verify parent page is responding to JSON-RPC `fetch` requests +- Check browser network tab for failed requests + +### Communication issues + +- Verify iframe src points to correct preview domain +- Check that JSON-RPC messages are properly formatted +- Ensure iframe has appropriate sandbox permissions + +## Development + +To modify the system: + +1. **iframe Client:** Edit `index.html`, `_iframe-client.js`, + `_iframe-client.css`, `sw.js` +2. **Protocol:** Update `MESSAGING_PROTOCOL.md` for any changes +3. **Testing:** Use `example-parent.html` for testing changes + +## License + +This system is designed for development and testing purposes. Ensure appropriate +security measures for production use. diff --git a/iframe-fetch-client/_iframe-client.css b/iframe-fetch-client/_iframe-client.css new file mode 100644 index 00000000..4b336c5b --- /dev/null +++ b/iframe-fetch-client/_iframe-client.css @@ -0,0 +1,39 @@ +body { + margin: 0; + padding: 20px; + font-family: system-ui, -apple-system, sans-serif; + background: #f5f5f5; +} + +.loading { + text-align: center; + padding: 50px; +} + +.spinner { + border: 4px solid #f3f3f3; + border-top: 4px solid #3498db; + border-radius: 50%; + width: 40px; + height: 40px; + animation: spin 2s linear infinite; + margin: 0 auto 20px; +} + +@keyframes spin { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } +} + +.error { + color: #e74c3c; + background: #fdf2f2; + border: 1px solid #fecaca; + border-radius: 4px; + padding: 15px; + margin: 20px 0; +} diff --git a/iframe-fetch-client/_iframe-client.js b/iframe-fetch-client/_iframe-client.js new file mode 100644 index 00000000..05d1505c --- /dev/null +++ b/iframe-fetch-client/_iframe-client.js @@ -0,0 +1,260 @@ +/** + * 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); + + // Replace current document with the site index content + this.replaceDocument(response.body); + } 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/index.html b/iframe-fetch-client/index.html new file mode 100644 index 00000000..5cf6d8ae --- /dev/null +++ b/iframe-fetch-client/index.html @@ -0,0 +1,17 @@ + + + + + + iframe Fetch Client + + + +
+
+

Loading iframe fetch client...

+

Waiting for ServiceWorker and parent communication

+
+ + + diff --git a/iframe-fetch-client/sw.js b/iframe-fetch-client/sw.js new file mode 100644 index 00000000..6ac58e47 --- /dev/null +++ b/iframe-fetch-client/sw.js @@ -0,0 +1,151 @@ +/** + * iframe Fetch Client ServiceWorker + * Intercepts requests and handles them via JSON-RPC communication + */ + +let pendingRequests = new Map(); +let requestIdCounter = 0; + +// Install event +self.addEventListener("install", (event) => { + console.log("ServiceWorker installing"); + self.skipWaiting(); +}); + +// Activate event +self.addEventListener("activate", (event) => { + console.log("ServiceWorker activating"); + event.waitUntil(self.clients.claim()); +}); + +// Message handling from main thread (JSON-RPC responses) +self.addEventListener("message", (event) => { + handleMainThreadMessage(event.data); +}); + +function handleMainThreadMessage(data) { + // Handle JSON-RPC responses relayed from main thread + if (data.jsonrpc === "2.0" && data.id !== undefined) { + handleJSONRPCResponse(data); + } +} + +function handleJSONRPCResponse(message) { + const { id, result, error } = message; + const pendingRequest = pendingRequests.get(id); + + if (!pendingRequest) { + console.warn("No pending request found for ID:", id); + return; + } + + pendingRequests.delete(id); + + if (error) { + pendingRequest.reject(new Error(`${error.message} (code: ${error.code})`)); + return; + } + + // Create response from serialized response + const { status, statusText, headers, body } = result; + const response = new Response(body, { + status: status || 200, + statusText: statusText || "OK", + headers: headers || {}, + }); + + pendingRequest.resolve(response); +} + +async function requestViaJSONRPC(request) { + return new Promise(async (resolve, reject) => { + const id = ++requestIdCounter; + + // Serialize the fetch request + let body = null; + if (request.body) { + try { + // Convert body to string (JSON-serializable) + body = await request.text(); + } catch (error) { + reject(new Error(`Failed to serialize request body: ${error.message}`)); + return; + } + } + + const serializedRequest = { + url: request.url, + method: request.method, + headers: Object.fromEntries(request.headers.entries()), + body: body, + }; + + pendingRequests.set(id, { resolve, reject, originalRequest: request }); + + // Send JSON-RPC request to main thread for relay to parent + self.clients.matchAll().then((clients) => { + if (clients.length > 0) { + clients[0].postMessage({ + jsonrpc: "2.0", + method: "fetch", + params: { request: serializedRequest }, + id, + }); + } else { + pendingRequests.delete(id); + reject(new Error("No clients available")); + } + }); + + // Timeout after 10 seconds + setTimeout(() => { + if (pendingRequests.has(id)) { + pendingRequests.delete(id); + reject(new Error(`Timeout requesting: ${request.url}`)); + } + }, 10000); + }); +} + +// Fetch event - intercept all requests +self.addEventListener("fetch", (event) => { + const url = new URL(event.request.url); + + // Ignore requests to other origins + if (url.origin !== location.origin) { + return; + } + + // Let iframe client system files be handled normally + if (url.pathname.startsWith("/_") || url.pathname === "/sw.js") { + return; + } + + // Let root path be handled normally (loads the iframe client page) + if (url.pathname === "/") { + return; + } + + // Handle all other requests through JSON-RPC communication + event.respondWith(handleRequest(event.request)); +}); + +async function handleRequest(request) { + try { + console.log("ServiceWorker handling request for:", request.url); + return await requestViaJSONRPC(request); + } catch (error) { + console.error("Failed to handle request:", request.url, error); + + // Return 404 for failed requests + return new Response(`Request failed: ${request.url}`, { + status: 404, + statusText: "Not Found", + headers: { + "Content-Type": "text/plain", + }, + }); + } +} + +console.log("ServiceWorker script loaded");