webhook-action/node_modules/eslint-module-utils/hash.js

60 lines
1.2 KiB
JavaScript
Raw Normal View History

/**
* utilities for hashing config objects.
* basically iteratively updates hash with a JSON-like format
*/
2022-11-10 10:43:16 +00:00
'use strict';
exports.__esModule = true;
2022-11-10 10:43:16 +00:00
const createHash = require('crypto').createHash;
2022-11-10 10:43:16 +00:00
const stringify = JSON.stringify;
function hashify(value, hash) {
2022-11-10 10:43:16 +00:00
if (!hash) hash = createHash('sha256');
2022-11-10 10:43:16 +00:00
if (Array.isArray(value)) {
hashArray(value, hash);
} else if (value instanceof Object) {
2022-11-10 10:43:16 +00:00
hashObject(value, hash);
} else {
2022-11-10 10:43:16 +00:00
hash.update(stringify(value) || 'undefined');
}
2022-11-10 10:43:16 +00:00
return hash;
}
2022-11-10 10:43:16 +00:00
exports.default = hashify;
function hashArray(array, hash) {
2022-11-10 10:43:16 +00:00
if (!hash) hash = createHash('sha256');
2022-11-10 10:43:16 +00:00
hash.update('[');
for (let i = 0; i < array.length; i++) {
2022-11-10 10:43:16 +00:00
hashify(array[i], hash);
hash.update(',');
}
2022-11-10 10:43:16 +00:00
hash.update(']');
2022-11-10 10:43:16 +00:00
return hash;
}
2022-11-10 10:43:16 +00:00
hashify.array = hashArray;
exports.hashArray = hashArray;
function hashObject(object, hash) {
2022-11-10 10:43:16 +00:00
if (!hash) hash = createHash('sha256');
2022-11-10 10:43:16 +00:00
hash.update('{');
Object.keys(object).sort().forEach(key => {
2022-11-10 10:43:16 +00:00
hash.update(stringify(key));
hash.update(':');
hashify(object[key], hash);
hash.update(',');
});
hash.update('}');
return hash;
}
2022-11-10 10:43:16 +00:00
hashify.object = hashObject;
exports.hashObject = hashObject;