Architecture Overview
The service worker acts as a programmable network proxy that intercepts all HTTP requests from the editor and handles them locally.How It Works
- Registration: Service worker registers on first load
- Interception: All fetch requests are intercepted
- Local Processing: Requests are handled using local storage
- Response: Results returned without touching the network
Request Routing
Opal uses Hono, a lightweight web framework, to route requests within the service worker:Request Types
The service worker handles several categories of requests:File Serving
Serves workspace files directly from IndexedDB/OPFS
Image Processing
Automatic WebP conversion and caching
Markdown Rendering
Server-side markdown to HTML conversion
Search Operations
Full-text and filename search across workspace
Key Features
1. Offline File Serving
Serve files from local storage as if they came from a server:- Resolves the workspace name from the URL
- Loads the workspace from local storage
- Reads the file from the disk
- Returns it as an HTTP response
2. Markdown Rendering
Render markdown to HTML without a backend:- Syntax highlighting for code blocks
- GitHub-flavored markdown
- Table of contents generation
- Image URL resolution
- Link transformations
3. Image Optimization
Automatic image format conversion and caching:4. Workspace Search
Full-text search across all workspace files:- Full-text content search
- Filename search with fuzzy matching
- Regular expression support
- Streaming results for large workspaces
- Case-insensitive matching
5. ZIP Export
Export entire workspace as a ZIP file:Request Signaling
Service workers can’t directly communicate with the main thread, so Opal uses a request signaling system:- Long-running operations (search, export)
- Progress reporting
- Cancellation support
- Bidirectional communication
Service Worker Lifecycle
Installation
Activation
Fetch Handling
Performance Optimization
Caching Strategy
Opal uses multiple cache levels:Streaming Responses
Large files are streamed to avoid memory issues:Background Sync
Service workers enable background synchronization:Debugging
DevTools Integration
View service worker activity in Chrome DevTools:- Open DevTools → Application → Service Workers
- Check “Update on reload” during development
- Use “Unregister” to clear the service worker
Logging
Opal includes comprehensive service worker logging:- Request routing
- File operations
- Performance metrics
- Error details
Browser Compatibility
Service workers require:
- HTTPS (or localhost for development)
- Modern browser (Chrome 40+, Firefox 44+, Safari 11.1+, Edge 17+)
Best Practices
Update strategy
Update strategy
Always call
skipWaiting() and clients.claim() to ensure users get the latest version:Bypass for navigation
Bypass for navigation
Error handling
Error handling
Always provide fallbacks for failed operations: