53 lines
1.6 KiB
TypeScript
53 lines
1.6 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import File from "vinyl";
|
|
import { PRODUCTION } from "./environment.js";
|
|
import { Observable } from "rxjs";
|
|
|
|
function fileHash(buffer: Buffer) {
|
|
const hash = createHash("sha256");
|
|
hash.update(buffer.toString());
|
|
return hash.digest("hex");
|
|
}
|
|
|
|
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(".");
|
|
|
|
mappings.set(file.basename, newName);
|
|
file.basename = newName;
|
|
|
|
return file;
|
|
};
|
|
|
|
export default function (manifestName: string) {
|
|
return (observable: Observable<File>): Observable<File> =>
|
|
new Observable((subscriber) => {
|
|
const mappings = new Map<string, string>();
|
|
const hash = hashPath(mappings);
|
|
|
|
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();
|
|
},
|
|
});
|
|
});
|
|
}
|