-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcache.ts
More file actions
50 lines (46 loc) · 1.6 KB
/
cache.ts
File metadata and controls
50 lines (46 loc) · 1.6 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
import * as Zod from 'zod'
import * as Fs from 'node:fs'
import * as Process from 'node:process'
import * as Path from 'node:path'
import { FetchAdShieldDomains } from './references/index.js'
const BaseCacheDir = (Process.env.INIT_CWD && Path.isAbsolute(Process.env.INIT_CWD))
? Process.env.INIT_CWD
: Process.cwd()
const CachePath = Path.join(Path.resolve(BaseCacheDir), '.buildcache')
const CacheDomainsPath = Path.join(CachePath, 'domains.json')
export function CreateCache(Domains: Set<string>) {
if (!Fs.existsSync(CachePath)) {
Fs.mkdirSync(CachePath)
} else if (!Fs.statSync(CachePath).isDirectory()) {
throw new Error('.buildcache exists and is not a directory!')
}
if (Fs.existsSync(CacheDomainsPath)) {
throw new Error('Cache already exists!')
}
Fs.writeFileSync(CacheDomainsPath, JSON.stringify([...Domains], null, 2), { encoding: 'utf-8' })
}
export async function LoadCache(): Promise<Set<string>> {
if (!Fs.existsSync(CacheDomainsPath)) {
throw new Error('Cache does not exist!')
}
const DomainsRaw = Fs.readFileSync(CacheDomainsPath, { encoding: 'utf-8' })
const DomainsArray: string[] = JSON.parse(DomainsRaw)
await Zod.array(Zod.string().refine((Value) => {
try {
new URLPattern(`https://${Value}/`)
return true
} catch {
return false
}
})).parseAsync(DomainsArray)
return new Set(DomainsArray)
}
export async function LoadDomainsFromCache(): Promise<Set<string>> {
if (!Fs.existsSync(CacheDomainsPath)) {
const Domains = await FetchAdShieldDomains()
CreateCache(Domains)
return Domains
} else {
return await LoadCache()
}
}