var debug = require('debug')('ylt:contentTypeChecker'); var Q = require('q'); var FileType = require('file-type'); var isSvg = require('is-svg'); var isJson = require('is-json'); var ContentTypeChecker = function() { async function checkContentType(entry) { var deferred = Q.defer(); // Setting isSomething values: switch(entry.type) { case 'html': entry.isHTML = true; break; case 'xml': entry.isXML = true; break; case 'css': entry.isCSS = true; break; case 'js': entry.isJS = true; break; case 'json': entry.isJSON = true; break; case 'image': entry.isImage = true; break; case 'webfont': entry.isWebFont = true; break; case 'video': entry.isVideo = true; break; case 'favicon': entry.isFavicon = true; break; } // Now let's check for mistakes by analysing body content. It happens more often then we think! // Ignore very small files as they are generally tracking pixels if (entry.weightCheck && entry.weightCheck.bodyBuffer && entry.weightCheck.bodySize > 100) { var foundType; try { foundType = await findContentType(entry.weightCheck.bodyBuffer); // If it's an image or a font, then rewrite. if (foundType !== null && (foundType.type === 'image' || foundType.type === 'webfont' || foundType.type === 'json')) { if (foundType.type !== entry.type) { debug('Content type %s is wrong for %s. It should be %s.', entry.type, entry.url, foundType.type); } rewriteContentType(entry, foundType); } } catch(err) { debug('Error while analyzing the contentType of %s', entry.url); debug(err); } } deferred.resolve(entry); return deferred.promise; } async function findContentType(bodyBuffer) { var bodyStr = bodyBuffer.toString(); // https://github.com/sindresorhus/is-svg/issues/7 if (/