-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmimeType.ts
61 lines (54 loc) · 2.29 KB
/
mimeType.ts
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
import { extension, typeByExtension } from "https://deno.land/std@0.185.0/media_types/mod.ts";
const textTypes = [
"text/",
"application/javascript",
"application/typescript",
"application/xml",
"application/xhtml+xml"
]
export const isJson = (mimeType: string | null | undefined) => !!mimeType && (mimeType.indexOf("/json") > 0 || mimeType.indexOf("+json") > 0 || mimeType === 'inode/directory');
export const isText = (mimeType: string | null | undefined) => !!mimeType && textTypes.some(tt => mimeType.startsWith(tt));
export const isZip = (mimeType: string | null | undefined) => !!mimeType && (mimeType.startsWith("application/") && mimeType.includes('zip'));
const multiExtensions: { [ mimeType: string]: string[] } = {
'image/jpeg': [ 'jpg', 'jpeg' ],
"application/typescript": [ 'ts', 'tsx' ],
"text/javascript": [ 'js', 'jsx' ]
}
const mappings: { [ mimeType: string]: string } = {
"text/x.nunjucks": "njk"
}
export function getExtension(mimeType: string): string | undefined {
if (mimeType.startsWith("application/schema-instance+json")
|| mimeType.startsWith("application/schema+json")) {
return "json";
}
if (mappings[mimeType]) {
return mappings[mimeType];
}
if (multiExtensions[mimeType]) {
return multiExtensions[mimeType][0];
}
return extension(mimeType);
}
export function addExtension(resourceName: string, mimeType: string) {
let ext = getExtension(mimeType);
if (ext === null) return resourceName;
ext = '.' + ext;
return resourceName + (resourceName.endsWith(ext) ? '' : ext);
}
export function getExtensions(mimeType: string): string[] | undefined {
if (multiExtensions[mimeType]) {
return multiExtensions[mimeType]
} else {
const ext = extension(mimeType);
return ext ? [ ext ] : undefined;
}
}
/** return mime type of a path or an extension */
export function getType(path: string): string | null {
const ext = path.indexOf('.') >= 0 ? path.split(".").pop() as string : path;
let [key, ] = Object.entries(mappings).find(([,value]) => value === ext) || [ null, null ];
if (!key) [key, ] = Object.entries(multiExtensions).find(([,values]) => values.includes(ext)) || [ null, null ];
if (!key) key = typeByExtension(ext) || null;
return key;
}