1 | const { writeFile, readFile } = require('fs')
|
2 | const { promisify } = require('util')
|
3 |
|
4 | const del = require('del')
|
5 | const pathExists = require('path-exists')
|
6 |
|
7 | const { getExpires, checkExpires } = require('./expire')
|
8 | const { getHash } = require('./hash')
|
9 |
|
10 | const pWriteFile = promisify(writeFile)
|
11 | const pReadFile = promisify(readFile)
|
12 |
|
13 |
|
14 |
|
15 | const 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 |
|
26 | const 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 |
|
36 | const writeManifest = async function({ manifestPath, manifestString }) {
|
37 | await pWriteFile(manifestPath, manifestString)
|
38 | }
|
39 |
|
40 |
|
41 | const removeManifest = async function(cachePath) {
|
42 | const manifestPath = getManifestPath(cachePath)
|
43 | await del(manifestPath, { force: true })
|
44 | }
|
45 |
|
46 |
|
47 | const getManifestPath = function(cachePath) {
|
48 | return `${cachePath}${CACHE_EXTENSION}`
|
49 | }
|
50 |
|
51 | const isManifest = function(filePath) {
|
52 | return filePath.endsWith(CACHE_EXTENSION)
|
53 | }
|
54 |
|
55 | const CACHE_EXTENSION = '.netlify.cache.json'
|
56 |
|
57 |
|
58 | const 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 |
|
68 | const 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 |
|
75 | module.exports = { getManifestInfo, writeManifest, removeManifest, isManifest, isExpired }
|