UNPKG

2.5 kBJavaScriptView Raw
1const { writeFile, readFile } = require('fs')
2const { promisify } = require('util')
3
4const del = require('del')
5const pathExists = require('path-exists')
6
7const { getExpires, checkExpires } = require('./expire')
8const { getHash } = require('./hash')
9
10const pWriteFile = promisify(writeFile)
11const pReadFile = promisify(readFile)
12
13// Retrieve cache manifest of a file to cache, which contains the file/directory
14// contents hash and the `expires` date.
15const getManifestInfo = async function({ cachePath, move, ttl, digests }) {
16 const manifestPath = getManifestPath(cachePath)
17 const expires = getExpires(ttl)
18 const hash = await getHash(digests, move)
19 const manifest = { expires, hash }
20 const manifestString = `${JSON.stringify(manifest, null, 2)}\n`
21 const identical = await isIdentical({ hash, manifestPath, manifestString })
22 return { manifestInfo: { manifestPath, manifestString }, identical }
23}
24
25// Whether the cache manifest has changed
26const isIdentical = async function({ hash, manifestPath, manifestString }) {
27 if (hash === undefined || !(await pathExists(manifestPath))) {
28 return false
29 }
30
31 const oldManifestString = await pReadFile(manifestPath, 'utf8')
32 return oldManifestString === manifestString
33}
34
35// Persist the cache manifest to filesystem
36const writeManifest = async function({ manifestPath, manifestString }) {
37 await pWriteFile(manifestPath, manifestString)
38}
39
40// Remove the cache manifest from filesystem
41const removeManifest = async function(cachePath) {
42 const manifestPath = getManifestPath(cachePath)
43 await del(manifestPath, { force: true })
44}
45
46// Retrieve the cache manifest filepath
47const getManifestPath = function(cachePath) {
48 return `${cachePath}${CACHE_EXTENSION}`
49}
50
51const isManifest = function(filePath) {
52 return filePath.endsWith(CACHE_EXTENSION)
53}
54
55const CACHE_EXTENSION = '.netlify.cache.json'
56
57// Check whether a file/directory is expired by checking its cache manifest
58const isExpired = async function(cachePath) {
59 const manifestPath = getManifestPath(cachePath)
60 if (!(await pathExists(manifestPath))) {
61 return false
62 }
63
64 const { expires } = await readManifest(cachePath)
65 return checkExpires(expires)
66}
67
68const readManifest = async function(cachePath) {
69 const manifestPath = getManifestPath(cachePath)
70 const manifestString = await pReadFile(manifestPath, 'utf8')
71 const manifest = JSON.parse(manifestString)
72 return manifest
73}
74
75module.exports = { getManifestInfo, writeManifest, removeManifest, isManifest, isExpired }