forked from OverZealous/cdnizer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (58 loc) · 1.96 KB
/
index.js
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
var path = require('path');
var _ = require('lodash');
var util = require('./lib/util');
var parseOptions = require('./lib/parseOptions');
// Used to reset lodash to default template settings
var lodashTemplateSettings = {
evaluate: _.templateSettings.evaluate,
interpolate: _.templateSettings.interpolate,
escape: _.templateSettings.escape
};
function makeCdnizer(opts) {
"use strict";
opts = parseOptions(opts);
function cdnizer(contents) {
var canAddFallback = opts.shouldAddFallback && contents.indexOf('<head') !== -1;
var didAddFallback = false;
_.union(opts.matchers, util.matchers).forEach(function(m) {
contents = contents.replace(m.pattern, function(match, pre, url, post) {
var fileInfo = util.findFileInfo(url, opts);
if(fileInfo) {
var result = pre;
var params = _.merge(util.getVersionInfo(fileInfo, opts), {
defaultCDNBase: opts.defaultCDNBase,
filepath: url,
// the split/join is to fix Windows idiotic backward paths.
filepathRel: path.join(opts.relativeRoot, url).split(path.sep).join('/').replace(/^\//, ''),
filename: path.basename(url),
filenameMin: util.getFilenameMin(url, opts),
package: fileInfo.package,
test: fileInfo.test
});
var excludeCdnPrefix = /^([a-z]+:)?\/\//i.test(url);
var cdnTemplate = opts.excludeAbsolute && excludeCdnPrefix
? '<%= filepath %>'
: fileInfo.cdn || opts.defaultCDN;
result += _.template(cdnTemplate, lodashTemplateSettings)(params);
result += post;
if(canAddFallback && m.fallback && fileInfo.test) {
result += _.template(opts.fallbackTest, lodashTemplateSettings)(params);
didAddFallback = true;
}
return result;
} else {
// do nothing
return match;
}
});
});
if(didAddFallback) {
contents = contents.replace(/<link|<script|<\/head/i, function(m) {
return opts.fallbackScript + m;
});
}
return contents;
}
return cdnizer;
}
module.exports = makeCdnizer;