UNPKG

3.17 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.toBase64 = exports.fromBase64 = void 0;
4const alphabetByEncoding = {};
5const alphabetByValue = new Array(64);
6for (let i = 0, start = "A".charCodeAt(0), limit = "Z".charCodeAt(0); i + start <= limit; i++) {
7 const char = String.fromCharCode(i + start);
8 alphabetByEncoding[char] = i;
9 alphabetByValue[i] = char;
10}
11for (let i = 0, start = "a".charCodeAt(0), limit = "z".charCodeAt(0); i + start <= limit; i++) {
12 const char = String.fromCharCode(i + start);
13 const index = i + 26;
14 alphabetByEncoding[char] = index;
15 alphabetByValue[index] = char;
16}
17for (let i = 0; i < 10; i++) {
18 alphabetByEncoding[i.toString(10)] = i + 52;
19 const char = i.toString(10);
20 const index = i + 52;
21 alphabetByEncoding[char] = index;
22 alphabetByValue[index] = char;
23}
24alphabetByEncoding["+"] = 62;
25alphabetByValue[62] = "+";
26alphabetByEncoding["/"] = 63;
27alphabetByValue[63] = "/";
28const bitsPerLetter = 6;
29const bitsPerByte = 8;
30const maxLetterValue = 0b111111;
31function fromBase64(input) {
32 let totalByteLength = (input.length / 4) * 3;
33 if (input.slice(-2) === "==") {
34 totalByteLength -= 2;
35 }
36 else if (input.slice(-1) === "=") {
37 totalByteLength--;
38 }
39 const out = new ArrayBuffer(totalByteLength);
40 const dataView = new DataView(out);
41 for (let i = 0; i < input.length; i += 4) {
42 let bits = 0;
43 let bitLength = 0;
44 for (let j = i, limit = i + 3; j <= limit; j++) {
45 if (input[j] !== "=") {
46 if (!(input[j] in alphabetByEncoding)) {
47 throw new TypeError(`Invalid character ${input[j]} in base64 string.`);
48 }
49 bits |= alphabetByEncoding[input[j]] << ((limit - j) * bitsPerLetter);
50 bitLength += bitsPerLetter;
51 }
52 else {
53 bits >>= bitsPerLetter;
54 }
55 }
56 const chunkOffset = (i / 4) * 3;
57 bits >>= bitLength % bitsPerByte;
58 const byteLength = Math.floor(bitLength / bitsPerByte);
59 for (let k = 0; k < byteLength; k++) {
60 const offset = (byteLength - k - 1) * bitsPerByte;
61 dataView.setUint8(chunkOffset + k, (bits & (255 << offset)) >> offset);
62 }
63 }
64 return new Uint8Array(out);
65}
66exports.fromBase64 = fromBase64;
67function toBase64(input) {
68 let str = "";
69 for (let i = 0; i < input.length; i += 3) {
70 let bits = 0;
71 let bitLength = 0;
72 for (let j = i, limit = Math.min(i + 3, input.length); j < limit; j++) {
73 bits |= input[j] << ((limit - j - 1) * bitsPerByte);
74 bitLength += bitsPerByte;
75 }
76 const bitClusterCount = Math.ceil(bitLength / bitsPerLetter);
77 bits <<= bitClusterCount * bitsPerLetter - bitLength;
78 for (let k = 1; k <= bitClusterCount; k++) {
79 const offset = (bitClusterCount - k) * bitsPerLetter;
80 str += alphabetByValue[(bits & (maxLetterValue << offset)) >> offset];
81 }
82 str += "==".slice(0, 4 - bitClusterCount);
83 }
84 return str;
85}
86exports.toBase64 = toBase64;