forked from na-trium-144/falling-nikochan
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathentry.ts
More file actions
542 lines (518 loc) · 16.8 KB
/
entry.ts
File metadata and controls
542 lines (518 loc) · 16.8 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
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
import { Context, Hono } from "hono";
import { handle } from "hono/service-worker";
import {
Bindings,
fetchError,
notFound,
onError,
redirectApp,
shareApp,
} from "@falling-nikochan/route";
import { locales } from "@falling-nikochan/i18n/staticMin.js";
import { TarFileType, TarReader } from "@gera2ld/tarjs";
const e: Bindings = {
MONGODB_URI: "",
IS_SERVICE_WORKER: "1",
};
// なぜconsoleが無い?
declare const self: ServiceWorkerGlobalScope & { console: Console };
const originalConsole = self.console;
self.console = {
...originalConsole,
log: (...args: unknown[]) => {
originalConsole.log(...args);
self.clients.matchAll().then((clients) => {
clients.forEach((client) => {
client.postMessage(args.map((a) => String(a)).join(" "));
});
});
},
error: (...args: unknown[]) => {
originalConsole.error(...args);
self.clients.matchAll().then((clients) => {
clients.forEach((client) => {
client.postMessage(args.map((a) => String(a)).join(" "));
});
});
},
warn: (...args: unknown[]) => {
originalConsole.warn(...args);
self.clients.matchAll().then((clients) => {
clients.forEach((client) => {
client.postMessage(args.map((a) => String(a)).join(" "));
});
});
},
info: (...args: unknown[]) => {
originalConsole.info(...args);
self.clients.matchAll().then((clients) => {
clients.forEach((client) => {
client.postMessage(args.map((a) => String(a)).join(" "));
});
});
},
};
// assetsを保存する
// cacheの中身の仕様を変更したときにはcacheの名前を変える
const mainCacheName = "main2";
const tmpCacheName = "tmp2";
const mainCache = () => caches.open(mainCacheName);
const tmpCache = () => caches.open(tmpCacheName);
// 設定など
const configCacheName = "config";
const configCache = () => caches.open(configCacheName);
async function clearOldCaches() {
await caches.keys().then((keys) =>
Promise.all(
keys
.filter(
(k) =>
![mainCacheName, tmpCacheName, configCacheName].includes(k) &&
!k.startsWith("brief") // used in @/common/briefCache
)
.map((k) => caches.delete(k))
)
);
}
async function fetchStatic(_e: any, url: URL): Promise<Response> {
const cache = await mainCache();
let pathname = url.pathname;
if (pathname.endsWith("/")) {
pathname = pathname.slice(0, -1);
}
if (pathname.endsWith(".html")) {
pathname = pathname.slice(0, -5);
}
pathname = pathname.replaceAll("[", "%5B").replaceAll("]", "%5D");
const res = await cache.match(pathname);
if (res) {
return res;
} else {
// 通常は全部cacheに入っているはずなのでここに来ることはほぼない
console.warn(`${url} is not in cache`);
const res = await fetch(
(process.env.ASSET_PREFIX || self.origin) + url.pathname
).catch(fetchError(e));
if (res.ok) {
const returnRes = returnBody(res.body, res.headers);
await (await mainCache()).put(url.pathname, returnRes.clone());
return returnRes;
} else {
return res;
}
}
}
// serviceWorkerからクライアントに返すため、cache-controlを削除したresponseを作成
function returnBody(body: string | ReadableStream | null, headers: Headers) {
return new Response(body, {
headers: {
...(headers.has("Content-Type") && {
"Content-Type": headers.get("Content-Type")!,
}),
"Cache-Control": "no-store",
},
});
}
// Determine Content-Type from a file path
function getContentType(pathname: string): string {
const ext = pathname.split(".").pop()?.toLowerCase() ?? "";
const types: Record<string, string> = {
html: "text/html; charset=utf-8",
css: "text/css; charset=utf-8",
js: "application/javascript; charset=utf-8",
mjs: "application/javascript; charset=utf-8",
json: "application/json; charset=utf-8",
txt: "text/plain; charset=utf-8",
svg: "image/svg+xml",
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
webp: "image/webp",
ico: "image/x-icon",
woff: "font/woff",
woff2: "font/woff2",
wasm: "application/wasm",
xml: "application/xml",
gz: "application/gzip",
};
return types[ext] ?? "application/octet-stream";
}
// Decompress gzip data using the browser's native DecompressionStream
async function decompressGzip(compressed: ArrayBuffer): Promise<ArrayBuffer> {
const stream = new Blob([compressed])
.stream()
.pipeThrough(new DecompressionStream("gzip"));
return new Response(stream).arrayBuffer();
}
interface InitAssetsState {
type: "initAssets";
state: InitAssetsResult;
progressNum?: number;
totalNum?: number;
progressSize?: number;
}
function sendInitState(
state: InitAssetsResult,
progressNum?: number,
totalNum?: number,
progressSize?: number
) {
// クライアントに初期化状態を送信する
self.clients.matchAll().then((clients) => {
clients.forEach((client) => {
client.postMessage({
type: "initAssets",
state,
progressNum,
totalNum,
progressSize,
} satisfies InitAssetsState);
});
});
return state;
}
let initInProgress = false;
type InitAssetsResult =
| "done"
| "failed"
| "updating"
| "noUpdate"
| "inProgress";
async function initAssetsCache(config: {
clearOld: boolean;
}): Promise<InitAssetsResult> {
if (initInProgress) {
console.warn("initAssetsCache: already in progress");
return sendInitState("inProgress");
}
initInProgress = true;
try {
const remoteRes = await fetch(
(process.env.ASSET_PREFIX || self.origin) + "/buildVer.json",
{ cache: "no-store" }
).catch(fetchError(e));
if (!remoteRes.ok) {
return sendInitState("failed");
}
const remoteVerRes = remoteRes.clone();
const remoteVer: BuildVer = await remoteRes.json();
const cacheVer: BuildVer | undefined = await configCache().then((cache) =>
cache.match("/buildVer").then((res) => res?.json())
);
if (
remoteVer.version === cacheVer?.version &&
remoteVer.commit === cacheVer?.commit &&
remoteVer.date === cacheVer?.date
) {
return sendInitState("noUpdate");
}
sendInitState("updating");
const cache = await mainCache();
const tmp = await tmpCache();
// tar.gz内のファイルをダウンロードして展開し、tmpCacheに入れる
const downloadTarAssets = async (): Promise<string[]> => {
const tarRes = await fetch(
(process.env.ASSET_PREFIX || self.origin) + "/staticFiles.tar.gz",
{ cache: "no-store" }
).catch(fetchError(e));
if (!tarRes.ok) {
throw new Error(`failed to fetch staticFiles.tar.gz: ${tarRes.status}`);
}
const tarBuffer = await decompressGzip(await tarRes.arrayBuffer());
const reader = await TarReader.load(tarBuffer);
const pathnames: string[] = [];
for (const info of reader.fileInfos) {
if (info.type !== TarFileType.File) continue;
const originalPath = "/" + info.name;
const contentType = getContentType(originalPath);
let pathname = originalPath;
if (pathname.endsWith(".html")) {
pathname = pathname.slice(0, -5);
}
const blob = reader.getFileBlob(info.name, contentType);
await tmp.put(
pathname,
new Response(blob, {
headers: { "Cache-Control": "no-store" },
})
);
pathnames.push(pathname);
}
return pathnames;
};
// _next/以下のファイルをダウンロードしてtmpCacheに入れる (進捗をクライアントに送信)
const downloadNextAssets = async (): Promise<string[]> => {
const nextFilesRes = await fetch(
(process.env.ASSET_PREFIX || self.origin) + "/nextFiles.txt",
{ cache: "no-store" }
).catch(fetchError(e));
if (!nextFilesRes.ok) {
throw new Error(
`failed to fetch nextFiles.txt: ${nextFilesRes.status}`
);
}
const nextFiles = (await nextFilesRes.text())
.split("\n")
.map((file) => file.replaceAll("[", "%5B").replaceAll("]", "%5D"));
// パス名にハッシュが入っているので既にキャッシュ済みのものはスキップ
const toFetch = (
await Promise.all(
nextFiles.map(async (pathname) =>
(await cache.match(pathname)) || (await tmp.match(pathname))
? null
: pathname
)
)
).filter((p): p is string => p !== null);
let failed = false;
const totalNum = toFetch.length;
let progressNum = 0;
let progressSize = 0;
sendInitState("updating", progressNum, totalNum, progressSize);
await Promise.all(
toFetch.map(async (pathname: string) => {
try {
const res = await fetch(
(process.env.ASSET_PREFIX || self.origin) + pathname,
{ cache: "no-cache" }
).catch(fetchError(e));
if (res.ok) {
const tmpBody = returnBody(res.clone().body, res.headers);
const [size] = await Promise.all([
res.arrayBuffer().then((a) => a.byteLength),
tmp.put(pathname, tmpBody),
]);
progressNum++;
progressSize += size;
sendInitState("updating", progressNum, totalNum, progressSize);
} else {
console.error(`failed to fetch ${pathname}: ${res.status}`);
failed = true;
}
} catch (err) {
console.error(`failed to fetch ${pathname}: ${err}`);
failed = true;
}
})
);
if (failed) {
throw new Error("failed to fetch some _next files");
}
return nextFiles;
};
let allPathnames: string[];
try {
const [tarPathnames, nextPathnames] = await Promise.all([
downloadTarAssets(),
downloadNextAssets(),
]);
allPathnames = [...tarPathnames, ...nextPathnames];
} catch (err) {
console.error(err);
return sendInitState("failed");
}
if (config.clearOld) {
const keys = await cache.keys();
await Promise.all(
keys.map(async (req) => {
if (!allPathnames.includes(new URL(req.url).pathname)) {
console.warn(`delete ${req.url}`);
await cache.delete(req);
}
})
);
}
// tmpからmainに移す
await Promise.all(
allPathnames.map(async (pathname: string) => {
const res = await tmp.match(pathname);
if (res) {
await cache.put(pathname, res);
await tmp.delete(pathname);
}
})
);
// finished
await configCache().then((cache) => cache.put("/buildVer", remoteVerRes));
console.log("initAssetsCache: finished");
return sendInitState("done");
} finally {
initInProgress = false;
}
}
interface BuildVer {
date: string;
commit: string;
version: string;
}
const languageDetector = async (c: Context, next: () => Promise<void>) => {
// headerもcookieも使えないので、その代わりにnavigator.languagesを使って検出するミドルウェア
const systemLangs = navigator.languages.map(
(l) => new Intl.Locale(l).language
);
const preferredLang = c.req.path.split("/")[1];
const cache = await configCache();
const preferredLang2 = await cache.match("/lang").then((res) => res?.text());
let lang: string;
if (preferredLang && locales.includes(preferredLang)) {
lang = preferredLang;
} else if (preferredLang2 && locales.includes(preferredLang2)) {
lang = preferredLang2;
} else {
lang = systemLangs.find((l) => locales.includes(l)) || "en";
}
c.set("language", lang);
cache.put("/lang", new Response(lang));
await next();
};
async function fetchAPI(input: string | URL | Request, init?: RequestInit) {
const inputReq = input instanceof Request ? input : new Request(input, init);
const inputUrl = new URL(inputReq.url);
const res = await fetch(inputReq.clone()).catch(fetchError(e));
// メインのバックエンドがダウンしていた場合(500番台のエラー or 403(cloudflareが返す) で、通信エラーでないとき)に、代替バックエンドを試す
// ただし別サーバーでcookieは使えないため、編集関係のAPIは除外
if (
(res.status >= 500 || res.status === 403) &&
process.env.BACKEND_ALT_PREFIX &&
!inputUrl.pathname.startsWith("/api/chartFile") &&
!inputUrl.pathname.startsWith("/api/newChartFile") &&
!inputUrl.pathname.startsWith("/api/hashPasswd")
) {
const altReq = new Request(
process.env.BACKEND_ALT_PREFIX + inputUrl.pathname + inputUrl.search,
{
body: inputReq.body ? await inputReq.blob() : null,
cache: inputReq.cache,
credentials: inputReq.credentials,
headers: inputReq.headers,
integrity: inputReq.integrity,
keepalive: inputReq.keepalive,
method: inputReq.method,
mode: inputReq.mode,
// priority: inputReq.priority,
redirect: inputReq.redirect,
referrer: inputReq.referrer,
referrerPolicy: inputReq.referrerPolicy,
signal: inputReq.signal,
}
);
const resAlt = await fetch(altReq).catch(fetchError(e));
if (resAlt.ok) {
return resAlt;
}
}
return res;
}
const app = new Hono({ strict: false })
.route(
"/share",
// fetch済みの新しいページ + 古いサーバーのコード ではバグを起こす可能性があるため、
// /shareページ自体についてはfetchせずcacheにあるもののみを使用する
shareApp({
fetchBrief: (_e, cid: string /*, _ctx */) =>
fetchAPI(self.origin + `/api/brief/${cid}`),
fetchStatic,
languageDetector,
})
)
.route(
"/",
redirectApp({
languageDetector,
fetchStatic,
})
)
.all("/api/*", (c) => fetchAPI(c.req.raw))
.all("/api", (c) => fetchAPI(c.req.raw))
.get("/sitemap.xml", (c) => fetchAPI(c.req.raw))
.get("/rss.xml", (c) => fetchAPI(c.req.raw))
.get("/og/*", async (c) => {
// return fetch(...) だと、30xリダイレクトを含む場合エラー
const res = await fetchAPI(c.req.url, {
credentials: "omit",
});
return new Response(res.body, {
headers: res.headers,
status: res.status,
});
})
.get("/worker/checkUpdate", async (c) => {
const result = await initAssetsCache({ clearOld: false });
switch (result) {
case "done":
return c.body(null, 200);
case "noUpdate":
return c.body(null, 204);
case "updating":
case "inProgress":
return c.body(null, 202);
case "failed":
return c.body(null, 502);
default:
result satisfies never;
}
})
.get("/worker/forceUpdate", async (c) => {
await configCache().then((cache) => cache.delete("/buildVer"));
const result = await initAssetsCache({ clearOld: false });
switch (result) {
case "done":
return c.body(null, 200);
case "noUpdate":
return c.body(null, 204);
case "updating":
case "inProgress":
return c.body(null, 202);
case "failed":
return c.body(null, 502);
default:
result satisfies never;
}
})
.get("/*", async (c) => {
if (
!c.req.path.includes(".") ||
c.req.path.endsWith(".txt") ||
c.req.path === "/favicon.ico"
) {
// キャッシュされた古いバージョンのページが読み込まれる問題を避けるために
// htmlとtxtについてはキャッシュよりも最新バージョンのfetchを優先する
// 1秒のタイムアウトを設け、fetchできなければキャッシュから返す
const abortController = new AbortController();
const timeout = setTimeout(() => abortController.abort(), 1000);
try {
const remoteRes = await fetch(
(process.env.ASSET_PREFIX || self.origin) + c.req.path,
{ cache: "no-cache", signal: abortController.signal }
).catch(fetchError(e));
clearTimeout(timeout);
if (remoteRes.ok) {
return returnBody(remoteRes.body, remoteRes.headers);
}
} catch {
// pass
}
}
return await fetchStatic(null, new URL(c.req.url));
})
.use(languageDetector)
.onError(onError({ fetchStatic }))
.notFound(notFound);
self.addEventListener("install", () => {
console.log("service worker install");
self.skipWaiting();
// e.waitUntil(initAssetsCache({ clearOld: true }));
});
self.addEventListener("activate", (e) => {
console.log("service worker activate");
e.waitUntil(Promise.all([self.clients.claim(), clearOldCaches()]));
});
self.addEventListener("fetch", (e) => {
if (
new URL(e.request.url).origin === self.origin ||
(process.env.ASSET_PREFIX &&
e.request.url.startsWith(process.env.ASSET_PREFIX))
) {
return handle(app, { fetch: undefined })(e);
}
});