@fedify/fedify
Version:
An ActivityPub server framework
60 lines (59 loc) • 1.91 kB
JavaScript
import * as constants from "./constants.js";
import { concat, decodeText, encodeText } from "./util.js";
/**
* Encode data with the specified base and add the multibase prefix.
*
* @throws {Error} Will throw if the encoding is not supported
*/
export function encode(nameOrCode, buf) {
const enc = encoding(nameOrCode);
const data = encodeText(enc.encode(buf));
return concat([enc.codeBuf, data], enc.codeBuf.length + data.length);
}
/**
* Takes a Uint8Array or string encoded with multibase header, decodes it and
* returns the decoded buffer
*
* @throws {Error} Will throw if the encoding is not supported
*/
export function decode(data) {
if (data instanceof Uint8Array) {
data = decodeText(data);
}
const prefix = data[0];
// Make all encodings case-insensitive except the ones that include upper and lower chars in the alphabet
if (["f", "F", "v", "V", "t", "T", "b", "B", "c", "C", "h", "k", "K"].includes(prefix)) {
data = data.toLowerCase();
}
const enc = encoding(data[0]);
return enc.decode(data.substring(1));
}
/**
* Get the encoding by name or code
* @throws {Error} Will throw if the encoding is not supported
*/
function encoding(nameOrCode) {
if (Object.prototype.hasOwnProperty.call(constants.names, nameOrCode)) {
return constants.names[nameOrCode];
}
else if (Object.prototype.hasOwnProperty.call(constants.codes,
/** @type {BaseCode} */ (nameOrCode))) {
return constants.codes[nameOrCode];
}
else {
throw new Error(`Unsupported encoding: ${nameOrCode}`);
}
}
/**
* Get encoding from data
*
* @param {string|Uint8Array} data
* @returns {Base}
* @throws {Error} Will throw if the encoding is not supported
*/
export function encodingFromData(data) {
if (data instanceof Uint8Array) {
data = decodeText(data);
}
return encoding(data[0]);
}