hash.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * utilities for hashing config objects.
  3. * basically iteratively updates hash with a JSON-like format
  4. */
  5. 'use strict';
  6. exports.__esModule = true;
  7. const createHash = require('crypto').createHash;
  8. const stringify = JSON.stringify;
  9. /** @type {import('./hash').default} */
  10. function hashify(value, hash) {
  11. if (!hash) { hash = createHash('sha256'); }
  12. if (Array.isArray(value)) {
  13. hashArray(value, hash);
  14. } else if (typeof value === 'function') {
  15. hash.update(String(value));
  16. } else if (value instanceof Object) {
  17. hashObject(value, hash);
  18. } else {
  19. hash.update(stringify(value) || 'undefined');
  20. }
  21. return hash;
  22. }
  23. exports.default = hashify;
  24. /** @type {import('./hash').hashArray} */
  25. function hashArray(array, hash) {
  26. if (!hash) { hash = createHash('sha256'); }
  27. hash.update('[');
  28. for (let i = 0; i < array.length; i++) {
  29. hashify(array[i], hash);
  30. hash.update(',');
  31. }
  32. hash.update(']');
  33. return hash;
  34. }
  35. hashify.array = hashArray;
  36. exports.hashArray = hashArray;
  37. /** @type {import('./hash').hashObject} */
  38. function hashObject(object, optionalHash) {
  39. const hash = optionalHash || createHash('sha256');
  40. hash.update('{');
  41. Object.keys(object).sort().forEach((key) => {
  42. hash.update(stringify(key));
  43. hash.update(':');
  44. // @ts-expect-error the key is guaranteed to exist on the object here
  45. hashify(object[key], hash);
  46. hash.update(',');
  47. });
  48. hash.update('}');
  49. return hash;
  50. }
  51. hashify.object = hashObject;
  52. exports.hashObject = hashObject;