-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
entry.js
57 lines (47 loc) · 1.31 KB
/
entry.js
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
import { Server } from 'SERVER';
import { manifest, prerendered } from 'MANIFEST';
import { getAssetFromKV } from '@cloudflare/kv-asset-handler';
const server = new Server(manifest);
const prefix = `/${manifest.appDir}/`;
addEventListener('fetch', (/** @type {FetchEvent} */ event) => {
event.respondWith(handle(event));
});
/**
* @param {FetchEvent} event
* @returns {Promise<Response>}
*/
async function handle(event) {
const { request } = event;
const url = new URL(request.url);
// generated assets
if (url.pathname.startsWith(prefix)) {
const res = await getAssetFromKV(event);
return new Response(res.body, {
headers: {
'cache-control': 'public, immutable, max-age=31536000',
'content-type': res.headers.get('content-type')
}
});
}
// prerendered pages and index.html files
const pathname = url.pathname.replace(/\/$/, '');
let file = pathname.substring(1);
try {
file = decodeURIComponent(file);
} catch (err) {
// ignore
}
if (
manifest.assets.has(file) ||
manifest.assets.has(file + '/index.html') ||
prerendered.has(pathname || '/')
) {
return await getAssetFromKV(event);
}
// dynamically-generated pages
try {
return await server.respond(request);
} catch (e) {
return new Response('Error rendering route:' + (e.message || e.toString()), { status: 500 });
}
}