-
Notifications
You must be signed in to change notification settings - Fork 203
/
Copy pathhashids.ts
295 lines (251 loc) · 8.47 KB
/
hashids.ts
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import type { NumberLike } from './util'
import {
fromAlphabet,
isIntegerNumber,
isPositiveAndFinite,
keepUnique,
makeAnyOfCharsRegExp,
makeAtLeastSomeCharRegExp,
onlyChars,
safeParseInt10,
shuffle,
splitAtIntervalAndMap,
toAlphabet,
withoutChars,
} from './util'
const MIN_ALPHABET_LENGTH = 16
const SEPARATOR_DIV = 3.5
const GUARD_DIV = 12
const HEXADECIMAL = 16
const SPLIT_AT_EVERY_NTH = 12
const MODULO_PART = 100
export default class Hashids {
private alphabet: string[]
private seps: string[]
private guards: string[]
private salt: string[]
private guardsRegExp: RegExp
private sepsRegExp: RegExp
private allowedCharsRegExp: RegExp
constructor(
salt = '',
private minLength = 0,
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',
seps = 'cfhistuCFHISTU',
) {
if (typeof minLength !== 'number') {
throw new TypeError(
`Hashids: Provided 'minLength' has to be a number (is ${typeof minLength})`,
)
}
if (typeof salt !== 'string') {
throw new TypeError(
`Hashids: Provided 'salt' has to be a string (is ${typeof salt})`,
)
}
if (typeof alphabet !== 'string') {
throw new TypeError(
`Hashids: Provided alphabet has to be a string (is ${typeof alphabet})`,
)
}
const saltChars = Array.from(salt)
const alphabetChars = Array.from(alphabet)
const sepsChars = Array.from(seps)
this.salt = saltChars
const uniqueAlphabet = keepUnique(alphabetChars)
if (uniqueAlphabet.length < MIN_ALPHABET_LENGTH) {
throw new Error(
`Hashids: alphabet must contain at least ${MIN_ALPHABET_LENGTH} unique characters, provided: ${uniqueAlphabet.join(
'',
)}`,
)
}
/** `alphabet` should not contains `seps` */
this.alphabet = withoutChars(uniqueAlphabet, sepsChars)
/** `seps` should contain only characters present in `alphabet` */
const filteredSeps = onlyChars(sepsChars, uniqueAlphabet)
this.seps = shuffle(filteredSeps, saltChars)
let sepsLength
let diff
if (
this.seps.length === 0 ||
this.alphabet.length / this.seps.length > SEPARATOR_DIV
) {
sepsLength = Math.ceil(this.alphabet.length / SEPARATOR_DIV)
if (sepsLength > this.seps.length) {
diff = sepsLength - this.seps.length
this.seps.push(...this.alphabet.slice(0, diff))
this.alphabet = this.alphabet.slice(diff)
}
}
this.alphabet = shuffle(this.alphabet, saltChars)
const guardCount = Math.ceil(this.alphabet.length / GUARD_DIV)
if (this.alphabet.length < 3) {
this.guards = this.seps.slice(0, guardCount)
this.seps = this.seps.slice(guardCount)
} else {
this.guards = this.alphabet.slice(0, guardCount)
this.alphabet = this.alphabet.slice(guardCount)
}
this.guardsRegExp = makeAnyOfCharsRegExp(this.guards)
this.sepsRegExp = makeAnyOfCharsRegExp(this.seps)
this.allowedCharsRegExp = makeAtLeastSomeCharRegExp([
...this.alphabet,
...this.guards,
...this.seps,
])
}
encode(numbers: NumberLike[] | string[] | string): string
encode(...numbers: NumberLike[]): string
encode(...numbers: string[]): string
encode<T extends NumberLike | string>(
first: T | T[],
...inputNumbers: T[]
): string {
const ret = ''
let numbers: T[] = Array.isArray(first)
? first
: [...(first != null ? [first] : []), ...inputNumbers]
if (numbers.length === 0) {
return ret
}
if (!numbers.every(isIntegerNumber)) {
numbers = numbers.map((n) =>
typeof n === 'bigint' || typeof n === 'number'
? n
: safeParseInt10(String(n)),
) as T[]
}
if (!(numbers as NumberLike[]).every(isPositiveAndFinite)) {
return ret
}
return this._encode(numbers as number[]).join('')
}
decode(id: string): NumberLike[] {
if (!id || typeof id !== 'string' || id.length === 0) return []
return this._decode(id)
}
/**
* @description Splits a hex string into groups of 12-digit hexadecimal numbers,
* then prefixes each with '1' and encodes the resulting array of numbers
*
* Encoding '00000000000f00000000000f000f' would be the equivalent of:
* Hashids.encode([0x100000000000f, 0x100000000000f, 0x1000f])
*
* This means that if your environment supports BigInts,
* you will get different (shorter) results if you provide
* a BigInt representation of your hex and use `encode` directly, e.g.:
* Hashids.encode(BigInt(`0x${hex}`))
*
* To decode such a representation back to a hex string, use the following snippet:
* Hashids.decode(id)[0].toString(16)
*/
encodeHex(inputHex: bigint | string): string {
let hex = inputHex
switch (typeof hex) {
case 'bigint':
hex = hex.toString(HEXADECIMAL)
break
case 'string':
if (!/^[\dA-Fa-f]+$/.test(hex)) return ''
break
default:
throw new Error(
`Hashids: The provided value is neither a string, nor a BigInt (got: ${typeof hex})`,
)
}
const numbers = splitAtIntervalAndMap(hex, SPLIT_AT_EVERY_NTH, (part) =>
Number.parseInt(`1${part}`, 16),
)
return this.encode(numbers)
}
decodeHex(id: string): string {
return this.decode(id)
.map((number) => number.toString(HEXADECIMAL).slice(1))
.join('')
}
isValidId(id: string): boolean {
return this.allowedCharsRegExp.test(id)
}
private _encode(numbers: NumberLike[]): string[] {
let { alphabet } = this
const numbersIdInt = numbers.reduce<number>(
(last, number, i) =>
last +
(typeof number === 'bigint'
? Number(number % BigInt(i + MODULO_PART))
: number % (i + MODULO_PART)),
0,
)
let ret: string[] = [alphabet[numbersIdInt % alphabet.length]!]
const lottery = [...ret]
const { seps } = this
const { guards } = this
numbers.forEach((number, i) => {
const buffer = lottery.concat(this.salt, alphabet)
alphabet = shuffle(alphabet, buffer)
const last = toAlphabet(number, alphabet)
ret.push(...last)
if (i + 1 < numbers.length) {
const charCode = last[0]!.codePointAt(0)! + i
const extraNumber =
typeof number === 'bigint'
? Number(number % BigInt(charCode))
: number % charCode
ret.push(seps[extraNumber % seps.length]!)
}
})
if (ret.length < this.minLength) {
const prefixGuardIndex =
(numbersIdInt + ret[0]!.codePointAt(0)!) % guards.length
ret.unshift(guards[prefixGuardIndex]!)
if (ret.length < this.minLength) {
const suffixGuardIndex =
(numbersIdInt + ret[2]!.codePointAt(0)!) % guards.length
ret.push(guards[suffixGuardIndex]!)
}
}
const halfLength = Math.floor(alphabet.length / 2)
while (ret.length < this.minLength) {
alphabet = shuffle(alphabet, alphabet)
ret.unshift(...alphabet.slice(halfLength))
ret.push(...alphabet.slice(0, halfLength))
const excess = ret.length - this.minLength
if (excess > 0) {
const halfOfExcess = excess / 2
ret = ret.slice(halfOfExcess, halfOfExcess + this.minLength)
}
}
return ret
}
private _decode(id: string): NumberLike[] {
if (!this.isValidId(id)) {
throw new Error(
`The provided ID (${id}) is invalid, as it contains characters that do not exist in the alphabet (${this.guards.join(
'',
)}${this.seps.join('')}${this.alphabet.join('')})`,
)
}
const idGuardsArray = id.split(this.guardsRegExp)
const splitIndex =
idGuardsArray.length === 3 || idGuardsArray.length === 2 ? 1 : 0
const idBreakdown = idGuardsArray[splitIndex]!
if (idBreakdown.length === 0) return []
const lotteryChar = idBreakdown[Symbol.iterator]().next().value as string
const idArray = idBreakdown.slice(lotteryChar.length).split(this.sepsRegExp)
let lastAlphabet: string[] = this.alphabet
const result: NumberLike[] = []
for (const subId of idArray) {
const buffer = [lotteryChar, ...this.salt, ...lastAlphabet]
const nextAlphabet = shuffle(
lastAlphabet,
buffer.slice(0, lastAlphabet.length),
)
result.push(fromAlphabet(Array.from(subId), nextAlphabet))
lastAlphabet = nextAlphabet
}
// if the result is different from what we'd expect, we return an empty result (malformed input):
if (this._encode(result).join('') !== id) return []
return result
}
}