-
Notifications
You must be signed in to change notification settings - Fork 3
/
crosshash.js
executable file
·75 lines (62 loc) · 1.7 KB
/
crosshash.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env node
const MD5 = require('crypto-js/md5');
const stringify = require('json-stable-stringify')
const ERROR_UNSAFE_NUMBER = 'ERROR_UNSAFE_NUMBER'
class CrossHashError extends Error {
constructor(message) {
super(message)
this.name = CrossHashError.name
}
}
const crosshash = (obj) => {
return md5(crossjson(obj))
}
const crossjson = (obj) => {
return stringify(obj, {replacer: replacer})
}
const md5 = (string) => {
return MD5(string).toString()
}
const replacer = (key, value) => {
if (typeof value === 'number') {
validateNumber(value)
}
return value
}
const validateNumber = (value) => {
if (!isSafeNumber(value)) {
throw new CrossHashError(`${ERROR_UNSAFE_NUMBER}: ${value}`)
}
}
const isSafeNumber = (value) => {
return -Number.MAX_SAFE_INTEGER <= value && value <= Number.MAX_SAFE_INTEGER
}
const main = () => {
const usage = `
crosshash — stable JSON serialization and hashing for Python and JavaScript
https://github.com/httpie/crosshash
Usage:
node crosshash.js --json '{"foo": "bar"}'
node crosshash.js --hash '{"foo": "bar"}'
`
const args = process.argv.slice(2)
if (args.length !== 2 || !['--json', '--hash'].includes(args[0])) {
console.log(usage)
process.exit(1)
}
const action = args[0]
const inputJson = JSON.parse(args[1])
const operation = {
'--json': crossjson,
'--hash': crosshash
}[action]
return operation(inputJson)
}
if (typeof require !== 'undefined' && typeof module !== 'undefined' && require.main === module) {
console.log(main())
}
module.exports = {
crosshash,
crossjson,
CrossHashError,
}