blog/lib/hash.ts

53 lines
1.6 KiB
TypeScript
Raw Normal View History

import { createHash } from "node:crypto";
import File from "vinyl";
2024-06-21 21:03:37 +00:00
import { PRODUCTION } from "./environment.js";
2024-06-26 21:42:33 +00:00
import { Observable } from "rxjs";
2024-06-21 21:03:37 +00:00
function fileHash(buffer: Buffer) {
const hash = createHash("sha256");
hash.update(buffer.toString());
return hash.digest("hex");
}
2024-06-26 21:42:33 +00:00
const hashPath =
(mappings: Map<string, string>) =>
(file: File): File => {
const hash = PRODUCTION ? fileHash(file.contents as Buffer) : "00000000";
const newName = [
file.basename.substring(0, file.basename.length - file.extname.length),
hash.substring(0, 8),
file.extname.substring(1),
].join(".");
2024-06-26 21:42:33 +00:00
mappings.set(file.basename, newName);
file.basename = newName;
2024-06-26 21:42:33 +00:00
return file;
};
2024-06-26 21:42:33 +00:00
export default function (manifestName: string) {
return (observable: Observable<File>): Observable<File> =>
new Observable((subscriber) => {
const mappings = new Map<string, string>();
const hash = hashPath(mappings);
2024-06-26 21:42:33 +00:00
observable.subscribe({
next(file) {
subscriber.next(hash(file));
},
error(e) {
subscriber.error(e);
},
complete() {
const mappingFile = new File({
path: manifestName,
contents: Buffer.from(JSON.stringify(Object.fromEntries(mappings))),
});
subscriber.next(mappingFile);
subscriber.complete();
},
});
});
}