forked from sveltejs/kit
/
worker.js
73 lines (61 loc) · 1.97 KB
/
worker.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { Server } from 'SERVER';
import { manifest, prerendered } from 'MANIFEST';
import * as Cache from 'worktop/cfw.cache';
const server = new Server(manifest);
const app_path = `/${manifest.appPath}/`;
/** @type {import('worktop/cfw').Module.Worker<{ ASSETS: import('worktop/cfw.durable').Durable.Object }>} */
const worker = {
async fetch(req, env, context) {
await server.init({ env });
// skip cache if "cache-control: no-cache" in request
let pragma = req.headers.get('cache-control') || '';
let res = !pragma.includes('no-cache') && (await Cache.lookup(req));
if (res) return res;
let { pathname } = new URL(req.url);
// static assets
if (pathname.startsWith(app_path)) {
res = await env.ASSETS.fetch(req);
if (!res.ok) return res;
const cache_control = pathname.startsWith(app_path + 'immutable/')
? 'public, immutable, max-age=31536000'
: 'no-cache';
res = new Response(res.body, {
headers: {
// include original headers, minus cache-control which
// is overridden, and etag which is no longer useful
'cache-control': cache_control,
'content-type': res.headers.get('content-type'),
'x-robots-tag': 'noindex'
}
});
} else {
// prerendered pages and index.html files
pathname = 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)
) {
res = await env.ASSETS.fetch(req);
} else {
// dynamically-generated pages
res = await server.respond(req, {
platform: { env, context, caches },
getClientAddress() {
return req.headers.get('cf-connecting-ip');
}
});
}
}
// Writes to Cache only if allowed & specified
pragma = res.headers.get('cache-control');
return pragma && res.ok ? Cache.save(req, res, context) : res;
}
};
export default worker;