UNPKG

1.56 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const crypto_1 = require("crypto");
4const fs = require("fs-extra");
5const path = require("path");
6const xxh = require("xxhashjs");
7const HEXBASE = 16;
8const defaultHashOptions = {
9 method: 'xxhash32',
10 shrink: 8,
11 append: false
12};
13const getxxhash = (content, options) => {
14 const hashFunc = options.method === 'xxhash32' ? xxh.h32 : xxh.h64;
15 const seed = 0;
16 return hashFunc(seed)
17 .update(content)
18 .digest()
19 .toString(HEXBASE);
20};
21const getHash = (content, options) => {
22 if (options.method && typeof options.method === 'function') {
23 return options.method(content);
24 }
25 if (options.method && options.method.indexOf('xxhash') === 0) {
26 return getxxhash(content, options);
27 }
28 try {
29 const hashFunc = crypto_1.default.createHash(options.method);
30 return hashFunc.update(content).digest('hex');
31 }
32 catch (e) {
33 return null;
34 }
35};
36function hash(content, options) {
37 options = options || defaultHashOptions;
38 let hash = getHash(content, options);
39 if (hash == null) {
40 // bad hash method fallback to defaults
41 // TODO: warning/error reporting?
42 hash = getHash(content, defaultHashOptions);
43 }
44 return options.shrink ? hash.substr(0, options.shrink) : hash;
45}
46exports.default = (file, options) => {
47 const content = fs.readFileSync(file);
48 const ext = path.extname(file);
49 return hash(content, options) + ext;
50};
51//# sourceMappingURL=hash.js.map
\No newline at end of file