@taekwondo-db/web-app 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +297 -2
  3. package/assets/css/abstracts/base.css +54 -0
  4. package/assets/css/abstracts/variables.css +125 -0
  5. package/assets/css/components/breadcrumb.css +14 -0
  6. package/assets/css/components/card.css +35 -0
  7. package/assets/css/components/categories.css +200 -0
  8. package/assets/css/components/detail.css +591 -0
  9. package/assets/css/components/grade.css +79 -0
  10. package/assets/css/components/header.css +131 -0
  11. package/assets/css/components/language.css +38 -0
  12. package/assets/css/components/layout.css +151 -0
  13. package/assets/css/components/link.css +26 -0
  14. package/assets/css/components/result.css +123 -0
  15. package/assets/css/components/search.css +193 -0
  16. package/assets/css/components/tag.css +137 -0
  17. package/assets/css/style.css +17 -0
  18. package/assets/fonts/noto-serif-kr.css +28 -0
  19. package/assets/js/email.js +11 -0
  20. package/assets/js/gallery.js +30 -0
  21. package/assets/js/language.js +11 -0
  22. package/assets/js/main.js +17 -0
  23. package/assets/js/pwa.js +48 -0
  24. package/assets/js/search.js +276 -0
  25. package/assets/js/sorting.js +26 -0
  26. package/bin/taekwondo-db.js +145 -0
  27. package/content/_content.gotmpl +27 -0
  28. package/hugo.toml +32 -0
  29. package/i18n/de.json +107 -0
  30. package/i18n/en.json +107 -0
  31. package/i18n/ko.json +107 -0
  32. package/layouts/404.html +23 -0
  33. package/layouts/_partials/breadcrumb.html +11 -0
  34. package/layouts/_partials/categories.html +17 -0
  35. package/layouts/_partials/category-cards.html +36 -0
  36. package/layouts/_partials/category-group.html +7 -0
  37. package/layouts/_partials/category-section.html +15 -0
  38. package/layouts/_partials/category-tile.html +4 -0
  39. package/layouts/_partials/description.html +10 -0
  40. package/layouts/_partials/email.html +6 -0
  41. package/layouts/_partials/favicons.html +42 -0
  42. package/layouts/_partials/fonts.html +33 -0
  43. package/layouts/_partials/grade-badge.html +11 -0
  44. package/layouts/_partials/grade-name.html +14 -0
  45. package/layouts/_partials/head.html +17 -0
  46. package/layouts/_partials/header.html +38 -0
  47. package/layouts/_partials/historic.html +23 -0
  48. package/layouts/_partials/icon.html +13 -0
  49. package/layouts/_partials/language-label.html +3 -0
  50. package/layouts/_partials/language.html +13 -0
  51. package/layouts/_partials/page-title.html +13 -0
  52. package/layouts/_partials/scripts.html +25 -0
  53. package/layouts/_partials/search-form.html +11 -0
  54. package/layouts/_partials/search-index.html +40 -0
  55. package/layouts/_partials/source-entry.html +13 -0
  56. package/layouts/_partials/t.html +2 -0
  57. package/layouts/_partials/technique/photo.html +45 -0
  58. package/layouts/_partials/technique/word-meaning.html +33 -0
  59. package/layouts/_partials/technique-name.html +5 -0
  60. package/layouts/_partials/technique-row.html +17 -0
  61. package/layouts/_partials/term/list.html +24 -0
  62. package/layouts/_partials/term-name.html +4 -0
  63. package/layouts/_partials/url.html +11 -0
  64. package/layouts/_shortcodes/email.html +2 -0
  65. package/layouts/_shortcodes/operator.html +18 -0
  66. package/layouts/baseof.html +39 -0
  67. package/layouts/group/page.html +24 -0
  68. package/layouts/groups.html +48 -0
  69. package/layouts/home.html +19 -0
  70. package/layouts/page.html +17 -0
  71. package/layouts/source/page.html +67 -0
  72. package/layouts/technique/page.html +160 -0
  73. package/layouts/term/page.html +97 -0
  74. package/lib/database.js +33 -0
  75. package/lib/export.js +423 -0
  76. package/lib/service-worker.js +167 -0
  77. package/lib/validate.js +179 -0
  78. package/package.json +42 -5
package/lib/export.js ADDED
@@ -0,0 +1,423 @@
1
+ /**
2
+ * Composes the database of a site and hands it to Hugo.
3
+ *
4
+ * Hugo cannot run the composition (whitelist, patches, `$ref`s, reverse
5
+ * references) itself, so it happens here, in Node, and Hugo receives the
6
+ * resolved result as a generated theme component next to this theme:
7
+ *
8
+ * .taekwondo-db/themes/web-app → symlink to this package
9
+ * .taekwondo-db/themes/taekwondo-data/
10
+ * data/taekwondo.json the resolved database
11
+ * assets/img/… images of the loaded techniques only
12
+ * assets/fonts/… fonts, flat — see copyFonts()
13
+ * assets/vendor/…, assets/js/vendor/… Bootstrap, the database's search
14
+ *
15
+ * The site itself stays a plain Hugo project: everything in its own
16
+ * `layouts/`, `assets/`, `i18n/` … takes precedence over both components.
17
+ */
18
+ import fs from "node:fs";
19
+ import { createRequire } from "node:module";
20
+ import path from "node:path";
21
+ import { fileURLToPath, pathToFileURL } from "node:url";
22
+ import {
23
+ builtinImageDir,
24
+ composeDatabase,
25
+ stripRefs,
26
+ TaekwondoDatabase,
27
+ } from "./database.js";
28
+
29
+ const require = createRequire(import.meta.url);
30
+
31
+ export const packageRoot = path.resolve(
32
+ path.dirname(fileURLToPath(import.meta.url)),
33
+ "..",
34
+ );
35
+ export const THEME = "web-app";
36
+ export const DATA_THEME = "taekwondo-data";
37
+
38
+ /** Data files found by name when a site has no `db/index.js`. */
39
+ const CONVENTIONAL_FILES = {
40
+ grades: "grades.json",
41
+ include: "whitelist.json",
42
+ patchTechniques: "patches/techniques.json",
43
+ patchTerms: "patches/terms.json",
44
+ sources: "sources.json",
45
+ terms: "terms.json",
46
+ };
47
+
48
+ /**
49
+ * @param {string} root site directory
50
+ * @param {string} [file] module exporting the `db` options, relative to `root`
51
+ * @returns {Promise<Record<string, any>>} options of `new TaekwondoDatabase()`;
52
+ * without the module those of the conventional files next to it, without
53
+ * any of them the complete Kukkiwon database
54
+ */
55
+ export async function loadDbOptions(root, file = "db/index.js") {
56
+ const full = path.resolve(root, file);
57
+ if (!fs.existsSync(full)) return conventionalDbOptions(path.dirname(full));
58
+ const module = await import(pathToFileURL(full).href);
59
+ return module.db ?? module.default ?? {};
60
+ }
61
+
62
+ /**
63
+ * `whitelist.json`, `patches/…`, `terms.json`, `sources.json`, `grades.json`
64
+ * and one `groups/<group>.json` per own or extended technique group.
65
+ */
66
+ function conventionalDbOptions(dir) {
67
+ const readJson = (file) => JSON.parse(fs.readFileSync(file, "utf8"));
68
+ const db = {};
69
+ for (const [option, name] of Object.entries(CONVENTIONAL_FILES)) {
70
+ const file = path.join(dir, name);
71
+ if (fs.existsSync(file)) db[option] = readJson(file);
72
+ }
73
+ const groupsDir = path.join(dir, "groups");
74
+ if (fs.existsSync(groupsDir)) {
75
+ const groups = fs
76
+ .readdirSync(groupsDir)
77
+ .filter((name) => name.endsWith(".json"))
78
+ .sort()
79
+ .map((name) => [
80
+ path.basename(name, ".json"),
81
+ readJson(path.join(groupsDir, name)),
82
+ ]);
83
+ if (groups.length > 0) db.techniqueGroups = Object.fromEntries(groups);
84
+ }
85
+ return db;
86
+ }
87
+
88
+ /**
89
+ * @param {Record<string, any>} db
90
+ * @param {string} root
91
+ * @param {string[]} [dirs] own image directories, relative to `root`
92
+ * @returns {string[]} absolute image directories; later ones win
93
+ */
94
+ export function imageDirsOf(db, root, dirs = ["img"]) {
95
+ const own = dirs.map((dir) => path.resolve(root, dir));
96
+ return db.includeBuiltins === false ? own : [builtinImageDir, ...own];
97
+ }
98
+
99
+ /**
100
+ * @param {object} options
101
+ * @param {string} options.root site directory
102
+ * @param {Record<string, any>} options.db
103
+ * @param {string[]} options.imageDirs absolute
104
+ * @returns {{ themesDir: string }}
105
+ */
106
+ export function exportSite({ root, db, imageDirs }) {
107
+ const database = new TaekwondoDatabase({
108
+ includeBuiltins: false,
109
+ ...composeDatabase(db),
110
+ });
111
+ const model = buildModel(database);
112
+
113
+ const themesDir = path.join(root, ".taekwondo-db", "themes");
114
+ const dataTheme = path.join(themesDir, DATA_THEME);
115
+ const assets = path.join(dataTheme, "assets");
116
+
117
+ linkTheme(path.join(themesDir, THEME));
118
+
119
+ const files = new Map();
120
+ files.set(
121
+ path.join(dataTheme, "data", "taekwondo.json"),
122
+ JSON.stringify(model),
123
+ );
124
+ copyImages(files, model, imageDirs, path.join(assets, "img"));
125
+ copyFonts(files, path.join(assets, "fonts"));
126
+ copyVendor(files, assets);
127
+ syncTree(dataTheme, files);
128
+
129
+ return { themesDir };
130
+ }
131
+
132
+ /**
133
+ * Brings `dir` to exactly `files` (path → content, or `{ from }` for a file
134
+ * to copy) in place: writes what changed, deletes what is no longer wanted.
135
+ *
136
+ * Never removes and recreates `dir` itself. `hugo server` watches the
137
+ * directories in it, and a watch ends with its directory — every change after
138
+ * that went unnoticed, and Hugo touching the half-deleted tree made the next
139
+ * export fail with ENOTEMPTY. Unchanged files are not rewritten either, so a
140
+ * change to the data does not look like a change to every font and image.
141
+ *
142
+ * @param {string} dir
143
+ * @param {Map<string, string | { from: string }>} files absolute paths
144
+ */
145
+ function syncTree(dir, files) {
146
+ for (const [file, content] of files) {
147
+ const wanted =
148
+ typeof content === "string"
149
+ ? Buffer.from(content)
150
+ : fs.readFileSync(content.from);
151
+ if (fs.existsSync(file) && fs.readFileSync(file).equals(wanted)) continue;
152
+ fs.mkdirSync(path.dirname(file), { recursive: true });
153
+ fs.writeFileSync(file, wanted);
154
+ }
155
+ prune(dir, files);
156
+ }
157
+
158
+ /** Deletes files under `dir` that are not in `keep`, then empty directories. */
159
+ function prune(dir, keep) {
160
+ if (!fs.existsSync(dir)) return;
161
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
162
+ const full = path.join(dir, entry.name);
163
+ if (entry.isDirectory()) {
164
+ prune(full, keep);
165
+ if (fs.readdirSync(full).length === 0) fs.rmdirSync(full);
166
+ } else if (!keep.has(full)) {
167
+ fs.rmSync(full);
168
+ }
169
+ }
170
+ }
171
+
172
+ function linkTheme(link) {
173
+ const target = fs.realpathSync(packageRoot);
174
+ try {
175
+ if (fs.realpathSync(link) === target) return;
176
+ } catch {}
177
+ fs.rmSync(link, { force: true, recursive: true });
178
+ fs.mkdirSync(path.dirname(link), { recursive: true });
179
+ fs.symlinkSync(target, link, "dir");
180
+ }
181
+
182
+ /** URL-safe and stable; Hugo would lower-case and hyphenate on its own. */
183
+ export function slugify(value) {
184
+ return value
185
+ .normalize("NFKD")
186
+ .replace(/[̀-ͯ]/g, "")
187
+ .toLowerCase()
188
+ .replace(/[^a-z0-9]+/g, "-")
189
+ .replace(/^-|-$/g, "");
190
+ }
191
+
192
+ /** `$space`, `$missing` … are building blocks of the data, not pages. */
193
+ const isInternal = (key) => key.startsWith("$");
194
+
195
+ const mapValues = (object = {}, fn) =>
196
+ Object.fromEntries(
197
+ Object.entries(object).map(([key, value]) => [key, fn(value)]),
198
+ );
199
+
200
+ const uniqueNames = (entries = []) => [...new Set(entries.map((e) => e.name))];
201
+
202
+ /** Hands out one slug per key and kind; two keys on one URL are an error. */
203
+ function slugRegistry() {
204
+ const taken = new Map();
205
+ return (kind, key) => {
206
+ const slug = slugify(key);
207
+ const id = `${kind}/${slug}`;
208
+ const owner = taken.get(id);
209
+ if (owner !== undefined && owner !== key) {
210
+ throw new Error(
211
+ `${kind} "${key}" and "${owner}" share the URL "${slug}"`,
212
+ );
213
+ }
214
+ taken.set(id, key);
215
+ return slug;
216
+ };
217
+ }
218
+
219
+ /**
220
+ * Everything the templates need, precomputed: references resolved to keys,
221
+ * reverse references, description segments, previous/next per group, the
222
+ * grade from which a technique is relevant. The templates only look things up.
223
+ */
224
+ function buildModel(database) {
225
+ const slugOf = slugRegistry();
226
+
227
+ const segments = (descriptions) =>
228
+ mapValues(descriptions, (text) =>
229
+ database.resolveDescription(text).map((segment) =>
230
+ segment.type === "text"
231
+ ? segment
232
+ : {
233
+ key: segment[segment.type].name,
234
+ label: segment.label,
235
+ type: segment.type,
236
+ },
237
+ ),
238
+ );
239
+ const citations = (sources = []) =>
240
+ sources.map((s) => ({ key: s.type.name, page: s.page ?? "" }));
241
+ const historic = (entries = []) =>
242
+ entries.map((h) => ({
243
+ hangeul: h.hangeul,
244
+ hanja: h.hanja ?? "",
245
+ name: h.name,
246
+ rr: h.rr,
247
+ sources: citations(h.sources),
248
+ }));
249
+
250
+ const groups = database.getGroups().map((key) => ({
251
+ key,
252
+ slug: slugOf("group", key),
253
+ techniques: database.getTechniquesByGroup(key).map((t) => t.name),
254
+ }));
255
+
256
+ // Lowest first; empty unless the site assigns techniques to grades.
257
+ const grades = database.getGrades().map(({ key, kind, level }) => ({
258
+ key,
259
+ kind,
260
+ level,
261
+ techniques: database.getTechniquesByGrade(key).map((t) => t.name),
262
+ }));
263
+
264
+ const neighbours = new Map();
265
+ for (const { techniques } of groups) {
266
+ techniques.forEach((name, index) => {
267
+ neighbours.set(name, {
268
+ next: techniques[index + 1] ?? "",
269
+ previous: techniques[index - 1] ?? "",
270
+ });
271
+ });
272
+ }
273
+
274
+ const techniques = {};
275
+ for (const [key, t] of database.getAllTechniques()) {
276
+ const terms = t.terms ?? [];
277
+ techniques[key] = {
278
+ description: segments(t.description),
279
+ generic: Boolean(t.generic),
280
+ grade: t.grade?.key ?? "",
281
+ group: t.group,
282
+ hangeul: terms.map((term) => term.hangeul).join(""),
283
+ historic: historic(t.historic),
284
+ images: (t.images ?? []).map((image) => ({
285
+ ai: Boolean(image.ai),
286
+ description: image.description ?? {},
287
+ src: image.src,
288
+ })),
289
+ name: key,
290
+ references: (t.references ?? []).map((r) => ({
291
+ key: r.technique.name,
292
+ type: r.type,
293
+ })),
294
+ slug: slugOf("technique", key),
295
+ sources: citations(t.sources),
296
+ supplementaryName: t.supplementaryName ?? "",
297
+ syllables: terms.map((term) => term.name).filter((n) => !isInternal(n)),
298
+ translation: t.translation ?? {},
299
+ videos: t.videos ?? [],
300
+ weight: t.weight ?? null,
301
+ ...neighbours.get(key),
302
+ };
303
+ }
304
+
305
+ const terms = {};
306
+ for (const [key, term] of database.getAllTerms()) {
307
+ if (isInternal(key)) continue;
308
+ terms[key] = {
309
+ combinations: uniqueNames(term.combinations),
310
+ description: segments(term.description),
311
+ forms: uniqueNames(term.forms),
312
+ hangeul: term.hangeul,
313
+ hanja: term.hanja ?? "",
314
+ historic: historic(term.historic),
315
+ lemma: term.lemma?.name ?? "",
316
+ name: key,
317
+ plain: mapValues(term.description, stripRefs),
318
+ slug: slugOf("term", key),
319
+ techniques: uniqueNames(term.techniques),
320
+ terms: uniqueNames(term.terms),
321
+ type: term.type ?? "",
322
+ };
323
+ }
324
+
325
+ const sources = {};
326
+ for (const [key, source] of database.getAllSources()) {
327
+ if (isInternal(key)) continue;
328
+ sources[key] = {
329
+ author: source.author ?? "",
330
+ description: source.description ?? {},
331
+ historic: uniqueNames(source.historic),
332
+ isbn: source.isbn ?? "",
333
+ name: key,
334
+ slug: slugOf("source", key),
335
+ techniques: uniqueNames(source.techniques),
336
+ title: source.title ?? key,
337
+ type: source.type ?? "",
338
+ url: source.url ?? "",
339
+ year: source.year != null ? String(source.year) : "",
340
+ };
341
+ }
342
+
343
+ return { grades, groups, sources, techniques, terms };
344
+ }
345
+
346
+ /** Only images a loaded technique refers to; a site's own image wins over the database's. */
347
+ function copyImages(files, model, imageDirs, target) {
348
+ const wanted = new Set(
349
+ Object.values(model.techniques).flatMap((t) => t.images.map((i) => i.src)),
350
+ );
351
+ for (const src of wanted) {
352
+ const found = imageDirs
353
+ .map((dir) => path.join(dir, src))
354
+ .findLast((file) => fs.existsSync(file));
355
+ if (found) files.set(path.join(target, src), { from: found });
356
+ }
357
+ }
358
+
359
+ /** Not via `require.resolve("<name>/package.json")`: `exports` may hide it. */
360
+ function packageDir(name) {
361
+ const dir = require.resolve
362
+ .paths(name)
363
+ .map((modules) => path.join(modules, name))
364
+ .find((candidate) => fs.existsSync(path.join(candidate, "package.json")));
365
+ if (!dir) throw new Error(`package not found: ${name}`);
366
+ return dir;
367
+ }
368
+
369
+ /**
370
+ * Flat in one directory, so the stylesheets refer to them by bare file name
371
+ * and the head can preload them under a stable URL.
372
+ *
373
+ * Without the `.woff` fallbacks: every browser of the last decade takes the
374
+ * `.woff2`. `font-display: optional` instead of `swap`: every page is a
375
+ * document of its own, and a late swap would make the text flicker on each
376
+ * navigation — see layouts/_partials/fonts.html. The Hangeul font is declared
377
+ * by the theme itself, in assets/fonts/noto-serif-kr.css.
378
+ */
379
+ function copyFonts(files, target) {
380
+ const plex = packageDir("@fontsource/ibm-plex-sans");
381
+ const plexFiles = fs.readdirSync(path.join(plex, "files"));
382
+ for (const weight of [400, 500, 600, 700]) {
383
+ const css = fs
384
+ .readFileSync(path.join(plex, `${weight}.css`), "utf8")
385
+ .replace(/,\s*url\([^)]*\.woff\) format\('woff'\)/g, "")
386
+ .replaceAll("url(./files/", "url(")
387
+ .replace(/font-display:\s*swap/g, "font-display: optional");
388
+ files.set(path.join(target, `ibm-plex-sans-${weight}.css`), css);
389
+ for (const file of plexFiles.filter((f) =>
390
+ f.endsWith(`-${weight}-normal.woff2`),
391
+ )) {
392
+ files.set(path.join(target, file), {
393
+ from: path.join(plex, "files", file),
394
+ });
395
+ }
396
+ }
397
+
398
+ const noto = packageDir("@fontsource/noto-serif-kr");
399
+ for (const weight of [500, 700]) {
400
+ const file = `noto-serif-kr-korean-${weight}-normal.woff2`;
401
+ files.set(path.join(target, file), {
402
+ from: path.join(noto, "files", file),
403
+ });
404
+ }
405
+ }
406
+
407
+ function copyVendor(files, assets) {
408
+ const bootstrap = fs
409
+ .readFileSync(
410
+ path.join(packageDir("bootstrap"), "dist/css/bootstrap.min.css"),
411
+ "utf8",
412
+ )
413
+ .replace(/\/\*# sourceMappingURL=.*\*\/\s*$/, "");
414
+ files.set(
415
+ path.join(assets, "vendor", "bootstrap", "bootstrap.min.css"),
416
+ bootstrap,
417
+ );
418
+ // The database's search, bundled with Fuse.js: the site searches exactly
419
+ // like the library.
420
+ files.set(path.join(assets, "js", "vendor", "taekwondo-search.mjs"), {
421
+ from: require.resolve("@taekwondo-db/database/search.browser.js"),
422
+ });
423
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Writes `sw.js` into a finished build. It makes the whole site work offline:
3
+ * every page, script, stylesheet, font and image. Only the linked videos stay
4
+ * online-only.
5
+ *
6
+ * The first install takes only the shell (CORE), so it is in control within
7
+ * seconds; the rest follows file by file in the background, the visitor's
8
+ * language first, and resumes on the next visit if it was cut off. Pages
9
+ * visited meanwhile are cached as they come.
10
+ *
11
+ * Offline-first: pages come from the cache even when online. A new deploy
12
+ * changes the file list and with it `sw.js`; the browser installs it in full
13
+ * in the background and the page offers to switch (see `assets/js/pwa.js`).
14
+ */
15
+ import crypto from "node:crypto";
16
+ import fs from "node:fs";
17
+ import path from "node:path";
18
+
19
+ const PRECACHE =
20
+ /\.(html|js|css|woff2|jpe?g|png|svg|webp|avif|ico|webmanifest|json)$/i;
21
+ const SKIP = new Set(["sw.js", "sw-reset.js"]);
22
+
23
+ /** Styles, scripts, icons, the Latin fonts and the top-level pages. */
24
+ function isCore(relative) {
25
+ if (relative.startsWith("img/") || relative.startsWith("search/"))
26
+ return false;
27
+ if (relative.startsWith("fonts/"))
28
+ return /^fonts\/(.+\.css|ibm-plex-sans-latin-)/.test(relative);
29
+ if (/\.(css|js|webmanifest|ico|png)$/.test(relative)) return true;
30
+ return /^([^/]+\/)?(index|404)\.html$/.test(relative);
31
+ }
32
+
33
+ /**
34
+ * @param {string} outDir
35
+ * @param {string} base deploy base path, ending in `/`
36
+ * @returns {number} number of files the service worker caches
37
+ */
38
+ export function writeServiceWorker(outDir, base = "/") {
39
+ const hash = crypto.createHash("sha256");
40
+ const urls = [];
41
+ const core = [];
42
+
43
+ for (const file of walk(outDir).sort()) {
44
+ const relative = path.relative(outDir, file).split(path.sep).join("/");
45
+ if (SKIP.has(relative) || !PRECACHE.test(relative)) continue;
46
+ hash.update(relative).update(fs.readFileSync(file));
47
+ const url = base + relative.replace(/(^|\/)index\.html$/, "$1");
48
+ urls.push(url);
49
+ if (isCore(relative)) core.push(url);
50
+ }
51
+
52
+ const version = hash.digest("hex").slice(0, 16);
53
+ fs.writeFileSync(
54
+ path.join(outDir, "sw.js"),
55
+ `const CACHE = ${JSON.stringify(`taekwondo-db-${version}`)};
56
+ const BASE = ${JSON.stringify(base)};
57
+ const CORE = ${JSON.stringify(core)};
58
+ const URLS = ${JSON.stringify(urls)};
59
+ const KNOWN = new Set(URLS);
60
+ const PARALLEL = 8;
61
+
62
+ const request = (url) => new Request(url, { credentials: "include" });
63
+
64
+ /** Fetches what the cache lacks, a few at a time; failures are left for the next run. */
65
+ async function fill(urls) {
66
+ const cache = await caches.open(CACHE);
67
+ const cached = new Set((await cache.keys()).map((r) => new URL(r.url).pathname));
68
+ const queue = urls.filter((url) => !cached.has(url));
69
+ const worker = async () => {
70
+ for (let url = queue.shift(); url; url = queue.shift()) {
71
+ try {
72
+ const response = await fetch(request(url));
73
+ if (response.ok) await cache.put(url, response);
74
+ } catch {}
75
+ }
76
+ };
77
+ await Promise.all(Array.from({ length: PARALLEL }, worker));
78
+ }
79
+
80
+ /** The visitor's language first: \`languages\` are the home paths of all languages. */
81
+ function prioritised(home, languages = []) {
82
+ const languageOf = (url) =>
83
+ languages.filter((prefix) => url.startsWith(prefix)).sort((a, b) => b.length - a.length)[0];
84
+ return [...URLS].sort((a, b) => (languageOf(b) === home) - (languageOf(a) === home));
85
+ }
86
+
87
+ let filling;
88
+
89
+ self.addEventListener("install", (event) => {
90
+ event.waitUntil(
91
+ (async () => {
92
+ await (await caches.open(CACHE)).addAll(CORE.map(request));
93
+ // An update is offered only once complete; the current version serves meanwhile.
94
+ if (self.registration.active) await fill(URLS);
95
+ else await self.skipWaiting();
96
+ })(),
97
+ );
98
+ });
99
+
100
+ self.addEventListener("activate", (event) => {
101
+ event.waitUntil(
102
+ caches
103
+ .keys()
104
+ .then((keys) => Promise.all(keys.filter((key) => key !== CACHE).map((key) => caches.delete(key))))
105
+ .then(() => self.clients.claim()),
106
+ );
107
+ });
108
+
109
+ self.addEventListener("message", (event) => {
110
+ if (event.data?.type === "SKIP_WAITING") self.skipWaiting();
111
+ if (event.data?.type === "PRECACHE") {
112
+ filling ??= fill(prioritised(event.data.home, event.data.languages)).finally(() => {
113
+ filling = undefined;
114
+ });
115
+ event.waitUntil(filling);
116
+ }
117
+ });
118
+
119
+ // Pages are cached as "/path/"; a link may omit the slash, which online the
120
+ // server would redirect. Offline, an unknown page gets the site's 404 page.
121
+ async function respond(event) {
122
+ const { request } = event;
123
+ const cache = await caches.open(CACHE);
124
+ const cached = await cache.match(request, { ignoreSearch: true });
125
+ if (cached) return cached;
126
+
127
+ const url = new URL(request.url);
128
+ if (request.mode === "navigate" && !url.pathname.endsWith("/")) {
129
+ const page = await cache.match(url.pathname + "/");
130
+ if (page) return Response.redirect(url.pathname + "/" + url.search, 301);
131
+ }
132
+
133
+ try {
134
+ const response = await fetch(request);
135
+ if (response.ok && KNOWN.has(url.pathname)) {
136
+ event.waitUntil(cache.put(url.pathname, response.clone()));
137
+ }
138
+ return response;
139
+ } catch (error) {
140
+ if (request.mode !== "navigate" || KNOWN.has(url.pathname)) throw error;
141
+ // "/de/…" gets the German 404 page; anything else the default language's.
142
+ const prefix = url.pathname.slice(BASE.length).split("/")[0];
143
+ const notFound =
144
+ (prefix && (await cache.match(BASE + prefix + "/404.html"))) ||
145
+ (await cache.match(BASE + "404.html"));
146
+ if (notFound) return new Response(notFound.body, { headers: notFound.headers, status: 404 });
147
+ throw error;
148
+ }
149
+ }
150
+
151
+ self.addEventListener("fetch", (event) => {
152
+ const { request } = event;
153
+ if (request.method !== "GET" || new URL(request.url).origin !== location.origin) return;
154
+ event.respondWith(respond(event));
155
+ });
156
+ `,
157
+ );
158
+
159
+ return urls.length;
160
+ }
161
+
162
+ function walk(dir) {
163
+ return fs
164
+ .readdirSync(dir, { recursive: true, withFileTypes: true })
165
+ .filter((entry) => entry.isFile())
166
+ .map((entry) => path.join(entry.parentPath, entry.name));
167
+ }