multiformats
Version:
Interface for multihash, multicodec, multibase and CID
58 lines • 1.59 kB
JavaScript
import { withSettings } from './base.js';
const alphabetSettings = alphabet => ({
alphabet,
padding: alphabet.indexOf('=') > -1,
url: alphabet.indexOf('-') > -1 && alphabet.indexOf('_') > -1
});
export default b64 => {
const encode = (input, {url, padding}) => {
let output = b64.encode(input);
if (url) {
output = output.replace(/\+/g, '-').replace(/\//g, '_');
}
const pad = output.indexOf('=');
if (pad > 0 && !padding) {
output = output.substring(0, pad);
}
return output;
};
const decode = (input, {alphabet}) => {
for (const char of input) {
if (alphabet.indexOf(char) < 0) {
throw new Error('invalid base64 character');
}
}
return b64.decode(input);
};
const codec = ({name, prefix, alphabet}) => withSettings({
name,
prefix,
settings: alphabetSettings(alphabet),
decode,
encode
});
return {
b64,
__browser: b64.__browser,
base64: codec({
name: 'base64',
prefix: 'm',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
}),
base64pad: codec({
name: 'base64pad',
prefix: 'M',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
}),
base64url: codec({
name: 'base64url',
prefix: 'u',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
}),
base64urlpad: codec({
name: 'base64urlpad',
prefix: 'U',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_='
})
};
};