UNPKG

gnablib

Version:

A lean, zero dependency library to provide a useful base for your project.

1 lines 1.66 kB
import{ContentError as t}from"../error/ContentError.js";const e="=",r=63;class a{constructor(t,e){this.tbl=t,this.reqPad=e,this._decode=this.buildDecode()}buildDecode(){const t=new Uint8Array(127);t[e.charCodeAt(0)]=65;for(let e=0;e<64;)t[this.tbl.charCodeAt(e++)]=e;return t}fromBytes(t,a){null==a&&(a=this.reqPad);let h="",c=2;for(;c<t.length;c+=3){const e=t[c-2]<<16|t[c-1]<<8|t[c];h+=this.tbl.charAt(e>>>18)+this.tbl.charAt(e>>>12&r)+this.tbl.charAt(e>>>6&r)+this.tbl.charAt(e&r)}switch(t.length-c+3-1){case 1:h+=this.tbl.charAt(t[c-2]>>>2)+this.tbl.charAt(t[c-2]<<4&r),a&&(h+=e+e);break;case 2:h+=this.tbl.charAt(t[c-2]>>>2)+this.tbl.charAt((t[c-2]<<4|t[c-1]>>>4)&r)+this.tbl.charAt(t[c-1]<<2&r),a&&(h+=e)}return h}toBytes(e,r){const a="toBytes",h=new Uint8Array(Math.ceil(3*e.length/4));let c=0,n=0,o=0,s=0;for(let r=0;r<e.length;r++){const i=this._decode[e.charCodeAt(r)];if(0===i)throw new t("Unknown char",a,e.charAt(r));if(65!==i){if(c>0)throw new t("Found after padding",a,e.charAt(r));o=o<<6|i-1,s+=6,s>=8&&(s-=8,h[n++]=o>>s)}else c++}switch(s){case 6:throw new t("Not enough characters",a,"");case 4:if(0==c&&!r)break;if(2!=c)throw new t("Bad padding, expecting 2 got",a,c);break;case 2:if(0==c&&!r)break;if(1!=c)throw new t("Bad padding, expecting 1 got",a,c);break;case 0:if(c>0)throw new t("Bad padding, expecting 0 got",a,c)}return h.subarray(0,n)}}export const base64=new a("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",!0);export const base64url=new a("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",!1);export const b64=new a("./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",!1);