-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompile-mime-match.js
74 lines (59 loc) · 1.82 KB
/
compile-mime-match.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
70
71
72
73
74
'use strict';
const rgxValidType = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
const typeEndingMatcher = '(?:$|;|\\s)';
const tokenMatcher = "[!#$%&'*+.^_`|~0-9A-Za-z-]+";
const escapeTokenChars = str => str.replace(/[$*+.^|-]/g, '\\$&');
function compileMimeMatch(mimeType) {
if (Array.isArray(mimeType)) {
if (mimeType.length > 1) {
return compileMulti(mimeType.map(normaliazeMimeType));
}
mimeType = mimeType[0];
}
return compileSingle(normaliazeMimeType(mimeType));
}
function normaliazeMimeType(mimeType) {
if (typeof mimeType !== 'string') {
throw new TypeError(`MIME type must be a string. Got '${typeof mimeType}'.`);
}
if (mimeType[0] === '+') { // '+suffix' shorthand
mimeType = '*/*' + mimeType;
}
if (!rgxValidType.test(mimeType)) {
throw new Error('MIME type must be in the "type/subtype" format or the "+suffix" short-form');
}
return mimeType;
}
function compileMulti(mimeTypes) {
const regex = new RegExp(
'^(?:' + mimeTypes.map(compileRegexString).join('|') + ')' + typeEndingMatcher,
'i'
);
return wrapRegex(regex);
}
function compileSingle(mimeType) {
const regex = new RegExp('^' + compileRegexString(mimeType) + typeEndingMatcher, 'i');
return wrapRegex(regex);
}
function compileRegexString(mimeType) {
let [type, subtype] = mimeType.split('/');
if (type === '*') {
type = tokenMatcher;
} else {
type = escapeTokenChars(type);
}
if (subtype === '*') {
subtype = tokenMatcher;
} else if (subtype.startsWith('*+')) {
subtype = tokenMatcher + escapeTokenChars(subtype.slice(1));
} else {
subtype = escapeTokenChars(subtype);
}
return type + '/' + subtype;
}
function wrapRegex(regex) {
return function mimeMatch(mimeType) {
return regex.test(mimeType);
};
}
module.exports = compileMimeMatch;