@typed/content-hash
Version:
Content hash a directory of HTML/JS/CSS files and other static assets
57 lines • 2.79 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.fsWriteDocuments = void 0;
const Env_1 = require("@typed/fp/Env");
const FxEnv_1 = require("@typed/fp/FxEnv");
const fs_1 = require("fs");
const path_1 = require("path");
const logging_1 = require("../application/services/logging");
const getHashedPath_1 = require("./hashes/getHashedPath");
const replaceHash_1 = require("./hashes/replaceHash");
const writeFile = (path, contents) => (0, Env_1.fromTask)(() => fs_1.promises.writeFile(path, contents));
const rename = (from, to) => (0, Env_1.fromTask)(() => fs_1.promises.rename(from, to));
const unlinkFile = (path) => (0, Env_1.fromTask)(() => fs_1.promises.unlink(path));
const sourceMapExt = '.map';
const sourceMapExtRegex = new RegExp(`${sourceMapExt}$`);
const fsWriteDocuments = (registry, hashLength) => {
const eff = (0, FxEnv_1.Do)(function* (_) {
yield* _((0, logging_1.debug)(`Writing registry...`));
yield* _((0, Env_1.zip)(Array.from(registry.values()).map((document) => (0, FxEnv_1.Do)(function* (_) {
const hashedPath = (0, getHashedPath_1.getHashedPath)(document, registry, hashLength);
const pathChanged = document.filePath !== hashedPath;
if (hashedPath.endsWith(sourceMapExt) && pathChanged) {
document = yield* _(tryToRewriteFilename(document, hashedPath));
}
if (!document.isBase64Encoded && pathChanged && (0, fs_1.existsSync)(document.filePath)) {
yield* _(unlinkFile(document.filePath));
}
if (!document.isBase64Encoded) {
yield* _(writeFile(hashedPath, document.contents));
}
if (document.isBase64Encoded && pathChanged) {
yield* _(rename(document.filePath, hashedPath));
}
}))));
});
return eff;
};
exports.fsWriteDocuments = fsWriteDocuments;
function tryToRewriteFilename(document, hashedPath) {
return (0, FxEnv_1.Do)(function* (_) {
try {
const raw = JSON.parse(document.contents);
const extension = document.fileExtension.replace(sourceMapExtRegex, '');
const parts = hashedPath.replace(new RegExp(`${document.fileExtension}$`), '').split(/\./g);
const hash = parts[parts.length - 1];
return {
...document,
contents: JSON.stringify({ ...raw, file: (0, replaceHash_1.replaceHash)(path_1.posix.basename(document.filePath), extension, hash) }, null, 2),
};
}
catch (error) {
yield* _((0, logging_1.info)(`Unable to rewrite sourceMap file name for ${document.filePath}`));
return document;
}
});
}
//# sourceMappingURL=fsWriteDocuments.js.map