forked from Cohesible/synapse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
69 lines (54 loc) · 2 KB
/
utils.ts
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import * as vm from 'node:vm'
import * as path from 'node:path'
import { SyncFs } from '../system'
import { throwIfNotFileNotFoundError } from '../utils'
export interface Context {
readonly vm: vm.Context
readonly globals: typeof globalThis
}
export function copyGlobalThis(): Context {
const ctx = vm.createContext()
const globals = vm.runInContext('this', ctx)
const keys = new Set(Object.getOwnPropertyNames(globals))
const propDenyList = new Set([
'crypto', // Node adds a prop that throws if in a different context
'console', // We want to add our own
])
const descriptors = Object.getOwnPropertyDescriptors(globalThis)
for (const k of Object.keys(descriptors)) {
if (!keys.has(k) && !propDenyList.has(k)) {
Object.defineProperty(globals, k, descriptors[k])
}
}
globals.ArrayBuffer = ArrayBuffer
// Needed for `esbuild`
globals.Uint8Array = Uint8Array
globals.console = globalThis.console
Object.defineProperty(globals, 'crypto', {
value: globalThis.crypto,
writable: false,
configurable: false,
})
return { vm: ctx, globals }
}
export type CodeCache = ReturnType<typeof createCodeCache>
export function createCodeCache(fs: Pick<SyncFs, 'readFileSync' | 'writeFileSync' | 'deleteFileSync'>, cacheDir: string) {
function getCachedData(key: string): Buffer | undefined {
const filePath = path.resolve(cacheDir, key)
try {
const d = fs.readFileSync(filePath)
return Buffer.isBuffer(d) ? d : Buffer.from(d)
} catch (e) {
throwIfNotFileNotFoundError(e)
}
}
function setCachedData(key: string, data: Uint8Array) {
const filePath = path.resolve(cacheDir, key)
fs.writeFileSync(filePath, data)
}
function evictCachedData(key: string) {
const filePath = path.resolve(cacheDir, key)
fs.deleteFileSync(filePath)
}
return { getCachedData, setCachedData, evictCachedData }
}