1+ import * as Zod from 'zod'
2+ import * as Fs from 'node:fs'
3+ import * as Process from 'node:process'
4+ import { FetchAdShieldDomains } from './references/index.js'
5+
6+ const CachePath = Process . cwd ( ) + '/.buildcache'
7+ const CacheDomainsPath = CachePath + '/domains.json'
8+
9+ export function CreateCache ( Domains : Set < string > ) {
10+ if ( ! Fs . existsSync ( CachePath ) ) {
11+ Fs . mkdirSync ( CachePath )
12+ } else if ( ! Fs . statSync ( CachePath ) . isDirectory ( ) ) {
13+ throw new Error ( '.buildcache exists and is not a directory!' )
14+ }
15+ if ( Fs . existsSync ( CacheDomainsPath ) ) {
16+ throw new Error ( 'Cache already exists!' )
17+ }
18+ Fs . writeFileSync ( CacheDomainsPath , JSON . stringify ( [ ...Domains ] , null , 2 ) , { encoding : 'utf-8' } )
19+ }
20+
21+ export async function LoadCache ( ) : Promise < Set < string > > {
22+ if ( ! Fs . existsSync ( CacheDomainsPath ) ) {
23+ throw new Error ( 'Cache does not exist!' )
24+ }
25+ const DomainsRaw = Fs . readFileSync ( CacheDomainsPath , { encoding : 'utf-8' } )
26+ const DomainsArray : string [ ] = JSON . parse ( DomainsRaw )
27+ await Zod . array ( Zod . string ( ) . refine ( ( Value ) => {
28+ try {
29+ new URLPattern ( `https://${ Value } /` )
30+ return true
31+ } catch {
32+ return false
33+ }
34+ } ) ) . parseAsync ( DomainsArray )
35+ return new Set ( DomainsArray )
36+ }
37+
38+ export async function LoadDomainsFromCache ( ) : Promise < Set < string > > {
39+ if ( ! Fs . existsSync ( CacheDomainsPath ) ) {
40+ const Domains = await FetchAdShieldDomains ( )
41+ CreateCache ( Domains )
42+ return Domains
43+ } else {
44+ return await LoadCache ( )
45+ }
46+ }
0 commit comments