UNPKG

1.86 kBJavaScriptView Raw
1const crypto = require('crypto');
2const fs = require('fs');
3const pkg = require('../package.json');
4const path = require('path');
5const glob = require('glob');
6
7// Small helper function to quickly create a hash from any given string.
8function createHashFromContent(content) {
9 const hash = crypto.createHash('sha256');
10 hash.update(content);
11 return hash.digest('hex');
12}
13
14/**
15 * Create a cache key from both the source, and the options used to minify the file.
16 */
17function createCacheKey(source, options) {
18 const content = `${source} ${JSON.stringify(options)} ${JSON.stringify(pkg)}`;
19 return createHashFromContent(content);
20}
21
22/**
23 * Attempt to read from cache. If the read fails, or cacheDir isn't defined return null.
24 */
25function retrieveFromCache(cacheKey, cacheDir) {
26 if (cacheDir) {
27 try {
28 return fs.readFileSync(path.join(cacheDir, `${cacheKey}.js`), 'utf8');
29 } catch (e) { void(0); } // this just means it is uncached.
30 }
31 return null;
32}
33
34/**
35 * Remove unused files from the cache. This prevents the cache from growing indefinitely.
36 */
37function pruneCache(usedCacheKeys, allCacheKeys, cacheDir) {
38 if (cacheDir) {
39 const unusedKeys = allCacheKeys.filter(key => usedCacheKeys.indexOf(key) === -1);
40 unusedKeys.forEach(key => {
41 fs.unlinkSync(path.join(cacheDir, `${key}.js`));
42 });
43 }
44}
45
46function getCacheKeysFromDisk(cacheDir) {
47 if (cacheDir) {
48 return glob.sync(path.join(cacheDir, '*.js')).map(fileName => path.basename(fileName, '.js'));
49 }
50 return [];
51}
52
53/**
54 * Attempt to write the file to the cache.
55 */
56function saveToCache(cacheKey, minifiedCode, cacheDir) {
57 if (cacheDir) {
58 fs.writeFileSync(path.join(cacheDir, `${cacheKey}.js`), minifiedCode);
59 }
60}
61
62module.exports = {
63 createHashFromContent,
64 createCacheKey,
65 retrieveFromCache,
66 pruneCache,
67 getCacheKeysFromDisk,
68 saveToCache,
69};