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

65 lines
1.4 KiB
JavaScript
Raw Normal View History

/**
* utilities for hashing config objects.
* basically iteratively updates hash with a JSON-like format
*/
2024-03-28 02:25:32 +00:00
2022-11-10 10:43:16 +00:00
'use strict';
2024-03-28 02:25:32 +00:00
2022-11-10 10:43:16 +00:00
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;
2024-03-28 02:25:32 +00:00
/** @type {import('./hash').default} */
function hashify(value, hash) {
2024-03-28 02:25:32 +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;
2024-03-28 02:25:32 +00:00
/** @type {import('./hash').hashArray} */
function hashArray(array, hash) {
2024-03-28 02:25:32 +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;
2024-03-28 02:25:32 +00:00
/** @type {import('./hash').hashObject} */
function hashObject(object, optionalHash) {
const hash = optionalHash || createHash('sha256');
2022-11-10 10:43:16 +00:00
hash.update('{');
2024-03-28 02:25:32 +00:00
Object.keys(object).sort().forEach((key) => {
2022-11-10 10:43:16 +00:00
hash.update(stringify(key));
hash.update(':');
2024-03-28 02:25:32 +00:00
// @ts-expect-error the key is guaranteed to exist on the object here
2022-11-10 10:43:16 +00:00
hashify(object[key], hash);
hash.update(',');
});
hash.update('}');
return hash;
}
2022-11-10 10:43:16 +00:00
hashify.object = hashObject;
exports.hashObject = hashObject;