Skip to content

Commit

Permalink
change hash, add public api
Browse files Browse the repository at this point in the history
  • Loading branch information
zeroby0 committed Aug 6, 2021
1 parent 4332dec commit b0ee0a9
Showing 1 changed file with 23 additions and 13 deletions.
36 changes: 23 additions & 13 deletions img.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,15 +122,25 @@ function getValidWidths(originalWidth, widths = [], allowUpscale = false) {
return filtered.sort((a, b) => a - b);
}

function getFileHash(src, options) {
const hash = createHash("sha1");

const opts = {
sharpOptions: options.sharpOptions,
sharpWebpOptions: options.sharpWebpOptions,
sharpPngOptions: options.sharpPngOptions,
sharpJpegOptions: options.sharpJpegOptions,
sharpAvifOptions: options.sharpAvifOptions
function getHash(src, imgOptions={}, length=10) {
const hash = createHash("sha256");

let opts = Object.assign({
"userOptions": {},
"sharpOptions": {},
"sharpWebpOptions": {},
"sharpPngOptions": {},
"sharpJpegOptions": {},
"sharpAvifOptions": {},
}, imgOptions);

opts = {
userOptions: opts.userOptions,
sharpOptions: opts.sharpOptions,
sharpWebpOptions: opts.sharpWebpOptions,
sharpPngOptions: opts.sharpPngOptions,
sharpJpegOptions: opts.sharpJpegOptions,
sharpAvifOptions: opts.sharpAvifOptions,
};

if(fs.existsSync(src)) {
Expand All @@ -141,12 +151,11 @@ function getFileHash(src, options) {
}

hash.update(JSON.stringify(opts));

return hash.digest('hex').substring(0, 8);
return hash.digest("base64url").substring(0, length);;
}

function getFilename(src, width, format, options = {}) {
let id = getFileHash(src, options);
let id = getHash(src, options);

if (typeof options.filenameFormat === "function") {
let filename = options.filenameFormat(id, src, width, format, options);
Expand All @@ -170,7 +179,7 @@ function getStats(src, format, urlPath, width, height, options = {}) {
let outputExtension = options.extensions[format] || format;

if(options.urlFormat && typeof options.urlFormat === "function") {
let id = getFileHash(src, options);
let id = getHash(src, options);

url = options.urlFormat({
id,
Expand Down Expand Up @@ -472,6 +481,7 @@ module.exports.statsSync = statsSync;
module.exports.statsByDimensionsSync = statsByDimensionsSync;
module.exports.getFormats = getFormatsArray;
module.exports.getWidths = getValidWidths;
module.exports.getHash = getHash;

const generateHTML = require("./generate-html");
module.exports.generateHTML = generateHTML;
Expand Down

0 comments on commit b0ee0a9

Please sign in to comment.