UNPKG

@thi.ng/mime

Version:

650+ file extension to MIME type mappings, based on mime-db

51 lines (50 loc) 1.68 kB
import { DB } from "./generated.js"; const __ext = (val) => val.substring(~~(val[0] === "1")).split(","); const __group = (mime) => { const [prefix, suffix] = mime.split("/"); const group = DB[prefix]; return group ? group[suffix] : void 0; }; const MIME_TYPES = ((defs) => { const res = {}; for (const groupID in defs) { const group = defs[groupID]; for (const type in group) { const mime = groupID + "/" + type; for (const e of __ext(group[type])) { const isLowPri = e[0] === "*"; const ext = isLowPri ? e.substring(1) : e; let coll = res[ext]; !coll && (coll = res[ext] = []); isLowPri ? coll.push(mime) : coll.unshift(mime); } } } return res; })(DB); const preferredType = (ext, fallback = MIME_TYPES.bin[0]) => { ext = ext.toLowerCase(); const type = MIME_TYPES[ext[0] === "." ? ext.substring(1) : ext]; return type ? type[0] : fallback; }; const preferredTypeForPath = (path, fallback) => preferredType(path.substring(path.lastIndexOf(".")), fallback); const preferredExtension = (mime, fallback = "bin") => { const group = __group(mime); const ext = group ? __ext(group) : void 0; return ext ? ext.find((x) => x[0] !== "*") || ext[0].substring(1) : fallback; }; const extensionsForType = (mime) => { const group = __group(mime); const ext = group ? __ext(group) : void 0; return ext ? ext.map((x) => x[0] === "*" ? x.substring(1) : x) : void 0; }; const isCompressible = (mime) => !!(__group(mime)?.[0] === "1"); export * from "./presets.js"; export { MIME_TYPES, extensionsForType, isCompressible, preferredExtension, preferredType, preferredTypeForPath };