-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime-sw.js
More file actions
63 lines (54 loc) · 1.76 KB
/
Copy pathruntime-sw.js
File metadata and controls
63 lines (54 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* runtime-sw.js
* The ZeroCMS Proxy Service Worker.
* Intercepts /preview/* requests and routes them to the WASM Runtime.
*/
const BYPASS_HEADER = 'x-zerocms-bypass';
self.addEventListener('install', event => {
self.skipWaiting();
});
self.addEventListener('activate', event => {
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', event => {
const url = new URL(event.request.url);
// Only intercept requests for the /preview prefix
if (url.pathname.startsWith('/preview/')) {
event.respondWith(handleRuntimeRequest(event));
}
});
/**
* Forwards requests to the WasmBridge (in a Web Worker or Main Thread).
*/
async function handleRuntimeRequest(event) {
const clients = await self.clients.matchAll();
const mainClient = clients.find(c => c.type === 'window' || c.type === 'worker');
if (!mainClient) {
return fetch(event.request);
}
// Communicate with the WasmBridge to get the WASM-rendered response
return new Promise((resolve) => {
const channel = new MessageChannel();
channel.port1.onmessage = (msg) => {
if (msg.data.error) {
resolve(new Response(msg.data.error, { status: 500 }));
} else {
// Construct the response from the WASM engine output
const headers = new Headers(msg.data.headers || {});
if (!headers.has('Content-Type')) {
headers.set('Content-Type', 'text/html');
}
resolve(new Response(msg.data.body, {
status: msg.data.status || 200,
headers: headers
}));
}
};
mainClient.postMessage({
type: 'RUNTIME_REQUEST',
url: event.request.url,
method: event.request.method,
headers: Object.fromEntries(event.request.headers.entries())
}, [channel.port2]);
});
}