1
- import { accessSync , constants , existsSync , mkdirSync , readFileSync , rmSync , writeFileSync } from 'node:fs' ;
1
+ import { existsSync } from 'node:fs' ;
2
+ import { access , constants , mkdir , readFile , rm , writeFile } from 'node:fs/promises' ;
2
3
import { createHash } from 'node:crypto' ;
3
4
import { basename , dirname , join } from 'pathe' ;
4
5
import type { Tagged } from 'type-fest' ;
@@ -33,14 +34,25 @@ export async function getCache(
33
34
const key = getKey ( id , source ) ;
34
35
const path = getCachePath ( key , option ) ;
35
36
36
- if ( existsSync ( path ) ) {
37
- const data = readFileSync ( path , 'utf8' ) ;
37
+ let data : Data | null = null ;
38
+ if ( isBun ( ) ) {
39
+ const file = Bun . file ( path ) ;
40
+ if ( ! ( await file . exists ( ) ) ) {
41
+ return null ;
42
+ }
43
+ data = await file . text ( ) ;
44
+ }
45
+ else {
46
+ if ( ! ( existsSync ( path ) ) ) {
47
+ return null ;
48
+ }
49
+ data = await readFile ( path , { encoding : 'utf8' } ) ;
50
+ }
38
51
39
- const hashComment = await getHashComment ( key ) ;
52
+ const hashComment = await getHashComment ( key ) ;
40
53
41
- if ( data . endsWith ( hashComment ) ) {
42
- return data ;
43
- }
54
+ if ( data . endsWith ( hashComment ) ) {
55
+ return data ;
44
56
}
45
57
46
58
return null ;
@@ -69,12 +81,17 @@ export async function setCache(
69
81
const hashComment = await getHashComment ( key ) ;
70
82
71
83
if ( data == null ) {
72
- rmSync ( path ) ;
84
+ await rm ( path ) ;
73
85
return ;
74
86
}
75
87
76
88
const cache = data + hashComment ;
77
- writeFileSync ( path , cache , { encoding : 'utf8' } ) ;
89
+ if ( isBun ( ) ) {
90
+ Bun . write ( path , cache , { createPath : true } ) ;
91
+ }
92
+ else {
93
+ await writeFile ( path , cache , { encoding : 'utf8' } ) ;
94
+ }
78
95
}
79
96
80
97
type CacheKey = Tagged < string , 'cache-key' > ;
@@ -104,11 +121,11 @@ function getCachePath(
104
121
return join ( option . base , key ) as CachePath ;
105
122
}
106
123
107
- function prepareCacheDir ( option : ResolvedCacheOptions ) : void {
124
+ async function prepareCacheDir ( option : ResolvedCacheOptions ) {
108
125
if ( cacheDir != null ) {
109
126
return ;
110
127
}
111
- mkdirSync ( option . base , { recursive : true } ) ;
128
+ await mkdir ( option . base , { recursive : true } ) ;
112
129
113
130
if ( ! isWritable ) {
114
131
throw new Error ( 'Cache directory is not writable.' ) ;
@@ -117,9 +134,9 @@ function prepareCacheDir(option: ResolvedCacheOptions): void {
117
134
cacheDir = option . base ;
118
135
}
119
136
120
- function isWritable ( filename : string ) : boolean {
137
+ async function isWritable ( filename : string ) : Promise < boolean > {
121
138
try {
122
- accessSync ( filename , constants . W_OK ) ;
139
+ await access ( filename , constants . W_OK ) ;
123
140
return true ;
124
141
}
125
142
catch {
0 commit comments