summaryrefslogtreecommitdiff
path: root/src/content/sw.js
blob: 03a09e4735b22d2d71bf51941ea4b2484ac0ff3e (plain) (blame)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
const CACHE_NAME = "static-shared-assets";

const FALLBACK_PATHS = {
	img: "/fallback-image-FIXME.svg",
	data: {
		static: "/fallback-data-FIXME.json",
	},
};

const leafValues = tree =>
	Object.values(tree).map(x =>
		typeof x !== "object"
			? x
			: leafValues(x)
	);

const collectLeaves = tree =>
	leafValues(tree).flat(Infinity);

const DEFAULT_INSTALL_PATHS = [
	"/",
	"index.html",
	"style.css",
	"img/favicon.svg",
	// "papo.js",
// ].concat(collectLeaves(FALLBACK_PATHS));
];

const mkInstallHandler = ({ self, caches }) => event => {
	self.skipWaiting();
	event.waitUntil(
		caches.open(CACHE_NAME).then(
			cache => cache.addAll(DEFAULT_INSTALL_PATHS),
		),
	);
};

const store = async (caches, request, response) => {
	const cache = await caches.open(CACHE_NAME);
	await cache.put(request, response);
};

const getPrefixIn = (paths, segments) => {
	if (paths === undefined) {
		return null;
	}

	if (segments.length === 0) {
		return null;
	}

	if (typeof paths === "string") {
		return paths;
	}

	return getPrefixIn(paths[segments[0]], segments.slice(1));
};

const fromCache = async (caches, fetch, { request, preloadResponse }) => {
	const cachedResponse = await caches.match(request);
	if (cachedResponse) {
		fetch(request).then(async freshResponse =>
			store(caches, request, freshResponse));
		return cachedResponse;
	}

	const preloadedResponse = await preloadResponse;
	if (preloadedResponse) {
		store(caches, request, preloadeResponse.clone());
		return preloadedResponse;
	}

	try {
		const fetchedResponse = await fetch(request);
		store(caches, request, fetchedResponse.clone());
		return fetchedResponse;
	} catch (e) {
		const fallbackResponse = await maybeFallback(caches, request);
		if (fallbackResponse) {
			return fallbackResponse;
		}

		throw e;
	}
};

const maybeFallback = async (caches, request, paths = FALLBACK_PATHS) => {
	const url          = new URL(request.url)
	const segments     = url.pathname.split("/").filter(s => !!s)
	const fallbackPath = getPrefixIn(paths, segments);

	if (fallbackPath) {
		return await caches.match(fallbackPath);
	}
	return null;
}

const CONFIG_PATHS = {
	immutable: {
		"some": {
			"path": true,
		},
	},
	staleOK: {
	},
};
const PRIORITY_ORDERING = [
	"immutable",
	"staleFallback",
	"stale",
];

const pullThroughCache = (env, ctx) => {
};

/*
// FIXME: handle base paths
 const STRATEGIES = [
	{
		name: "immutable",
		routes: new Set([
			"/cas",
		]),
		fn: immutable,
	},
	{
		name: "staleFallback",
		routes: {
			"/img/icon/": "",
		},
		fn: staleFallback,
	},
	{
		name: "staleOnly",
		routes: new Set([
			// FIXME: add "/"
			"/index.html": true,
			"/style.css": true,
			"/papo.js": true,
		]),
	img: "/fallback-image-FIXME.svg",
	data: {
		static: "/fallback-data-FIXME.json",
	},
		fn: staleOnly,
	},
};
*/

const asSegments = pathname =>
	pathname.split("/").filter(s => !!s);

const requestSegments = ({ url }) =>
	asSegments(new URL(url).pathname);

/*
 const strategyFor = (segments, paths = CONFIG_PATHS) => {
	for (const strategy of PRIORITY_ORDERING) {
		if (getPrefixIn(paths[strategy.name], segments)) {
			return strategy;
		}
	}
};
*/

const networkOnly = async (_env, { fetch, event }) => {
	const preloaded = await event.preloadResponse;
	if (preloaded) {
		return preloaded;
	}

	return await fetch(event.request);
};

const strategyFor = (segments, paths = CONFIG_PATHS) => {
	return networkOnly;
};

// FIXME: noop if "Connection": "Upgrade" is in header
// if (event.request.headers.get("Connection").toLowerCase() == "upgrade");
// out([...event.request.headers.entries()]);
const mkFetchHandler = env => (event, mkfetch = () => fetch) => {
	if (event.request.method !== "GET") {
		return;
	}

	const segments = requestSegments(event.request);
	const strategyFn = strategyFor(segments);
	event.respondWith(strategyFn(env, {
		event,
		segments,
		fetch: mkfetch(),
	}));
};

const mkActivateHandler = ({ self, clients }) => event =>
	event.waitUntil(Promise.all([
		clients.claim(),
		self.registration.navigationPreload?.enable(),
	]));

const registerListeners = env => {
	env.self.addEventListener("install",   mkInstallHandler(env));
	env.self.addEventListener("activate", mkActivateHandler(env));
	env.self.addEventListener("fetch",       mkFetchHandler(env));
};

const main = ({
	self,
	caches,
	clients,
	out = console.log,
	err = console.warn,
} = {}) =>
	registerListeners({
		self,
		caches,
		clients,
		baseSegments: asSegments(self.location.pathname),
		out,
		err,
	});