@@ -6,6 +6,8 @@ import type { Transformed } from './apply-transformers';
6
6
7
7
const getTime = ( ) => Math . floor ( Date . now ( ) / 1e8 ) ;
8
8
9
+ const tmpdir = os . tmpdir ( ) ;
10
+ const noop = ( ) => { } ;
9
11
class FileCache < ReturnType > extends Map < string , ReturnType > {
10
12
/**
11
13
* By using tmpdir, the expectation is for the OS to clean any files
@@ -17,7 +19,16 @@ class FileCache<ReturnType> extends Map<string, ReturnType> {
17
19
* Note on Windows, temp files are not cleaned up automatically.
18
20
* https://superuser.com/a/1599897
19
21
*/
20
- cacheDirectory = path . join ( os . tmpdir ( ) , 'tsx' ) ;
22
+ cacheDirectory = path . join (
23
+ // Write permissions by anyone
24
+ tmpdir ,
25
+
26
+ // Write permissions only by current user
27
+ `tsx-${ os . userInfo ( ) . uid } ` ,
28
+ ) ;
29
+
30
+ // Maintained so we can remove it on Windows
31
+ oldCacheDirectory = path . join ( tmpdir , 'tsx' ) ;
21
32
22
33
cacheFiles : {
23
34
time : number ;
@@ -40,7 +51,10 @@ class FileCache<ReturnType> extends Map<string, ReturnType> {
40
51
} ;
41
52
} ) ;
42
53
43
- setImmediate ( ( ) => this . expireDiskCache ( ) ) ;
54
+ setImmediate ( ( ) => {
55
+ this . expireDiskCache ( ) ;
56
+ this . removeOldCacheDirectory ( ) ;
57
+ } ) ;
44
58
}
45
59
46
60
get ( key : string ) {
@@ -90,10 +104,7 @@ class FileCache<ReturnType> extends Map<string, ReturnType> {
90
104
fs . promises . writeFile (
91
105
path . join ( this . cacheDirectory , `${ time } -${ key } ` ) ,
92
106
JSON . stringify ( value ) ,
93
- ) . catch (
94
-
95
- ( ) => { } ,
96
- ) ;
107
+ ) . catch ( noop ) ;
97
108
}
98
109
99
110
return this ;
@@ -105,13 +116,32 @@ class FileCache<ReturnType> extends Map<string, ReturnType> {
105
116
for ( const cache of this . cacheFiles ) {
106
117
// Remove if older than ~7 days
107
118
if ( ( time - cache . time ) > 7 ) {
108
- fs . promises . unlink ( path . join ( this . cacheDirectory , cache . fileName ) ) . catch (
109
-
110
- ( ) => { } ,
111
- ) ;
119
+ fs . promises . unlink ( path . join ( this . cacheDirectory , cache . fileName ) ) . catch ( noop ) ;
112
120
}
113
121
}
114
122
}
123
+
124
+ async removeOldCacheDirectory ( ) {
125
+ try {
126
+ const exists = await fs . promises . access ( this . oldCacheDirectory ) . then ( ( ) => true ) ;
127
+ if ( exists ) {
128
+ if ( 'rm' in fs . promises ) {
129
+ await fs . promises . rm (
130
+ this . oldCacheDirectory ,
131
+ {
132
+ recursive : true ,
133
+ force : true ,
134
+ } ,
135
+ ) ;
136
+ } else {
137
+ await fs . promises . rmdir (
138
+ this . oldCacheDirectory ,
139
+ { recursive : true } ,
140
+ ) ;
141
+ }
142
+ }
143
+ } catch { }
144
+ }
115
145
}
116
146
117
147
export default (
0 commit comments