Files
twtxt-lib/dist-node/hashTwt.js
Eric Woodward c776b5df6a add support for v2 hashing algorithm.
update README.md and demo file to be more in sync.
update to v0.10.0.
2026-03-29 22:34:43 -04:00

45 lines
1.4 KiB
JavaScript

import { blake2b } from "@exodus/blakejs";
import { base32Encode } from "./utils.js";
import { HASH_V2_EPOCH } from "./constants.js";
const dateRegex = /^(\d{4})-(\d{2})-(\d{2})([tT ])(\d{2}):(\d{2}):(\d{2})\.?(\d{3})?(?:(?:([+-]\d{2}):?(\d{2}))|Z)?$/;
const formatRFC3339 = (date) => {
const pad = (num = 0) => `${+num < 10 ? 0 : ""}${+num}`;
const padYear = (num = 0) => `${+num < 1e3 ? 0 : ""}${+num < 100 ? 0 : ""}${+num < 10 ? 0 : ""}${+num}`;
let m = dateRegex.exec(date);
if (m && m?.[9] === void 0) {
m[9] = "+00";
}
if (m && m?.[10] === void 0) {
m[10] = "00";
}
const offset = `${m?.[9]}:${m?.[10]}`.replace(/[+-]?00:00$/, "Z");
return [
padYear(m?.[1]),
"-",
pad(m?.[2]),
"-",
pad(m?.[3]),
m?.[4],
pad(m?.[5]),
":",
pad(m?.[6]),
":",
pad(m?.[7]),
//ignore milliseconds (m[8])
offset
].join("");
};
function hashTwt(twt, version = 0) {
const created = formatRFC3339(twt.created);
const payload = [twt.url, created, twt.content].join("\n");
const encoded = base32Encode(blake2b(payload, void 0, 32)).toLowerCase();
const createdDate = new Date(twt.created), epochDate = new Date(HASH_V2_EPOCH);
if (version === 1 || !version && createdDate < epochDate)
return encoded.slice(-7);
return encoded.slice(0, 12);
}
export {
hashTwt as default
};
//# sourceMappingURL=hashTwt.js.map