import { readdir } from 'node:fs/promises'; import { resolve } from 'node:path'; const directory = resolve('src/assets/images/bg/generic'); const imageFile = /\.(?:avif|webp|png|jpe?g|gif)$/i; const imagePath = '/images/bg/generic/'; const offsetBasis = 0x811c9dc5; const prime = 0x01000193; const encoder = new TextEncoder(); export async function genericBackgrounds() { const paths = (await readdir(directory, { withFileTypes: true })) .filter((entry) => entry.isFile() && imageFile.test(entry.name)) .map((entry) => `${imagePath}${encodeURIComponent(entry.name)}`) .sort(); if (!paths.length) throw new Error('No supported images in src/assets/images/bg/generic/'); return paths; } /** Select the same generic art in the content catalog and asset pipeline. * @param {string} id Page path without leading or trailing slashes. * @param {string[]} backgrounds Sorted paths from genericBackgrounds(). */ export function defaultBackground(id, backgrounds) { let hash = offsetBasis; for (const byte of encoder.encode(`/${id}/`)) hash = Math.imul(hash ^ byte, prime); return backgrounds[(hash >>> 0) % backgrounds.length]; }