Files
blog/scripts/version-service-worker.mjs
T
biss 351bc8a226
自动部署 / deploy (push) Failing after 43s
Load optional resources on demand
2026-11-30 20:24:44 +08:00

32 lines
1.1 KiB
JavaScript

import { createHash } from 'node:crypto';
import { readdir, readFile, writeFile } from 'node:fs/promises';
import { join, relative, resolve } from 'node:path';
const root = resolve('dist');
const worker = join(root, 'sw.js');
const hash = createHash('sha256');
const source = await readFile(resolve('public/sw.js'), 'utf8');
hash.update(source);
hash.update('\0');
async function collect(directory) {
const entries = await readdir(directory, { withFileTypes: true });
const files = await Promise.all(entries.map((entry) => {
const path = join(directory, entry.name);
return entry.isDirectory() ? collect(path) : [path];
}));
return files.flat();
}
const files = (await collect(root)).filter((path) => path !== worker).sort();
for (const path of files) {
hash.update(relative(root, path).replaceAll('\\', '/'));
hash.update('\0');
hash.update(await readFile(path));
hash.update('\0');
}
const versioned = source.replace(/^const CACHE_VERSION = '[^']+';/m, `const CACHE_VERSION = '${hash.digest('hex').slice(0, 16)}';`);
if (versioned === source) throw new Error('Service worker cache version was not found');
await writeFile(worker, versioned);