1 |
|
2 |
|
3 | import type {Readable} from 'stream';
|
4 | import type {FileSystem} from '@parcel/fs';
|
5 |
|
6 | import crypto from 'crypto';
|
7 | import {objectSortedEntriesDeep} from './collection';
|
8 |
|
9 | type StringHashEncoding = 'hex' | 'latin1' | 'binary' | 'base64';
|
10 |
|
11 | export function md5FromString(
|
12 | string: string | Buffer,
|
13 | encoding: StringHashEncoding = 'hex',
|
14 | ): string {
|
15 | return crypto
|
16 | .createHash('md5')
|
17 | .update(string)
|
18 | .digest(encoding);
|
19 | }
|
20 |
|
21 | export function md5FromReadableStream(stream: Readable): Promise<string> {
|
22 | return new Promise((resolve, reject) => {
|
23 | stream.on('error', err => {
|
24 | reject(err);
|
25 | });
|
26 | stream
|
27 | .pipe(crypto.createHash('md5').setEncoding('hex'))
|
28 | .on('finish', function() {
|
29 | resolve(this.read());
|
30 | })
|
31 | .on('error', err => {
|
32 | reject(err);
|
33 | });
|
34 | });
|
35 | }
|
36 |
|
37 | export function md5FromObject(
|
38 | obj: {+[string]: mixed, ...},
|
39 | encoding: StringHashEncoding = 'hex',
|
40 | ): string {
|
41 | return md5FromString(JSON.stringify(objectSortedEntriesDeep(obj)), encoding);
|
42 | }
|
43 |
|
44 | export function md5FromFilePath(
|
45 | fs: FileSystem,
|
46 | filePath: string,
|
47 | ): Promise<string> {
|
48 | return md5FromReadableStream(fs.createReadStream(filePath));
|
49 | }
|