-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathcachebust.js
More file actions
168 lines (134 loc) · 7.73 KB
/
cachebust.js
File metadata and controls
168 lines (134 loc) · 7.73 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
'use strict';
var fs = require('fs');
var url = require('url');
var path = require('path');
var grunt = require('grunt');
var opts;
var fileDoesntExist = function(normalizedPath, reference) {
grunt.log.warn('Static asset "' + normalizedPath + '" skipped because it wasn\'t found, original reference=' + reference);
return false;
};
var doesFileExist = function(filepath) {
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
};
var removeIgnoredPatterns = function(parsedUrl) {
if (opts.ignorePatterns) {
var matched = opts.ignorePatterns.some(function(pattern) {
return new RegExp(pattern, 'ig').test(parsedUrl.href);
});
if (matched) {
return false;
}
}
return true;
};
module.exports = function(grunt) {
grunt.registerMultiTask('cacheBust', 'Bust static assets from the cache using content hashing', function() {
opts = this.options(require('./lib/defaultOptions'));
var processedFileMap = {};
var filesToDelete = [];
var utils = require('./lib/utils');
var findStaticAssets = require('./lib/findStaticAssets')(opts);
// Kick things off!
this.files.forEach(function(file) {
file.src
.filter(doesFileExist)
.forEach(function(filepath) {
var markup = grunt.file.read(filepath);
findStaticAssets(markup, (/\.css$/).test(filepath))
.filter(removeIgnoredPatterns)
.forEach(function(parsedUrl) {
var normalizedPath = utils.normalizePath(opts, file, path.dirname(filepath), parsedUrl);
var originalReference = decodeURI(parsedUrl.href);
var newPathname = decodeURI(parsedUrl.pathname);
var generateFileHash = utils.generateFileHash(opts);
var removePreviousHash = utils.removePreviousHash(opts);
var newReference;
var domain;
if (opts.rename) {
// If the file has already been cached, use that
if (processedFileMap[parsedUrl.pathname]) {
markup = markup.replace(new RegExp(utils.regexEscape(parsedUrl.pathname), 'g'), processedFileMap[parsedUrl.pathname]);
} else {
// Remove any previous hashes from the filename
normalizedPath = removePreviousHash(normalizedPath);
newPathname = removePreviousHash(newPathname);
// Replacing specific terms in the import path so renaming files
if (opts.replaceTerms && opts.replaceTerms.length > 0) {
opts.replaceTerms.forEach(function(obj) {
grunt.util._.each(obj, function(replacement, term) {
normalizedPath = normalizedPath.replace(term, replacement);
newPathname = newPathname.replace(term, replacement);
});
});
}
// Check if file exists
if (!grunt.file.exists(normalizedPath)) {
return fileDoesntExist(normalizedPath, parsedUrl.pathname);
}
// Generate the file hash
var fileHash = generateFileHash(grunt.file.read(normalizedPath, {
encoding: null
}));
// Create our new filename
var newFilename = utils.addFileHash(normalizedPath, fileHash, opts.separator);
// Create the new reference
domain = (parsedUrl.hostname ? (parsedUrl.protocol ? parsedUrl.protocol : '') + '//' + (parsedUrl.hostname ? parsedUrl.hostname : '') : '');
newReference = domain + utils.addFileHash(newPathname, fileHash, opts.separator) + (parsedUrl.hash ? parsedUrl.hash : '');
// Update the reference in the markup
markup = markup.replace(new RegExp(utils.regexEscape(originalReference)), newReference);
// Create our new file
grunt.file.copy(normalizedPath, newFilename);
grunt.verbose.writeln(newFilename + ' was created!');
}
} else {
// Remove any previous hashes from the filename
normalizedPath = removePreviousHash(normalizedPath);
newPathname = removePreviousHash(newPathname);
// Check if file exists
if (!grunt.file.exists(normalizedPath)) {
return fileDoesntExist(normalizedPath, parsedUrl.pathname);
}
// Create the new reference
domain = (parsedUrl.hostname ? (parsedUrl.protocol ? parsedUrl.protocol : '') + '//' + (parsedUrl.hostname ? parsedUrl.hostname : '') : '');
newReference = domain + newPathname + '?' + generateFileHash(grunt.file.read(normalizedPath, {
encoding: null
})) + (parsedUrl.hash ? parsedUrl.hash : '');
// Update the reference in the markup
markup = markup.replace(new RegExp(utils.regexEscape(originalReference)), newReference);
}
processedFileMap[parsedUrl.pathname] = newReference;
if (opts.deleteOriginals) {
filesToDelete.push(normalizedPath);
}
});
if (opts.enableUrlFragmentHint && opts.removeUrlFragmentHint) {
markup = markup.replace(/#grunt-cache-bust/g, '');
}
// Write back to the source file with changes
grunt.file.write(filepath, markup);
// Log that we've busted the file
grunt.log.writeln(['The file ', filepath, ' was busted!'].join(''));
});
});
// Delete the original files
if (opts.deleteOriginals) {
filesToDelete.forEach(function(filename) {
if (grunt.file.exists(filename)) {
grunt.file.delete(filename);
}
});
}
// Generate a JSON file with the swapped file names if requested
if (opts.jsonOutput) {
var name = typeof opts.jsonOutput === 'string' ? opts.jsonOutput : opts.jsonOutputFilename;
grunt.log.writeln(['File map has been exported to ', path.normalize(opts.baseDir + '/' + name), '!'].join(''));
grunt.file.write(path.normalize(opts.baseDir + '/' + name), JSON.stringify(processedFileMap));
}
});
};