-
Notifications
You must be signed in to change notification settings - Fork 57
/
manifest.ts
71 lines (57 loc) · 2.42 KB
/
manifest.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
69
70
71
import { mkdir, readFile, rm, writeFile } from 'fs/promises'
import { dirname } from 'path'
import { pathExists } from 'path-exists'
import { getExpires, checkExpires } from './expire.js'
import { getHash } from './hash.js'
// Retrieve cache manifest of a file to cache, which contains the file/directory
// contents hash and the `expires` date.
export const getManifestInfo = async function ({ cachePath, move, ttl, digests }) {
const manifestPath = getManifestPath(cachePath)
const expires = getExpires(ttl)
const hash = await getHash(digests, move)
const manifest = { expires, hash }
const manifestString = `${JSON.stringify(manifest, null, 2)}\n`
const identical = await isIdentical({ hash, manifestPath, manifestString })
return { manifestInfo: { manifestPath, manifestString }, identical }
}
// Whether the cache manifest has changed
const isIdentical = async function ({ hash, manifestPath, manifestString }) {
if (hash === undefined || !(await pathExists(manifestPath))) {
return false
}
const oldManifestString = await readFile(manifestPath, 'utf8')
return oldManifestString === manifestString
}
// Persist the cache manifest to filesystem
export const writeManifest = async function ({ manifestPath, manifestString }) {
await mkdir(dirname(manifestPath), { recursive: true })
await writeFile(manifestPath, manifestString)
}
// Remove the cache manifest from filesystem
export const removeManifest = async function (cachePath: string): Promise<void> {
const manifestPath = getManifestPath(cachePath)
await rm(manifestPath, { force: true, recursive: true, maxRetries: 3 })
}
// Retrieve the cache manifest filepath
const getManifestPath = function (cachePath: string): string {
return `${cachePath}${CACHE_EXTENSION}`
}
export const isManifest = function (filePath) {
return filePath.endsWith(CACHE_EXTENSION)
}
const CACHE_EXTENSION = '.netlify.cache.json'
// Check whether a file/directory is expired by checking its cache manifest
export const isExpired = async function (cachePath) {
const manifestPath = getManifestPath(cachePath)
if (!(await pathExists(manifestPath))) {
return false
}
const { expires } = await readManifest(cachePath)
return checkExpires(expires)
}
const readManifest = async function (cachePath) {
const manifestPath = getManifestPath(cachePath)
const manifestString = await readFile(manifestPath, 'utf-8')
const manifest = JSON.parse(manifestString)
return manifest
}