-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathparseAllowedFormats.ts
More file actions
71 lines (62 loc) · 2.36 KB
/
Copy pathparseAllowedFormats.ts
File metadata and controls
71 lines (62 loc) · 2.36 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
import { AllowedFileFormatsPreviewType, AllowedFileFormatsType } from "../../typings/FileUploaderProps";
import { FileCheckFormat, predefinedFormats } from "./predefinedFormats";
export type MimeCheckFormat = {
[key: string]: string[];
};
export function getImageUploaderFormats(): FileCheckFormat[] {
return [predefinedFormats.anyImageFile];
}
export function parseAllowedFormats(
allowedFileFormats: Array<AllowedFileFormatsPreviewType | AllowedFileFormatsType>
): FileCheckFormat[] {
const map = new Map<string, FileCheckFormat>();
for (const format of allowedFileFormats) {
if (format.configMode === "simple") {
const f = predefinedFormats[format.predefinedType];
map.set(f.description, f);
} else {
const key =
(typeof format.typeFormatDescription === "string"
? format.typeFormatDescription
: format.typeFormatDescription?.value) || "default"; // todo: wait for load?
const [mime, exts] = [parseMimeType(format.mimeType.trim()), parseExtensionsList(format.extensions)];
const mapEntry = map.get(key);
if (mapEntry) {
mapEntry.entries.push([mime, exts]);
} else {
map.set(key, {
entries: [[mime, exts]],
description: key
});
}
}
}
return Array.from(map.values());
}
function parseMimeType(c: string): string {
if (c === "") {
return "dummy/mime";
}
if (/^[^/]+\/[^/]+$/.test(c)) {
// "type/subtype" string
const [type, subtype] = c.split("/");
return `${type.trim()}/${subtype.trim()}`;
}
throw new Error(`Value '${c}' is not recognized. Accepted format: 'image/jpeg'`);
}
function parseExtensionsList(config: string): string[] {
return config
.trim()
.split(",")
.map(c => c.trim())
.filter(c => c)
.map(c => {
if (/^\.[^/\\?*<>|:".]+$/.test(c)) {
// ".ext" string - allowing most characters except those invalid in filenames
return c;
}
throw new Error(
`Value '${c}' is not recognized. Extension must start with a dot and contain only valid filename characters (e.g. '.pdf', '.doc', '.tar-gz')`
);
});
}