diff --git a/src/App.tsx b/src/App.tsx index eaff61b9..a439f73b 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -78,7 +78,7 @@ const defaultConfig: AppConfig = { gitProxyOrigins: ["https://github.com", "https://gitlab.com"], faviconUrl: "https://favicon.shakespeare.diy/?url={href}", ngitWebUrl: "https://nostrhub.io/{naddr}", - previewDomain: "local-shakespeare.dev", + previewDomain: "iframe.diy", showcaseEnabled: true, showcaseCurator: "naddr1qvzqqqr4xqpzq7q6z5ns2hm5c8msyv83qwzxpxe52j8c4d4q5m92wsp9sflelkh9qqjrvdrxxajnqvny95mkyc33956xvwfk94sn2vek94sn2et9ve3kycfexfnryvty32j", fsPathProjects: "/projects", diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index e085690c..7228702e 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -25,6 +25,7 @@ import { Terminal as TerminalComponent } from '@/components/Terminal'; import { useSearchParams } from 'react-router-dom'; import { useAppContext } from '@/hooks/useAppContext'; import { isMediaFile } from '@/lib/fileUtils'; +import { getPreviewInjectedScript } from '@/lib/previewInjectedScript'; interface PreviewPaneProps { projectId: string; @@ -248,6 +249,18 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable } }, [historyIndex, navigationHistory]); + const sendNotification = useCallback((method: string, params?: Record) => { + if (iframeRef.current?.contentWindow) { + const message = { + jsonrpc: '2.0' as const, + method, + params: params || {}, + }; + const targetOrigin = `https://${projectId}.${previewDomain}`; + iframeRef.current.contentWindow.postMessage(message, targetOrigin); + } + }, [projectId, previewDomain]); + const sendNavigationCommand = useCallback((method: string, params?: Record) => { if (iframeRef.current?.contentWindow) { const message = { @@ -275,6 +288,18 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable setIsFullscreen(prev => !prev); }, []); + /** Virtual path where the injected preview script is served. */ + const INJECTED_SCRIPT_PATH = '/__injected__/preview.js'; + + /** Inject a script tag into an HTML string using DOMParser. */ + const injectScript = useCallback((html: string): string => { + const doc = new DOMParser().parseFromString(html, 'text/html'); + const tag = doc.createElement('script'); + tag.src = INJECTED_SCRIPT_PATH; + doc.head.insertBefore(tag, doc.head.firstChild); + return '\n' + doc.documentElement.outerHTML; + }, []); + const handleFetch = useCallback(async (request: JSONRPCRequest) => { const { params, id } = request; const { request: fetchRequest } = params; @@ -301,24 +326,52 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable const path = url.pathname; const filePath = path; + // Serve the injected preview script at its virtual path + if (path === INJECTED_SCRIPT_PATH) { + sendResponse({ + jsonrpc: '2.0', + result: { + status: 200, + statusText: 'OK', + headers: { + 'Content-Type': 'application/javascript', + 'Cache-Control': 'no-cache', + }, + body: encodeBase64(new TextEncoder().encode(getPreviewInjectedScript())), + }, + id + }); + return; + } + // Skip SPA fallback for static assets (files with extensions) const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path); // SPA routing: try to serve the exact file first try { const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath); + const contentType = getContentType(filePath); console.log(`Serving file: ${filePath}`); + // Inject preview script into HTML responses + let body: string; + if (contentType === 'text/html') { + const html = new TextDecoder().decode(bytes); + body = encodeBase64(new TextEncoder().encode(injectScript(html))); + } else { + body = encodeBase64(bytes); + } + sendResponse({ jsonrpc: '2.0', result: { status: 200, statusText: 'OK', headers: { - 'Content-Type': getContentType(filePath), + 'Content-Type': contentType, 'Cache-Control': 'no-cache', }, - body: encodeBase64(bytes), + body, }, id }); @@ -349,6 +402,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html'); console.log(`Serving index.html fallback for: ${path}`); + // Inject preview script into SPA fallback HTML + const html = new TextDecoder().decode(bytes); + const body = encodeBase64(new TextEncoder().encode(injectScript(html))); + sendResponse({ jsonrpc: '2.0', result: { @@ -358,7 +415,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable 'Content-Type': 'text/html', 'Cache-Control': 'no-cache', }, - body: encodeBase64(bytes), + body, }, id }); @@ -389,7 +446,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable id }); } - }, [projectId, projectsManager, sendResponse, sendError, previewDomain]); + }, [projectId, projectsManager, sendResponse, sendError, previewDomain, injectScript]); // Setup messaging protocol for iframe communication useEffect(() => { @@ -397,24 +454,30 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable // Verify origin for security const expectedOrigin = `https://${projectId}.${previewDomain}`; if (event.origin !== expectedOrigin) { - console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`); return; } const message = event.data; - console.log('Received message from iframe:', message); - if (message.jsonrpc === '2.0' && message.method === 'fetch') { + if (!message || typeof message !== 'object' || message.jsonrpc !== '2.0') return; + + // Handle iframe.diy handshake: respond to "ready" with "init" + if (message.method === 'ready') { + sendNotification('init', { version: 1 }); + return; + } + + if (message.method === 'fetch') { handleFetch(message); - } else if (message.jsonrpc === '2.0' && message.method === 'console') { + } else if (message.method === 'console') { handleConsoleMessage(message); - } else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') { + } else if (message.method === 'updateNavigationState') { handleUpdateNavigationState(message); } }; window.addEventListener('message', handleMessage); return () => window.removeEventListener('message', handleMessage); - }, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]); + }, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, sendNotification, projectId, previewDomain]); useEffect(() => { if (selectedFile) { @@ -650,7 +713,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable src={`https://${projectId}.${previewDomain}/`} className="w-full h-full border-0" title="Project Preview" - sandbox="allow-scripts allow-same-origin allow-forms" /> ) : ( diff --git a/src/contexts/AppContext.ts b/src/contexts/AppContext.ts index 8b4b9cf0..f1e48e35 100644 --- a/src/contexts/AppContext.ts +++ b/src/contexts/AppContext.ts @@ -44,7 +44,7 @@ export interface AppConfig { faviconUrl: string; /** Nostr Git web URL template (e.g., "https://nostrhub.io/{naddr}") */ ngitWebUrl: string; - /** Preview domain for iframe sandboxing (e.g., "local-shakespeare.dev") */ + /** Preview domain for iframe sandboxing (e.g., "iframe.diy") */ previewDomain: string; /** Selected language */ language?: string; diff --git a/src/hooks/useGenerateProjectInfo.test.ts b/src/hooks/useGenerateProjectInfo.test.ts index b114ef99..3baccdde 100644 --- a/src/hooks/useGenerateProjectInfo.test.ts +++ b/src/hooks/useGenerateProjectInfo.test.ts @@ -66,7 +66,7 @@ describe('useGenerateProjectInfo', () => { gitProxyOrigins: ['https://github.com', 'https://gitlab.com'], faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico', ngitWebUrl: 'https://nostrhub.io/{naddr}', - previewDomain: 'local-shakespeare.dev', + previewDomain: 'iframe.diy', showcaseEnabled: true, showcaseCurator: '', graspMetadata: { @@ -230,7 +230,7 @@ describe('useGenerateProjectInfo', () => { gitProxyOrigins: ['https://github.com', 'https://gitlab.com'], faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico', ngitWebUrl: 'https://nostrhub.io/{naddr}', - previewDomain: 'local-shakespeare.dev', + previewDomain: 'iframe.diy', showcaseEnabled: true, showcaseCurator: '', graspMetadata: { diff --git a/src/lib/SessionManager.test.ts b/src/lib/SessionManager.test.ts index 494a8af2..bd87040e 100644 --- a/src/lib/SessionManager.test.ts +++ b/src/lib/SessionManager.test.ts @@ -46,7 +46,7 @@ const testConfig: AppConfig = { gitProxyOrigins: ['https://github.com', 'https://gitlab.com'], faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico', ngitWebUrl: 'https://nostrhub.io/{naddr}', - previewDomain: 'local-shakespeare.dev', + previewDomain: 'iframe.diy', language: 'en', showcaseEnabled: true, showcaseCurator: '', diff --git a/src/lib/previewInjectedScript.ts b/src/lib/previewInjectedScript.ts new file mode 100644 index 00000000..f39ef982 --- /dev/null +++ b/src/lib/previewInjectedScript.ts @@ -0,0 +1,297 @@ +/** + * Script injected into preview iframe HTML responses. + * + * When using iframe.diy as the preview domain, the outer frame handles + * service worker registration and document loading. However, Shakespeare + * needs additional capabilities inside the rendered app: + * + * 1. Console interception - forward console.log/warn/error/info/debug to parent + * 2. Navigation handling - track SPA navigation and handle navigate/refresh commands + * 3. Global error handlers - capture uncaught errors and unhandled rejections + * + * This script is injected into of HTML responses served by the fetch handler. + * It communicates with the parent via window.parent.postMessage using JSON-RPC 2.0. + * + * Note: In iframe.diy's architecture, the "parent" of the inner iframe is the + * outer frame, which transparently relays non-runtime JSON-RPC messages to the + * actual parent (Shakespeare). So posting to window.parent works correctly. + */ + +/** + * Returns the injectable script as a string. + * This runs inside the inner iframe of iframe.diy. + */ +export function getPreviewInjectedScript(): string { + return `(function() { + 'use strict'; + + // ========================================================================= + // Path normalization + // + // iframe.diy loads the inner iframe at /index.html. Normalize this to / + // before any SPA router initializes, so React Router etc. see the correct + // path. + // ========================================================================= + + if (window.location.pathname === '/index.html') { + history.replaceState(null, '', '/'); + } + + // ========================================================================= + // JSON-RPC ID generator + // + // iframe.diy's outer frame only relays JSON-RPC *requests* (messages with + // an "id" field) between inner iframe and parent. Notifications (no "id") + // are silently dropped. So all messages to the parent must include an id. + // ========================================================================= + + function rpcId() { + return crypto.randomUUID(); + } + + // ========================================================================= + // Console Interceptor + // ========================================================================= + + var originalConsole = {}; + var consoleMethods = ['log', 'warn', 'error', 'info', 'debug']; + + consoleMethods.forEach(function(method) { + if (typeof console[method] === 'function') { + originalConsole[method] = console[method]; + + console[method] = function() { + var args = Array.prototype.slice.call(arguments); + + // Call original method + try { + originalConsole[method].apply(console, args); + } catch (e) { + // Continue if original fails + } + + // Serialize arguments + var message = args.map(function(arg) { + if (arg === undefined) return 'undefined'; + if (arg === null) return 'null'; + if (typeof arg === 'object') { + try { + return JSON.stringify(arg, function(key, value) { + if (value instanceof Error) { + return { + name: value.name, + message: value.message, + stack: value.stack + }; + } + return value; + }); + } catch (e) { + return String(arg); + } + } + return String(arg); + }).join(' '); + + // Send to parent (must include id for iframe.diy relay) + try { + window.parent.postMessage({ + jsonrpc: '2.0', + id: rpcId(), + method: 'console', + params: { level: method, message: message } + }, '*'); + } catch (e) { + // Ignore postMessage errors + } + }; + } + }); + + // ========================================================================= + // Navigation Handler + // ========================================================================= + + var currentSemanticPath = '/'; + + // Try to restore initial path from sessionStorage (after refresh) + try { + var storedPath = sessionStorage.getItem('iframe_initial_path'); + if (storedPath) { + currentSemanticPath = storedPath; + sessionStorage.removeItem('iframe_initial_path'); + } + } catch (e) { + // Ignore sessionStorage errors + } + + function extractSemanticPath(urlOrString) { + try { + var url = typeof urlOrString === 'string' + ? new URL(urlOrString, window.location.origin) + : urlOrString; + return url.pathname + url.search + url.hash; + } catch (e) { + return window.location.pathname + window.location.search + window.location.hash; + } + } + + function updateNavigationState() { + var semanticPath = currentSemanticPath || extractSemanticPath(window.location); + + try { + window.parent.postMessage({ + jsonrpc: '2.0', + id: ++rpcId, + method: 'updateNavigationState', + params: { + currentUrl: semanticPath, + canGoBack: false, + canGoForward: false + } + }, '*'); + } catch (e) { + // Ignore postMessage errors + } + } + + function handleNavigate(url) { + try { + var targetUrl = new URL(url, window.location.origin); + if (targetUrl.origin !== window.location.origin) { + return; + } + + var semanticPath = extractSemanticPath(targetUrl); + currentSemanticPath = semanticPath; + updateNavigationState(); + + // Use the original pushState to trigger SPA navigation + originalPushState.call(window.history, {}, '', semanticPath); + window.dispatchEvent(new PopStateEvent('popstate', { state: {} })); + } catch (e) { + // Ignore invalid URLs + } + } + + function handleRefresh() { + var path = currentSemanticPath || '/'; + try { + sessionStorage.setItem('iframe_initial_path', path); + } catch (e) { + // Ignore sessionStorage errors + } + window.location.reload(); + } + + // Listen for commands from parent (navigate, refresh) + window.addEventListener('message', function(event) { + // Only accept messages from parent window + if (event.source !== window.parent) return; + + var message = event.data; + if (message && message.jsonrpc === '2.0') { + switch (message.method) { + case 'navigate': + handleNavigate(message.params.url); + break; + case 'refresh': + handleRefresh(); + break; + } + } + }); + + // Listen for popstate events (back/forward navigation) + window.addEventListener('popstate', function() { + currentSemanticPath = extractSemanticPath(window.location); + updateNavigationState(); + }); + + // Listen for hash changes + window.addEventListener('hashchange', function() { + currentSemanticPath = extractSemanticPath(window.location); + updateNavigationState(); + }); + + // Override history.pushState and history.replaceState to detect SPA navigation + var originalPushState = window.history.pushState; + var originalReplaceState = window.history.replaceState; + + window.history.pushState = function() { + var result = originalPushState.apply(window.history, arguments); + var semanticPath = arguments[2] + ? extractSemanticPath(arguments[2]) + : extractSemanticPath(window.location); + currentSemanticPath = semanticPath; + updateNavigationState(); + return result; + }; + + window.history.replaceState = function() { + var result = originalReplaceState.apply(window.history, arguments); + var semanticPath = arguments[2] + ? extractSemanticPath(arguments[2]) + : extractSemanticPath(window.location); + currentSemanticPath = semanticPath; + updateNavigationState(); + return result; + }; + + // Send initial navigation state + updateNavigationState(); + + // After a short delay, navigate to initial path if needed (for refresh support) + if (currentSemanticPath && currentSemanticPath !== '/') { + setTimeout(function() { + var current = window.location.pathname + window.location.search + window.location.hash; + if (current !== currentSemanticPath) { + handleNavigate(currentSemanticPath); + } + }, 150); + } + + // ========================================================================= + // Global Error Handlers + // ========================================================================= + + window.addEventListener('error', function(event) { + try { + window.parent.postMessage({ + jsonrpc: '2.0', + id: ++rpcId, + method: 'console', + params: { + level: 'error', + message: 'Uncaught Error: ' + event.message, + source: event.filename, + lineno: event.lineno, + colno: event.colno, + stack: event.error ? event.error.stack : undefined + } + }, '*'); + } catch (e) { + // Ignore postMessage errors + } + }); + + window.addEventListener('unhandledrejection', function(event) { + try { + window.parent.postMessage({ + jsonrpc: '2.0', + id: ++rpcId, + method: 'console', + params: { + level: 'error', + message: 'Unhandled Promise Rejection: ' + (event.reason ? (event.reason.message || String(event.reason)) : 'Unknown'), + reason: event.reason, + promise: event.promise ? 'Promise object' : 'No promise object' + } + }, '*'); + } catch (e) { + // Ignore postMessage errors + } + }); + +})();`; +} diff --git a/src/lib/system.test.ts b/src/lib/system.test.ts index a4251818..62084a27 100644 --- a/src/lib/system.test.ts +++ b/src/lib/system.test.ts @@ -33,7 +33,7 @@ const testConfig: AppConfig = { gitProxyOrigins: ['https://github.com', 'https://gitlab.com'], faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico', ngitWebUrl: 'https://nostrhub.io/{naddr}', - previewDomain: 'local-shakespeare.dev', + previewDomain: 'iframe.diy', language: 'en', showcaseEnabled: true, showcaseCurator: '', diff --git a/src/pages/SystemSettings.tsx b/src/pages/SystemSettings.tsx index 023aa5db..fdee6d08 100644 --- a/src/pages/SystemSettings.tsx +++ b/src/pages/SystemSettings.tsx @@ -602,7 +602,7 @@ export function SystemSettings() { { const value = e.target.value; diff --git a/src/test/TestApp.tsx b/src/test/TestApp.tsx index 2b6f36a5..67403c20 100644 --- a/src/test/TestApp.tsx +++ b/src/test/TestApp.tsx @@ -47,7 +47,7 @@ export function TestApp({ children }: TestAppProps) { gitProxyOrigins: ['https://github.com', 'https://gitlab.com'], faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico', ngitWebUrl: 'https://nostrhub.io/{naddr}', - previewDomain: 'local-shakespeare.dev', + previewDomain: 'iframe.diy', language: 'en', showcaseEnabled: true, showcaseCurator: '',