36 lines
1.7 KiB
JavaScript
36 lines
1.7 KiB
JavaScript
import { createHash } from 'node:crypto';
|
|
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import { webUrl } from './policy.mjs';
|
|
import { fetchList } from './downloads.mjs';
|
|
|
|
export const DEFAULT_LISTS = Object.freeze([
|
|
'https://easylist.to/easylist/easylist.txt',
|
|
'https://easylist.to/easylist/easyprivacy.txt',
|
|
]);
|
|
|
|
export function normalizeLists(value) {
|
|
if (!Array.isArray(value) || value.length > 8) throw new Error('Use at most eight filter list URLs.');
|
|
return [...new Set(value.map(address => {
|
|
const url = new URL(webUrl(address, { blank: false }));
|
|
if (url.protocol !== 'https:' || (url.port && url.port !== '443')) throw new Error('Use an HTTPS filter list URL.');
|
|
return url.href;
|
|
}))];
|
|
}
|
|
|
|
export async function loadLists(addresses, { directory, download = false, fetch = fetchList } = {}) {
|
|
return Promise.all(normalizeLists(addresses).map(async address => {
|
|
const bundled = DEFAULT_LISTS.indexOf(address);
|
|
if (bundled !== -1) return readFile(new URL(`../assets/filters/${bundled === 0 ? 'easylist' : 'easyprivacy'}.txt`, import.meta.url), 'utf8');
|
|
const file = directory && path.join(directory, 'filter-lists', createHash('sha256').update(address).digest('hex') + '.txt');
|
|
if (!file) throw new Error('Filter storage is unavailable.');
|
|
try { return await readFile(file, 'utf8'); }
|
|
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
if (!download) throw new Error('A filter list is missing. Save the browser settings to download it again.');
|
|
const text = await fetch(address);
|
|
await mkdir(path.dirname(file), { recursive: true });
|
|
await writeFile(file, text, { mode: 0o600 });
|
|
return text;
|
|
}));
|
|
}
|