Debian Codegraph @

node/@bufbuild/protobuf/dist/commonjs/wire/base64-encoding.js

raw
1 "use strict";
2 // Copyright 2021-2026 Buf Technologies, Inc.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 Object.defineProperty(exports, "__esModule", { value: true });
16 exports.base64Decode = base64Decode;
17 exports.base64Encode = base64Encode;
18 // Native Uint8Array.prototype.setFromBase64, if the runtime provides it.
19 const nativeSetFromBase64 = Uint8Array.prototype.setFromBase64;
20 /**
21 * Decodes a base64 string to a byte array.
22 *
23 * - ignores white-space, including line breaks and tabs
24 * - allows inner padding (can decode concatenated base64 strings)
25 * - does not require padding
26 * - understands base64url encoding:
27 * "-" instead of "+",
28 * "_" instead of "/",
29 * no padding
30 */
31 function base64Decode(base64Str) {
32 const len = base64Str.length;
33 // Decoded size, assuming a well-formed string: three bytes per group of
34 // four characters, minus one byte for each padding character.
35 let size = len - ((len + 3) >> 2);
36 if ((len & 3) == 0 && base64Str[len - 1] == "=") {
37 size -= base64Str[len - 2] == "=" ? 2 : 1;
38 }
39 const bytes = new Uint8Array(size);
40 let written = -1;
41 if (nativeSetFromBase64) {
42 try {
43 const result = nativeSetFromBase64.call(bytes, base64Str);
44 if (result.read == len) {
45 written = result.written;
46 }
47 }
48 catch (_a) {
49 // The native decoder rejects base64url and inner padding, which we accept.
50 }
51 }
52 if (written < 0) {
53 written = setFromBase64(bytes, base64Str);
54 }
55 return written == size ? bytes : bytes.subarray(0, written);
56 }
57 /** Writes into `bytes` from index 0 and returns the number of bytes written. */
58 function setFromBase64(bytes, base64Str) {
59 const table = getDecodeTable();
60 let bytePos = 0, // position in byte array
61 groupPos = 0, // position in base64 group
62 b, // current byte
63 p = 0; // previous byte
64 for (let i = 0; i < base64Str.length; i++) {
65 b = table[base64Str.charCodeAt(i)];
66 if (b === undefined) {
67 switch (base64Str[i]) {
68 // @ts-ignore TS7029: Fallthrough case in switch -- ignore instead of expect-error for compiler settings without noFallthroughCasesInSwitch: true
69 case "=":
70 groupPos = 0; // reset state when padding found
71 case "\n":
72 case "\r":
73 case "\t":
74 case " ":
75 continue; // skip white-space, and padding
76 default:
77 throw Error("invalid base64 string");
78 }
79 }
80 switch (groupPos) {
81 case 0:
82 p = b;
83 groupPos = 1;
84 break;
85 case 1:
86 bytes[bytePos++] = (p << 2) | ((b & 48) >> 4);
87 p = b;
88 groupPos = 2;
89 break;
90 case 2:
91 bytes[bytePos++] = ((p & 15) << 4) | ((b & 60) >> 2);
92 p = b;
93 groupPos = 3;
94 break;
95 case 3:
96 bytes[bytePos++] = ((p & 3) << 6) | b;
97 groupPos = 0;
98 break;
99 }
100 }
101 if (groupPos == 1)
102 throw Error("invalid base64 string");
103 return bytePos;
104 }
105 const nativeToBase64 = Uint8Array.prototype.toBase64;
106 const toBase64OptionsMap = {
107 std: { alphabet: "base64", omitPadding: false },
108 std_raw: { alphabet: "base64", omitPadding: true },
109 url: { alphabet: "base64url", omitPadding: true },
110 };
111 /**
112 * Encode a byte array to a base64 string.
113 *
114 * By default, this function uses the standard base64 encoding with padding.
115 *
116 * To encode without padding, use encoding = "std_raw".
117 *
118 * To encode with the URL encoding, use encoding = "url", which replaces the
119 * characters +/ by their URL-safe counterparts -_, and omits padding.
120 */
121 function base64Encode(bytes, encoding = "std") {
122 if (nativeToBase64) {
123 return nativeToBase64.call(bytes, toBase64OptionsMap[encoding]);
124 }
125 const table = getEncodeTable(encoding);
126 const pad = encoding == "std";
127 let base64 = "", groupPos = 0, // position in base64 group
128 b, // current byte
129 p = 0; // carry over from previous byte
130 for (let i = 0; i < bytes.length; i++) {
131 b = bytes[i];
132 switch (groupPos) {
133 case 0:
134 base64 += table[b >> 2];
135 p = (b & 3) << 4;
136 groupPos = 1;
137 break;
138 case 1:
139 base64 += table[p | (b >> 4)];
140 p = (b & 15) << 2;
141 groupPos = 2;
142 break;
143 case 2:
144 base64 += table[p | (b >> 6)];
145 base64 += table[b & 63];
146 groupPos = 0;
147 break;
148 }
149 }
150 // add output padding
151 if (groupPos) {
152 base64 += table[p];
153 if (pad) {
154 base64 += "=";
155 if (groupPos == 1)
156 base64 += "=";
157 }
158 }
159 return base64;
160 }
161 // lookup table from base64 character to byte
162 let encodeTableStd;
163 let encodeTableUrl;
164 // lookup table from base64 character *code* to byte because lookup by number is fast
165 let decodeTable;
166 function getEncodeTable(encoding) {
167 if (!encodeTableStd) {
168 encodeTableStd =
169 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
170 encodeTableUrl = encodeTableStd.slice(0, -2).concat("-", "_");
171 }
172 return encoding == "url"
173 ? // biome-ignore lint/style/noNonNullAssertion: TS fails to narrow down
174 encodeTableUrl
175 : encodeTableStd;
176 }
177 function getDecodeTable() {
178 if (!decodeTable) {
179 decodeTable = [];
180 const encodeTable = getEncodeTable("std");
181 for (let i = 0; i < encodeTable.length; i++)
182 decodeTable[encodeTable[i].charCodeAt(0)] = i;
183 // support base64url variants
184 decodeTable["-".charCodeAt(0)] = encodeTable.indexOf("+");
185 decodeTable["_".charCodeAt(0)] = encodeTable.indexOf("/");
186 }
187 return decodeTable;
188 }