Skip to content

Instantly share code, notes, and snippets.

@kelunik
Forked from halfnibble/HashFunction.ts
Created October 6, 2020 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kelunik/d1826d868a30ed8343b54e1334f07827 to your computer and use it in GitHub Desktop.
Save kelunik/d1826d868a30ed8343b54e1334f07827 to your computer and use it in GitHub Desktop.
Hash function to debug absolute paths sent to the update chunk hash method in webpack.
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
/**
* Interface for Webpack's hashFunction
*/
export interface IHashFunction {
update: (data: string | Buffer, encoding: string) => IHashFunction;
digest: (encoding: string) => string | Buffer;
new (algorithm: string): IHashFunction;
}
/**
* Webpack hashFunction based on md5
* with debugging.
*/
export function HashFunction(algorithm: string): IHashFunction {
const _algorithm: string = algorithm ? algorithm : 'md5';
this._hashFunction = crypto.createHash(_algorithm);
// This dynamically creates the absolute path to our project's root directy, which is
// 4 levels up from where we keep this file.
// You could just manually set _absolutePath, e.g. to "Users/sally/workspace/myproject"
const numberOfNestedDirs = 4;
this._absolutePath = path.join(...__dirname.split(path.sep).slice(0, -numberOfNestedDirs));
if (path.sep === '/') {
// Add back leading '/' in *nix fs.
this._absolutePath = '/' + this._absolutePath;
}
const logPath: string = path.join(this._absolutePath, 'abs_path_errors.log');
this._logFile = fs.createWriteStream(logPath, {flags: 'a+'});
this.update = (data: string | Buffer, encoding: string): IHashFunction => {
if (data.indexOf(this._absolutePath) !== -1) {
this._logFile.write(
'Absolute Path Detected: ' + data.slice(0, 2000) + '\n\n'
);
debugger; // tslint:disable-line:no-debugger
} else {
this._hashFunction.update(data, encoding);
}
return this;
};
this.digest = (encoding: string): string => {
return this._hashFunction.digest('hex').substring(0, 16);
};
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment