diff --git a/dist/serverless.mjs b/dist/serverless.mjs index 2fc0704..726e874 100644 --- a/dist/serverless.mjs +++ b/dist/serverless.mjs @@ -1,2230 +1,10983 @@ -var Ka=Object.create;var it=Object.defineProperty;var Wa=Object.getOwnPropertyDescriptor;var Ga=Object.getOwnPropertyNames;var Va=Object.getPrototypeOf,za=Object.prototype.hasOwnProperty;var o=(r,e)=>it(r,"name",{value:e,configurable:!0});var ue=(r,e)=>()=>(r&&(e=r(r=0)),e);var B=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),de=(r,e)=>{for(var t in e) -it(r,t,{get:e[t],enumerable:!0})},kn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e== -"function")for(let i of Ga(e))!za.call(r,i)&&i!==t&&it(r,i,{get:()=>e[i],enumerable:!(n= -Wa(e,i))||n.enumerable});return r};var qe=(r,e,t)=>(t=r!=null?Ka(Va(r)):{},kn(e||!r||!r.__esModule?it(t,"default",{ -value:r,enumerable:!0}):t,r)),X=r=>kn(it({},"__esModule",{value:!0}),r);var jn=B(Pt=>{"use strict";p();Pt.byteLength=Ya;Pt.toByteArray=Xa;Pt.fromByteArray= -ro;var ge=[],pe=[],Ja=typeof Uint8Array<"u"?Uint8Array:Array,ar="ABCDEFGHIJKLMNO\ -PQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Re=0,Qn=ar.length;Re0)throw new Error("Invalid string. Length must be a multip\ -le of 4");var t=r.indexOf("=");t===-1&&(t=e);var n=t===e?0:4-t%4;return[t,n]}o($n, -"getLens");function Ya(r){var e=$n(r),t=e[0],n=e[1];return(t+n)*3/4-n}o(Ya,"byte\ -Length");function Za(r,e,t){return(e+t)*3/4-t}o(Za,"_byteLength");function Xa(r){ -var e,t=$n(r),n=t[0],i=t[1],s=new Ja(Za(r,n,i)),a=0,u=i>0?n-4:n,c;for(c=0;c>16&255,s[a++]=e>>8&255,s[a++]=e&255;return i===2&&(e= -pe[r.charCodeAt(c)]<<2|pe[r.charCodeAt(c+1)]>>4,s[a++]=e&255),i===1&&(e=pe[r.charCodeAt( -c)]<<10|pe[r.charCodeAt(c+1)]<<4|pe[r.charCodeAt(c+2)]>>2,s[a++]=e>>8&255,s[a++]= -e&255),s}o(Xa,"toByteArray");function eo(r){return ge[r>>18&63]+ge[r>>12&63]+ge[r>> -6&63]+ge[r&63]}o(eo,"tripletToBase64");function to(r,e,t){for(var n,i=[],s=e;su?u:a+s));return n===1?(e=r[t-1],i.push(ge[e>>2]+ -ge[e<<4&63]+"==")):n===2&&(e=(r[t-2]<<8)+r[t-1],i.push(ge[e>>10]+ge[e>>4&63]+ge[e<< -2&63]+"=")),i.join("")}o(ro,"fromByteArray")});var Hn=B(or=>{p();or.read=function(r,e,t,n,i){var s,a,u=i*8-n-1,c=(1<> -1,h=-7,f=t?i-1:0,y=t?-1:1,w=r[e+f];for(f+=y,s=w&(1<<-h)-1,w>>=-h,h+=u;h>0;s=s*256+ -r[e+f],f+=y,h-=8);for(a=s&(1<<-h)-1,s>>=-h,h+=n;h>0;a=a*256+r[e+f],f+=y,h-=8);if(s=== -0)s=1-l;else{if(s===c)return a?NaN:(w?-1:1)*(1/0);a=a+Math.pow(2,n),s=s-l}return(w? --1:1)*a*Math.pow(2,s-n)};or.write=function(r,e,t,n,i,s){var a,u,c,l=s*8-i-1,h=(1<< -l)-1,f=h>>1,y=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,w=n?0:s-1,b=n?1:-1,U=e<0|| -e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,a=h):(a=Math. -floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-a))<1&&(a--,c*=2),a+f>=1?e+=y/c:e+= -y*Math.pow(2,1-f),e*c>=2&&(a++,c/=2),a+f>=h?(u=0,a=h):a+f>=1?(u=(e*c-1)*Math.pow( -2,i),a=a+f):(u=e*Math.pow(2,f-1)*Math.pow(2,i),a=0));i>=8;r[t+w]=u&255,w+=b,u/=256, -i-=8);for(a=a<0;r[t+w]=a&255,w+=b,a/=256,l-=8);r[t+w-b]|=U*128}});var oi=B($e=>{"use strict";p();var ur=jn(),ke=Hn(),Kn=typeof Symbol=="function"&& -typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;$e.Buffer= -d;$e.SlowBuffer=uo;$e.INSPECT_MAX_BYTES=50;var Bt=2147483647;$e.kMaxLength=Bt;d. -TYPED_ARRAY_SUPPORT=no();!d.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console. -error=="function"&&console.error("This browser lacks typed array (Uint8Array) su\ -pport which is required by `buffer` v5.x. Use `buffer` v4.x if you require old b\ -rowser support.");function no(){try{let r=new Uint8Array(1),e={foo:o(function(){ -return 42},"foo")};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf( -r,e),r.foo()===42}catch{return!1}}o(no,"typedArraySupport");Object.defineProperty( -d.prototype,"parent",{enumerable:!0,get:o(function(){if(d.isBuffer(this))return this. -buffer},"get")});Object.defineProperty(d.prototype,"offset",{enumerable:!0,get:o( -function(){if(d.isBuffer(this))return this.byteOffset},"get")});function xe(r){if(r> -Bt)throw new RangeError('The value "'+r+'" is invalid for option "size"');let e=new Uint8Array( -r);return Object.setPrototypeOf(e,d.prototype),e}o(xe,"createBuffer");function d(r,e,t){ -if(typeof r=="number"){if(typeof e=="string")throw new TypeError('The "string" a\ -rgument must be of type string. Received type number');return fr(r)}return zn(r, -e,t)}o(d,"Buffer");d.poolSize=8192;function zn(r,e,t){if(typeof r=="string")return so( -r,e);if(ArrayBuffer.isView(r))return ao(r);if(r==null)throw new TypeError("The f\ -irst argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-l\ -ike Object. Received type "+typeof r);if(Se(r,ArrayBuffer)||r&&Se(r.buffer,ArrayBuffer)|| -typeof SharedArrayBuffer<"u"&&(Se(r,SharedArrayBuffer)||r&&Se(r.buffer,SharedArrayBuffer))) -return lr(r,e,t);if(typeof r=="number")throw new TypeError('The "value" argument\ - must not be of type number. Received type number');let n=r.valueOf&&r.valueOf(); -if(n!=null&&n!==r)return d.from(n,e,t);let i=oo(r);if(i)return i;if(typeof Symbol< -"u"&&Symbol.toPrimitive!=null&&typeof r[Symbol.toPrimitive]=="function")return d. -from(r[Symbol.toPrimitive]("string"),e,t);throw new TypeError("The first argumen\ -t must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. \ -Received type "+typeof r)}o(zn,"from");d.from=function(r,e,t){return zn(r,e,t)}; -Object.setPrototypeOf(d.prototype,Uint8Array.prototype);Object.setPrototypeOf(d, -Uint8Array);function Jn(r){if(typeof r!="number")throw new TypeError('"size" arg\ -ument must be of type number');if(r<0)throw new RangeError('The value "'+r+'" is\ - invalid for option "size"')}o(Jn,"assertSize");function io(r,e,t){return Jn(r), -r<=0?xe(r):e!==void 0?typeof t=="string"?xe(r).fill(e,t):xe(r).fill(e):xe(r)}o(io, -"alloc");d.alloc=function(r,e,t){return io(r,e,t)};function fr(r){return Jn(r),xe( -r<0?0:dr(r)|0)}o(fr,"allocUnsafe");d.allocUnsafe=function(r){return fr(r)};d.allocUnsafeSlow= -function(r){return fr(r)};function so(r,e){if((typeof e!="string"||e==="")&&(e="\ -utf8"),!d.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let t=Yn(r,e)| -0,n=xe(t),i=n.write(r,e);return i!==t&&(n=n.slice(0,i)),n}o(so,"fromString");function cr(r){ -let e=r.length<0?0:dr(r.length)|0,t=xe(e);for(let n=0;n= -Bt)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+ -Bt.toString(16)+" bytes");return r|0}o(dr,"checked");function uo(r){return+r!=r&& -(r=0),d.alloc(+r)}o(uo,"SlowBuffer");d.isBuffer=o(function(e){return e!=null&&e. -_isBuffer===!0&&e!==d.prototype},"isBuffer");d.compare=o(function(e,t){if(Se(e,Uint8Array)&& -(e=d.from(e,e.offset,e.byteLength)),Se(t,Uint8Array)&&(t=d.from(t,t.offset,t.byteLength)), -!d.isBuffer(e)||!d.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments\ - must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,i=t. -length;for(let s=0,a=Math.min(n,i);si.length?(d.isBuffer( -a)||(a=d.from(a)),a.copy(i,s)):Uint8Array.prototype.set.call(i,a,s);else if(d.isBuffer( -a))a.copy(i,s);else throw new TypeError('"list" argument must be an Array of Buf\ -fers');s+=a.length}return i},"concat");function Yn(r,e){if(d.isBuffer(r))return r. -length;if(ArrayBuffer.isView(r)||Se(r,ArrayBuffer))return r.byteLength;if(typeof r!= -"string")throw new TypeError('The "string" argument must be one of type string, \ -Buffer, or ArrayBuffer. Received type '+typeof r);let t=r.length,n=arguments.length> -2&&arguments[2]===!0;if(!n&&t===0)return 0;let i=!1;for(;;)switch(e){case"ascii":case"\ -latin1":case"binary":return t;case"utf8":case"utf-8":return hr(r).length;case"uc\ -s2":case"ucs-2":case"utf16le":case"utf-16le":return t*2;case"hex":return t>>>1;case"\ -base64":return ai(r).length;default:if(i)return n?-1:hr(r).length;e=(""+e).toLowerCase(), -i=!0}}o(Yn,"byteLength");d.byteLength=Yn;function co(r,e,t){let n=!1;if((e===void 0|| -e<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)|| -(t>>>=0,e>>>=0,t<=e))return"";for(r||(r="utf8");;)switch(r){case"hex":return Eo( -this,e,t);case"utf8":case"utf-8":return Xn(this,e,t);case"ascii":return go(this, -e,t);case"latin1":case"binary":return So(this,e,t);case"base64":return mo(this,e, -t);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return bo(this,e,t);default: -if(n)throw new TypeError("Unknown encoding: "+r);r=(r+"").toLowerCase(),n=!0}}o( -co,"slowToString");d.prototype._isBuffer=!0;function Ne(r,e,t){let n=r[e];r[e]=r[t], -r[t]=n}o(Ne,"swap");d.prototype.swap16=o(function(){let e=this.length;if(e%2!==0) -throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t< -e;t+=2)Ne(this,t,t+1);return this},"swap16");d.prototype.swap32=o(function(){let e=this. -length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bit\ -s");for(let t=0;tt&&(e+=" ... "),""},"inspect");Kn&&(d.prototype[Kn]=d.prototype.inspect);d.prototype.compare= -o(function(e,t,n,i,s){if(Se(e,Uint8Array)&&(e=d.from(e,e.offset,e.byteLength)),!d. -isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffe\ -r or Uint8Array. Received type '+typeof e);if(t===void 0&&(t=0),n===void 0&&(n=e? -e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),t<0||n>e.length||i<0|| -s>this.length)throw new RangeError("out of range index");if(i>=s&&t>=n)return 0; -if(i>=s)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0; -let a=s-i,u=n-t,c=Math.min(a,u),l=this.slice(i,s),h=e.slice(t,n);for(let f=0;f2147483647?t=2147483647: -t<-2147483648&&(t=-2147483648),t=+t,yr(t)&&(t=i?0:r.length-1),t<0&&(t=r.length+t), -t>=r.length){if(i)return-1;t=r.length-1}else if(t<0)if(i)t=0;else return-1;if(typeof e== -"string"&&(e=d.from(e,n)),d.isBuffer(e))return e.length===0?-1:Wn(r,e,t,n,i);if(typeof e== -"number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array. -prototype.indexOf.call(r,e,t):Uint8Array.prototype.lastIndexOf.call(r,e,t):Wn(r, -[e],t,n,i);throw new TypeError("val must be string, number or Buffer")}o(Zn,"bid\ -irectionalIndexOf");function Wn(r,e,t,n,i){let s=1,a=r.length,u=e.length;if(n!== -void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="\ -utf-16le")){if(r.length<2||e.length<2)return-1;s=2,a/=2,u/=2,t/=2}function c(h,f){ -return s===1?h[f]:h.readUInt16BE(f*s)}o(c,"read");let l;if(i){let h=-1;for(l=t;l< -a;l++)if(c(r,l)===c(e,h===-1?0:l-h)){if(h===-1&&(h=l),l-h+1===u)return h*s}else h!== --1&&(l-=l-h),h=-1}else for(t+u>a&&(t=a-u),l=t;l>=0;l--){let h=!0;for(let f=0;fi&&(n=i)):n=i;let s=e.length;n> -s/2&&(n=s/2);let a;for(a=0;a>>0,isFinite(n)? -(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.wri\ -te(string, encoding, offset[, length]) is no longer supported");let s=this.length- -t;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError( -"Attempt to write outside buffer bounds");i||(i="utf8");let a=!1;for(;;)switch(i){case"\ -hex":return lo(this,e,t,n);case"utf8":case"utf-8":return ho(this,e,t,n);case"asc\ -ii":case"latin1":case"binary":return fo(this,e,t,n);case"base64":return po(this, -e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return yo(this,e,t,n);default: -if(a)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),a=!0}},"\ -write");d.prototype.toJSON=o(function(){return{type:"Buffer",data:Array.prototype. -slice.call(this._arr||this,0)}},"toJSON");function mo(r,e,t){return e===0&&t===r. -length?ur.fromByteArray(r):ur.fromByteArray(r.slice(e,t))}o(mo,"base64Slice");function Xn(r,e,t){ -t=Math.min(r.length,t);let n=[],i=e;for(;i239?4:s>223? -3:s>191?2:1;if(i+u<=t){let c,l,h,f;switch(u){case 1:s<128&&(a=s);break;case 2:c= -r[i+1],(c&192)===128&&(f=(s&31)<<6|c&63,f>127&&(a=f));break;case 3:c=r[i+1],l=r[i+ -2],(c&192)===128&&(l&192)===128&&(f=(s&15)<<12|(c&63)<<6|l&63,f>2047&&(f<55296|| -f>57343)&&(a=f));break;case 4:c=r[i+1],l=r[i+2],h=r[i+3],(c&192)===128&&(l&192)=== -128&&(h&192)===128&&(f=(s&15)<<18|(c&63)<<12|(l&63)<<6|h&63,f>65535&&f<1114112&& -(a=f))}}a===null?(a=65533,u=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320| -a&1023),n.push(a),i+=u}return wo(n)}o(Xn,"utf8Slice");var Gn=4096;function wo(r){ -let e=r.length;if(e<=Gn)return String.fromCharCode.apply(String,r);let t="",n=0; -for(;nn)&&(t=n);let i="";for(let s=e;sn&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),tt)throw new RangeError( -"Trying to access beyond buffer length")}o(ee,"checkOffset");d.prototype.readUintLE= -d.prototype.readUIntLE=o(function(e,t,n){e=e>>>0,t=t>>>0,n||ee(e,t,this.length); -let i=this[e],s=1,a=0;for(;++a>>0,t=t>>>0, -n||ee(e,t,this.length);let i=this[e+--t],s=1;for(;t>0&&(s*=256);)i+=this[e+--t]* -s;return i},"readUIntBE");d.prototype.readUint8=d.prototype.readUInt8=o(function(e,t){ -return e=e>>>0,t||ee(e,1,this.length),this[e]},"readUInt8");d.prototype.readUint16LE= -d.prototype.readUInt16LE=o(function(e,t){return e=e>>>0,t||ee(e,2,this.length),this[e]| -this[e+1]<<8},"readUInt16LE");d.prototype.readUint16BE=d.prototype.readUInt16BE= -o(function(e,t){return e=e>>>0,t||ee(e,2,this.length),this[e]<<8|this[e+1]},"rea\ -dUInt16BE");d.prototype.readUint32LE=d.prototype.readUInt32LE=o(function(e,t){return e= -e>>>0,t||ee(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216}, -"readUInt32LE");d.prototype.readUint32BE=d.prototype.readUInt32BE=o(function(e,t){ -return e=e>>>0,t||ee(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<< -8|this[e+3])},"readUInt32BE");d.prototype.readBigUInt64LE=Ce(o(function(e){e=e>>> -0,Qe(e,"offset");let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&st(e,this.length- -8);let i=t+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,s=this[++e]+this[++e]* -2**8+this[++e]*2**16+n*2**24;return BigInt(i)+(BigInt(s)<>>0,Qe(e,"offset");let t=this[e], -n=this[e+7];(t===void 0||n===void 0)&&st(e,this.length-8);let i=t*2**24+this[++e]* -2**16+this[++e]*2**8+this[++e],s=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+ -n;return(BigInt(i)<>>0,t=t>>>0,n||ee(e,t,this.length);let i=this[e],s=1,a=0;for(;++a< -t&&(s*=256);)i+=this[e+a]*s;return s*=128,i>=s&&(i-=Math.pow(2,8*t)),i},"readInt\ -LE");d.prototype.readIntBE=o(function(e,t,n){e=e>>>0,t=t>>>0,n||ee(e,t,this.length); -let i=t,s=1,a=this[e+--i];for(;i>0&&(s*=256);)a+=this[e+--i]*s;return s*=128,a>= -s&&(a-=Math.pow(2,8*t)),a},"readIntBE");d.prototype.readInt8=o(function(e,t){return e= -e>>>0,t||ee(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]},"readInt8"); -d.prototype.readInt16LE=o(function(e,t){e=e>>>0,t||ee(e,2,this.length);let n=this[e]| -this[e+1]<<8;return n&32768?n|4294901760:n},"readInt16LE");d.prototype.readInt16BE= -o(function(e,t){e=e>>>0,t||ee(e,2,this.length);let n=this[e+1]|this[e]<<8;return n& -32768?n|4294901760:n},"readInt16BE");d.prototype.readInt32LE=o(function(e,t){return e= -e>>>0,t||ee(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},"\ -readInt32LE");d.prototype.readInt32BE=o(function(e,t){return e=e>>>0,t||ee(e,4,this. -length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},"readInt32BE");d.prototype. -readBigInt64LE=Ce(o(function(e){e=e>>>0,Qe(e,"offset");let t=this[e],n=this[e+7]; -(t===void 0||n===void 0)&&st(e,this.length-8);let i=this[e+4]+this[e+5]*2**8+this[e+ -6]*2**16+(n<<24);return(BigInt(i)<>>0,Qe(e,"offset");let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&st(e, -this.length-8);let i=(t<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt( -i)<>>0,t||ee(e,4,this. -length),ke.read(this,e,!0,23,4)},"readFloatLE");d.prototype.readFloatBE=o(function(e,t){ -return e=e>>>0,t||ee(e,4,this.length),ke.read(this,e,!1,23,4)},"readFloatBE");d. -prototype.readDoubleLE=o(function(e,t){return e=e>>>0,t||ee(e,8,this.length),ke. -read(this,e,!0,52,8)},"readDoubleLE");d.prototype.readDoubleBE=o(function(e,t){return e= -e>>>0,t||ee(e,8,this.length),ke.read(this,e,!1,52,8)},"readDoubleBE");function ce(r,e,t,n,i,s){ -if(!d.isBuffer(r))throw new TypeError('"buffer" argument must be a Buffer instan\ -ce');if(e>i||er.length)throw new RangeError("Index out of range")}o(ce,"checkInt");d.prototype. -writeUintLE=d.prototype.writeUIntLE=o(function(e,t,n,i){if(e=+e,t=t>>>0,n=n>>>0, -!i){let u=Math.pow(2,8*n)-1;ce(this,e,t,n,u,0)}let s=1,a=0;for(this[t]=e&255;++a< -n&&(s*=256);)this[t+a]=e/s&255;return t+n},"writeUIntLE");d.prototype.writeUintBE= -d.prototype.writeUIntBE=o(function(e,t,n,i){if(e=+e,t=t>>>0,n=n>>>0,!i){let u=Math. -pow(2,8*n)-1;ce(this,e,t,n,u,0)}let s=n-1,a=1;for(this[t+s]=e&255;--s>=0&&(a*=256);) -this[t+s]=e/a&255;return t+n},"writeUIntBE");d.prototype.writeUint8=d.prototype. -writeUInt8=o(function(e,t,n){return e=+e,t=t>>>0,n||ce(this,e,t,1,255,0),this[t]= -e&255,t+1},"writeUInt8");d.prototype.writeUint16LE=d.prototype.writeUInt16LE=o(function(e,t,n){ -return e=+e,t=t>>>0,n||ce(this,e,t,2,65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2}, -"writeUInt16LE");d.prototype.writeUint16BE=d.prototype.writeUInt16BE=o(function(e,t,n){ -return e=+e,t=t>>>0,n||ce(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2}, -"writeUInt16BE");d.prototype.writeUint32LE=d.prototype.writeUInt32LE=o(function(e,t,n){ -return e=+e,t=t>>>0,n||ce(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>> -16,this[t+1]=e>>>8,this[t]=e&255,t+4},"writeUInt32LE");d.prototype.writeUint32BE= -d.prototype.writeUInt32BE=o(function(e,t,n){return e=+e,t=t>>>0,n||ce(this,e,t,4, -4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+ -4},"writeUInt32BE");function ei(r,e,t,n,i){si(e,n,i,r,t,7);let s=Number(e&BigInt( -4294967295));r[t++]=s,s=s>>8,r[t++]=s,s=s>>8,r[t++]=s,s=s>>8,r[t++]=s;let a=Number( -e>>BigInt(32)&BigInt(4294967295));return r[t++]=a,a=a>>8,r[t++]=a,a=a>>8,r[t++]= -a,a=a>>8,r[t++]=a,t}o(ei,"wrtBigUInt64LE");function ti(r,e,t,n,i){si(e,n,i,r,t,7); -let s=Number(e&BigInt(4294967295));r[t+7]=s,s=s>>8,r[t+6]=s,s=s>>8,r[t+5]=s,s=s>> -8,r[t+4]=s;let a=Number(e>>BigInt(32)&BigInt(4294967295));return r[t+3]=a,a=a>>8, -r[t+2]=a,a=a>>8,r[t+1]=a,a=a>>8,r[t]=a,t+8}o(ti,"wrtBigUInt64BE");d.prototype.writeBigUInt64LE= -Ce(o(function(e,t=0){return ei(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}, -"writeBigUInt64LE"));d.prototype.writeBigUInt64BE=Ce(o(function(e,t=0){return ti( -this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))},"writeBigUInt64BE"));d.prototype. -writeIntLE=o(function(e,t,n,i){if(e=+e,t=t>>>0,!i){let c=Math.pow(2,8*n-1);ce(this, -e,t,n,c-1,-c)}let s=0,a=1,u=0;for(this[t]=e&255;++s>0)-u&255;return t+n},"writeIntLE");d.prototype.writeIntBE= -o(function(e,t,n,i){if(e=+e,t=t>>>0,!i){let c=Math.pow(2,8*n-1);ce(this,e,t,n,c- -1,-c)}let s=n-1,a=1,u=0;for(this[t+s]=e&255;--s>=0&&(a*=256);)e<0&&u===0&&this[t+ -s+1]!==0&&(u=1),this[t+s]=(e/a>>0)-u&255;return t+n},"writeIntBE");d.prototype.writeInt8= -o(function(e,t,n){return e=+e,t=t>>>0,n||ce(this,e,t,1,127,-128),e<0&&(e=255+e+1), -this[t]=e&255,t+1},"writeInt8");d.prototype.writeInt16LE=o(function(e,t,n){return e= -+e,t=t>>>0,n||ce(this,e,t,2,32767,-32768),this[t]=e&255,this[t+1]=e>>>8,t+2},"wr\ -iteInt16LE");d.prototype.writeInt16BE=o(function(e,t,n){return e=+e,t=t>>>0,n||ce( -this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,t+2},"writeInt16BE");d.prototype. -writeInt32LE=o(function(e,t,n){return e=+e,t=t>>>0,n||ce(this,e,t,4,2147483647,-2147483648), -this[t]=e&255,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},"writeInt32\ -LE");d.prototype.writeInt32BE=o(function(e,t,n){return e=+e,t=t>>>0,n||ce(this,e, -t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>> -16,this[t+2]=e>>>8,this[t+3]=e&255,t+4},"writeInt32BE");d.prototype.writeBigInt64LE= -Ce(o(function(e,t=0){return ei(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x\ -7fffffffffffffff"))},"writeBigInt64LE"));d.prototype.writeBigInt64BE=Ce(o(function(e,t=0){ -return ti(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}, -"writeBigInt64BE"));function ri(r,e,t,n,i,s){if(t+n>r.length)throw new RangeError( -"Index out of range");if(t<0)throw new RangeError("Index out of range")}o(ri,"ch\ -eckIEEE754");function ni(r,e,t,n,i){return e=+e,t=t>>>0,i||ri(r,e,t,4,34028234663852886e22, --34028234663852886e22),ke.write(r,e,t,n,23,4),t+4}o(ni,"writeFloat");d.prototype. -writeFloatLE=o(function(e,t,n){return ni(this,e,t,!0,n)},"writeFloatLE");d.prototype. -writeFloatBE=o(function(e,t,n){return ni(this,e,t,!1,n)},"writeFloatBE");function ii(r,e,t,n,i){ -return e=+e,t=t>>>0,i||ri(r,e,t,8,17976931348623157e292,-17976931348623157e292), -ke.write(r,e,t,n,52,8),t+8}o(ii,"writeDouble");d.prototype.writeDoubleLE=o(function(e,t,n){ -return ii(this,e,t,!0,n)},"writeDoubleLE");d.prototype.writeDoubleBE=o(function(e,t,n){ -return ii(this,e,t,!1,n)},"writeDoubleBE");d.prototype.copy=o(function(e,t,n,i){ -if(!d.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0), -!i&&i!==0&&(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i=this.length)throw new RangeError("Index out of ran\ -ge");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this. -length),e.length-t>>0,n=n===void 0?this.length:n>>>0,e||(e=0);let s;if(typeof e== -"number")for(s=t;s2**32?i=Vn(String(t)):typeof t=="\ -bigint"&&(i=String(t),(t>BigInt(2)**BigInt(32)||t<-(BigInt(2)**BigInt(32)))&&(i= -Vn(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);function Vn(r){ -let e="",t=r.length,n=r[0]==="-"?1:0;for(;t>=n+4;t-=3)e=`_${r.slice(t-3,t)}${e}`; -return`${r.slice(0,t)}${e}`}o(Vn,"addNumericalSeparator");function xo(r,e,t){Qe( -e,"offset"),(r[e]===void 0||r[e+t]===void 0)&&st(e,r.length-(t+1))}o(xo,"checkBo\ -unds");function si(r,e,t,n,i,s){if(r>t||r -3?e===0||e===BigInt(0)?u=`>= 0${a} and < 2${a} ** ${(s+1)*8}${a}`:u=`>= -(2${a} \ -** ${(s+1)*8-1}${a}) and < 2 ** ${(s+1)*8-1}${a}`:u=`>= ${e}${a} and <= ${t}${a}`, -new Oe.ERR_OUT_OF_RANGE("value",u,r)}xo(n,i,s)}o(si,"checkIntBI");function Qe(r,e){ -if(typeof r!="number")throw new Oe.ERR_INVALID_ARG_TYPE(e,"number",r)}o(Qe,"vali\ -dateNumber");function st(r,e,t){throw Math.floor(r)!==r?(Qe(r,t),new Oe.ERR_OUT_OF_RANGE( -t||"offset","an integer",r)):e<0?new Oe.ERR_BUFFER_OUT_OF_BOUNDS:new Oe.ERR_OUT_OF_RANGE( -t||"offset",`>= ${t?1:0} and <= ${e}`,r)}o(st,"boundsError");var Ao=/[^+/0-9A-Za-z-_]/g; -function vo(r){if(r=r.split("=")[0],r=r.trim().replace(Ao,""),r.length<2)return""; -for(;r.length%4!==0;)r=r+"=";return r}o(vo,"base64clean");function hr(r,e){e=e|| -1/0;let t,n=r.length,i=null,s=[];for(let a=0;a55295&& -t<57344){if(!i){if(t>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(a+1=== -n){(e-=3)>-1&&s.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&s. -push(239,191,189),i=t;continue}t=(i-55296<<10|t-56320)+65536}else i&&(e-=3)>-1&& -s.push(239,191,189);if(i=null,t<128){if((e-=1)<0)break;s.push(t)}else if(t<2048){ -if((e-=2)<0)break;s.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;s. -push(t>>12|224,t>>6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;s.push( -t>>18|240,t>>12&63|128,t>>6&63|128,t&63|128)}else throw new Error("Invalid code \ -point")}return s}o(hr,"utf8ToBytes");function Co(r){let e=[];for(let t=0;t>8,i=t%256, -s.push(i),s.push(n);return s}o(_o,"utf16leToBytes");function ai(r){return ur.toByteArray( -vo(r))}o(ai,"base64ToBytes");function Rt(r,e,t,n){let i;for(i=0;i=e.length|| -i>=r.length);++i)e[i+t]=r[i];return i}o(Rt,"blitBuffer");function Se(r,e){return r instanceof -e||r!=null&&r.constructor!=null&&r.constructor.name!=null&&r.constructor.name=== -e.name}o(Se,"isInstance");function yr(r){return r!==r}o(yr,"numberIsNaN");var Lo=function(){ -let r="0123456789abcdef",e=new Array(256);for(let t=0;t<16;++t){let n=t*16;for(let i=0;i< -16;++i)e[n+i]=r[t]+r[i]}return e}();function Ce(r){return typeof BigInt>"u"?To:r} -o(Ce,"defineBigIntMethod");function To(){throw new Error("BigInt not supported")} -o(To,"BufferBigIntNotDefined")});var _,L,T,A,m,g,p=ue(()=>{"use strict";_=globalThis,L=globalThis.setImmediate??(r=>setTimeout( -r,0)),T=globalThis.clearImmediate??(r=>clearTimeout(r)),A=globalThis.crypto??{}; -A.subtle??={};m=typeof globalThis.Buffer=="function"&&typeof globalThis.Buffer.allocUnsafe== -"function"?globalThis.Buffer:oi().Buffer,g=globalThis.process??{};g.env??={};try{ -g.nextTick(()=>{})}catch{let e=Promise.resolve();g.nextTick=e.then.bind(e)}});var Te=B((cf,Lr)=>{"use strict";p();var We=typeof Reflect=="object"?Reflect:null, -Ii=We&&typeof We.apply=="function"?We.apply:o(function(e,t,n){return Function.prototype. -apply.call(e,t,n)},"ReflectApply"),Ot;We&&typeof We.ownKeys=="function"?Ot=We.ownKeys: -Object.getOwnPropertySymbols?Ot=o(function(e){return Object.getOwnPropertyNames( -e).concat(Object.getOwnPropertySymbols(e))},"ReflectOwnKeys"):Ot=o(function(e){return Object. -getOwnPropertyNames(e)},"ReflectOwnKeys");function Cu(r){console&&console.warn&& -console.warn(r)}o(Cu,"ProcessEmitWarning");var Bi=Number.isNaN||o(function(e){return e!== -e},"NumberIsNaN");function k(){k.init.call(this)}o(k,"EventEmitter");Lr.exports= -k;Lr.exports.once=Uu;k.EventEmitter=k;k.prototype._events=void 0;k.prototype._eventsCount= -0;k.prototype._maxListeners=void 0;var Pi=10;function kt(r){if(typeof r!="functi\ -on")throw new TypeError('The "listener" argument must be of type Function. Recei\ -ved type '+typeof r)}o(kt,"checkListener");Object.defineProperty(k,"defaultMaxLi\ -steners",{enumerable:!0,get:o(function(){return Pi},"get"),set:o(function(r){if(typeof r!= -"number"||r<0||Bi(r))throw new RangeError('The value of "defaultMaxListeners" is\ - out of range. It must be a non-negative number. Received '+r+".");Pi=r},"set")}); -k.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this). -_events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners= -this._maxListeners||void 0};k.prototype.setMaxListeners=o(function(e){if(typeof e!= -"number"||e<0||Bi(e))throw new RangeError('The value of "n" is out of range. It \ -must be a non-negative number. Received '+e+".");return this._maxListeners=e,this}, -"setMaxListeners");function Ri(r){return r._maxListeners===void 0?k.defaultMaxListeners: -r._maxListeners}o(Ri,"_getMaxListeners");k.prototype.getMaxListeners=o(function(){ -return Ri(this)},"getMaxListeners");k.prototype.emit=o(function(e){for(var t=[], -n=1;n -0&&(a=t[0]),a instanceof Error)throw a;var u=new Error("Unhandled error."+(a?" ("+ -a.message+")":""));throw u.context=a,u}var c=s[e];if(c===void 0)return!1;if(typeof c== -"function")Ii(c,this,t);else for(var l=c.length,h=qi(c,l),n=0;n0&&a.length>i&&!a.warned){a.warned=!0;var u=new Error("Po\ -ssible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners a\ -dded. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExce\ -ededWarning",u.emitter=r,u.type=e,u.count=a.length,Cu(u)}return r}o(Ni,"_addList\ -ener");k.prototype.addListener=o(function(e,t){return Ni(this,e,t,!1)},"addListe\ -ner");k.prototype.on=k.prototype.addListener;k.prototype.prependListener=o(function(e,t){ -return Ni(this,e,t,!0)},"prependListener");function _u(){if(!this.fired)return this. -target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0? -this.listener.call(this.target):this.listener.apply(this.target,arguments)}o(_u, -"onceWrapper");function Mi(r,e,t){var n={fired:!1,wrapFn:void 0,target:r,type:e, -listener:t},i=_u.bind(n);return i.listener=t,n.wrapFn=i,i}o(Mi,"_onceWrap");k.prototype. -once=o(function(e,t){return kt(t),this.on(e,Mi(this,e,t)),this},"once");k.prototype. -prependOnceListener=o(function(e,t){return kt(t),this.prependListener(e,Mi(this, -e,t)),this},"prependOnceListener");k.prototype.removeListener=o(function(e,t){var n, -i,s,a,u;if(kt(t),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this; -if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null): -(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if(typeof n!= -"function"){for(s=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){u=n[a]. -listener,s=a;break}if(s<0)return this;s===0?n.shift():Lu(n,s),n.length===1&&(i[e]= -n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,u||t)}return this}, -"removeListener");k.prototype.off=k.prototype.removeListener;k.prototype.removeAllListeners= -o(function(e){var t,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener=== -void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount= -0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]), -this;if(arguments.length===0){var s=Object.keys(n),a;for(i=0;i=0;i--)this.removeListener(e,t[i]);return this},"removeAllListeners");function Fi(r,e,t){ -var n=r._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i== -"function"?t?[i.listener||i]:[i]:t?Tu(i):qi(i,i.length)}o(Fi,"_listeners");k.prototype. -listeners=o(function(e){return Fi(this,e,!0)},"listeners");k.prototype.rawListeners= -o(function(e){return Fi(this,e,!1)},"rawListeners");k.listenerCount=function(r,e){ -return typeof r.listenerCount=="function"?r.listenerCount(e):Di.call(r,e)};k.prototype. -listenerCount=Di;function Di(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t== -"function")return 1;if(t!==void 0)return t.length}return 0}o(Di,"listenerCount"); -k.prototype.eventNames=o(function(){return this._eventsCount>0?Ot(this._events): -[]},"eventNames");function qi(r,e){for(var t=new Array(e),n=0;nPu});var Pu,lt=ue(()=>{"use strict";p();Pu={}});function ht(r){let e=1779033703,t=3144134277,n=1013904242,i=2773480762,s=1359893119, -a=2600822924,u=528734635,c=1541459225,l=0,h=0,f=[1116352408,1899447441,3049323471, -3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278, -1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078, -604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808, -3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372, -1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800, -3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556, -883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452, -2361852424,2428436474,2756734187,3204031479,3329325298],y=o((E,S)=>E>>>S|E<<32-S, -"rrot"),w=new Uint32Array(64),b=new Uint8Array(64),U=o(()=>{for(let M=0,$=0;M<16;M++, -$+=4)w[M]=b[$]<<24|b[$+1]<<16|b[$+2]<<8|b[$+3];for(let M=16;M<64;M++){let $=y(w[M- -15],7)^y(w[M-15],18)^w[M-15]>>>3,j=y(w[M-2],17)^y(w[M-2],19)^w[M-2]>>>10;w[M]=w[M- -16]+$+w[M-7]+j|0}let E=e,S=t,x=n,N=i,P=s,F=a,Q=u,Y=c;for(let M=0;M<64;M++){let $=y( -P,6)^y(P,11)^y(P,25),j=P&F^~P&Q,H=Y+$+j+f[M]+w[M]|0,W=y(E,2)^y(E,13)^y(E,22),G=E& -S^E&x^S&x,D=W+G|0;Y=Q,Q=F,F=P,P=N+H|0,N=x,x=S,S=E,E=H+D|0}e=e+E|0,t=t+S|0,n=n+x| -0,i=i+N|0,s=s+P|0,a=a+F|0,u=u+Q|0,c=c+Y|0,h=0},"process"),v=o(E=>{typeof E=="str\ -ing"&&(E=new TextEncoder().encode(E));for(let S=0;S{if(b[h++]=128,h==64&&U(),h+8>64){for(;h<64;) -b[h++]=0;U()}for(;h<58;)b[h++]=0;let E=l*8;b[h++]=E/1099511627776&255,b[h++]=E/4294967296& -255,b[h++]=E>>>24,b[h++]=E>>>16&255,b[h++]=E>>>8&255,b[h++]=E&255,U();let S=new Uint8Array( -32);return S[0]=e>>>24,S[1]=e>>>16&255,S[2]=e>>>8&255,S[3]=e&255,S[4]=t>>>24,S[5]= -t>>>16&255,S[6]=t>>>8&255,S[7]=t&255,S[8]=n>>>24,S[9]=n>>>16&255,S[10]=n>>>8&255, -S[11]=n&255,S[12]=i>>>24,S[13]=i>>>16&255,S[14]=i>>>8&255,S[15]=i&255,S[16]=s>>> -24,S[17]=s>>>16&255,S[18]=s>>>8&255,S[19]=s&255,S[20]=a>>>24,S[21]=a>>>16&255,S[22]= -a>>>8&255,S[23]=a&255,S[24]=u>>>24,S[25]=u>>>16&255,S[26]=u>>>8&255,S[27]=u&255, -S[28]=c>>>24,S[29]=c>>>16&255,S[30]=c>>>8&255,S[31]=c&255,S},"digest");return r=== -void 0?{add:v,digest:C}:(v(r),C())}var ki=ue(()=>{"use strict";p();o(ht,"sha256")});var ft,Qi=ue(()=>{"use strict";p();ft=class r{static{o(this,"Md5")}static hashByteArray(e,t=!1){ -return this.onePassHasher.start().appendByteArray(e).end(t)}static hashStr(e,t=!1){ -return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){ -return this.onePassHasher.start().appendAsciiStr(e).end(t)}static stateIdentity=new Int32Array( -[1732584193,-271733879,-1732584194,271733878]);static buffer32Identity=new Int32Array( -[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);static hexChars="0123456789abcdef";static hexOut=[];static onePassHasher=new r;static _hex(e){ -let t=r.hexChars,n=r.hexOut,i,s,a,u;for(u=0;u<4;u+=1)for(s=u*8,i=e[u],a=0;a<8;a+= -2)n[s+1+a]=t.charAt(i&15),i>>>=4,n[s+0+a]=t.charAt(i&15),i>>>=4;return n.join("")}static _md5cycle(e,t){ -let n=e[0],i=e[1],s=e[2],a=e[3];n+=(i&s|~i&a)+t[0]-680876936|0,n=(n<<7|n>>>25)+i| -0,a+=(n&i|~n&s)+t[1]-389564586|0,a=(a<<12|a>>>20)+n|0,s+=(a&n|~a&i)+t[2]+606105819| -0,s=(s<<17|s>>>15)+a|0,i+=(s&a|~s&n)+t[3]-1044525330|0,i=(i<<22|i>>>10)+s|0,n+=(i& -s|~i&a)+t[4]-176418897|0,n=(n<<7|n>>>25)+i|0,a+=(n&i|~n&s)+t[5]+1200080426|0,a=(a<< -12|a>>>20)+n|0,s+=(a&n|~a&i)+t[6]-1473231341|0,s=(s<<17|s>>>15)+a|0,i+=(s&a|~s&n)+ -t[7]-45705983|0,i=(i<<22|i>>>10)+s|0,n+=(i&s|~i&a)+t[8]+1770035416|0,n=(n<<7|n>>> -25)+i|0,a+=(n&i|~n&s)+t[9]-1958414417|0,a=(a<<12|a>>>20)+n|0,s+=(a&n|~a&i)+t[10]- -42063|0,s=(s<<17|s>>>15)+a|0,i+=(s&a|~s&n)+t[11]-1990404162|0,i=(i<<22|i>>>10)+s| -0,n+=(i&s|~i&a)+t[12]+1804603682|0,n=(n<<7|n>>>25)+i|0,a+=(n&i|~n&s)+t[13]-40341101| -0,a=(a<<12|a>>>20)+n|0,s+=(a&n|~a&i)+t[14]-1502002290|0,s=(s<<17|s>>>15)+a|0,i+= -(s&a|~s&n)+t[15]+1236535329|0,i=(i<<22|i>>>10)+s|0,n+=(i&a|s&~a)+t[1]-165796510| -0,n=(n<<5|n>>>27)+i|0,a+=(n&s|i&~s)+t[6]-1069501632|0,a=(a<<9|a>>>23)+n|0,s+=(a& -i|n&~i)+t[11]+643717713|0,s=(s<<14|s>>>18)+a|0,i+=(s&n|a&~n)+t[0]-373897302|0,i= -(i<<20|i>>>12)+s|0,n+=(i&a|s&~a)+t[5]-701558691|0,n=(n<<5|n>>>27)+i|0,a+=(n&s|i& -~s)+t[10]+38016083|0,a=(a<<9|a>>>23)+n|0,s+=(a&i|n&~i)+t[15]-660478335|0,s=(s<<14| -s>>>18)+a|0,i+=(s&n|a&~n)+t[4]-405537848|0,i=(i<<20|i>>>12)+s|0,n+=(i&a|s&~a)+t[9]+ -568446438|0,n=(n<<5|n>>>27)+i|0,a+=(n&s|i&~s)+t[14]-1019803690|0,a=(a<<9|a>>>23)+ -n|0,s+=(a&i|n&~i)+t[3]-187363961|0,s=(s<<14|s>>>18)+a|0,i+=(s&n|a&~n)+t[8]+1163531501| -0,i=(i<<20|i>>>12)+s|0,n+=(i&a|s&~a)+t[13]-1444681467|0,n=(n<<5|n>>>27)+i|0,a+=(n& -s|i&~s)+t[2]-51403784|0,a=(a<<9|a>>>23)+n|0,s+=(a&i|n&~i)+t[7]+1735328473|0,s=(s<< -14|s>>>18)+a|0,i+=(s&n|a&~n)+t[12]-1926607734|0,i=(i<<20|i>>>12)+s|0,n+=(i^s^a)+ -t[5]-378558|0,n=(n<<4|n>>>28)+i|0,a+=(n^i^s)+t[8]-2022574463|0,a=(a<<11|a>>>21)+ -n|0,s+=(a^n^i)+t[11]+1839030562|0,s=(s<<16|s>>>16)+a|0,i+=(s^a^n)+t[14]-35309556| -0,i=(i<<23|i>>>9)+s|0,n+=(i^s^a)+t[1]-1530992060|0,n=(n<<4|n>>>28)+i|0,a+=(n^i^s)+ -t[4]+1272893353|0,a=(a<<11|a>>>21)+n|0,s+=(a^n^i)+t[7]-155497632|0,s=(s<<16|s>>> -16)+a|0,i+=(s^a^n)+t[10]-1094730640|0,i=(i<<23|i>>>9)+s|0,n+=(i^s^a)+t[13]+681279174| -0,n=(n<<4|n>>>28)+i|0,a+=(n^i^s)+t[0]-358537222|0,a=(a<<11|a>>>21)+n|0,s+=(a^n^i)+ -t[3]-722521979|0,s=(s<<16|s>>>16)+a|0,i+=(s^a^n)+t[6]+76029189|0,i=(i<<23|i>>>9)+ -s|0,n+=(i^s^a)+t[9]-640364487|0,n=(n<<4|n>>>28)+i|0,a+=(n^i^s)+t[12]-421815835|0, -a=(a<<11|a>>>21)+n|0,s+=(a^n^i)+t[15]+530742520|0,s=(s<<16|s>>>16)+a|0,i+=(s^a^n)+ -t[2]-995338651|0,i=(i<<23|i>>>9)+s|0,n+=(s^(i|~a))+t[0]-198630844|0,n=(n<<6|n>>> -26)+i|0,a+=(i^(n|~s))+t[7]+1126891415|0,a=(a<<10|a>>>22)+n|0,s+=(n^(a|~i))+t[14]- -1416354905|0,s=(s<<15|s>>>17)+a|0,i+=(a^(s|~n))+t[5]-57434055|0,i=(i<<21|i>>>11)+ -s|0,n+=(s^(i|~a))+t[12]+1700485571|0,n=(n<<6|n>>>26)+i|0,a+=(i^(n|~s))+t[3]-1894986606| -0,a=(a<<10|a>>>22)+n|0,s+=(n^(a|~i))+t[10]-1051523|0,s=(s<<15|s>>>17)+a|0,i+=(a^ -(s|~n))+t[1]-2054922799|0,i=(i<<21|i>>>11)+s|0,n+=(s^(i|~a))+t[8]+1873313359|0,n= -(n<<6|n>>>26)+i|0,a+=(i^(n|~s))+t[15]-30611744|0,a=(a<<10|a>>>22)+n|0,s+=(n^(a|~i))+ -t[6]-1560198380|0,s=(s<<15|s>>>17)+a|0,i+=(a^(s|~n))+t[13]+1309151649|0,i=(i<<21| -i>>>11)+s|0,n+=(s^(i|~a))+t[4]-145523070|0,n=(n<<6|n>>>26)+i|0,a+=(i^(n|~s))+t[11]- -1120210379|0,a=(a<<10|a>>>22)+n|0,s+=(n^(a|~i))+t[2]+718787259|0,s=(s<<15|s>>>17)+ -a|0,i+=(a^(s|~n))+t[9]-343485551|0,i=(i<<21|i>>>11)+s|0,e[0]=n+e[0]|0,e[1]=i+e[1]| -0,e[2]=s+e[2]|0,e[3]=a+e[3]|0}_dataLength=0;_bufferLength=0;_state=new Int32Array( -4);_buffer=new ArrayBuffer(68);_buffer8;_buffer32;constructor(){this._buffer8=new Uint8Array( -this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}start(){ -return this._dataLength=0,this._bufferLength=0,this._state.set(r.stateIdentity), -this}appendStr(e){let t=this._buffer8,n=this._buffer32,i=this._bufferLength,s,a; -for(a=0;a>>6)+192,t[i++]=s&63|128;else if(s<55296||s>56319)t[i++]=(s>>>12)+224,t[i++]= -s>>>6&63|128,t[i++]=s&63|128;else{if(s=(s-55296)*1024+(e.charCodeAt(++a)-56320)+ -65536,s>1114111)throw new Error("Unicode standard supports code points up to U+1\ -0FFFF");t[i++]=(s>>>18)+240,t[i++]=s>>>12&63|128,t[i++]=s>>>6&63|128,t[i++]=s&63| -128}i>=64&&(this._dataLength+=64,r._md5cycle(this._state,n),i-=64,n[0]=n[16])}return this. -_bufferLength=i,this}appendAsciiStr(e){let t=this._buffer8,n=this._buffer32,i=this. -_bufferLength,s,a=0;for(;;){for(s=Math.min(e.length-a,64-i);s--;)t[i++]=e.charCodeAt( -a++);if(i<64)break;this._dataLength+=64,r._md5cycle(this._state,n),i=0}return this. -_bufferLength=i,this}appendByteArray(e){let t=this._buffer8,n=this._buffer32,i=this. -_bufferLength,s,a=0;for(;;){for(s=Math.min(e.length-a,64-i);s--;)t[i++]=e[a++];if(i< -64)break;this._dataLength+=64,r._md5cycle(this._state,n),i=0}return this._bufferLength= -i,this}getState(){let e=this._state;return{buffer:String.fromCharCode.apply(null, -Array.from(this._buffer8)),buflen:this._bufferLength,length:this._dataLength,state:[ -e[0],e[1],e[2],e[3]]}}setState(e){let t=e.buffer,n=e.state,i=this._state,s;for(this. -_dataLength=e.length,this._bufferLength=e.buflen,i[0]=n[0],i[1]=n[1],i[2]=n[2],i[3]= -n[3],s=0;s>2)+1;this._dataLength+=t;let a=this._dataLength* -8;if(n[t]=128,n[t+1]=n[t+2]=n[t+3]=0,i.set(r.buffer32Identity.subarray(s),s),t>55&& -(r._md5cycle(this._state,i),i.set(r.buffer32Identity)),a<=4294967295)i[14]=a;else{ -let u=a.toString(16).match(/(.*?)(.{0,8})$/);if(u===null)return;let c=parseInt(u[2], -16),l=parseInt(u[1],16)||0;i[14]=c,i[15]=l}return r._md5cycle(this._state,i),e?this. -_state:r._hex(this._state)}}});var Tr={};de(Tr,{createHash:()=>Ru,createHmac:()=>Nu,randomBytes:()=>Bu});function Bu(r){ -return A.getRandomValues(m.alloc(r))}function Ru(r){if(r==="sha256")return{update:o( -function(e){return{digest:o(function(){return m.from(ht(e))},"digest")}},"update")}; -if(r==="md5")return{update:o(function(e){return{digest:o(function(){return typeof e== -"string"?ft.hashStr(e):ft.hashByteArray(e)},"digest")}},"update")};throw new Error( -`Hash type '${r}' not supported`)}function Nu(r,e){if(r!=="sha256")throw new Error( -`Only sha256 is supported (requested: '${r}')`);return{update:o(function(t){return{ -digest:o(function(){typeof e=="string"&&(e=new TextEncoder().encode(e)),typeof t== -"string"&&(t=new TextEncoder().encode(t));let n=e.length;if(n>64)e=ht(e);else if(n< -64){let c=new Uint8Array(64);c.set(e),e=c}let i=new Uint8Array(64),s=new Uint8Array( -64);for(let c=0;c<64;c++)i[c]=54^e[c],s[c]=92^e[c];let a=new Uint8Array(t.length+ -64);a.set(i,0),a.set(t,64);let u=new Uint8Array(96);return u.set(s,0),u.set(ht(a), -64),m.from(ht(u))},"digest")}},"update")}}var Ur=ue(()=>{"use strict";p();ki();Qi(); -o(Bu,"randomBytes");o(Ru,"createHash");o(Nu,"createHmac")});var Pr=B($i=>{"use strict";p();$i.parse=function(r,e){return new Ir(r,e).parse()}; -var Ir=class r{static{o(this,"ArrayParser")}constructor(e,t){this.source=e,this. -transform=t||Mu,this.position=0,this.entries=[],this.recorded=[],this.dimension= -0}isEof(){return this.position>=this.source.length}nextCharacter(){var e=this.source[this. -position++];return e==="\\"?{value:this.source[this.position++],escaped:!0}:{value:e, -escaped:!1}}record(e){this.recorded.push(e)}newEntry(e){var t;(this.recorded.length> -0||e)&&(t=this.recorded.join(""),t==="NULL"&&!e&&(t=null),t!==null&&(t=this.transform( -t)),this.entries.push(t),this.recorded=[])}consumeDimensions(){if(this.source[0]=== -"[")for(;!this.isEof();){var e=this.nextCharacter();if(e.value==="=")break}}parse(e){ -var t,n,i;for(this.consumeDimensions();!this.isEof();)if(t=this.nextCharacter(), -t.value==="{"&&!i)this.dimension++,this.dimension>1&&(n=new r(this.source.substr( -this.position-1),this.transform),this.entries.push(n.parse(!0)),this.position+=n. -position-2);else if(t.value==="}"&&!i){if(this.dimension--,!this.dimension&&(this. -newEntry(),e))return this.entries}else t.value==='"'&&!t.escaped?(i&&this.newEntry( -!0),i=!i):t.value===","&&!i?this.newEntry():this.record(t.value);if(this.dimension!== -0)throw new Error("array dimension not balanced");return this.entries}};function Mu(r){ -return r}o(Mu,"identity")});var Br=B((_f,ji)=>{p();var Fu=Pr();ji.exports={create:o(function(r,e){return{parse:o( -function(){return Fu.parse(r,e)},"parse")}},"create")}});var Wi=B((Uf,Ki)=>{"use strict";p();var Du=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/, -qu=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,Ou=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,ku=/^-?infinity$/; -Ki.exports=o(function(e){if(ku.test(e))return Number(e.replace("i","I"));var t=Du. -exec(e);if(!t)return Qu(e)||null;var n=!!t[8],i=parseInt(t[1],10);n&&(i=Hi(i));var s=parseInt( -t[2],10)-1,a=t[3],u=parseInt(t[4],10),c=parseInt(t[5],10),l=parseInt(t[6],10),h=t[7]; -h=h?1e3*parseFloat(h):0;var f,y=$u(e);return y!=null?(f=new Date(Date.UTC(i,s,a, -u,c,l,h)),Rr(i)&&f.setUTCFullYear(i),y!==0&&f.setTime(f.getTime()-y)):(f=new Date( -i,s,a,u,c,l,h),Rr(i)&&f.setFullYear(i)),f},"parseDate");function Qu(r){var e=qu. -exec(r);if(e){var t=parseInt(e[1],10),n=!!e[4];n&&(t=Hi(t));var i=parseInt(e[2], -10)-1,s=e[3],a=new Date(t,i,s);return Rr(t)&&a.setFullYear(t),a}}o(Qu,"getDate"); -function $u(r){if(r.endsWith("+00"))return 0;var e=Ou.exec(r.split(" ")[1]);if(e){ -var t=e[1];if(t==="Z")return 0;var n=t==="-"?-1:1,i=parseInt(e[2],10)*3600+parseInt( -e[3]||0,10)*60+parseInt(e[4]||0,10);return i*n*1e3}}o($u,"timeZoneOffset");function Hi(r){ -return-(r-1)}o(Hi,"bcYearToNegativeYear");function Rr(r){return r>=0&&r<100}o(Rr, -"is0To99")});var Vi=B((Bf,Gi)=>{p();Gi.exports=Hu;var ju=Object.prototype.hasOwnProperty;function Hu(r){ -for(var e=1;e{"use strict";p();var Ku=Vi();Ji.exports=Ge;function Ge(r){if(!(this instanceof -Ge))return new Ge(r);Ku(this,nc(r))}o(Ge,"PostgresInterval");var Wu=["seconds","\ -minutes","hours","days","months","years"];Ge.prototype.toPostgres=function(){var r=Wu. -filter(this.hasOwnProperty,this);return this.milliseconds&&r.indexOf("seconds")< -0&&r.push("seconds"),r.length===0?"0":r.map(function(e){var t=this[e]||0;return e=== -"seconds"&&this.milliseconds&&(t=(t+this.milliseconds/1e3).toFixed(6).replace(/\.?0+$/, -"")),t+" "+e},this).join(" ")};var Gu={years:"Y",months:"M",days:"D",hours:"H",minutes:"\ -M",seconds:"S"},Vu=["years","months","days"],zu=["hours","minutes","seconds"];Ge. -prototype.toISOString=Ge.prototype.toISO=function(){var r=Vu.map(t,this).join(""), -e=zu.map(t,this).join("");return"P"+r+"T"+e;function t(n){var i=this[n]||0;return n=== -"seconds"&&this.milliseconds&&(i=(i+this.milliseconds/1e3).toFixed(6).replace(/0+$/, -"")),i+Gu[n]}};var Nr="([+-]?\\d+)",Ju=Nr+"\\s+years?",Yu=Nr+"\\s+mons?",Zu=Nr+"\ -\\s+days?",Xu="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",ec=new RegExp([ -Ju,Yu,Zu,Xu].map(function(r){return"("+r+")?"}).join("\\s*")),zi={years:2,months:4, -days:6,hours:9,minutes:10,seconds:11,milliseconds:12},tc=["hours","minutes","sec\ -onds","milliseconds"];function rc(r){var e=r+"000000".slice(r.length);return parseInt( -e,10)/1e3}o(rc,"parseMilliseconds");function nc(r){if(!r)return{};var e=ec.exec( -r),t=e[8]==="-";return Object.keys(zi).reduce(function(n,i){var s=zi[i],a=e[s];return!a|| -(a=i==="milliseconds"?rc(a):parseInt(a,10),!a)||(t&&~tc.indexOf(i)&&(a*=-1),n[i]= -a),n},{})}o(nc,"parse")});var Xi=B((qf,Zi)=>{"use strict";p();Zi.exports=o(function(e){if(/^\\x/.test(e))return new m( -e.substr(2),"hex");for(var t="",n=0;n{p();var dt=Pr(),pt=Br(),Qt=Wi(),ts=Yi(),rs=Xi();function $t(r){ -return o(function(t){return t===null?t:r(t)},"nullAllowed")}o($t,"allowNull");function ns(r){ -return r===null?r:r==="TRUE"||r==="t"||r==="true"||r==="y"||r==="yes"||r==="on"|| -r==="1"}o(ns,"parseBool");function ic(r){return r?dt.parse(r,ns):null}o(ic,"pars\ -eBoolArray");function sc(r){return parseInt(r,10)}o(sc,"parseBaseTenInt");function Mr(r){ -return r?dt.parse(r,$t(sc)):null}o(Mr,"parseIntegerArray");function ac(r){return r? -dt.parse(r,$t(function(e){return is(e).trim()})):null}o(ac,"parseBigIntegerArray"); -var oc=o(function(r){if(!r)return null;var e=pt.create(r,function(t){return t!== -null&&(t=Or(t)),t});return e.parse()},"parsePointArray"),Fr=o(function(r){if(!r) -return null;var e=pt.create(r,function(t){return t!==null&&(t=parseFloat(t)),t}); -return e.parse()},"parseFloatArray"),ye=o(function(r){if(!r)return null;var e=pt. -create(r);return e.parse()},"parseStringArray"),Dr=o(function(r){if(!r)return null; -var e=pt.create(r,function(t){return t!==null&&(t=Qt(t)),t});return e.parse()},"\ -parseDateArray"),uc=o(function(r){if(!r)return null;var e=pt.create(r,function(t){ -return t!==null&&(t=ts(t)),t});return e.parse()},"parseIntervalArray"),cc=o(function(r){ -return r?dt.parse(r,$t(rs)):null},"parseByteAArray"),qr=o(function(r){return parseInt( -r,10)},"parseInteger"),is=o(function(r){var e=String(r);return/^\d+$/.test(e)?e: -r},"parseBigInteger"),es=o(function(r){return r?dt.parse(r,$t(JSON.parse)):null}, -"parseJsonArray"),Or=o(function(r){return r[0]!=="("?null:(r=r.substring(1,r.length- -1).split(","),{x:parseFloat(r[0]),y:parseFloat(r[1])})},"parsePoint"),lc=o(function(r){ -if(r[0]!=="<"&&r[1]!=="(")return null;for(var e="(",t="",n=!1,i=2;i{"use strict";p();var le=1e6;function fc(r){var e=r.readInt32BE( -0),t=r.readUInt32BE(4),n="";e<0&&(e=~e+(t===0),t=~t+1>>>0,n="-");var i="",s,a,u, -c,l,h;{if(s=e%le,e=e/le>>>0,a=4294967296*s+t,t=a/le>>>0,u=""+(a-le*t),t===0&&e=== -0)return n+u+i;for(c="",l=6-u.length,h=0;h>> -0,a=4294967296*s+t,t=a/le>>>0,u=""+(a-le*t),t===0&&e===0)return n+u+i;for(c="",l= -6-u.length,h=0;h>>0,a=4294967296*s+t,t=a/ -le>>>0,u=""+(a-le*t),t===0&&e===0)return n+u+i;for(c="",l=6-u.length,h=0;h{p();var dc=us(),V=o(function(r,e,t,n,i){t=t||0,n=n||!1,i=i||function(w,b,U){ -return w*Math.pow(2,U)+b};var s=t>>3,a=o(function(w){return n?~w&255:w},"inv"),u=255, -c=8-t%8;e>t%8);var l=0;t%8+e>=8&&(l=i(0,a(r[s])& -u,c));for(var h=e+t>>3,f=s+1;f0&& -(l=i(l,a(r[h])>>8-y,y)),l},"parseBits"),hs=o(function(r,e,t){var n=Math.pow(2,t- -1)-1,i=V(r,1),s=V(r,t,1);if(s===0)return 0;var a=1,u=o(function(l,h,f){l===0&&(l= -1);for(var y=1;y<=f;y++)a/=2,(h&1<0&&(l+=a);return l},"parsePrecisionBits"), -c=V(r,e,t+1,!1,u);return s==Math.pow(2,t+1)-1?c===0?i===0?1/0:-1/0:NaN:(i===0?1: --1)*Math.pow(2,s-n)*c},"parseFloatFromBits"),pc=o(function(r){return V(r,1)==1?-1* -(V(r,15,1,!0)+1):V(r,15,1)},"parseInt16"),cs=o(function(r){return V(r,1)==1?-1*(V( -r,31,1,!0)+1):V(r,31,1)},"parseInt32"),yc=o(function(r){return hs(r,23,8)},"pars\ -eFloat32"),mc=o(function(r){return hs(r,52,11)},"parseFloat64"),wc=o(function(r){ -var e=V(r,16,32);if(e==49152)return NaN;for(var t=Math.pow(1e4,V(r,16,16)),n=0,i=[], -s=V(r,16),a=0;a>3,(i+=h<<3)>>3), -f;console.log("ERROR: ElementType not implemented: "+l)},"parseElement"),c=o(function(l,h){ -var f=[],y;if(l.length>1){var w=l.shift();for(y=0;y0},"parseBool"),Ec=o(function(r){r(20,dc),r(21,pc),r(23,cs),r(26, -cs),r(1700,wc),r(700,yc),r(701,mc),r(16,Sc),r(1114,ls.bind(null,!1)),r(1184,ls.bind( -null,!0)),r(1e3,yt),r(1007,yt),r(1016,yt),r(1008,yt),r(1009,yt),r(25,gc)},"init"); -fs.exports={init:Ec}});var ys=B((Jf,ps)=>{p();ps.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23, -REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194, -SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703, -TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033, -BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186, -TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203, -REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220, -PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642, -REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var gt=B(wt=>{p();var bc=as(),xc=ds(),Ac=Br(),vc=ys();wt.getTypeParser=Cc;wt.setTypeParser= -_c;wt.arrayParser=Ac;wt.builtins=vc;var mt={text:{},binary:{}};function ms(r){return String( -r)}o(ms,"noParse");function Cc(r,e){return e=e||"text",mt[e]&&mt[e][r]||ms}o(Cc, -"getTypeParser");function _c(r,e,t){typeof e=="function"&&(t=e,e="text"),mt[e][r]= -t}o(_c,"setTypeParser");bc.init(function(r,e){mt.text[r]=e});xc.init(function(r,e){ -mt.binary[r]=e})});var St=B((td,kr)=>{"use strict";p();kr.exports={host:"localhost",user:g.platform=== -"win32"?g.env.USERNAME:g.env.USER,database:void 0,password:null,connectionString:void 0, -port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:3e4,client_encoding:"",ssl:!1, -application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1, -statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1, -connect_timeout:0,keepalives:1,keepalives_idle:0};var Ve=gt(),Lc=Ve.getTypeParser( -20,"text"),Tc=Ve.getTypeParser(1016,"text");kr.exports.__defineSetter__("parseIn\ -t8",function(r){Ve.setTypeParser(20,"text",r?Ve.getTypeParser(23,"text"):Lc),Ve. -setTypeParser(1016,"text",r?Ve.getTypeParser(1007,"text"):Tc)})});var Et=B((nd,gs)=>{"use strict";p();var Uc=(Ur(),X(Tr)),Ic=St();function Pc(r){var e=r. -replace(/\\/g,"\\\\").replace(/"/g,'\\"');return'"'+e+'"'}o(Pc,"escapeElement"); -function ws(r){for(var e="{",t=0;t0&&(e=e+","),r[t]===null||typeof r[t]> -"u"?e=e+"NULL":Array.isArray(r[t])?e=e+ws(r[t]):r[t]instanceof m?e+="\\\\x"+r[t]. -toString("hex"):e+=Pc(jt(r[t]));return e=e+"}",e}o(ws,"arrayString");var jt=o(function(r,e){ -if(r==null)return null;if(r instanceof m)return r;if(ArrayBuffer.isView(r)){var t=m. -from(r.buffer,r.byteOffset,r.byteLength);return t.length===r.byteLength?t:t.slice( -r.byteOffset,r.byteOffset+r.byteLength)}return r instanceof Date?Ic.parseInputDatesAsUTC? -Nc(r):Rc(r):Array.isArray(r)?ws(r):typeof r=="object"?Bc(r,e):r.toString()},"pre\ -pareValue");function Bc(r,e){if(r&&typeof r.toPostgres=="function"){if(e=e||[],e. -indexOf(r)!==-1)throw new Error('circular reference detected while preparing "'+ -r+'" for query');return e.push(r),jt(r.toPostgres(jt),e)}return JSON.stringify(r)} -o(Bc,"prepareObject");function ae(r,e){for(r=""+r;r.length{"use strict";p();var $r=(Ur(),X(Tr));function Dc(r){if(r.indexOf( -"SCRAM-SHA-256")===-1)throw new Error("SASL: Only mechanism SCRAM-SHA-256 is cur\ -rently supported");let e=$r.randomBytes(18).toString("base64");return{mechanism:"\ -SCRAM-SHA-256",clientNonce:e,response:"n,,n=*,r="+e,message:"SASLInitialResponse"}} -o(Dc,"startSession");function qc(r,e,t){if(r.message!=="SASLInitialResponse")throw new Error( -"SASL: Last message was not SASLInitialResponse");if(typeof e!="string")throw new Error( -"SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(typeof t!= -"string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a\ - string");let n=Qc(t);if(n.nonce.startsWith(r.clientNonce)){if(n.nonce.length=== -r.clientNonce.length)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server n\ -once is too short")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serv\ -er nonce does not start with client nonce");var i=m.from(n.salt,"base64"),s=Hc(e, -i,n.iteration),a=ze(s,"Client Key"),u=jc(a),c="n=*,r="+r.clientNonce,l="r="+n.nonce+ -",s="+n.salt+",i="+n.iteration,h="c=biws,r="+n.nonce,f=c+","+l+","+h,y=ze(u,f),w=bs( -a,y),b=w.toString("base64"),U=ze(s,"Server Key"),v=ze(U,f);r.message="SASLRespon\ -se",r.serverSignature=v.toString("base64"),r.response=h+",p="+b}o(qc,"continueSe\ -ssion");function Oc(r,e){if(r.message!=="SASLResponse")throw new Error("SASL: La\ -st message was not SASLResponse");if(typeof e!="string")throw new Error("SASL: S\ -CRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:t}=$c( -e);if(t!==r.serverSignature)throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: s\ -erver signature does not match")}o(Oc,"finalizeSession");function kc(r){if(typeof r!= -"string")throw new TypeError("SASL: text must be a string");return r.split("").map( -(e,t)=>r.charCodeAt(t)).every(e=>e>=33&&e<=43||e>=45&&e<=126)}o(kc,"isPrintableC\ -hars");function Ss(r){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/. -test(r)}o(Ss,"isBase64");function Es(r){if(typeof r!="string")throw new TypeError( -"SASL: attribute pairs text must be a string");return new Map(r.split(",").map(e=>{ -if(!/^.=/.test(e))throw new Error("SASL: Invalid attribute pair entry");let t=e[0], -n=e.substring(2);return[t,n]}))}o(Es,"parseAttributePairs");function Qc(r){let e=Es( -r),t=e.get("r");if(t){if(!kc(t))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAG\ -E: nonce must only contain printable characters")}else throw new Error("SASL: SC\ -RAM-SERVER-FIRST-MESSAGE: nonce missing");let n=e.get("s");if(n){if(!Ss(n))throw new Error( -"SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw new Error("S\ -ASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let i=e.get("i");if(i){if(!/^[1-9][0-9]*$/. -test(i))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration cou\ -nt")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing"); -let s=parseInt(i,10);return{nonce:t,salt:n,iteration:s}}o(Qc,"parseServerFirstMe\ -ssage");function $c(r){let t=Es(r).get("v");if(t){if(!Ss(t))throw new Error("SAS\ -L: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw new Error( -"SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:t}} -o($c,"parseServerFinalMessage");function bs(r,e){if(!m.isBuffer(r))throw new TypeError( -"first argument must be a Buffer");if(!m.isBuffer(e))throw new TypeError("second\ - argument must be a Buffer");if(r.length!==e.length)throw new Error("Buffer leng\ -ths must match");if(r.length===0)throw new Error("Buffers cannot be empty");return m. -from(r.map((t,n)=>r[n]^e[n]))}o(bs,"xorBuffers");function jc(r){return $r.createHash( -"sha256").update(r).digest()}o(jc,"sha256");function ze(r,e){return $r.createHmac( -"sha256",r).update(e).digest()}o(ze,"hmacSha256");function Hc(r,e,t){for(var n=ze( -r,m.concat([e,m.from([0,0,0,1])])),i=n,s=0;sKc});function Kc(...r){return r.join("/")}var Hr=ue(()=>{ -"use strict";p();o(Kc,"join")});var Kr={};de(Kr,{stat:()=>Wc});function Wc(r,e){e(new Error("No filesystem"))}var Wr=ue( -()=>{"use strict";p();o(Wc,"stat")});var Gr={};de(Gr,{default:()=>Gc});var Gc,Vr=ue(()=>{"use strict";p();Gc={}});var vs={};de(vs,{StringDecoder:()=>zr});var zr,Cs=ue(()=>{"use strict";p();zr=class{static{ -o(this,"StringDecoder")}td;constructor(e){this.td=new TextDecoder(e)}write(e){return this. -td.decode(e,{stream:!0})}end(e){return this.td.decode(e)}}});var Us=B((md,Ts)=>{"use strict";p();var{Transform:Vc}=(Vr(),X(Gr)),{StringDecoder:zc}=(Cs(),X(vs)), -Ue=Symbol("last"),Ht=Symbol("decoder");function Jc(r,e,t){let n;if(this.overflow){ -if(n=this[Ht].write(r).split(this.matcher),n.length===1)return t();n.shift(),this. -overflow=!1}else this[Ue]+=this[Ht].write(r),n=this[Ue].split(this.matcher);this[Ue]= -n.pop();for(let i=0;ithis.maxLength,this.overflow&&!this.skipOverflow){ -t(new Error("maximum buffer reached"));return}t()}o(Jc,"transform");function Yc(r){ -if(this[Ue]+=this[Ht].end(),this[Ue])try{Ls(this,this.mapper(this[Ue]))}catch(e){ -return r(e)}r()}o(Yc,"flush");function Ls(r,e){e!==void 0&&r.push(e)}o(Ls,"push"); -function _s(r){return r}o(_s,"noop");function Zc(r,e,t){switch(r=r||/\r?\n/,e=e|| -_s,t=t||{},arguments.length){case 1:typeof r=="function"?(e=r,r=/\r?\n/):typeof r== -"object"&&!(r instanceof RegExp)&&!r[Symbol.split]&&(t=r,r=/\r?\n/);break;case 2: -typeof r=="function"?(t=e,e=r,r=/\r?\n/):typeof e=="object"&&(t=e,e=_s)}t=Object. -assign({},t),t.autoDestroy=!0,t.transform=Jc,t.flush=Yc,t.readableObjectMode=!0; -let n=new Vc(t);return n[Ue]="",n[Ht]=new zc("utf8"),n.matcher=r,n.mapper=e,n.maxLength= -t.maxLength,n.skipOverflow=t.skipOverflow||!1,n.overflow=!1,n._destroy=function(i,s){ -this._writableState.errorEmitted=!1,s(i)},n}o(Zc,"split");Ts.exports=Zc});var Bs=B((Sd,Ae)=>{"use strict";p();var Is=(Hr(),X(jr)),Xc=(Vr(),X(Gr)).Stream,el=Us(), -Ps=(lt(),X(ct)),tl=5432,Kt=g.platform==="win32",bt=g.stderr,rl=56,nl=7,il=61440, -sl=32768;function al(r){return(r&il)==sl}o(al,"isRegFile");var Je=["host","port", -"database","user","password"],Jr=Je.length,ol=Je[Jr-1];function Yr(){var r=bt instanceof -Xc&&bt.writable===!0;if(r){var e=Array.prototype.slice.call(arguments).concat(` -`);bt.write(Ps.format.apply(Ps,e))}}o(Yr,"warn");Object.defineProperty(Ae.exports, -"isWin",{get:o(function(){return Kt},"get"),set:o(function(r){Kt=r},"set")});Ae. -exports.warnTo=function(r){var e=bt;return bt=r,e};Ae.exports.getFileName=function(r){ -var e=r||g.env,t=e.PGPASSFILE||(Kt?Is.join(e.APPDATA||"./","postgresql","pgpass.\ -conf"):Is.join(e.HOME||"./",".pgpass"));return t};Ae.exports.usePgPass=function(r,e){ -return Object.prototype.hasOwnProperty.call(g.env,"PGPASSWORD")?!1:Kt?!0:(e=e||"\ -",al(r.mode)?r.mode&(rl|nl)?(Yr('WARNING: password file "%s" has group or \ -world access; permissions should be u=rw (0600) or less',e),!1):!0:(Yr('WARNING:\ - password file "%s" is not a plain file',e),!1))};var ul=Ae.exports.match=function(r,e){ -return Je.slice(0,-1).reduce(function(t,n,i){return i==1&&Number(r[n]||tl)===Number( -e[n])?t&&!0:t&&(e[n]==="*"||e[n]===r[n])},!0)};Ae.exports.getPassword=function(r,e,t){ -var n,i=e.pipe(el());function s(c){var l=cl(c);l&&ll(l)&&ul(r,l)&&(n=l[ol],i.end())} -o(s,"onLine");var a=o(function(){e.destroy(),t(n)},"onEnd"),u=o(function(c){e.destroy(), -Yr("WARNING: error on reading file: %s",c),t(void 0)},"onErr");e.on("error",u),i. -on("data",s).on("end",a).on("error",u)};var cl=Ae.exports.parseLine=function(r){ -if(r.length<11||r.match(/^\s+#/))return null;for(var e="",t="",n=0,i=0,s=0,a={}, -u=!1,c=o(function(h,f,y){var w=r.substring(f,y);Object.hasOwnProperty.call(g.env, -"PGPASS_NO_DEESCAPE")||(w=w.replace(/\\([:\\])/g,"$1")),a[Je[h]]=w},"addToObj"), -l=0;l=0&&e==":"&&t!=="\\"&&(c(n,i,l+1),i=l+2,n+=1)}return a=Object.keys(a).length=== -Jr?a:null,a},ll=Ae.exports.isValidEntry=function(r){for(var e={0:function(a){return a. -length>0},1:function(a){return a==="*"?!0:(a=Number(a),isFinite(a)&&a>0&&a<9007199254740992&& -Math.floor(a)===a)},2:function(a){return a.length>0},3:function(a){return a.length> -0},4:function(a){return a.length>0}},t=0;t{"use strict";p();var xd=(Hr(),X(jr)),Rs=(Wr(),X(Kr)),Wt=Bs(); -Zr.exports=function(r,e){var t=Wt.getFileName();Rs.stat(t,function(n,i){if(n||!Wt. -usePgPass(i,t))return e(void 0);var s=Rs.createReadStream(t);Wt.getPassword(r,s, -e)})};Zr.exports.warnTo=Wt.warnTo});var Vt=B((Cd,Ms)=>{"use strict";p();var hl=gt();function Gt(r){this._types=r||hl, -this.text={},this.binary={}}o(Gt,"TypeOverrides");Gt.prototype.getOverrides=function(r){ -switch(r){case"text":return this.text;case"binary":return this.binary;default:return{}}}; -Gt.prototype.setTypeParser=function(r,e,t){typeof e=="function"&&(t=e,e="text"), -this.getOverrides(e)[r]=t};Gt.prototype.getTypeParser=function(r,e){return e=e|| -"text",this.getOverrides(e)[r]||this._types.getTypeParser(r,e)};Ms.exports=Gt});var Fs={};de(Fs,{default:()=>fl});var fl,Ds=ue(()=>{"use strict";p();fl={}});var qs={};de(qs,{parse:()=>Xr});function Xr(r,e=!1){let{protocol:t}=new URL(r),n="\ -http:"+r.substring(t.length),{username:i,password:s,host:a,hostname:u,port:c,pathname:l, -search:h,searchParams:f,hash:y}=new URL(n);s=decodeURIComponent(s),i=decodeURIComponent( -i),l=decodeURIComponent(l);let w=i+":"+s,b=e?Object.fromEntries(f.entries()):h;return{ -href:r,protocol:t,auth:w,username:i,password:s,host:a,hostname:u,port:c,pathname:l, -search:h,query:b,hash:y}}var en=ue(()=>{"use strict";p();o(Xr,"parse")});var ks=B((Pd,Os)=>{"use strict";p();var dl=(en(),X(qs)),tn=(Wr(),X(Kr));function rn(r){ -if(r.charAt(0)==="/"){var t=r.split(" ");return{host:t[0],database:t[1]}}var e=dl. -parse(/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(r)?encodeURI(r).replace(/\%25(\d\d)/g, -"%$1"):r,!0),t=e.query;for(var n in t)Array.isArray(t[n])&&(t[n]=t[n][t[n].length- -1]);var i=(e.auth||":").split(":");if(t.user=i[0],t.password=i.splice(1).join(":"), -t.port=e.port,e.protocol=="socket:")return t.host=decodeURI(e.pathname),t.database= -e.query.db,t.client_encoding=e.query.encoding,t;t.host||(t.host=e.hostname);var s=e. -pathname;if(!t.host&&s&&/^%2f/i.test(s)){var a=s.split("/");t.host=decodeURIComponent( -a[0]),s=a.splice(1).join("/")}switch(s&&s.charAt(0)==="/"&&(s=s.slice(1)||null), -t.database=s&&decodeURI(s),(t.ssl==="true"||t.ssl==="1")&&(t.ssl=!0),t.ssl==="0"&& -(t.ssl=!1),(t.sslcert||t.sslkey||t.sslrootcert||t.sslmode)&&(t.ssl={}),t.sslcert&& -(t.ssl.cert=tn.readFileSync(t.sslcert).toString()),t.sslkey&&(t.ssl.key=tn.readFileSync( -t.sslkey).toString()),t.sslrootcert&&(t.ssl.ca=tn.readFileSync(t.sslrootcert).toString()), -t.sslmode){case"disable":{t.ssl=!1;break}case"prefer":case"require":case"verify-\ -ca":case"verify-full":break;case"no-verify":{t.ssl.rejectUnauthorized=!1;break}} -return t}o(rn,"parse");Os.exports=rn;rn.parse=rn});var zt=B((Nd,js)=>{"use strict";p();var pl=(Ds(),X(Fs)),$s=St(),Qs=ks().parse,oe=o( -function(r,e,t){return t===void 0?t=g.env["PG"+r.toUpperCase()]:t===!1||(t=g.env[t]), -e[r]||t||$s[r]},"val"),yl=o(function(){switch(g.env.PGSSLMODE){case"disable":return!1;case"\ -prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify": -return{rejectUnauthorized:!1}}return $s.ssl},"readSSLConfigFromEnvironment"),Ye=o( -function(r){return"'"+(""+r).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},"quo\ -teParamValue"),me=o(function(r,e,t){var n=e[t];n!=null&&r.push(t+"="+Ye(n))},"ad\ -d"),nn=class{static{o(this,"ConnectionParameters")}constructor(e){e=typeof e=="s\ -tring"?Qs(e):e||{},e.connectionString&&(e=Object.assign({},e,Qs(e.connectionString))), -this.user=oe("user",e),this.database=oe("database",e),this.database===void 0&&(this. -database=this.user),this.port=parseInt(oe("port",e),10),this.host=oe("host",e),Object. -defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:oe( -"password",e)}),this.binary=oe("binary",e),this.options=oe("options",e),this.ssl= -typeof e.ssl>"u"?yl():e.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this. -ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this. -ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.client_encoding= -oe("client_encoding",e),this.replication=oe("replication",e),this.isDomainSocket= -!(this.host||"").indexOf("/"),this.application_name=oe("application_name",e,"PGA\ -PPNAME"),this.fallback_application_name=oe("fallback_application_name",e,!1),this. -statement_timeout=oe("statement_timeout",e,!1),this.lock_timeout=oe("lock_timeou\ -t",e,!1),this.idle_in_transaction_session_timeout=oe("idle_in_transaction_sessio\ -n_timeout",e,!1),this.query_timeout=oe("query_timeout",e,!1),e.connectionTimeoutMillis=== -void 0?this.connect_timeout=g.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math. -floor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive=== -!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle= -Math.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){var t=[]; -me(t,this,"user"),me(t,this,"password"),me(t,this,"port"),me(t,this,"application\ -_name"),me(t,this,"fallback_application_name"),me(t,this,"connect_timeout"),me(t, -this,"options");var n=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this. -ssl}:{};if(me(t,n,"sslmode"),me(t,n,"sslca"),me(t,n,"sslkey"),me(t,n,"sslcert"), -me(t,n,"sslrootcert"),this.database&&t.push("dbname="+Ye(this.database)),this.replication&& -t.push("replication="+Ye(this.replication)),this.host&&t.push("host="+Ye(this.host)), -this.isDomainSocket)return e(null,t.join(" "));this.client_encoding&&t.push("cli\ -ent_encoding="+Ye(this.client_encoding)),pl.lookup(this.host,function(i,s){return i? -e(i,null):(t.push("hostaddr="+Ye(s)),e(null,t.join(" ")))})}};js.exports=nn});var Ws=B((Dd,Ks)=>{"use strict";p();var ml=gt(),Hs=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/, -sn=class{static{o(this,"Result")}constructor(e,t){this.command=null,this.rowCount= -null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types= -t,this.RowCtor=null,this.rowAsArray=e==="array",this.rowAsArray&&(this.parseRow= -this._parseRowAsArray)}addCommandComplete(e){var t;e.text?t=Hs.exec(e.text):t=Hs. -exec(e.command),t&&(this.command=t[1],t[3]?(this.oid=parseInt(t[2],10),this.rowCount= -parseInt(t[3],10)):t[2]&&(this.rowCount=parseInt(t[2],10)))}_parseRowAsArray(e){ -for(var t=new Array(e.length),n=0,i=e.length;n{"use strict";p();var{EventEmitter:wl}=Te(),Gs=Ws(),Vs=Et(),an=class extends wl{static{ -o(this,"Query")}constructor(e,t,n){super(),e=Vs.normalizeQueryConfig(e,t,n),this. -text=e.text,this.values=e.values,this.rows=e.rows,this.types=e.types,this.name=e. -name,this.binary=e.binary,this.portal=e.portal||"",this.callback=e.callback,this. -_rowMode=e.rowMode,g.domain&&e.callback&&(this.callback=g.domain.bind(e.callback)), -this._result=new Gs(this._rowMode,this.types),this._results=this._result,this.isPreparedStatement= -!1,this._canceledDueToError=!1,this._promise=null}requiresPreparation(){return this. -name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){ -this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]), -this._result=new Gs(this._rowMode,this.types),this._results.push(this._result))}handleRowDescription(e){ -this._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this. -callback||!this.listeners("row").length}handleDataRow(e){let t;if(!this._canceledDueToError){ -try{t=this._result.parseRow(e.fields)}catch(n){this._canceledDueToError=n;return} -this.emit("row",t,this._result),this._accumulateRows&&this._result.addRow(t)}}handleCommandComplete(e,t){ -this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&t.sync()}handleEmptyQuery(e){ -this.rows&&e.sync()}handleError(e,t){if(this._canceledDueToError&&(e=this._canceledDueToError, -this._canceledDueToError=!1),this.callback)return this.callback(e);this.emit("er\ -ror",e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError( -this._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(t){ -g.nextTick(()=>{throw t})}this.emit("end",this._results)}submit(e){if(typeof this. -text!="string"&&typeof this.name!="string")return new Error("A query must have e\ -ither text or a name. Supplying neither is unsupported.");let t=e.parsedStatements[this. -name];return this.text&&t&&this.text!==t?new Error(`Prepared statements must be \ -unique - '${this.name}' was used for a different statement`):this.values&&!Array. -isArray(this.values)?new Error("Query values must be an array"):(this.requiresPreparation()? -this.prepare(e):e.query(this.text),null)}hasBeenParsed(e){return this.name&&e.parsedStatements[this. -name]}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,t){e.execute( -{portal:this.portal,rows:t}),t?e.flush():e.sync()}prepare(e){this.isPreparedStatement= -!0,this.hasBeenParsed(e)||e.parse({text:this.text,name:this.name,types:this.types}); -try{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this. -binary,valueMapper:Vs.prepareValue})}catch(t){this.handleError(t,e);return}e.describe( -{type:"P",name:this.portal||""}),this._getRows(e,this.rows)}handleCopyInResponse(e){ -e.sendCopyFail("No source stream defined")}handleCopyData(e,t){}};zs.exports=an});var Zs={};de(Zs,{Socket:()=>we,isIP:()=>gl});function gl(r){return 0}var Ys,Sl,we, -Jt=ue(()=>{"use strict";p();Ys=qe(Te(),1);o(gl,"isIP");Sl=o(r=>r.replace(/^[^.]+\./, -"api."),"transformHost"),we=class r extends Ys.EventEmitter{static{o(this,"Socke\ -t")}static defaults={poolQueryViaFetch:!1,fetchEndpoint:o(e=>"https://"+Sl(e)+"/\ -sql","fetchEndpoint"),fetchConnectionCache:!0,fetchFunction:void 0,webSocketConstructor:void 0, -wsProxy:o(e=>e+"/v2","wsProxy"),useSecureWebSocket:!0,forceDisablePgSSL:!0,coalesceWrites:!0, -pipelineConnect:"password",subtls:void 0,rootCerts:"",pipelineTLS:!1,disableSNI:!1};static opts={};opts={};static get poolQueryViaFetch(){ -return r.opts.poolQueryViaFetch??r.defaults.poolQueryViaFetch}static set poolQueryViaFetch(e){ -r.opts.poolQueryViaFetch=e}static get fetchEndpoint(){return r.opts.fetchEndpoint?? -r.defaults.fetchEndpoint}static set fetchEndpoint(e){r.opts.fetchEndpoint=e}static get fetchConnectionCache(){ -return!0}static set fetchConnectionCache(e){console.warn("The `fetchConnectionCa\ -che` option is deprecated (now always `true`)")}static get fetchFunction(){return r. -opts.fetchFunction??r.defaults.fetchFunction}static set fetchFunction(e){r.opts. -fetchFunction=e}static get webSocketConstructor(){return r.opts.webSocketConstructor?? -r.defaults.webSocketConstructor}static set webSocketConstructor(e){r.opts.webSocketConstructor= -e}get webSocketConstructor(){return this.opts.webSocketConstructor??r.webSocketConstructor}set webSocketConstructor(e){ -this.opts.webSocketConstructor=e}static get wsProxy(){return r.opts.wsProxy??r.defaults. -wsProxy}static set wsProxy(e){r.opts.wsProxy=e}get wsProxy(){return this.opts.wsProxy?? -r.wsProxy}set wsProxy(e){this.opts.wsProxy=e}static get coalesceWrites(){return r. -opts.coalesceWrites??r.defaults.coalesceWrites}static set coalesceWrites(e){r.opts. -coalesceWrites=e}get coalesceWrites(){return this.opts.coalesceWrites??r.coalesceWrites}set coalesceWrites(e){ -this.opts.coalesceWrites=e}static get useSecureWebSocket(){return r.opts.useSecureWebSocket?? -r.defaults.useSecureWebSocket}static set useSecureWebSocket(e){r.opts.useSecureWebSocket= -e}get useSecureWebSocket(){return this.opts.useSecureWebSocket??r.useSecureWebSocket}set useSecureWebSocket(e){ -this.opts.useSecureWebSocket=e}static get forceDisablePgSSL(){return r.opts.forceDisablePgSSL?? -r.defaults.forceDisablePgSSL}static set forceDisablePgSSL(e){r.opts.forceDisablePgSSL= -e}get forceDisablePgSSL(){return this.opts.forceDisablePgSSL??r.forceDisablePgSSL}set forceDisablePgSSL(e){ -this.opts.forceDisablePgSSL=e}static get disableSNI(){return r.opts.disableSNI?? -r.defaults.disableSNI}static set disableSNI(e){r.opts.disableSNI=e}get disableSNI(){ -return this.opts.disableSNI??r.disableSNI}set disableSNI(e){this.opts.disableSNI= -e}static get pipelineConnect(){return r.opts.pipelineConnect??r.defaults.pipelineConnect}static set pipelineConnect(e){ -r.opts.pipelineConnect=e}get pipelineConnect(){return this.opts.pipelineConnect?? -r.pipelineConnect}set pipelineConnect(e){this.opts.pipelineConnect=e}static get subtls(){ -return r.opts.subtls??r.defaults.subtls}static set subtls(e){r.opts.subtls=e}get subtls(){ -return this.opts.subtls??r.subtls}set subtls(e){this.opts.subtls=e}static get pipelineTLS(){ -return r.opts.pipelineTLS??r.defaults.pipelineTLS}static set pipelineTLS(e){r.opts. -pipelineTLS=e}get pipelineTLS(){return this.opts.pipelineTLS??r.pipelineTLS}set pipelineTLS(e){ -this.opts.pipelineTLS=e}static get rootCerts(){return r.opts.rootCerts??r.defaults. -rootCerts}static set rootCerts(e){r.opts.rootCerts=e}get rootCerts(){return this. -opts.rootCerts??r.rootCerts}set rootCerts(e){this.opts.rootCerts=e}wsProxyAddrForHost(e,t){ -let n=this.wsProxy;if(n===void 0)throw new Error("No WebSocket proxy is configur\ -ed. Please see https://github.com/neondatabase/serverless/blob/main/CONFIG.md#ws\ -proxy-string--host-string-port-number--string--string");return typeof n=="functi\ -on"?n(e,t):`${n}?address=${e}:${t}`}connecting=!1;pending=!0;writable=!0;encrypted=!1;authorized=!1;destroyed=!1;ws=null;writeBuffer;tlsState=0;tlsRead;tlsWrite;setNoDelay(){ -return this}setKeepAlive(){return this}ref(){return this}unref(){return this}connect(e,t,n){ -this.connecting=!0,n&&this.once("connect",n);let i=o(()=>{this.connecting=!1,this. -pending=!1,this.emit("connect"),this.emit("ready")},"handleWebSocketOpen"),s=o((u,c=!1)=>{ -u.binaryType="arraybuffer",u.addEventListener("error",l=>{this.emit("error",l),this. -emit("close")}),u.addEventListener("message",l=>{if(this.tlsState===0){let h=m.from( -l.data);this.emit("data",h)}}),u.addEventListener("close",()=>{this.emit("close")}), -c?i():u.addEventListener("open",i)},"configureWebSocket"),a;try{a=this.wsProxyAddrForHost( -t,typeof e=="string"?parseInt(e,10):e)}catch(u){this.emit("error",u),this.emit("\ -close");return}try{let c=(this.useSecureWebSocket?"wss:":"ws:")+"//"+a;if(this.webSocketConstructor!== -void 0)this.ws=new this.webSocketConstructor(c),s(this.ws);else try{this.ws=new WebSocket( -c),s(this.ws)}catch{this.ws=new __unstable_WebSocket(c),s(this.ws)}}catch(u){let l=(this. -useSecureWebSocket?"https:":"http:")+"//"+a;fetch(l,{headers:{Upgrade:"websocket"}}). -then(h=>{if(this.ws=h.webSocket,this.ws==null)throw u;this.ws.accept(),s(this.ws, -!0)}).catch(h=>{this.emit("error",new Error(`All attempts to open a WebSocket to\ - connect to the database failed. Please refer to https://github.com/neondatabase\ -/serverless/blob/main/CONFIG.md#websocketconstructor-typeof-websocket--undefined\ -. Details: ${h.message}`)),this.emit("close")})}}async startTls(e){if(this.subtls=== -void 0)throw new Error("For Postgres SSL connections, you must set `neonConfig.s\ -ubtls` to the subtls library. See https://github.com/neondatabase/serverless/blo\ -b/main/CONFIG.md for more information.");this.tlsState=1;let t=this.subtls.TrustedCert. -fromPEM(this.rootCerts),n=new this.subtls.WebSocketReadQueue(this.ws),i=n.read.bind( -n),s=this.rawWrite.bind(this),[a,u]=await this.subtls.startTls(e,t,i,s,{useSNI:!this. -disableSNI,expectPreData:this.pipelineTLS?new Uint8Array([83]):void 0});this.tlsRead= -a,this.tlsWrite=u,this.tlsState=2,this.encrypted=!0,this.authorized=!0,this.emit( -"secureConnection",this),this.tlsReadLoop()}async tlsReadLoop(){for(;;){let e=await this. -tlsRead();if(e===void 0)break;{let t=m.from(e);this.emit("data",t)}}}rawWrite(e){ -if(!this.coalesceWrites){this.ws.send(e);return}if(this.writeBuffer===void 0)this. -writeBuffer=e,setTimeout(()=>{this.ws.send(this.writeBuffer),this.writeBuffer=void 0}, -0);else{let t=new Uint8Array(this.writeBuffer.length+e.length);t.set(this.writeBuffer), -t.set(e,this.writeBuffer.length),this.writeBuffer=t}}write(e,t="utf8",n=i=>{}){return e. -length===0?(n(),!0):(typeof e=="string"&&(e=m.from(e,t)),this.tlsState===0?(this. -rawWrite(e),n()):this.tlsState===1?this.once("secureConnection",()=>{this.write( -e,t,n)}):(this.tlsWrite(e),n()),!0)}end(e=m.alloc(0),t="utf8",n=()=>{}){return this. -write(e,t,()=>{this.ws.close(),n()}),this}destroy(){return this.destroyed=!0,this. -end()}}});var bn=B(I=>{"use strict";p();Object.defineProperty(I,"__esModule",{value:!0});I. -NoticeMessage=I.DataRowMessage=I.CommandCompleteMessage=I.ReadyForQueryMessage=I. -NotificationResponseMessage=I.BackendKeyDataMessage=I.AuthenticationMD5Password= -I.ParameterStatusMessage=I.ParameterDescriptionMessage=I.RowDescriptionMessage=I. -Field=I.CopyResponse=I.CopyDataMessage=I.DatabaseError=I.copyDone=I.emptyQuery=I. -replicationStart=I.portalSuspended=I.noData=I.closeComplete=I.bindComplete=I.parseComplete= -void 0;I.parseComplete={name:"parseComplete",length:5};I.bindComplete={name:"bin\ -dComplete",length:5};I.closeComplete={name:"closeComplete",length:5};I.noData={name:"\ -noData",length:5};I.portalSuspended={name:"portalSuspended",length:5};I.replicationStart= -{name:"replicationStart",length:4};I.emptyQuery={name:"emptyQuery",length:4};I.copyDone= -{name:"copyDone",length:4};var on=class extends Error{static{o(this,"DatabaseErr\ -or")}constructor(e,t,n){super(e),this.length=t,this.name=n}};I.DatabaseError=on; -var un=class{static{o(this,"CopyDataMessage")}constructor(e,t){this.length=e,this. -chunk=t,this.name="copyData"}};I.CopyDataMessage=un;var cn=class{static{o(this,"\ -CopyResponse")}constructor(e,t,n,i){this.length=e,this.name=t,this.binary=n,this. -columnTypes=new Array(i)}};I.CopyResponse=cn;var ln=class{static{o(this,"Field")}constructor(e,t,n,i,s,a,u){ -this.name=e,this.tableID=t,this.columnID=n,this.dataTypeID=i,this.dataTypeSize=s, -this.dataTypeModifier=a,this.format=u}};I.Field=ln;var hn=class{static{o(this,"R\ -owDescriptionMessage")}constructor(e,t){this.length=e,this.fieldCount=t,this.name= -"rowDescription",this.fields=new Array(this.fieldCount)}};I.RowDescriptionMessage= -hn;var fn=class{static{o(this,"ParameterDescriptionMessage")}constructor(e,t){this. -length=e,this.parameterCount=t,this.name="parameterDescription",this.dataTypeIDs= -new Array(this.parameterCount)}};I.ParameterDescriptionMessage=fn;var dn=class{static{ -o(this,"ParameterStatusMessage")}constructor(e,t,n){this.length=e,this.parameterName= -t,this.parameterValue=n,this.name="parameterStatus"}};I.ParameterStatusMessage=dn; -var pn=class{static{o(this,"AuthenticationMD5Password")}constructor(e,t){this.length= -e,this.salt=t,this.name="authenticationMD5Password"}};I.AuthenticationMD5Password= -pn;var yn=class{static{o(this,"BackendKeyDataMessage")}constructor(e,t,n){this.length= -e,this.processID=t,this.secretKey=n,this.name="backendKeyData"}};I.BackendKeyDataMessage= -yn;var mn=class{static{o(this,"NotificationResponseMessage")}constructor(e,t,n,i){ -this.length=e,this.processId=t,this.channel=n,this.payload=i,this.name="notifica\ -tion"}};I.NotificationResponseMessage=mn;var wn=class{static{o(this,"ReadyForQue\ -ryMessage")}constructor(e,t){this.length=e,this.status=t,this.name="readyForQuer\ -y"}};I.ReadyForQueryMessage=wn;var gn=class{static{o(this,"CommandCompleteMessag\ -e")}constructor(e,t){this.length=e,this.text=t,this.name="commandComplete"}};I.CommandCompleteMessage= -gn;var Sn=class{static{o(this,"DataRowMessage")}constructor(e,t){this.length=e,this. -fields=t,this.name="dataRow",this.fieldCount=t.length}};I.DataRowMessage=Sn;var En=class{static{ -o(this,"NoticeMessage")}constructor(e,t){this.length=e,this.message=t,this.name= -"notice"}};I.NoticeMessage=En});var Xs=B(Yt=>{"use strict";p();Object.defineProperty(Yt,"__esModule",{value:!0}); -Yt.Writer=void 0;var xn=class{static{o(this,"Writer")}constructor(e=256){this.size= -e,this.offset=5,this.headerPosition=0,this.buffer=m.allocUnsafe(e)}ensure(e){var t=this. -buffer.length-this.offset;if(t>1)+e;this. -buffer=m.allocUnsafe(i),n.copy(this.buffer)}}addInt32(e){return this.ensure(4),this. -buffer[this.offset++]=e>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this. -offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this. -ensure(2),this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0& -255,this}addCString(e){if(!e)this.ensure(1);else{var t=m.byteLength(e);this.ensure( -t+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=t}return this.buffer[this. -offset++]=0,this}addString(e=""){var t=m.byteLength(e);return this.ensure(t),this. -buffer.write(e,this.offset),this.offset+=t,this}add(e){return this.ensure(e.length), -e.copy(this.buffer,this.offset),this.offset+=e.length,this}join(e){if(e){this.buffer[this. -headerPosition]=e;let t=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE( -t,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){var t=this. -join(e);return this.offset=5,this.headerPosition=0,this.buffer=m.allocUnsafe(this. -size),t}};Yt.Writer=xn});var ta=B(Xt=>{"use strict";p();Object.defineProperty(Xt,"__esModule",{value:!0}); -Xt.serialize=void 0;var An=Xs(),z=new An.Writer,El=o(r=>{z.addInt16(3).addInt16( -0);for(let n of Object.keys(r))z.addCString(n).addCString(r[n]);z.addCString("cl\ -ient_encoding").addCString("UTF8");var e=z.addCString("").flush(),t=e.length+4;return new An. -Writer().addInt32(t).add(e).flush()},"startup"),bl=o(()=>{let r=m.allocUnsafe(8); -return r.writeInt32BE(8,0),r.writeInt32BE(80877103,4),r},"requestSsl"),xl=o(r=>z. -addCString(r).flush(112),"password"),Al=o(function(r,e){return z.addCString(r).addInt32( -m.byteLength(e)).addString(e),z.flush(112)},"sendSASLInitialResponseMessage"),vl=o( -function(r){return z.addString(r).flush(112)},"sendSCRAMClientFinalMessage"),Cl=o( -r=>z.addCString(r).flush(81),"query"),ea=[],_l=o(r=>{let e=r.name||"";e.length>63&& -(console.error("Warning! Postgres only supports 63 characters for query names."), -console.error("You supplied %s (%s)",e,e.length),console.error("This can cause c\ -onflicts and silent errors executing queries"));let t=r.types||ea;for(var n=t.length, -i=z.addCString(e).addCString(r.text).addInt16(n),s=0;s{let e=r.portal||"",t=r.statement|| -"",n=r.binary||!1,i=r.values||ea,s=i.length;return z.addCString(e).addCString(t), -z.addInt16(s),Ll(i,r.valueMapper),z.addInt16(s),z.add(Ze.flush()),z.addInt16(n?1: -0),z.flush(66)},"bind"),Ul=m.from([69,0,0,0,9,0,0,0,0,0]),Il=o(r=>{if(!r||!r.portal&& -!r.rows)return Ul;let e=r.portal||"",t=r.rows||0,n=m.byteLength(e),i=4+n+1+4,s=m. -allocUnsafe(1+i);return s[0]=69,s.writeInt32BE(i,1),s.write(e,5,"utf-8"),s[n+5]= -0,s.writeUInt32BE(t,s.length-4),s},"execute"),Pl=o((r,e)=>{let t=m.allocUnsafe(16); -return t.writeInt32BE(16,0),t.writeInt16BE(1234,4),t.writeInt16BE(5678,6),t.writeInt32BE( -r,8),t.writeInt32BE(e,12),t},"cancel"),vn=o((r,e)=>{let n=4+m.byteLength(e)+1,i=m. -allocUnsafe(1+n);return i[0]=r,i.writeInt32BE(n,1),i.write(e,5,"utf-8"),i[n]=0,i}, -"cstringMessage"),Bl=z.addCString("P").flush(68),Rl=z.addCString("S").flush(68), -Nl=o(r=>r.name?vn(68,`${r.type}${r.name||""}`):r.type==="P"?Bl:Rl,"describe"),Ml=o( -r=>{let e=`${r.type}${r.name||""}`;return vn(67,e)},"close"),Fl=o(r=>z.add(r).flush( -100),"copyData"),Dl=o(r=>vn(102,r),"copyFail"),Zt=o(r=>m.from([r,0,0,0,4]),"code\ -OnlyBuffer"),ql=Zt(72),Ol=Zt(83),kl=Zt(88),Ql=Zt(99),$l={startup:El,password:xl, -requestSsl:bl,sendSASLInitialResponseMessage:Al,sendSCRAMClientFinalMessage:vl,query:Cl, -parse:_l,bind:Tl,execute:Il,describe:Nl,close:Ml,flush:o(()=>ql,"flush"),sync:o( -()=>Ol,"sync"),end:o(()=>kl,"end"),copyData:Fl,copyDone:o(()=>Ql,"copyDone"),copyFail:Dl, -cancel:Pl};Xt.serialize=$l});var ra=B(er=>{"use strict";p();Object.defineProperty(er,"__esModule",{value:!0}); -er.BufferReader=void 0;var jl=m.allocUnsafe(0),Cn=class{static{o(this,"BufferRea\ -der")}constructor(e=0){this.offset=e,this.buffer=jl,this.encoding="utf-8"}setBuffer(e,t){ -this.offset=e,this.buffer=t}int16(){let e=this.buffer.readInt16BE(this.offset);return this. -offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){ -let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}string(e){let t=this. -buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,t}cstring(){ -let e=this.offset,t=e;for(;this.buffer[t++]!==0;);return this.offset=t,this.buffer. -toString(this.encoding,e,t-1)}bytes(e){let t=this.buffer.slice(this.offset,this. -offset+e);return this.offset+=e,t}};er.BufferReader=Cn});var sa=B(tr=>{"use strict";p();Object.defineProperty(tr,"__esModule",{value:!0}); -tr.Parser=void 0;var J=bn(),Hl=ra(),_n=1,Kl=4,na=_n+Kl,ia=m.allocUnsafe(0),Ln=class{static{ -o(this,"Parser")}constructor(e){if(this.buffer=ia,this.bufferLength=0,this.bufferOffset= -0,this.reader=new Hl.BufferReader,e?.mode==="binary")throw new Error("Binary mod\ -e not supported yet");this.mode=e?.mode||"text"}parse(e,t){this.mergeBuffer(e);let n=this. -bufferOffset+this.bufferLength,i=this.bufferOffset;for(;i+na<=n;){let s=this.buffer[i], -a=this.buffer.readUInt32BE(i+_n),u=_n+a;if(u+i<=n){let c=this.handlePacket(i+na, -s,a,this.buffer);t(c),i+=u}else break}i===n?(this.buffer=ia,this.bufferLength=0, -this.bufferOffset=0):(this.bufferLength=n-i,this.bufferOffset=i)}mergeBuffer(e){ -if(this.bufferLength>0){let t=this.bufferLength+e.byteLength;if(t+this.bufferOffset> -this.buffer.byteLength){let i;if(t<=this.buffer.byteLength&&this.bufferOffset>=this. -bufferLength)i=this.buffer;else{let s=this.buffer.byteLength*2;for(;t>=s;)s*=2;i= -m.allocUnsafe(s)}this.buffer.copy(i,0,this.bufferOffset,this.bufferOffset+this.bufferLength), -this.buffer=i,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength), -this.bufferLength=t}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,t,n,i){ -switch(t){case 50:return J.bindComplete;case 49:return J.parseComplete;case 51:return J. -closeComplete;case 110:return J.noData;case 115:return J.portalSuspended;case 99: -return J.copyDone;case 87:return J.replicationStart;case 73:return J.emptyQuery;case 68: -return this.parseDataRowMessage(e,n,i);case 67:return this.parseCommandCompleteMessage( -e,n,i);case 90:return this.parseReadyForQueryMessage(e,n,i);case 65:return this. -parseNotificationMessage(e,n,i);case 82:return this.parseAuthenticationResponse( -e,n,i);case 83:return this.parseParameterStatusMessage(e,n,i);case 75:return this. -parseBackendKeyData(e,n,i);case 69:return this.parseErrorMessage(e,n,i,"error");case 78: -return this.parseErrorMessage(e,n,i,"notice");case 84:return this.parseRowDescriptionMessage( -e,n,i);case 116:return this.parseParameterDescriptionMessage(e,n,i);case 71:return this. -parseCopyInMessage(e,n,i);case 72:return this.parseCopyOutMessage(e,n,i);case 100: -return this.parseCopyData(e,n,i);default:return new J.DatabaseError("received in\ -valid response: "+t.toString(16),n,"error")}}parseReadyForQueryMessage(e,t,n){this. -reader.setBuffer(e,n);let i=this.reader.string(1);return new J.ReadyForQueryMessage( -t,i)}parseCommandCompleteMessage(e,t,n){this.reader.setBuffer(e,n);let i=this.reader. -cstring();return new J.CommandCompleteMessage(t,i)}parseCopyData(e,t,n){let i=n. -slice(e,e+(t-4));return new J.CopyDataMessage(t,i)}parseCopyInMessage(e,t,n){return this. -parseCopyMessage(e,t,n,"copyInResponse")}parseCopyOutMessage(e,t,n){return this. -parseCopyMessage(e,t,n,"copyOutResponse")}parseCopyMessage(e,t,n,i){this.reader. -setBuffer(e,n);let s=this.reader.byte()!==0,a=this.reader.int16(),u=new J.CopyResponse( -t,i,s,a);for(let c=0;c{"use strict";p();Object.defineProperty(Ie,"__esModule",{value:!0}); -Ie.DatabaseError=Ie.serialize=Ie.parse=void 0;var Wl=bn();Object.defineProperty( -Ie,"DatabaseError",{enumerable:!0,get:o(function(){return Wl.DatabaseError},"get")}); -var Gl=ta();Object.defineProperty(Ie,"serialize",{enumerable:!0,get:o(function(){ -return Gl.serialize},"get")});var Vl=sa();function zl(r,e){let t=new Vl.Parser;return r. -on("data",n=>t.parse(n,e)),new Promise(n=>r.on("end",()=>n()))}o(zl,"parse");Ie. -parse=zl});var aa={};de(aa,{connect:()=>Jl});function Jl({socket:r,servername:e}){return r. -startTls(e),r}var oa=ue(()=>{"use strict";p();o(Jl,"connect")});var In=B((hp,la)=>{"use strict";p();var ua=(Jt(),X(Zs)),Yl=Te().EventEmitter,{parse:Zl, -serialize:te}=Tn(),ca=te.flush(),Xl=te.sync(),eh=te.end(),Un=class extends Yl{static{ -o(this,"Connection")}constructor(e){super(),e=e||{},this.stream=e.stream||new ua. -Socket,this._keepAlive=e.keepAlive,this._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis, -this.lastBuffer=!1,this.parsedStatements={},this.ssl=e.ssl||!1,this._ending=!1,this. -_emitMessage=!1;var t=this;this.on("newListener",function(n){n==="message"&&(t._emitMessage= -!0)})}connect(e,t){var n=this;this._connecting=!0,this.stream.setNoDelay(!0),this. -stream.connect(e,t),this.stream.once("connect",function(){n._keepAlive&&n.stream. -setKeepAlive(!0,n._keepAliveInitialDelayMillis),n.emit("connect")});let i=o(function(s){ -n._ending&&(s.code==="ECONNRESET"||s.code==="EPIPE")||n.emit("error",s)},"report\ -StreamError");if(this.stream.on("error",i),this.stream.on("close",function(){n.emit( -"end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("da\ -ta",function(s){var a=s.toString("utf8");switch(a){case"S":break;case"N":return n. -stream.end(),n.emit("error",new Error("The server does not support SSL connectio\ -ns"));default:return n.stream.end(),n.emit("error",new Error("There was an error\ - establishing an SSL connection"))}var u=(oa(),X(aa));let c={socket:n.stream};n. -ssl!==!0&&(Object.assign(c,n.ssl),"key"in n.ssl&&(c.key=n.ssl.key)),ua.isIP(t)=== -0&&(c.servername=t);try{n.stream=u.connect(c)}catch(l){return n.emit("error",l)} -n.attachListeners(n.stream),n.stream.on("error",i),n.emit("sslconnect")})}attachListeners(e){ -e.on("end",()=>{this.emit("end")}),Zl(e,t=>{var n=t.name==="error"?"errorMessage": -t.name;this._emitMessage&&this.emit("message",t),this.emit(n,t)})}requestSsl(){this. -stream.write(te.requestSsl())}startup(e){this.stream.write(te.startup(e))}cancel(e,t){ -this._send(te.cancel(e,t))}password(e){this._send(te.password(e))}sendSASLInitialResponseMessage(e,t){ -this._send(te.sendSASLInitialResponseMessage(e,t))}sendSCRAMClientFinalMessage(e){ -this._send(te.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable? -this.stream.write(e):!1}query(e){this._send(te.query(e))}parse(e){this._send(te. -parse(e))}bind(e){this._send(te.bind(e))}execute(e){this._send(te.execute(e))}flush(){ -this.stream.writable&&this.stream.write(ca)}sync(){this._ending=!0,this._send(ca), -this._send(Xl)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this. -_ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this. -stream.write(eh,()=>{this.stream.end()})}close(e){this._send(te.close(e))}describe(e){ -this._send(te.describe(e))}sendCopyFromChunk(e){this._send(te.copyData(e))}endCopyFrom(){ -this._send(te.copyDone())}sendCopyFail(e){this._send(te.copyFail(e))}};la.exports= -Un});var da=B((yp,fa)=>{"use strict";p();var th=Te().EventEmitter,pp=(lt(),X(ct)),rh=Et(), -Pn=As(),nh=Ns(),ih=Vt(),sh=zt(),ha=Js(),ah=St(),oh=In(),rr=class extends th{static{ -o(this,"Client")}constructor(e){super(),this.connectionParameters=new sh(e),this. -user=this.connectionParameters.user,this.database=this.connectionParameters.database, -this.port=this.connectionParameters.port,this.host=this.connectionParameters.host, -Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0, -value:this.connectionParameters.password}),this.replication=this.connectionParameters. -replication;var t=e||{};this._Promise=t.Promise||_.Promise,this._types=new ih(t. -types),this._ending=!1,this._connecting=!1,this._connected=!1,this._connectionError= -!1,this._queryable=!0,this.connection=t.connection||new oh({stream:t.stream,ssl:this. -connectionParameters.ssl,keepAlive:t.keepAlive||!1,keepAliveInitialDelayMillis:t. -keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding|| -"utf8"}),this.queryQueue=[],this.binary=t.binary||ah.binary,this.processID=null, -this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl. -key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis= -t.connectionTimeoutMillis||0}_errorAllQueries(e){let t=o(n=>{g.nextTick(()=>{n.handleError( -e,this.connection)})},"enqueueError");this.activeQuery&&(t(this.activeQuery),this. -activeQuery=null),this.queryQueue.forEach(t),this.queryQueue.length=0}_connect(e){ -var t=this,n=this.connection;if(this._connectionCallback=e,this._connecting||this. -_connected){let i=new Error("Client has already been connected. You cannot reuse\ - a client.");g.nextTick(()=>{e(i)});return}this._connecting=!0,this.connectionTimeoutHandle, -this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{n. -_ending=!0,n.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis)), -this.host&&this.host.indexOf("/")===0?n.connect(this.host+"/.s.PGSQL."+this.port): -n.connect(this.port,this.host),n.on("connect",function(){t.ssl?n.requestSsl():n. -startup(t.getStartupConf())}),n.on("sslconnect",function(){n.startup(t.getStartupConf())}), -this._attachListeners(n),n.once("end",()=>{let i=this._ending?new Error("Connect\ -ion terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this. -connectionTimeoutHandle),this._errorAllQueries(i),this._ending||(this._connecting&& -!this._connectionError?this._connectionCallback?this._connectionCallback(i):this. -_handleErrorEvent(i):this._connectionError||this._handleErrorEvent(i)),g.nextTick( -()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this. -_Promise((t,n)=>{this._connect(i=>{i?n(i):t()})})}_attachListeners(e){e.on("auth\ -enticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),e.on( -"authenticationMD5Password",this._handleAuthMD5Password.bind(this)),e.on("authen\ -ticationSASL",this._handleAuthSASL.bind(this)),e.on("authenticationSASLContinue", -this._handleAuthSASLContinue.bind(this)),e.on("authenticationSASLFinal",this._handleAuthSASLFinal. -bind(this)),e.on("backendKeyData",this._handleBackendKeyData.bind(this)),e.on("e\ -rror",this._handleErrorEvent.bind(this)),e.on("errorMessage",this._handleErrorMessage. -bind(this)),e.on("readyForQuery",this._handleReadyForQuery.bind(this)),e.on("not\ -ice",this._handleNotice.bind(this)),e.on("rowDescription",this._handleRowDescription. -bind(this)),e.on("dataRow",this._handleDataRow.bind(this)),e.on("portalSuspended", -this._handlePortalSuspended.bind(this)),e.on("emptyQuery",this._handleEmptyQuery. -bind(this)),e.on("commandComplete",this._handleCommandComplete.bind(this)),e.on( -"parseComplete",this._handleParseComplete.bind(this)),e.on("copyInResponse",this. -_handleCopyInResponse.bind(this)),e.on("copyData",this._handleCopyData.bind(this)), -e.on("notification",this._handleNotification.bind(this))}_checkPgPass(e){let t=this. -connection;typeof this.password=="function"?this._Promise.resolve().then(()=>this. -password()).then(n=>{if(n!==void 0){if(typeof n!="string"){t.emit("error",new TypeError( -"Password must be a string"));return}this.connectionParameters.password=this.password= -n}else this.connectionParameters.password=this.password=null;e()}).catch(n=>{t.emit( -"error",n)}):this.password!==null?e():nh(this.connectionParameters,n=>{n!==void 0&& -(this.connectionParameters.password=this.password=n),e()})}_handleAuthCleartextPassword(e){ -this._checkPgPass(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){ -this._checkPgPass(()=>{let t=rh.postgresMd5PasswordHash(this.user,this.password, -e.salt);this.connection.password(t)})}_handleAuthSASL(e){this._checkPgPass(()=>{ -this.saslSession=Pn.startSession(e.mechanisms),this.connection.sendSASLInitialResponseMessage( -this.saslSession.mechanism,this.saslSession.response)})}_handleAuthSASLContinue(e){ -Pn.continueSession(this.saslSession,this.password,e.data),this.connection.sendSCRAMClientFinalMessage( -this.saslSession.response)}_handleAuthSASLFinal(e){Pn.finalizeSession(this.saslSession, -e.data),this.saslSession=null}_handleBackendKeyData(e){this.processID=e.processID, -this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting= -!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&& -(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("c\ -onnect"));let{activeQuery:t}=this;this.activeQuery=null,this.readyForQuery=!0,t&& -t.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){ -if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle), -this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){ -if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1, -this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting) -return this._handleErrorWhileConnecting(e);let t=this.activeQuery;if(!t){this._handleErrorEvent( -e);return}this.activeQuery=null,t.handleError(e,this.connection)}_handleRowDescription(e){ -this.activeQuery.handleRowDescription(e)}_handleDataRow(e){this.activeQuery.handleDataRow( -e)}_handlePortalSuspended(e){this.activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){ -this.activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(e){this. -activeQuery.handleCommandComplete(e,this.connection)}_handleParseComplete(e){this. -activeQuery.name&&(this.connection.parsedStatements[this.activeQuery.name]=this. -activeQuery.text)}_handleCopyInResponse(e){this.activeQuery.handleCopyInResponse( -this.connection)}_handleCopyData(e){this.activeQuery.handleCopyData(e,this.connection)}_handleNotification(e){ -this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){ -var e=this.connectionParameters,t={user:e.user,database:e.database},n=e.application_name|| -e.fallback_application_name;return n&&(t.application_name=n),e.replication&&(t.replication= -""+e.replication),e.statement_timeout&&(t.statement_timeout=String(parseInt(e.statement_timeout, -10))),e.lock_timeout&&(t.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&& -(t.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout, -10))),e.options&&(t.options=e.options),t}cancel(e,t){if(e.activeQuery===t){var n=this. -connection;this.host&&this.host.indexOf("/")===0?n.connect(this.host+"/.s.PGSQL."+ -this.port):n.connect(this.port,this.host),n.on("connect",function(){n.cancel(e.processID, -e.secretKey)})}else e.queryQueue.indexOf(t)!==-1&&e.queryQueue.splice(e.queryQueue. -indexOf(t),1)}setTypeParser(e,t,n){return this._types.setTypeParser(e,t,n)}getTypeParser(e,t){ -return this._types.getTypeParser(e,t)}escapeIdentifier(e){return'"'+e.replace(/"/g, -'""')+'"'}escapeLiteral(e){for(var t=!1,n="'",i=0;i{this.activeQuery.handleError(e,this.connection),this.readyForQuery= -!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this.activeQuery=null,this. -emit("drain"))}query(e,t,n){var i,s,a,u,c;if(e==null)throw new TypeError("Client\ - was passed a null or undefined query");return typeof e.submit=="function"?(a=e. -query_timeout||this.connectionParameters.query_timeout,s=i=e,typeof t=="function"&& -(i.callback=i.callback||t)):(a=this.connectionParameters.query_timeout,i=new ha( -e,t,n),i.callback||(s=new this._Promise((l,h)=>{i.callback=(f,y)=>f?h(f):l(y)}))), -a&&(c=i.callback,u=setTimeout(()=>{var l=new Error("Query read timeout");g.nextTick( -()=>{i.handleError(l,this.connection)}),c(l),i.callback=()=>{};var h=this.queryQueue. -indexOf(i);h>-1&&this.queryQueue.splice(h,1),this._pulseQueryQueue()},a),i.callback= -(l,h)=>{clearTimeout(u),c(l,h)}),this.binary&&!i.binary&&(i.binary=!0),i._result&& -!i._result._types&&(i._result._types=this._types),this._queryable?this._ending?(g. -nextTick(()=>{i.handleError(new Error("Client was closed and is not queryable"), -this.connection)}),s):(this.queryQueue.push(i),this._pulseQueryQueue(),s):(g.nextTick( -()=>{i.handleError(new Error("Client has encountered a connection error and is n\ -ot queryable"),this.connection)}),s)}ref(){this.connection.ref()}unref(){this.connection. -unref()}end(e){if(this._ending=!0,!this.connection._connecting)if(e)e();else return this. -_Promise.resolve();if(this.activeQuery||!this._queryable?this.connection.stream. -destroy():this.connection.end(),e)this.connection.once("end",e);else return new this. -_Promise(t=>{this.connection.once("end",t)})}};rr.Query=ha;fa.exports=rr});var wa=B((gp,ma)=>{"use strict";p();var uh=Te().EventEmitter,pa=o(function(){},"\ -NOOP"),ya=o((r,e)=>{let t=r.findIndex(e);return t===-1?void 0:r.splice(t,1)[0]}, -"removeWhere"),Bn=class{static{o(this,"IdleItem")}constructor(e,t,n){this.client= -e,this.idleListener=t,this.timeoutId=n}},Xe=class{static{o(this,"PendingItem")}constructor(e){ -this.callback=e}};function ch(){throw new Error("Release called on client which \ -has already been released to the pool.")}o(ch,"throwOnDoubleRelease");function nr(r,e){ -if(e)return{callback:e,result:void 0};let t,n,i=o(function(a,u){a?t(a):n(u)},"cb"), -s=new r(function(a,u){n=a,t=u}).catch(a=>{throw Error.captureStackTrace(a),a});return{ -callback:i,result:s}}o(nr,"promisify");function lh(r,e){return o(function t(n){n. -client=e,e.removeListener("error",t),e.on("error",()=>{r.log("additional client \ -error after disconnection due to error",n)}),r._remove(e),r.emit("error",n,e)},"\ -idleListener")}o(lh,"makeIdleListener");var Rn=class extends uh{static{o(this,"P\ -ool")}constructor(e,t){super(),this.options=Object.assign({},e),e!=null&&"passwo\ -rd"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1, -writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty( -this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this. -options.poolSize||10,this.options.maxUses=this.options.maxUses||1/0,this.options. -allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds= -this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this. -Client=this.options.Client||t||ir().Client,this.Promise=this.options.Promise||_. -Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis= -1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue= -[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_isFull(){return this._clients. -length>=this.options.max}_pulseQueue(){if(this.log("pulse queue"),this.ended){this. -log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"), -this._idle.length&&this._idle.slice().map(t=>{this._remove(t.client)}),this._clients. -length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){ -this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return; -let e=this._pendingQueue.shift();if(this._idle.length){let t=this._idle.pop();clearTimeout( -t.timeoutId);let n=t.client;n.ref&&n.ref();let i=t.idleListener;return this._acquireClient( -n,e,i,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpecte\ -d condition")}_remove(e){let t=ya(this._idle,n=>n.client===e);t!==void 0&&clearTimeout( -t.timeoutId),this._clients=this._clients.filter(n=>n!==e),e.end(),this.emit("rem\ -ove",e)}connect(e){if(this.ending){let i=new Error("Cannot use a pool after call\ -ing end on the pool");return e?e(i):this.Promise.reject(i)}let t=nr(this.Promise, -e),n=t.result;if(this._isFull()||this._idle.length){if(this._idle.length&&g.nextTick( -()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue. -push(new Xe(t.callback)),n;let i=o((u,c,l)=>{clearTimeout(a),t.callback(u,c,l)}, -"queueCallback"),s=new Xe(i),a=setTimeout(()=>{ya(this._pendingQueue,u=>u.callback=== -i),s.timedOut=!0,t.callback(new Error("timeout exceeded when trying to connect"))}, -this.options.connectionTimeoutMillis);return this._pendingQueue.push(s),n}return this. -newClient(new Xe(t.callback)),n}newClient(e){let t=new this.Client(this.options); -this._clients.push(t);let n=lh(this,t);this.log("checking client timeout");let i, -s=!1;this.options.connectionTimeoutMillis&&(i=setTimeout(()=>{this.log("ending c\ -lient due to timeout"),s=!0,t.connection?t.connection.stream.destroy():t.end()}, -this.options.connectionTimeoutMillis)),this.log("connecting new client"),t.connect( -a=>{if(i&&clearTimeout(i),t.on("error",n),a)this.log("client failed to connect", -a),this._clients=this._clients.filter(u=>u!==t),s&&(a.message="Connection termin\ -ated due to connection timeout"),this._pulseQueue(),e.timedOut||e.callback(a,void 0, -pa);else{if(this.log("new client connected"),this.options.maxLifetimeSeconds!==0){ -let u=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired. -add(t),this._idle.findIndex(l=>l.client===t)!==-1&&this._acquireClient(t,new Xe( -(l,h,f)=>f()),n,!1)},this.options.maxLifetimeSeconds*1e3);u.unref(),t.once("end", -()=>clearTimeout(u))}return this._acquireClient(t,e,n,!0)}})}_acquireClient(e,t,n,i){ -i&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,n), -e.removeListener("error",n),t.timedOut?i&&this.options.verify?this.options.verify( -e,e.release):e.release():i&&this.options.verify?this.options.verify(e,s=>{if(s)return e. -release(s),t.callback(s,void 0,pa);t.callback(void 0,e,e.release)}):t.callback(void 0, -e,e.release)}_releaseOnce(e,t){let n=!1;return i=>{n&&ch(),n=!0,this._release(e, -t,i)}}_release(e,t,n){if(e.on("error",t),e._poolUseCount=(e._poolUseCount||0)+1, -this.emit("release",n,e),n||this.ending||!e._queryable||e._ending||e._poolUseCount>= -this.options.maxUses){e._poolUseCount>=this.options.maxUses&&this.log("remove ex\ -pended client"),this._remove(e),this._pulseQueue();return}if(this._expired.has(e)){ -this.log("remove expired client"),this._expired.delete(e),this._remove(e),this._pulseQueue(); -return}let s;this.options.idleTimeoutMillis&&(s=setTimeout(()=>{this.log("remove\ - idle client"),this._remove(e)},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&& -s.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new Bn(e,t,s)), -this._pulseQueue()}query(e,t,n){if(typeof e=="function"){let s=nr(this.Promise,e); -return L(function(){return s.callback(new Error("Passing a function as the first\ - parameter to pool.query is not supported"))}),s.result}typeof t=="function"&&(n= -t,t=void 0);let i=nr(this.Promise,n);return n=i.callback,this.connect((s,a)=>{if(s) -return n(s);let u=!1,c=o(l=>{u||(u=!0,a.release(l),n(l))},"onError");a.once("err\ -or",c),this.log("dispatching query");try{a.query(e,t,(l,h)=>{if(this.log("query \ -dispatched"),a.removeListener("error",c),!u)return u=!0,a.release(l),l?n(l):n(void 0, -h)})}catch(l){return a.release(l),n(l)}}),i.result}end(e){if(this.log("ending"), -this.ending){let n=new Error("Called end on pool more than once");return e?e(n): -this.Promise.reject(n)}this.ending=!0;let t=nr(this.Promise,e);return this._endCallback= -t.callback,this._pulseQueue(),t.result}get waitingCount(){return this._pendingQueue. -length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients. -reduce((e,t)=>e+(this._expired.has(t)?1:0),0)}get totalCount(){return this._clients. -length}};ma.exports=Rn});var ga={};de(ga,{default:()=>hh});var hh,Sa=ue(()=>{"use strict";p();hh={}});var Ea=B((xp,fh)=>{fh.exports={name:"pg",version:"8.8.0",description:"PostgreSQL\ - client - pure javascript & libpq with the same API",keywords:["database","libpq", -"pg","postgre","postgres","postgresql","rdbms"],homepage:"https://github.com/bri\ -anc/node-postgres",repository:{type:"git",url:"git://github.com/brianc/node-post\ -gres.git",directory:"packages/pg"},author:"Brian Carlson ",main:"./lib",dependencies:{"buffer-writer":"2.0.0","packet-reader":"1.0.0", -"pg-connection-string":"^2.5.0","pg-pool":"^3.5.2","pg-protocol":"^1.5.0","pg-ty\ -pes":"^2.1.0",pgpass:"1.x"},devDependencies:{async:"2.6.4",bluebird:"3.5.2",co:"\ -4.6.0","pg-copy-streams":"0.3.0"},peerDependencies:{"pg-native":">=3.0.1"},peerDependenciesMeta:{ -"pg-native":{optional:!0}},scripts:{test:"make test-all"},files:["lib","SPONSORS\ -.md"],license:"MIT",engines:{node:">= 8.0.0"},gitHead:"c99fb2c127ddf8d712500db2c\ -7b9a5491a178655"}});var Aa=B((Ap,xa)=>{"use strict";p();var ba=Te().EventEmitter,dh=(lt(),X(ct)),Nn=Et(), -et=xa.exports=function(r,e,t){ba.call(this),r=Nn.normalizeQueryConfig(r,e,t),this. -text=r.text,this.values=r.values,this.name=r.name,this.callback=r.callback,this. -state="new",this._arrayMode=r.rowMode==="array",this._emitRowEvents=!1,this.on("\ -newListener",function(n){n==="row"&&(this._emitRowEvents=!0)}.bind(this))};dh.inherits( -et,ba);var ph={sqlState:"code",statementPosition:"position",messagePrimary:"mess\ -age",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"\ -dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"\ -routine"};et.prototype.handleError=function(r){var e=this.native.pq.resultErrorFields(); -if(e)for(var t in e){var n=ph[t]||t;r[n]=e[t]}this.callback?this.callback(r):this. -emit("error",r),this.state="error"};et.prototype.then=function(r,e){return this. -_getPromise().then(r,e)};et.prototype.catch=function(r){return this._getPromise(). -catch(r)};et.prototype._getPromise=function(){return this._promise?this._promise: -(this._promise=new Promise(function(r,e){this._once("end",r),this._once("error", -e)}.bind(this)),this._promise)};et.prototype.submit=function(r){this.state="runn\ -ing";var e=this;this.native=r.native,r.native.arrayMode=this._arrayMode;var t=o( -function(s,a,u){if(r.native.arrayMode=!1,L(function(){e.emit("_done")}),s)return e. -handleError(s);e._emitRowEvents&&(u.length>1?a.forEach((c,l)=>{c.forEach(h=>{e.emit( -"row",h,u[l])})}):a.forEach(function(c){e.emit("row",c,u)})),e.state="end",e.emit( -"end",u),e.callback&&e.callback(null,u)},"after");if(g.domain&&(t=g.domain.bind( -t)),this.name){this.name.length>63&&(console.error("Warning! Postgres only suppo\ -rts 63 characters for query names."),console.error("You supplied %s (%s)",this.name, -this.name.length),console.error("This can cause conflicts and silent errors exec\ -uting queries"));var n=(this.values||[]).map(Nn.prepareValue);if(r.namedQueries[this. -name]){if(this.text&&r.namedQueries[this.name]!==this.text){let s=new Error(`Pre\ -pared statements must be unique - '${this.name}' was used for a different statem\ -ent`);return t(s)}return r.native.execute(this.name,n,t)}return r.native.prepare( -this.name,this.text,n.length,function(s){return s?t(s):(r.namedQueries[e.name]=e. -text,e.native.execute(e.name,n,t))})}else if(this.values){if(!Array.isArray(this. -values)){let s=new Error("Query values must be an array");return t(s)}var i=this. -values.map(Nn.prepareValue);r.native.query(this.text,i,t)}else r.native.query(this. -text,t)}});var La=B((Lp,_a)=>{"use strict";p();var yh=(Sa(),X(ga)),mh=Vt(),_p=Ea(),va=Te(). -EventEmitter,wh=(lt(),X(ct)),gh=zt(),Ca=Aa(),he=_a.exports=function(r){va.call(this), -r=r||{},this._Promise=r.Promise||_.Promise,this._types=new mh(r.types),this.native= -new yh({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting= -!1,this._connected=!1,this._queryable=!0;var e=this.connectionParameters=new gh( -r);this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1, -writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port= -e.port,this.namedQueries={}};he.Query=Ca;wh.inherits(he,va);he.prototype._errorAllQueries= -function(r){let e=o(t=>{g.nextTick(()=>{t.native=this.native,t.handleError(r)})}, -"enqueueError");this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery= -null),this._queryQueue.forEach(e),this._queryQueue.length=0};he.prototype._connect= -function(r){var e=this;if(this._connecting){g.nextTick(()=>r(new Error("Client h\ -as already been connected. You cannot reuse a client.")));return}this._connecting= -!0,this.connectionParameters.getLibpqConnectionString(function(t,n){if(t)return r( -t);e.native.connect(n,function(i){if(i)return e.native.end(),r(i);e._connected=!0, -e.native.on("error",function(s){e._queryable=!1,e._errorAllQueries(s),e.emit("er\ -ror",s)}),e.native.on("notification",function(s){e.emit("notification",{channel:s. -relname,payload:s.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),r()})})};he. -prototype.connect=function(r){if(r){this._connect(r);return}return new this._Promise( -(e,t)=>{this._connect(n=>{n?t(n):e()})})};he.prototype.query=function(r,e,t){var n, -i,s,a,u;if(r==null)throw new TypeError("Client was passed a null or undefined qu\ -ery");if(typeof r.submit=="function")s=r.query_timeout||this.connectionParameters. -query_timeout,i=n=r,typeof e=="function"&&(r.callback=e);else if(s=this.connectionParameters. -query_timeout,n=new Ca(r,e,t),!n.callback){let c,l;i=new this._Promise((h,f)=>{c= -h,l=f}),n.callback=(h,f)=>h?l(h):c(f)}return s&&(u=n.callback,a=setTimeout(()=>{ -var c=new Error("Query read timeout");g.nextTick(()=>{n.handleError(c,this.connection)}), -u(c),n.callback=()=>{};var l=this._queryQueue.indexOf(n);l>-1&&this._queryQueue. -splice(l,1),this._pulseQueryQueue()},s),n.callback=(c,l)=>{clearTimeout(a),u(c,l)}), -this._queryable?this._ending?(n.native=this.native,g.nextTick(()=>{n.handleError( -new Error("Client was closed and is not queryable"))}),i):(this._queryQueue.push( -n),this._pulseQueryQueue(),i):(n.native=this.native,g.nextTick(()=>{n.handleError( -new Error("Client has encountered a connection error and is not queryable"))}),i)}; -he.prototype.end=function(r){var e=this;this._ending=!0,this._connected||this.once( -"connect",this.end.bind(this,r));var t;return r||(t=new this._Promise(function(n,i){ -r=o(s=>s?i(s):n(),"cb")})),this.native.end(function(){e._errorAllQueries(new Error( -"Connection terminated")),g.nextTick(()=>{e.emit("end"),r&&r()})}),t};he.prototype. -_hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="\ -error"&&this._activeQuery.state!=="end"};he.prototype._pulseQueryQueue=function(r){ -if(this._connected&&!this._hasActiveQuery()){var e=this._queryQueue.shift();if(!e){ -r||this.emit("drain");return}this._activeQuery=e,e.submit(this);var t=this;e.once( -"_done",function(){t._pulseQueryQueue()})}};he.prototype.cancel=function(r){this. -_activeQuery===r?this.native.cancel(function(){}):this._queryQueue.indexOf(r)!== --1&&this._queryQueue.splice(this._queryQueue.indexOf(r),1)};he.prototype.ref=function(){}; -he.prototype.unref=function(){};he.prototype.setTypeParser=function(r,e,t){return this. -_types.setTypeParser(r,e,t)};he.prototype.getTypeParser=function(r,e){return this. -_types.getTypeParser(r,e)}});var Mn=B((Ip,Ta)=>{"use strict";p();Ta.exports=La()});var ir=B((Rp,xt)=>{"use strict";p();var Sh=da(),Eh=St(),bh=In(),xh=wa(),{DatabaseError:Ah}=Tn(), -vh=o(r=>class extends xh{static{o(this,"BoundPool")}constructor(t){super(t,r)}}, -"poolFactory"),Fn=o(function(r){this.defaults=Eh,this.Client=r,this.Query=this.Client. -Query,this.Pool=vh(this.Client),this._pools=[],this.Connection=bh,this.types=gt(), -this.DatabaseError=Ah},"PG");typeof g.env.NODE_PG_FORCE_NATIVE<"u"?xt.exports=new Fn( -Mn()):(xt.exports=new Fn(Sh),Object.defineProperty(xt.exports,"native",{configurable:!0, -enumerable:!1,get(){var r=null;try{r=new Fn(Mn())}catch(e){if(e.code!=="MODULE_N\ -OT_FOUND")throw e}return Object.defineProperty(xt.exports,"native",{value:r}),r}}))});p();var Cr={};de(Cr,{SocketReadQueue:()=>Xo,TrustedCert:()=>mi,WebSocketReadQueue:()=>Zo, -startTls:()=>Yo});p();function ie(...r){if(r.length===1&&r[0]instanceof Uint8Array)return r[0];let e=r. -reduce((i,s)=>i+s.length,0),t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+= -i.length;return t}o(ie,"p");function ot(r,e){let t=r.length;if(t!==e.length)return!1; -for(let n=0;nthis.data.length)throw new Error("Expected length e\ -xceeds remaining data length");return this.indent+=e,this.indents[t]=this.indent, -[()=>{if(this.indent-=e,this.indents[this.offset]=this.indent,this.offset!==n)throw new Error( -`${r} bytes expected but ${this.offset-t} read`)},()=>n-this.offset]}expectLengthUint8(r){ -let e=this.readUint8();return this.expectLength(e)}expectLengthUint16(r){let e=this. -readUint16();return this.expectLength(e)}expectLengthUint24(r){let e=this.readUint24(); -return this.expectLength(e)}expectLengthUint32(r){let e=this.readUint32();return this. -expectLength(e)}expectLengthUint8Incl(r){let e=this.readUint8();return this.expectLength( -e-1)}expectLengthUint16Incl(r){let e=this.readUint16();return this.expectLength( -e-2)}expectLengthUint24Incl(r){let e=this.readUint24();return this.expectLength( -e-3)}expectLengthUint32Incl(r){let e=this.readUint32();return this.expectLength( -e-4)}writeBytes(r){return this.data.set(r,this.offset),this.offset+=r.length,this}writeUTF8String(r){ -let e=ui.encode(r);return this.writeBytes(e),this}writeUTF8StringNullTerminated(r){ -let e=ui.encode(r);return this.writeBytes(e),this.writeUint8(0),this}writeUint8(r,e){ -return this.dataView.setUint8(this.offset,r),this.offset+=1,this}writeUint16(r,e){ -return this.dataView.setUint16(this.offset,r),this.offset+=2,this}writeUint24(r,e){ -return this.writeUint8((r&16711680)>>16),this.writeUint16(r&65535,e),this}writeUint32(r,e){ -return this.dataView.setUint32(this.offset,r),this.offset+=4,this}_writeLengthGeneric(r,e,t){ -let n=this.offset;this.offset+=r;let i=this.offset;return this.indent+=1,this.indents[i]= -this.indent,()=>{let s=this.offset-(e?n:i);if(r===1)this.dataView.setUint8(n,s);else if(r=== -2)this.dataView.setUint16(n,s);else if(r===3)this.dataView.setUint8(n,(s&16711680)>> -16),this.dataView.setUint16(n+1,s&65535);else if(r===4)this.dataView.setUint32(n, -s);else throw new Error(`Invalid length for length field: ${r}`);this.indent-=1, -this.indents[this.offset]=this.indent}}writeLengthUint8(r){return this._writeLengthGeneric( -1,!1,r)}writeLengthUint16(r){return this._writeLengthGeneric(2,!1,r)}writeLengthUint24(r){ -return this._writeLengthGeneric(3,!1,r)}writeLengthUint32(r){return this._writeLengthGeneric( -4,!1,r)}writeLengthUint8Incl(r){return this._writeLengthGeneric(1,!0,r)}writeLengthUint16Incl(r){ -return this._writeLengthGeneric(2,!0,r)}writeLengthUint24Incl(r){return this._writeLengthGeneric( -3,!0,r)}writeLengthUint32Incl(r){return this._writeLengthGeneric(4,!0,r)}array(){ -return this.data.subarray(0,this.offset)}commentedString(r=!1){let e=this.indents[0]!== -void 0?Sr.repeat(this.indents[0]):"",t=this.indents[0]??0,n=r?this.data.length:this. -offset;for(let i=0;it. -toString(16).padStart(2,"0")).join(e)}o(_e,"K");function Po(r,e){let t,n,[i]=r.expectLength( -r.remaining());r.expectUint8(2,0);let[s]=r.expectLengthUint24(0);r.expectUint16( -771,0);let a=r.readBytes(32);if(ot(a,[207,33,173,116,229,154,97,17,190,29,140,2, -30,101,184,145,194,162,17,22,122,187,140,94,7,158,9,226,200,168,51,156]))throw new Error( -"Unexpected HelloRetryRequest");r.expectUint8(e.length,0),r.expectBytes(e,0),r.expectUint16( -4865,0),r.expectUint8(0,0);let[u,c]=r.expectLengthUint16(0);for(;c()>0;){let l=r. -readUint16(0),[h]=r.expectLengthUint16(0);if(l===43)r.expectUint16(772,0),n=!0;else if(l=== -51)r.expectUint16(23,0),r.expectUint16(65),t=r.readBytes(65);else throw new Error( -`Unexpected extension 0x${_e([l])}`);h()}if(u(),s(),i(),n!==!0)throw new Error("\ -No TLS version provided");if(t===void 0)throw new Error("No key provided");return t} -o(Po,"Ut");var Qh=new RegExp(` .+|^(${Sr})+`,"gm"),at=16384,Bo=at+1+255;async function Er(r,e,t=at){ -let n=await r(5);if(n===void 0)return;if(n.length<5)throw new Error("TLS record \ -header truncated");let i=new Ee(n),s=i.readUint8();if(s<20||s>24)throw new Error( -`Illegal TLS record type 0x${s.toString(16)}`);if(e!==void 0&&s!==e)throw new Error( -`Unexpected TLS record type 0x${s.toString(16).padStart(2,"0")} (expected 0x${e. -toString(16).padStart(2,"0")})`);i.expectUint16(771,"TLS record version 1.2 (mid\ -dlebox compatibility)");let a=i.readUint16(0);if(a>t)throw new Error(`Record too\ - long: ${a} bytes`);let u=await r(a);if(u===void 0||u.length>3,s=Math.ceil(t/i),a=new Uint8Array(s*i),u=await O.importKey("raw",r,{name:"\ -HMAC",hash:{name:`SHA-${n}`}},!1,["sign"]),c=new Uint8Array(0);for(let l=0;l>8,n&255],[li.length+s.length],li,s,[t.length], -t);return No(r,a,n,i)}o(se,"S");async function Mo(r,e,t,n,i){let s=n>>>3,a=new Uint8Array( -s),u=await O.importKey("raw",r,{name:"ECDH",namedCurve:"P-256"},!1,[]),c=await O. -deriveBits({name:"ECDH",public:u},e,256),l=new Uint8Array(c),h=await O.digest("S\ -HA-256",t),f=new Uint8Array(h),y=await xr(new Uint8Array(1),a,n),w=await O.digest( -`SHA-${n}`,new Uint8Array(0)),b=new Uint8Array(w),U=await se(y,"derived",b,s,n), -v=await xr(U,l,n),C=await se(v,"c hs traffic",f,s,n),E=await se(v,"s hs traffic", -f,s,n),S=await se(C,"key",new Uint8Array(0),i,n),x=await se(E,"key",new Uint8Array( -0),i,n),N=await se(C,"iv",new Uint8Array(0),12,n),P=await se(E,"iv",new Uint8Array( -0),12,n);return{serverHandshakeKey:x,serverHandshakeIV:P,clientHandshakeKey:S,clientHandshakeIV:N, -handshakeSecret:v,clientSecret:C,serverSecret:E}}o(Mo,"Kt");async function Fo(r,e,t,n){ -let i=t>>>3,s=new Uint8Array(i),a=await O.digest(`SHA-${t}`,new Uint8Array(0)),u=new Uint8Array( -a),c=await se(r,"derived",u,i,t),l=await xr(c,s,t),h=await se(l,"c ap traffic",e, -i,t),f=await se(l,"s ap traffic",e,i,t),y=await se(h,"key",new Uint8Array(0),n,t), -w=await se(f,"key",new Uint8Array(0),n,t),b=await se(h,"iv",new Uint8Array(0),12, -t),U=await se(f,"iv",new Uint8Array(0),12,t);return{serverApplicationKey:w,serverApplicationIV:U, -clientApplicationKey:y,clientApplicationIV:b}}o(Fo,"Tt");var Nt=class{static{o(this, -"Z")}constructor(r,e,t){this.mode=r,this.key=e,this.initialIv=t}recordsProcessed=0n;priorPromise=Promise. -resolve(new Uint8Array);async process(r,e,t){let n=this.processUnsequenced(r,e,t); -return this.priorPromise=this.priorPromise.then(()=>n)}async processUnsequenced(r,e,t){ -let n=this.recordsProcessed;this.recordsProcessed+=1n;let i=this.initialIv.slice(), -s=BigInt(i.length),a=s-1n;for(let h=0n;h>(h<<3n);if(f===0n)break; -i[Number(a-h)]^=Number(f&0xffn)}let u=e<<3,c={name:"AES-GCM",iv:i,tagLength:u,additionalData:t}, -l=await O[this.mode](c,this.key,r);return new Uint8Array(l)}};function Mt(r){return r> -64&&r<91?r-65:r>96&&r<123?r-71:r>47&&r<58?r+4:r===43?62:r===47?63:r===61?64:void 0} -o(Mt,"yt");function Do(r){let e=r.length,t=0,n=0,i=64,s=64,a=64,u=64,c=new Uint8Array( -e*.75);for(;t>4,c[n++]=(s&15)<<4|a>>2,c[n++]=(a&3)<< -6|u;let l=s===64?0:a===64?2:u===64?1:0;return c.subarray(0,n-l)}o(Do,"Dt");var Ft=class extends Ee{static{ -o(this,"M")}readASN1Length(r){let e=this.readUint8();if(e<128)return e;let t=e&127, -n=0;if(t===1)return this.readUint8(n);if(t===2)return this.readUint16(n);if(t=== -3)return this.readUint24(n);if(t===4)return this.readUint32(n);throw new Error(`\ -ASN.1 length fields are only supported up to 4 bytes (this one is ${t} bytes)`)}expectASN1Length(r){ -let e=this.readASN1Length(r);return this.expectLength(e)}readASN1OID(){let[r,e]=this. -expectASN1Length(0),t=this.readUint8(),n=`${Math.floor(t/40)}.${t%40}`;for(;e()> -0;){let i=0;for(;;){let s=this.readUint8();if(i<<=7,i+=s&127,s<128)break}n+=`.${i}`} -return r(),n}readASN1Boolean(){let[r,e]=this.expectASN1Length(0),t=e();if(t!==1) -throw new Error(`Boolean has weird length: ${t}`);let n=this.readUint8(),i;if(n=== -255)i=!0;else if(n===0)i=!1;else throw new Error(`Boolean has weird value: 0x${_e( -[n])}`);return r(),i}readASN1UTCTime(){let[r,e]=this.expectASN1Length(0),t=this. -readUTF8String(e()).match(/^(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)Z$/);if(!t)throw new Error( -"Unrecognised ASN.1 UTC time format");let[,n,i,s,a,u,c]=t,l=parseInt(n,10),h=l+(l>= -50?1900:2e3),f=new Date(`${h}-${i}-${s}T${a}:${u}:${c}Z`);return r(),f}readASN1BitString(){ -let[r,e]=this.expectASN1Length(0),t=this.readUint8(0),n=e(),i=this.readBytes(n); -if(t>7)throw new Error(`Invalid right pad value: ${t}`);if(t>0){let s=8-t;for(let a=n- -1;a>0;a--)i[a]=255&i[a-1]<>>t;i[0]=i[0]>>>t}return r(),i}};function hi(r,e=(n,i)=>i,t){ -return JSON.stringify(r,(n,i)=>e(n,typeof i!="object"||i===null||Array.isArray(i)? -i:Object.fromEntries(Object.entries(i).sort(([s],[a])=>sa?1:0))),t)}o(hi, -"mt");var mr=1,Dt=2,ne=48,qo=49,He=6,Oo=19,ko=12,fi=23,wr=5,Me=4,gr=3,Qo=163,je=128, -$o={"2.5.4.6":"C","2.5.4.10":"O","2.5.4.11":"OU","2.5.4.3":"CN","2.5.4.7":"L","2\ -.5.4.8":"ST","2.5.4.12":"T","2.5.4.42":"GN","2.5.4.43":"I","2.5.4.4":"SN","1.2.8\ -40.113549.1.9.1":"E-mail"};function jo(r){let{length:e}=r;if(e>4)throw new Error( -`Bit string length ${e} would overflow JS bit operators`);let t=0,n=0;for(let i=r. -length-1;i>=0;i--)t|=r[i]<0;){r.expectUint8(qo, -0);let[s]=r.expectASN1Length(0);r.expectUint8(ne,0);let[a]=r.expectASN1Length(0); -r.expectUint8(He,0);let u=r.readASN1OID(),c=$o[u]??u,l=r.readUint8();if(l!==Oo&& -l!==ko)throw new Error(`Unexpected item type in certificate ${e}: 0x${_e([l])}`); -let[h,f]=r.expectASN1Length(0),y=r.readUTF8String(f());if(h(),a(),s(),t[c]!==void 0) -throw new Error(`Duplicate OID ${c} in certificate ${e}`);t[c]=y}return n(),t}o( -di,"Ct");function Ho(r,e=0){let t=[],[n,i]=r.expectASN1Length(0);for(;i()>0;){let s=r. -readUint8(0),[a,u]=r.expectASN1Length(0),c;s===(e|2)?c=r.readUTF8String(u()):c=r. -readBytes(u()),t.push({name:c,type:s}),a()}return n(),t}o(Ho,"Bt");function Ko(r){ -let e={"1.2.840.113549.1.1.1":{name:"RSAES-PKCS1-v1_5"},"1.2.840.113549.1.1.5":{ -name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}},"1.2.840.113549.1.1.11":{name:"RSA\ -SSA-PKCS1-v1_5",hash:{name:"SHA-256"}},"1.2.840.113549.1.1.12":{name:"RSASSA-PKC\ -S1-v1_5",hash:{name:"SHA-384"}},"1.2.840.113549.1.1.13":{name:"RSASSA-PKCS1-v1_5", -hash:{name:"SHA-512"}},"1.2.840.113549.1.1.10":{name:"RSA-PSS"},"1.2.840.113549.\ -1.1.7":{name:"RSA-OAEP"},"1.2.840.10045.2.1":{name:"ECDSA",hash:{name:"SHA-1"}}, -"1.2.840.10045.4.1":{name:"ECDSA",hash:{name:"SHA-1"}},"1.2.840.10045.4.3.2":{name:"\ -ECDSA",hash:{name:"SHA-256"}},"1.2.840.10045.4.3.3":{name:"ECDSA",hash:{name:"SH\ -A-384"}},"1.2.840.10045.4.3.4":{name:"ECDSA",hash:{name:"SHA-512"}},"1.3.133.16.\ -840.63.0.2":{name:"ECDH",kdf:"SHA-1"},"1.3.132.1.11.1":{name:"ECDH",kdf:"SHA-256"}, -"1.3.132.1.11.2":{name:"ECDH",kdf:"SHA-384"},"1.3.132.1.11.3":{name:"ECDH",kdf:"\ -SHA-512"},"2.16.840.1.101.3.4.1.2":{name:"AES-CBC",length:128},"2.16.840.1.101.3\ -.4.1.22":{name:"AES-CBC",length:192},"2.16.840.1.101.3.4.1.42":{name:"AES-CBC",length:256}, -"2.16.840.1.101.3.4.1.6":{name:"AES-GCM",length:128},"2.16.840.1.101.3.4.1.26":{ -name:"AES-GCM",length:192},"2.16.840.1.101.3.4.1.46":{name:"AES-GCM",length:256}, -"2.16.840.1.101.3.4.1.4":{name:"AES-CFB",length:128},"2.16.840.1.101.3.4.1.24":{ -name:"AES-CFB",length:192},"2.16.840.1.101.3.4.1.44":{name:"AES-CFB",length:256}, -"2.16.840.1.101.3.4.1.5":{name:"AES-KW",length:128},"2.16.840.1.101.3.4.1.25":{name:"\ -AES-KW",length:192},"2.16.840.1.101.3.4.1.45":{name:"AES-KW",length:256},"1.2.84\ -0.113549.2.7":{name:"HMAC",hash:{name:"SHA-1"}},"1.2.840.113549.2.9":{name:"HMAC", -hash:{name:"SHA-256"}},"1.2.840.113549.2.10":{name:"HMAC",hash:{name:"SHA-384"}}, -"1.2.840.113549.2.11":{name:"HMAC",hash:{name:"SHA-512"}},"1.2.840.113549.1.9.16\ -.3.5":{name:"DH"},"1.3.14.3.2.26":{name:"SHA-1"},"2.16.840.1.101.3.4.2.1":{name:"\ -SHA-256"},"2.16.840.1.101.3.4.2.2":{name:"SHA-384"},"2.16.840.1.101.3.4.2.3":{name:"\ -SHA-512"},"1.2.840.113549.1.5.12":{name:"PBKDF2"},"1.2.840.10045.3.1.7":{name:"P\ --256"},"1.3.132.0.34":{name:"P-384"},"1.3.132.0.35":{name:"P-521"}}[r];if(e===void 0) -throw new Error(`Unsupported algorithm identifier: ${r}`);return e}o(Ko,"Ft");function yi(r,e=[]){ -return Object.values(r).forEach(t=>{typeof t=="string"?e=[...e,t]:e=yi(t,e)}),e} -o(yi,"Ot");function Wo(r){return yi(r).join(" / ")}o(Wo,"Pt");var Go=["digitalSi\ -gnature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","k\ -eyCertSign","cRLSign","encipherOnly","decipherOnly"],vr=class Ar{static{o(this,"\ -r")}serialNumber;algorithm;issuer;validityPeriod;subject;publicKey;signature;keyUsage;subjectAltNames;extKeyUsage;authorityKeyIdentifier;subjectKeyIdentifier;basicConstraints;signedData;static distinguishedNamesAreEqual(e,t){ -return hi(e)===hi(t)}static readableDN(e){return Object.entries(e).map(t=>t.join( -"=")).join(", ")}constructor(e){let t=e instanceof Ft?e:new Ft(e);t.expectUint8( -ne,0);let[n]=t.expectASN1Length(0),i=t.offset;t.expectUint8(ne,0);let[s]=t.expectASN1Length( -0);t.expectBytes([160,3,2,1,2],0),t.expectUint8(Dt,0);let[a,u]=t.expectASN1Length( -0);this.serialNumber=t.subarray(u()),a(),t.expectUint8(ne,0);let[c,l]=t.expectASN1Length( -0);t.expectUint8(He,0),this.algorithm=t.readASN1OID(),l()>0&&(t.expectUint8(wr,0), -t.expectUint8(0,0)),c(),this.issuer=di(t,"issuer"),t.expectUint8(ne,0);let[h]=t. -expectASN1Length(0);t.expectUint8(fi,0);let f=t.readASN1UTCTime();t.expectUint8( -fi,0);let y=t.readASN1UTCTime();this.validityPeriod={notBefore:f,notAfter:y},h(), -this.subject=di(t,"subject");let w=t.offset;t.expectUint8(ne,0);let[b]=t.expectASN1Length( -0);t.expectUint8(ne,0);let[U,v]=t.expectASN1Length(0),C=[];for(;v()>0;){let Y=t. -readUint8();if(Y===He){let M=t.readASN1OID();C.push(M)}else Y===wr&&t.expectUint8( -0,0)}U(),t.expectUint8(gr,0);let E=t.readASN1BitString();this.publicKey={identifiers:C, -data:E,all:t.data.subarray(w,t.offset)},b(),t.expectUint8(Qo,0);let[S]=t.expectASN1Length(); -t.expectUint8(ne,0);let[x,N]=t.expectASN1Length(0);for(;N()>0;){t.expectUint8(ne, -0);let[Y,M]=t.expectASN1Length();t.expectUint8(He,0);let $=t.readASN1OID();if($=== -"2.5.29.17"){t.expectUint8(Me,0);let[j]=t.expectASN1Length(0);t.expectUint8(ne,0); -let H=Ho(t,je);this.subjectAltNames=H.filter(W=>W.type===(2|je)).map(W=>W.name), -j()}else if($==="2.5.29.15"){t.expectUint8(mr,0);let j=t.readASN1Boolean();t.expectUint8( -Me,0);let[H]=t.expectASN1Length(0);t.expectUint8(gr,0);let W=t.readASN1BitString(), -G=jo(W),D=new Set(Go.filter((K,q)=>G&1<0;){t.expectUint8(He, -0);let G=t.readASN1OID();G==="1.3.6.1.5.5.7.3.1"&&(this.extKeyUsage.serverTls=!0), -G==="1.3.6.1.5.5.7.3.2"&&(this.extKeyUsage.clientTls=!0)}H(),j()}else if($==="2.\ -5.29.35"){t.expectUint8(Me,0);let[j]=t.expectASN1Length(0);t.expectUint8(ne,0);let[ -H,W]=t.expectASN1Length(0);for(;W()>0;){let G=t.readUint8();if(G===(je|0)){let[D, -K]=t.expectASN1Length(0);this.authorityKeyIdentifier=t.readBytes(K()),D()}else if(G=== -(je|1)){let[D,K]=t.expectASN1Length(0);t.skip(K(),0),D()}else if(G===(je|2)){let[ -D,K]=t.expectASN1Length(0);t.skip(K(),0),D()}else if(G===(je|33)){let[D,K]=t.expectASN1Length( -0);t.skip(K(),0),D()}else throw new Error(`Unexpected data type ${G} in authorit\ -yKeyIdentifier certificate extension`)}H(),j()}else if($==="2.5.29.14"){t.expectUint8( -Me,0);let[j]=t.expectASN1Length(0);t.expectUint8(Me,0);let[H,W]=t.expectASN1Length( -0);this.subjectKeyIdentifier=t.readBytes(W()),H(),j()}else if($==="2.5.29.19"){let j, -H=t.readUint8();if(H===mr&&(j=t.readASN1Boolean(),H=t.readUint8()),H!==Me)throw new Error( -"Unexpected type in certificate basic constraints");let[W]=t.expectASN1Length(0); -t.expectUint8(ne,0);let[G,D]=t.expectASN1Length(),K;D()>0&&(t.expectUint8(mr,0), -K=t.readASN1Boolean());let q;if(D()>0){t.expectUint8(Dt,0);let R=t.readASN1Length( -0);if(q=R===1?t.readUint8():R===2?t.readUint16():R===3?t.readUint24():void 0,q=== -void 0)throw new Error("Too many bytes in max path length in certificate basicCo\ -nstraints")}G(),W(),this.basicConstraints={critical:j,ca:K,pathLength:q}}else t. -skip(M(),0);Y()}x(),S(),s(),this.signedData=t.data.subarray(i,t.offset),t.expectUint8( -ne,0);let[P,F]=t.expectASN1Length(0);t.expectUint8(He,0);let Q=t.readASN1OID();if(F()> -0&&(t.expectUint8(wr,0),t.expectUint8(0,0)),P(),Q!==this.algorithm)throw new Error( -`Certificate specifies different signature algorithms inside (${this.algorithm})\ - and out (${Q})`);t.expectUint8(gr,0),this.signature=t.readASN1BitString(),n()}static fromPEM(e){ -let t="[A-Z0-9 ]+",n=new RegExp(`-{5}BEGIN ${t}-{5}([a-zA-Z0-9=+\\/\\n\\r]+)-{5}END\ - ${t}-{5}`,"g"),i=[],s=null;for(;s=n.exec(e);){let a=s[1].replace(/[\r\n]/g,""), -u=Do(a),c=new this(u);i.push(c)}return i}subjectAltNameMatchingHost(e){let t=/[.][^.]+[.][^.]+$/; -return(this.subjectAltNames??[]).find(n=>{let i=n,s=e;if(t.test(e)&&t.test(i)&&i. -startsWith("*.")&&(i=i.slice(1),s=s.slice(s.indexOf("."))),i===s)return!0})}isValidAtMoment(e=new Date){ -return e>=this.validityPeriod.notBefore&&e<=this.validityPeriod.notAfter}description(){ -return"subject: "+Ar.readableDN(this.subject)+(this.subjectAltNames?` -subject alt names: `+this.subjectAltNames.join(", "):"")+(this.subjectKeyIdentifier? -` -subject key id: ${_e(this.subjectKeyIdentifier," ")}`:"")+` -issuer: `+Ar.readableDN(this.issuer)+(this.authorityKeyIdentifier?` -authority key id: ${_e(this.authorityKeyIdentifier," ")}`:"")+` -validity: `+this.validityPeriod.notBefore.toISOString()+" \u2013 "+this.validityPeriod. -notAfter.toISOString()+` (${this.isValidAtMoment()?"currently valid":"not valid"}\ -)`+(this.keyUsage?` -key usage (${this.keyUsage.critical?"critical":"non-critical"}): `+[...this.keyUsage. -usages].join(", "):"")+(this.extKeyUsage?` -extended key usage: TLS server \u2014\xA0${this.extKeyUsage.serverTls}, TLS clie\ -nt \u2014\xA0${this.extKeyUsage.clientTls}`:"")+(this.basicConstraints?` -basic constraints (${this.basicConstraints.critical?"critical":"non-critical"}):\ - CA \u2014\xA0${this.basicConstraints.ca}, path length \u2014 ${this.basicConstraints. -pathLength}`:"")+` -signature algorithm: `+Wo(Ko(this.algorithm))}toJSON(){return{serialNumber:[...this. -serialNumber],algorithm:this.algorithm,issuer:this.issuer,validityPeriod:{notBefore:this. -validityPeriod.notBefore.toISOString(),notAfter:this.validityPeriod.notAfter.toISOString()}, -subject:this.subject,publicKey:{identifiers:this.publicKey.identifiers,data:[...this. -publicKey.data],all:[...this.publicKey.all]},signature:[...this.signature],keyUsage:{ -critical:this.keyUsage?.critical,usages:[...this.keyUsage?.usages??[]]},subjectAltNames:this. -subjectAltNames,extKeyUsage:this.extKeyUsage,authorityKeyIdentifier:this.authorityKeyIdentifier&& -[...this.authorityKeyIdentifier],subjectKeyIdentifier:this.subjectKeyIdentifier&& -[...this.subjectKeyIdentifier],basicConstraints:this.basicConstraints,signedData:[ -...this.signedData]}}},mi=class extends vr{static{o(this,"st")}};async function wi(r,e,t,n,i){ -r.expectUint8(ne,0);let[s]=r.expectASN1Length(0);r.expectUint8(Dt,0);let[a,u]=r. -expectASN1Length(0),c=r.readBytes(u());a(),r.expectUint8(Dt,0);let[l,h]=r.expectASN1Length( -0),f=r.readBytes(h());l(),s();let y=o((v,C)=>v.length>C?v.subarray(v.length-C):v. -lengthvr.distinguishedNamesAreEqual(b.subject,l.issuer)):f=t.find(b=>b.subjectKeyIdentifier!== -void 0&&ot(b.subjectKeyIdentifier,h)),f===void 0&&(f=e[u+1]),f===void 0)throw new Error( -"Ran out of certificates before reaching trusted root");let y=f instanceof mi;if(f. -isValidAtMoment()!==!0)throw new Error("Signing certificate is not valid now");if(i&& -f.keyUsage?.usages.has("digitalSignature")!==!0)throw new Error("Signing certifi\ -cate keyUsage does not include digital signatures");if(f.basicConstraints?.ca!== -!0)throw new Error("Signing certificate basicConstraints do not indicate a CA ce\ -rtificate");let{pathLength:w}=f.basicConstraints;if(w!==void 0&&w0;){let R=u. -readUint16(0);if(R===0)u.expectUint16(0,0);else if(R===10){let[Z,fe]=u.expectLengthUint16( -"groups data");u.skip(fe(),0),Z()}else throw new Error(`Unsupported server encry\ -pted extension type 0x${_e([R]).padStart(4,"0")}`)}l(),c(),u.remaining()===0&&u. -extend(await e());let f=!1,y=u.readUint8();if(y===13){f=!0;let[R]=u.expectLengthUint24( -"certificate request data");u.expectUint8(0,0);let[Z,fe]=u.expectLengthUint16("c\ -ertificate request extensions");u.skip(fe(),0),Z(),R(),u.remaining()===0&&u.extend( -await e()),y=u.readUint8()}if(y!==11)throw new Error(`Unexpected handshake messa\ -ge type 0x${_e([y])}`);let[w]=u.expectLengthUint24(0);u.expectUint8(0,0);let[b,U]=u. -expectLengthUint24(0),v=[];for(;U()>0;){let[R]=u.expectLengthUint24(0),Z=new vr( -u);v.push(Z),R();let[fe,ve]=u.expectLengthUint16(),Lt=u.subarray(ve());fe()}if(b(), -w(),v.length===0)throw new Error("No certificates supplied");let C=v[0],E=u.data. -subarray(0,u.offset),S=ie(n,E),x=await O.digest("SHA-256",S),N=new Uint8Array(x), -P=ie(zo.encode(" ".repeat(64)+"TLS 1.3, server CertificateVerify"),[0],N);u.remaining()=== -0&&u.extend(await e()),u.expectUint8(15,0);let[F]=u.expectLengthUint24(0),Q=u.readUint16(); -if(Q===1027){let[R]=u.expectLengthUint16();await wi(u,C.publicKey.all,P,"P-256", -"SHA-256"),R()}else if(Q===2052){let[R,Z]=u.expectLengthUint16(),fe=u.subarray(Z()); -R();let ve=await O.importKey("spki",C.publicKey.all,{name:"RSA-PSS",hash:"SHA-25\ -6"},!1,["verify"]);if(await O.verify({name:"RSA-PSS",saltLength:32},ve,fe,P)!==!0) -throw new Error("RSA-PSS-RSAE-SHA256 certificate verify failed")}else throw new Error( -`Unsupported certificate verify signature type 0x${_e([Q]).padStart(4,"0")}`);F(); -let Y=u.data.subarray(0,u.offset),M=ie(n,Y),$=await se(t,"finished",new Uint8Array( -0),32,256),j=await O.digest("SHA-256",M),H=await O.importKey("raw",$,{name:"HMAC", -hash:{name:"SHA-256"}},!1,["sign"]),W=await O.sign("HMAC",H,j),G=new Uint8Array( -W);u.remaining()===0&&u.extend(await e()),u.expectUint8(20,0);let[D,K]=u.expectLengthUint24( -0),q=u.readBytes(K());if(D(),u.remaining()!==0)throw new Error("Unexpected extra\ - bytes in server handshake");if(ot(q,G)!==!0)throw new Error("Invalid server ver\ -ify hash");if(!await Vo(r,v,i,s,a))throw new Error("Validated certificate chain \ -did not end in a trusted root");return[u.data,f]}o(Jo,"Vt");async function Yo(r,e,t,n,{ -useSNI:i,requireServerTlsExtKeyUsage:s,requireDigitalSigKeyUsage:a,writePreData:u, -expectPreData:c,commentPreData:l}={}){i??=!0,s??=!0,a??=!0;let h=await O.generateKey( -{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]),f=await O.exportKey( -"raw",h.publicKey),y=new Uint8Array(32);A.getRandomValues(y);let w=Io(r,f,y,i).array(), -b=u?ie(u,w):w;if(n(b),c){let re=await t(c.length);if(!re||!ot(re,c))throw new Error( -"Pre data did not match expectation")}let U=await Er(t,22);if(U===void 0)throw new Error( -"Connection closed while awaiting server hello");let v=new Ee(U.content),C=Po(v, -y),E=await Er(t,20);if(E===void 0)throw new Error("Connection closed awaiting se\ -rver cipher change");let S=new Ee(E.content),[x]=S.expectLength(1);S.expectUint8( -1,0),x();let N=w.subarray(5),P=U.content,F=ie(N,P),Q=await Mo(C,h.privateKey,F,256, -16),Y=await O.importKey("raw",Q.serverHandshakeKey,{name:"AES-GCM"},!1,["decrypt"]), -M=new Nt("decrypt",Y,Q.serverHandshakeIV),$=await O.importKey("raw",Q.clientHandshakeKey, -{name:"AES-GCM"},!1,["encrypt"]),j=new Nt("encrypt",$,Q.clientHandshakeIV),H=o(async()=>{ -let re=await br(t,M,22);if(re===void 0)throw new Error("Premature end of encrypt\ -ed server handshake");return re},"C"),[W,G]=await Jo(r,H,Q.serverSecret,F,e,s,a), -D=new Ee(6);D.writeUint8(20,0),D.writeUint16(771,0);let K=D.writeLengthUint16(); -D.writeUint8(1,0),K();let q=D.array(),R=new Uint8Array(0);if(G){let re=new Ee(8); -re.writeUint8(11,0);let nt=re.writeLengthUint24("client certificate data");re.writeUint8( -0,0),re.writeUint24(0,0),nt(),R=re.array()}let Z=ie(F,W,R),fe=await O.digest("SH\ -A-256",Z),ve=new Uint8Array(fe),Lt=await se(Q.clientSecret,"finished",new Uint8Array( -0),32,256),Ma=await O.importKey("raw",Lt,{name:"HMAC",hash:{name:"SHA-256"}},!1, -["sign"]),Fa=await O.sign("HMAC",Ma,ve),Da=new Uint8Array(Fa),Tt=new Ee(36);Tt.writeUint8( -20,0);let qa=Tt.writeLengthUint24(0);Tt.writeBytes(Da),qa();let Oa=Tt.array(),Dn=await ci( -ie(R,Oa),j,22),qn=ve;if(R.length>0){let re=Z.subarray(0,Z.length-R.length),nt=await O. -digest("SHA-256",re);qn=new Uint8Array(nt)}let Ut=await Fo(Q.handshakeSecret,qn, -256,16),ka=await O.importKey("raw",Ut.clientApplicationKey,{name:"AES-GCM"},!0,[ -"encrypt"]),Qa=new Nt("encrypt",ka,Ut.clientApplicationIV),$a=await O.importKey( -"raw",Ut.serverApplicationKey,{name:"AES-GCM"},!0,["decrypt"]),ja=new Nt("decryp\ -t",$a,Ut.serverApplicationIV),It=!1;return[()=>{if(!It){let re=ie(q,...Dn);n(re), -It=!0}return br(t,ja)},async re=>{let nt=It;It=!0;let On=await ci(re,Qa,23),Ha=nt? -ie(...On):ie(q,...Dn,...On);n(Ha)}]}o(Yo,"he");var gi=class{static{o(this,"xt")}queue;outstandingRequest;constructor(){ -this.queue=[]}enqueue(r){this.queue.push(r),this.dequeue()}dequeue(){if(this.outstandingRequest=== -void 0)return;let{resolve:r,bytes:e}=this.outstandingRequest,t=this.bytesInQueue(); -if(te)return this.queue[0]=n.subarray(e),r(n.subarray(0,e)); -{let s=new Uint8Array(e),a=e,u=0;for(;a>0;){let c=this.queue[0],l=c.length;l<=a? -(this.queue.shift(),s.set(c,u),u+=l,a-=l):(this.queue[0]=c.subarray(a),s.set(c.subarray( -0,a),u),a-=a,u+=a)}return r(s)}}bytesInQueue(){return this.queue.reduce((r,e)=>r+ -e.length,0)}async read(r){if(this.outstandingRequest!==void 0)throw new Error("C\ -an\u2019t read while already awaiting read");return new Promise(e=>{this.outstandingRequest= -{resolve:e,bytes:r},this.dequeue()})}},Zo=class extends gi{static{o(this,"vt")}constructor(r){ -super(),this.socket=r,r.addEventListener("message",e=>this.enqueue(new Uint8Array( -e.data))),r.addEventListener("close",()=>this.dequeue())}socketIsNotClosed(){let{ -socket:r}=this,{readyState:e}=r;return e<=1}},Xo=class extends gi{static{o(this, -"Lt")}constructor(r){super(),this.socket=r,r.on("data",e=>this.enqueue(new Uint8Array( -e))),r.on("close",()=>this.dequeue())}socketIsNotClosed(){let{socket:r}=this,{readyState:e}=r; -return e==="opening"||e==="open"}};var Si=`-----BEGIN CERTIFICATE----- -MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw -TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh -cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4 -WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu -ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY -MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc -h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+ -0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U -A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW -T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH -B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC -B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv -KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn -OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn -jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw -qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI -rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV -HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq -hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL -ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ -3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK -NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5 -ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur -TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC -jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc -oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq -4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA -mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d -emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc= ------END CERTIFICATE----- -`;p();var tu=Object.getOwnPropertyNames,ru=Object.getOwnPropertySymbols,nu=Object.prototype. -hasOwnProperty;function Ei(r,e){return o(function(n,i,s){return r(n,i,s)&&e(n,i, -s)},"isEqual")}o(Ei,"combineComparators");function qt(r){return o(function(t,n,i){ -if(!t||!n||typeof t!="object"||typeof n!="object")return r(t,n,i);var s=i.cache, -a=s.get(t),u=s.get(n);if(a&&u)return a===n&&u===t;s.set(t,n),s.set(n,t);var c=r( -t,n,i);return s.delete(t),s.delete(n),c},"isCircular")}o(qt,"createIsCircular"); -function bi(r){return tu(r).concat(ru(r))}o(bi,"getStrictProperties");var Ti=Object. -hasOwn||function(r,e){return nu.call(r,e)};function Ke(r,e){return r||e?r===e:r=== -e||r!==r&&e!==e}o(Ke,"sameValueZeroEqual");var Ui="_owner",xi=Object.getOwnPropertyDescriptor, -Ai=Object.keys;function iu(r,e,t){var n=r.length;if(e.length!==n)return!1;for(;n-- > -0;)if(!t.equals(r[n],e[n],n,n,r,e,t))return!1;return!0}o(iu,"areArraysEqual");function su(r,e){ -return Ke(r.getTime(),e.getTime())}o(su,"areDatesEqual");function vi(r,e,t){if(r. -size!==e.size)return!1;for(var n={},i=r.entries(),s=0,a,u;(a=i.next())&&!a.done;){ -for(var c=e.entries(),l=!1,h=0;(u=c.next())&&!u.done;){var f=a.value,y=f[0],w=f[1], -b=u.value,U=b[0],v=b[1];!l&&!n[h]&&(l=t.equals(y,U,s,h,r,e,t)&&t.equals(w,v,y,U, -r,e,t))&&(n[h]=!0),h++}if(!l)return!1;s++}return!0}o(vi,"areMapsEqual");function au(r,e,t){ -var n=Ai(r),i=n.length;if(Ai(e).length!==i)return!1;for(var s;i-- >0;)if(s=n[i], -s===Ui&&(r.$$typeof||e.$$typeof)&&r.$$typeof!==e.$$typeof||!Ti(e,s)||!t.equals(r[s], -e[s],s,s,r,e,t))return!1;return!0}o(au,"areObjectsEqual");function ut(r,e,t){var n=bi( -r),i=n.length;if(bi(e).length!==i)return!1;for(var s,a,u;i-- >0;)if(s=n[i],s===Ui&& -(r.$$typeof||e.$$typeof)&&r.$$typeof!==e.$$typeof||!Ti(e,s)||!t.equals(r[s],e[s], -s,s,r,e,t)||(a=xi(r,s),u=xi(e,s),(a||u)&&(!a||!u||a.configurable!==u.configurable|| -a.enumerable!==u.enumerable||a.writable!==u.writable)))return!1;return!0}o(ut,"a\ -reObjectsEqualStrict");function ou(r,e){return Ke(r.valueOf(),e.valueOf())}o(ou, -"arePrimitiveWrappersEqual");function uu(r,e){return r.source===e.source&&r.flags=== -e.flags}o(uu,"areRegExpsEqual");function Ci(r,e,t){if(r.size!==e.size)return!1;for(var n={}, -i=r.values(),s,a;(s=i.next())&&!s.done;){for(var u=e.values(),c=!1,l=0;(a=u.next())&& -!a.done;)!c&&!n[l]&&(c=t.equals(s.value,a.value,s.value,a.value,r,e,t))&&(n[l]=!0), -l++;if(!c)return!1}return!0}o(Ci,"areSetsEqual");function cu(r,e){var t=r.length; -if(e.length!==t)return!1;for(;t-- >0;)if(r[t]!==e[t])return!1;return!0}o(cu,"are\ -TypedArraysEqual");var lu="[object Arguments]",hu="[object Boolean]",fu="[object\ - Date]",du="[object Map]",pu="[object Number]",yu="[object Object]",mu="[object \ -RegExp]",wu="[object Set]",gu="[object String]",Su=Array.isArray,_i=typeof ArrayBuffer== -"function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,Li=Object.assign,Eu=Object. -prototype.toString.call.bind(Object.prototype.toString);function bu(r){var e=r.areArraysEqual, -t=r.areDatesEqual,n=r.areMapsEqual,i=r.areObjectsEqual,s=r.arePrimitiveWrappersEqual, -a=r.areRegExpsEqual,u=r.areSetsEqual,c=r.areTypedArraysEqual;return o(function(h,f,y){ -if(h===f)return!0;if(h==null||f==null||typeof h!="object"||typeof f!="object")return h!== -h&&f!==f;var w=h.constructor;if(w!==f.constructor)return!1;if(w===Object)return i( -h,f,y);if(Su(h))return e(h,f,y);if(_i!=null&&_i(h))return c(h,f,y);if(w===Date)return t( -h,f,y);if(w===RegExp)return a(h,f,y);if(w===Map)return n(h,f,y);if(w===Set)return u( -h,f,y);var b=Eu(h);return b===fu?t(h,f,y):b===mu?a(h,f,y):b===du?n(h,f,y):b===wu? -u(h,f,y):b===yu?typeof h.then!="function"&&typeof f.then!="function"&&i(h,f,y):b=== -lu?i(h,f,y):b===hu||b===pu||b===gu?s(h,f,y):!1},"comparator")}o(bu,"createEquali\ -tyComparator");function xu(r){var e=r.circular,t=r.createCustomConfig,n=r.strict, -i={areArraysEqual:n?ut:iu,areDatesEqual:su,areMapsEqual:n?Ei(vi,ut):vi,areObjectsEqual:n? -ut:au,arePrimitiveWrappersEqual:ou,areRegExpsEqual:uu,areSetsEqual:n?Ei(Ci,ut):Ci, -areTypedArraysEqual:n?ut:cu};if(t&&(i=Li({},i,t(i))),e){var s=qt(i.areArraysEqual), -a=qt(i.areMapsEqual),u=qt(i.areObjectsEqual),c=qt(i.areSetsEqual);i=Li({},i,{areArraysEqual:s, -areMapsEqual:a,areObjectsEqual:u,areSetsEqual:c})}return i}o(xu,"createEqualityC\ -omparatorConfig");function Au(r){return function(e,t,n,i,s,a,u){return r(e,t,u)}} -o(Au,"createInternalEqualityComparator");function vu(r){var e=r.circular,t=r.comparator, -n=r.createState,i=r.equals,s=r.strict;if(n)return o(function(c,l){var h=n(),f=h. -cache,y=f===void 0?e?new WeakMap:void 0:f,w=h.meta;return t(c,l,{cache:y,equals:i, -meta:w,strict:s})},"isEqual");if(e)return o(function(c,l){return t(c,l,{cache:new WeakMap, -equals:i,meta:void 0,strict:s})},"isEqual");var a={cache:void 0,equals:i,meta:void 0, -strict:s};return o(function(c,l){return t(c,l,a)},"isEqual")}o(vu,"createIsEqual"); -var _r=Le(),Zh=Le({strict:!0}),Xh=Le({circular:!0}),ef=Le({circular:!0,strict:!0}), -tf=Le({createInternalComparator:o(function(){return Ke},"createInternalComparato\ -r")}),rf=Le({strict:!0,createInternalComparator:o(function(){return Ke},"createI\ -nternalComparator")}),nf=Le({circular:!0,createInternalComparator:o(function(){return Ke}, -"createInternalComparator")}),sf=Le({circular:!0,createInternalComparator:o(function(){ -return Ke},"createInternalComparator"),strict:!0});function Le(r){r===void 0&&(r= -{});var e=r.circular,t=e===void 0?!1:e,n=r.createInternalComparator,i=r.createState, -s=r.strict,a=s===void 0?!1:s,u=xu(r),c=bu(u),l=n?n(c):Au(c);return vu({circular:t, -comparator:c,createState:i,equals:l,strict:a})}o(Le,"createCustomEqual");p();var sr=qe(ir());Jt();p();en();Jt();var Pa=qe(Et()),Ba=qe(Vt());var Fe=class extends Error{static{o(this,"NeonDbError")}name="NeonDbError";severity;code;detail;hint;position;internalPosition;internalQuery;where;schema;table;column;dataType;constraint;file;line;routine;sourceError}, -Ua="transaction() expects an array of queries, or a function returning an array \ -of queries",Ch=["severity","code","detail","hint","position","internalPosition", -"internalQuery","where","schema","table","column","dataType","constraint","file", -"line","routine"];function be(r,{arrayMode:e,fullResults:t,fetchOptions:n,isolationLevel:i, -readOnly:s,deferrable:a,queryCallback:u,resultCallback:c}={}){if(!r)throw new Error( -"No database connection string was provided to `neon()`. Perhaps an environment \ -variable has not been set?");let l;try{l=Xr(r)}catch{throw new Error("Database c\ -onnection string provided to `neon()` is not a valid URL. Connection string: "+String( -r))}let{protocol:h,username:f,password:y,hostname:w,port:b,pathname:U}=l;if(h!== -"postgres:"&&h!=="postgresql:"||!f||!y||!w||!U)throw new Error("Database connect\ -ion string format for `neon()` should be: postgresql://user:password@host.tld/db\ -name?option=value");function v(E,...S){let x,N;if(typeof E=="string")x=E,N=S[1], -S=S[0]??[];else{x="";for(let F=0;F(0,Pa.prepareValue)(F));let P={query:x,params:S};return u&&u(P),_h(C, -P,N)}o(v,"resolve"),v.transaction=async(E,S)=>{if(typeof E=="function"&&(E=E(v)), -!Array.isArray(E))throw new Error(Ua);E.forEach(P=>{if(P[Symbol.toStringTag]!=="\ -NeonQueryPromise")throw new Error(Ua)});let x=E.map(P=>P.parameterizedQuery),N=E. -map(P=>P.opts??{});return C(x,N,S)};async function C(E,S,x){let{fetchEndpoint:N, -fetchFunction:P}=we,F=typeof N=="function"?N(w,b):N,Q=Array.isArray(E)?{queries:E}: -E,Y=n??{},M=e??!1,$=t??!1,j=i,H=s,W=a;x!==void 0&&(x.fetchOptions!==void 0&&(Y={ -...Y,...x.fetchOptions}),x.arrayMode!==void 0&&(M=x.arrayMode),x.fullResults!==void 0&& -($=x.fullResults),x.isolationLevel!==void 0&&(j=x.isolationLevel),x.readOnly!==void 0&& -(H=x.readOnly),x.deferrable!==void 0&&(W=x.deferrable)),S!==void 0&&!Array.isArray( -S)&&S.fetchOptions!==void 0&&(Y={...Y,...S.fetchOptions});let G={"Neon-Connectio\ -n-String":r,"Neon-Raw-Text-Output":"true","Neon-Array-Mode":"true"};Array.isArray( -E)&&(j!==void 0&&(G["Neon-Batch-Isolation-Level"]=j),H!==void 0&&(G["Neon-Batch-\ -Read-Only"]=String(H)),W!==void 0&&(G["Neon-Batch-Deferrable"]=String(W)));let D; -try{D=await(P??fetch)(F,{method:"POST",body:JSON.stringify(Q),headers:G,...Y})}catch(K){ -let q=new Fe(`Error connecting to database: ${K.message}`);throw q.sourceError=K, -q}if(D.ok){let K=await D.json();if(Array.isArray(E)){let q=K.results;if(!Array.isArray( -q))throw new Fe("Neon internal error: unexpected result format");return q.map((R,Z)=>{ -let fe=S[Z]??{},ve=fe.arrayMode??M,Lt=fe.fullResults??$;return Ia(R,{arrayMode:ve, -fullResults:Lt,parameterizedQuery:E[Z],resultCallback:c,types:fe.types})})}else{ -let q=S??{},R=q.arrayMode??M,Z=q.fullResults??$;return Ia(K,{arrayMode:R,fullResults:Z, -parameterizedQuery:E,resultCallback:c,types:q.types})}}else{let{status:K}=D;if(K=== -400){let q=await D.json(),R=new Fe(q.message);for(let Z of Ch)R[Z]=q[Z]??void 0; -throw R}else{let q=await D.text();throw new Fe(`Server error (HTTP status ${K}):\ - ${q}`)}}}return o(C,"execute"),v}o(be,"neon");function _h(r,e,t){return{[Symbol. -toStringTag]:"NeonQueryPromise",parameterizedQuery:e,opts:t,then:o((n,i)=>r(e,t). -then(n,i),"then"),catch:o(n=>r(e,t).catch(n),"catch"),finally:o(n=>r(e,t).finally( -n),"finally")}}o(_h,"createNeonQueryPromise");function Ia(r,{arrayMode:e,fullResults:t, -parameterizedQuery:n,resultCallback:i,types:s}){let a=new Ba.default(s),u=r.fields. -map(h=>h.name),c=r.fields.map(h=>a.getTypeParser(h.dataTypeID)),l=e===!0?r.rows. -map(h=>h.map((f,y)=>f===null?null:c[y](f))):r.rows.map(h=>Object.fromEntries(h.map( -(f,y)=>[u[y],f===null?null:c[y](f)])));return i&&i(n,r,l,{arrayMode:e,fullResults:t}), -t?(r.viaNeonFetch=!0,r.rowAsArray=e,r.rows=l,r._parsers=c,r._types=a,r):l}o(Ia,"\ -processQueryResult");var Ra=qe(zt()),tt=qe(ir());var Pe=class extends sr.Client{constructor(t){super(t);this.config=t}static{o(this, -"NeonClient")}get neonConfig(){return this.connection.stream}connect(t){let{neonConfig:n}=this; -n.forceDisablePgSSL&&(this.ssl=this.connection.ssl=!1),this.ssl&&n.useSecureWebSocket&& -console.warn("SSL is enabled for both Postgres (e.g. ?sslmode=require in the con\ -nection string + forceDisablePgSSL = false) and the WebSocket tunnel (useSecureW\ -ebSocket = true). Double encryption will increase latency and CPU usage. It may \ -be appropriate to disable SSL in the Postgres connection parameters or set force\ -DisablePgSSL = true.");let i=this.config?.host!==void 0||this.config?.connectionString!== -void 0||g.env.PGHOST!==void 0,s=g.env.USER??g.env.USERNAME;if(!i&&this.host==="l\ -ocalhost"&&this.user===s&&this.database===s&&this.password===null)throw new Error( -`No database host or connection string was set, and key parameters have default \ -values (host: localhost, user: ${s}, db: ${s}, password: null). Is an environmen\ -t variable missing? Alternatively, if you intended to connect with these paramet\ -ers, please set the host to 'localhost' explicitly.`);let a=super.connect(t),u=n. -pipelineTLS&&this.ssl,c=n.pipelineConnect==="password";if(!u&&!n.pipelineConnect) -return a;let l=this.connection;if(u&&l.on("connect",()=>l.stream.emit("data","S")), -c){l.removeAllListeners("authenticationCleartextPassword"),l.removeAllListeners( -"readyForQuery"),l.once("readyForQuery",()=>l.on("readyForQuery",this._handleReadyForQuery. -bind(this)));let h=this.ssl?"sslconnect":"connect";l.on(h,()=>{this._handleAuthCleartextPassword(), -this._handleReadyForQuery()})}return a}async _handleAuthSASLContinue(t){let n=this. -saslSession,i=this.password,s=t.data;if(n.message!=="SASLInitialResponse"||typeof i!= -"string"||typeof s!="string")throw new Error("SASL: protocol error");let a=Object. -fromEntries(s.split(",").map(q=>{if(!/^.=/.test(q))throw new Error("SASL: Invali\ -d attribute pair entry");let R=q[0],Z=q.substring(2);return[R,Z]})),u=a.r,c=a.s, -l=a.i;if(!u||!/^[!-+--~]+$/.test(u))throw new Error("SASL: SCRAM-SERVER-FIRST-ME\ -SSAGE: nonce missing/unprintable");if(!c||!/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/. -test(c))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing/not base\ -64");if(!l||!/^[1-9][0-9]*$/.test(l))throw new Error("SASL: SCRAM-SERVER-FIRST-M\ -ESSAGE: missing/invalid iteration count");if(!u.startsWith(n.clientNonce))throw new Error( -"SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce"); -if(u.length===n.clientNonce.length)throw new Error("SASL: SCRAM-SERVER-FIRST-MES\ -SAGE: server nonce is too short");let h=parseInt(l,10),f=m.from(c,"base64"),y=new TextEncoder, -w=y.encode(i),b=await A.subtle.importKey("raw",w,{name:"HMAC",hash:{name:"SHA-25\ -6"}},!1,["sign"]),U=new Uint8Array(await A.subtle.sign("HMAC",b,m.concat([f,m.from( -[0,0,0,1])]))),v=U;for(var C=0;Cv[R]^U[R]));let E=v,S=await A.subtle.importKey( -"raw",E,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),x=new Uint8Array(await A. -subtle.sign("HMAC",S,y.encode("Client Key"))),N=await A.subtle.digest("SHA-256", -x),P="n=*,r="+n.clientNonce,F="r="+u+",s="+c+",i="+h,Q="c=biws,r="+u,Y=P+","+F+"\ -,"+Q,M=await A.subtle.importKey("raw",N,{name:"HMAC",hash:{name:"SHA-256"}},!1,[ -"sign"]);var $=new Uint8Array(await A.subtle.sign("HMAC",M,y.encode(Y))),j=m.from( -x.map((q,R)=>x[R]^$[R])),H=j.toString("base64");let W=await A.subtle.importKey("\ -raw",E,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),G=await A.subtle.sign("H\ -MAC",W,y.encode("Server Key")),D=await A.subtle.importKey("raw",G,{name:"HMAC",hash:{ -name:"SHA-256"}},!1,["sign"]);var K=m.from(await A.subtle.sign("HMAC",D,y.encode( -Y)));n.message="SASLResponse",n.serverSignature=K.toString("base64"),n.response= -Q+",p="+H,this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}}; -function Lh(r,e){if(e)return{callback:e,result:void 0};let t,n,i=o(function(a,u){ -a?t(a):n(u)},"cb"),s=new r(function(a,u){n=a,t=u});return{callback:i,result:s}}o( -Lh,"promisify");var De=class extends sr.Pool{static{o(this,"NeonPool")}Client=Pe;hasFetchUnsupportedListeners=!1;on(e,t){ -return e!=="error"&&(this.hasFetchUnsupportedListeners=!0),super.on(e,t)}query(e,t,n){ -if(!we.poolQueryViaFetch||this.hasFetchUnsupportedListeners||typeof e=="function") -return super.query(e,t,n);typeof t=="function"&&(n=t,t=void 0);let i=Lh(this.Promise, -n);n=i.callback;try{let s=new Ra.default(this.options),a=encodeURIComponent,u=encodeURI, -c=`postgresql://${a(s.user)}:${a(s.password)}@${a(s.host)}/${u(s.database)}`,l=typeof e== -"string"?e:e.text,h=t??e.values??[];be(c,{fullResults:!0,arrayMode:e.rowMode==="\ -array"})(l,h,{types:e.types??this.options?.types}).then(y=>n(void 0,y)).catch(y=>n( -y))}catch(s){n(s)}return i.result}};p();async function Th(r){let e=Date.now(),t=await r();return[Date.now()-e,t]}o(Th,"t\ -imed");async function rt(r,e,t=(n,i)=>{}){let n=[];for(let s=0;ss+a,0),n]}o(rt,"timedRepeat\ -s");async function At(r,e){let{sql:t,test:n}=e,{rows:i}=await(typeof r=="functio\ -n"?r(t):r.query(t));if(!n(i))throw new Error(`Result fails test -Query: ${t} -Result: ${JSON.stringify(i)}`);return i}o(At,"runQuery");async function vt(r,e,t,n){ -await e.connect();let i=await rt(r,()=>At(e,n));return t.waitUntil(e.end()),i}o( -vt,"clientRunQuery");async function Ct(r,e,t,n){let i=new De({connectionString:e}), -s=await rt(r,()=>At(i,n));return t.waitUntil(i.end()),s}o(Ct,"poolRunQuery");async function Na(r,e,t,n){ -let i=be(e,{fullResults:!0});return await rt(r,()=>At(i,n))}o(Na,"httpRunQuery");p();var _t=[{sql:"SELECT * FROM employees LIMIT 10",test:o(r=>r.length>1&&typeof r[0]. -first_name=="string","test")},{sql:"SELECT now()",test:o(r=>/^2\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d+Z$/. -test(r[0].now.toISOString()),"test")}];async function o0(r,e,t){let n=[];for(let i of _t){let[,[[,s]]]=await Ct(1,e.NEON_DB_URL, -t,i);n.push(s)}for(let i of _t){let[,[[,s]]]=await Na(1,e.NEON_DB_URL,t,i);n.push( -s)}return new Response(JSON.stringify(n,null,2),{headers:{"Content-Type":"applic\ -ation/json"}})}o(o0,"cf");var Be={waitUntil(r){},passThroughOnException(){}};async function Uh(r,e=(...t)=>{}){ -let t=be(r.NEON_DB_URL),[[n],[i]]=await t.transaction([t`SELECT ${1}::int AS "batchInt"`, -t`SELECT ${"hello"} AS "batchStr"`]);if(e("batch results:",JSON.stringify(n),JSON. -stringify(i),` -`),n.batchInt!==1||i.batchStr!=="hello")throw new Error("Batch query problem");let[ -[s],[a]]=await t.transaction(x=>[x`SELECT ${1}::int AS "batchInt"`,x`SELECT ${"h\ -ello"} AS "batchStr"`]);if(e("batch results:",JSON.stringify(s),JSON.stringify(a), -` -`),s.batchInt!==1||a.batchStr!=="hello")throw new Error("Batch query problem");let u=await t. -transaction(x=>[]);e("empty txn result:",JSON.stringify(u),` -`);let[[[c]],[[l]]]=await t.transaction(x=>[x`SELECT ${1}::int AS "batchInt"`,x`SELECT ${"\ -hello"} AS "batchStr"`],{arrayMode:!0,isolationLevel:"Serializable",readOnly:!0}); -if(e("array mode (via transaction options) batch results:",JSON.stringify(c),JSON. -stringify(l),` -`),c!==1||l!=="hello")throw new Error("Batch query problem");let h=be(r.NEON_DB_URL, -{arrayMode:!0,isolationLevel:"RepeatableRead"}),[[[f]],[[y]]]=await h.transaction( -x=>[x`SELECT ${1}::int AS "batchInt"`,x`SELECT ${"hello"} AS "batchStr"`]);if(e( -"array mode (via neon options) batch results:",JSON.stringify(f),JSON.stringify( -y),` -`),f!==1||y!=="hello")throw new Error("Batch query problem");let w=be(r.NEON_DB_URL, -{arrayMode:!0}),[[b],[U]]=await w.transaction(x=>[x`SELECT ${1}::int AS "batchInt"`, -x`SELECT ${"hello"} AS "batchStr"`],{arrayMode:!1});if(e("ordinary (via overridd\ -en options) batch results:",JSON.stringify(b),JSON.stringify(U),` -`),b.batchInt!==1||U.batchStr!=="hello")throw new Error("Batch query problem");let[ -[v],[C]]=await t.transaction(x=>[x`SELECT ${1}::int AS "batchInt"`,x('SELECT $1 \ -AS "batchStr"',["hello"],{arrayMode:!0})]);if(e("query options on individual bat\ -ch queries:",JSON.stringify(v),JSON.stringify(C),` -`),v.batchInt!==1||C[0]!=="hello")throw new Error("Batch query problem");let E;try{ -await t.transaction(x=>[x`SELECT ${1}::int AS "batchInt"`,`SELECT 'hello' AS "ba\ -tchStr"`])}catch(x){E=x}if(E===void 0)throw new Error("Error should have been ra\ -ised for string passed to `transaction()`");e("successfully caught invalid query\ - passed to `transaction()`\n");let S;try{let x=r.NEON_DB_URL.replace(/@/,"x@");await be( -x).transaction(N=>[N`SELECT 'never' AS this_should_be_seen_precisely`])}catch(x){ -S=x}if(S===void 0)throw new Error("Error should have been raised for bad passwor\ -d");e("successfully caught invalid password passed to `neon()`\n")}o(Uh,"batchQu\ -eryTest");async function u0(r,e,t=(...n)=>{}){let n=[1,3],i=9;t(`Warm-up ... - -`),await Ct(1,r.NEON_DB_URL,Be,_t[0]);let s=0;t(` +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// node_modules/base64-js/index.js +var require_base64_js = __commonJS({ + "node_modules/base64-js/index.js"(exports) { + "use strict"; + init_shims(); + exports.byteLength = byteLength; + exports.toByteArray = toByteArray; + exports.fromByteArray = fromByteArray; + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; + var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + var i; + var len; + revLookup["-".charCodeAt(0)] = 62; + revLookup["_".charCodeAt(0)] = 63; + function getLens(b64) { + var len2 = b64.length; + if (len2 % 4 > 0) { + throw new Error("Invalid string. Length must be a multiple of 4"); + } + var validLen = b64.indexOf("="); + if (validLen === -1) validLen = len2; + var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; + return [validLen, placeHoldersLen]; + } + __name(getLens, "getLens"); + function byteLength(b64) { + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + __name(byteLength, "byteLength"); + function _byteLength(b64, validLen, placeHoldersLen) { + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + __name(_byteLength, "_byteLength"); + function toByteArray(b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + var curByte = 0; + var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; + var i2; + for (i2 = 0; i2 < len2; i2 += 4) { + tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)]; + arr[curByte++] = tmp >> 16 & 255; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 2) { + tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 1) { + tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + return arr; + } + __name(toByteArray, "toByteArray"); + function tripletToBase64(num) { + return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; + } + __name(tripletToBase64, "tripletToBase64"); + function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + for (var i2 = start; i2 < end; i2 += 3) { + tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255); + output.push(tripletToBase64(tmp)); + } + return output.join(""); + } + __name(encodeChunk, "encodeChunk"); + function fromByteArray(uint8) { + var tmp; + var len2 = uint8.length; + var extraBytes = len2 % 3; + var parts = []; + var maxChunkLength = 16383; + for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) { + parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength)); + } + if (extraBytes === 1) { + tmp = uint8[len2 - 1]; + parts.push( + lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==" + ); + } else if (extraBytes === 2) { + tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; + parts.push( + lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=" + ); + } + return parts.join(""); + } + __name(fromByteArray, "fromByteArray"); + } +}); + +// node_modules/ieee754/index.js +var require_ieee754 = __commonJS({ + "node_modules/ieee754/index.js"(exports) { + init_shims(); + exports.read = function(buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + i += d; + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) { + } + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) { + } + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); + }; + exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt2 = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : -1; + var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + value = Math.abs(value); + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt2 / c; + } else { + value += rt2 * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) { + } + e = e << mLen | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) { + } + buffer[offset + i - d] |= s * 128; + }; + } +}); + +// node_modules/buffer/index.js +var require_buffer = __commonJS({ + "node_modules/buffer/index.js"(exports) { + "use strict"; + init_shims(); + var base64 = require_base64_js(); + var ieee754 = require_ieee754(); + var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; + exports.Buffer = Buffer3; + exports.SlowBuffer = SlowBuffer; + exports.INSPECT_MAX_BYTES = 50; + var K_MAX_LENGTH = 2147483647; + exports.kMaxLength = K_MAX_LENGTH; + Buffer3.TYPED_ARRAY_SUPPORT = typedArraySupport(); + if (!Buffer3.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") { + console.error( + "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support." + ); + } + function typedArraySupport() { + try { + const arr = new Uint8Array(1); + const proto = { foo: /* @__PURE__ */ __name(function() { + return 42; + }, "foo") }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42; + } catch (e) { + return false; + } + } + __name(typedArraySupport, "typedArraySupport"); + Object.defineProperty(Buffer3.prototype, "parent", { + enumerable: true, + get: /* @__PURE__ */ __name(function() { + if (!Buffer3.isBuffer(this)) return void 0; + return this.buffer; + }, "get") + }); + Object.defineProperty(Buffer3.prototype, "offset", { + enumerable: true, + get: /* @__PURE__ */ __name(function() { + if (!Buffer3.isBuffer(this)) return void 0; + return this.byteOffset; + }, "get") + }); + function createBuffer(length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"'); + } + const buf = new Uint8Array(length); + Object.setPrototypeOf(buf, Buffer3.prototype); + return buf; + } + __name(createBuffer, "createBuffer"); + function Buffer3(arg, encodingOrOffset, length) { + if (typeof arg === "number") { + if (typeof encodingOrOffset === "string") { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ); + } + return allocUnsafe(arg); + } + return from(arg, encodingOrOffset, length); + } + __name(Buffer3, "Buffer"); + Buffer3.poolSize = 8192; + function from(value, encodingOrOffset, length) { + if (typeof value === "string") { + return fromString(value, encodingOrOffset); + } + if (ArrayBuffer.isView(value)) { + return fromArrayView(value); + } + if (value == null) { + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value + ); + } + if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + if (typeof value === "number") { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ); + } + const valueOf = value.valueOf && value.valueOf(); + if (valueOf != null && valueOf !== value) { + return Buffer3.from(valueOf, encodingOrOffset, length); + } + const b = fromObject(value); + if (b) return b; + if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { + return Buffer3.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length); + } + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value + ); + } + __name(from, "from"); + Buffer3.from = function(value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length); + }; + Object.setPrototypeOf(Buffer3.prototype, Uint8Array.prototype); + Object.setPrototypeOf(Buffer3, Uint8Array); + function assertSize(size) { + if (typeof size !== "number") { + throw new TypeError('"size" argument must be of type number'); + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"'); + } + } + __name(assertSize, "assertSize"); + function alloc(size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(size); + } + if (fill !== void 0) { + return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); + } + return createBuffer(size); + } + __name(alloc, "alloc"); + Buffer3.alloc = function(size, fill, encoding) { + return alloc(size, fill, encoding); + }; + function allocUnsafe(size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0); + } + __name(allocUnsafe, "allocUnsafe"); + Buffer3.allocUnsafe = function(size) { + return allocUnsafe(size); + }; + Buffer3.allocUnsafeSlow = function(size) { + return allocUnsafe(size); + }; + function fromString(string, encoding) { + if (typeof encoding !== "string" || encoding === "") { + encoding = "utf8"; + } + if (!Buffer3.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + const length = byteLength(string, encoding) | 0; + let buf = createBuffer(length); + const actual = buf.write(string, encoding); + if (actual !== length) { + buf = buf.slice(0, actual); + } + return buf; + } + __name(fromString, "fromString"); + function fromArrayLike(array) { + const length = array.length < 0 ? 0 : checked(array.length) | 0; + const buf = createBuffer(length); + for (let i = 0; i < length; i += 1) { + buf[i] = array[i] & 255; + } + return buf; + } + __name(fromArrayLike, "fromArrayLike"); + function fromArrayView(arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy = new Uint8Array(arrayView); + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); + } + return fromArrayLike(arrayView); + } + __name(fromArrayView, "fromArrayView"); + function fromArrayBuffer(array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds'); + } + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds'); + } + let buf; + if (byteOffset === void 0 && length === void 0) { + buf = new Uint8Array(array); + } else if (length === void 0) { + buf = new Uint8Array(array, byteOffset); + } else { + buf = new Uint8Array(array, byteOffset, length); + } + Object.setPrototypeOf(buf, Buffer3.prototype); + return buf; + } + __name(fromArrayBuffer, "fromArrayBuffer"); + function fromObject(obj) { + if (Buffer3.isBuffer(obj)) { + const len = checked(obj.length) | 0; + const buf = createBuffer(len); + if (buf.length === 0) { + return buf; + } + obj.copy(buf, 0, 0, len); + return buf; + } + if (obj.length !== void 0) { + if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { + return createBuffer(0); + } + return fromArrayLike(obj); + } + if (obj.type === "Buffer" && Array.isArray(obj.data)) { + return fromArrayLike(obj.data); + } + } + __name(fromObject, "fromObject"); + function checked(length) { + if (length >= K_MAX_LENGTH) { + throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); + } + return length | 0; + } + __name(checked, "checked"); + function SlowBuffer(length) { + if (+length != length) { + length = 0; + } + return Buffer3.alloc(+length); + } + __name(SlowBuffer, "SlowBuffer"); + Buffer3.isBuffer = /* @__PURE__ */ __name(function isBuffer(b) { + return b != null && b._isBuffer === true && b !== Buffer3.prototype; + }, "isBuffer"); + Buffer3.compare = /* @__PURE__ */ __name(function compare(a, b) { + if (isInstance(a, Uint8Array)) a = Buffer3.from(a, a.offset, a.byteLength); + if (isInstance(b, Uint8Array)) b = Buffer3.from(b, b.offset, b.byteLength); + if (!Buffer3.isBuffer(a) || !Buffer3.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ); + } + if (a === b) return 0; + let x = a.length; + let y = b.length; + for (let i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + if (x < y) return -1; + if (y < x) return 1; + return 0; + }, "compare"); + Buffer3.isEncoding = /* @__PURE__ */ __name(function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "latin1": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return true; + default: + return false; + } + }, "isEncoding"); + Buffer3.concat = /* @__PURE__ */ __name(function concat(list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + if (list.length === 0) { + return Buffer3.alloc(0); + } + let i; + if (length === void 0) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + const buffer = Buffer3.allocUnsafe(length); + let pos = 0; + for (i = 0; i < list.length; ++i) { + let buf = list[i]; + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + if (!Buffer3.isBuffer(buf)) buf = Buffer3.from(buf); + buf.copy(buffer, pos); + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ); + } + } else if (!Buffer3.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } else { + buf.copy(buffer, pos); + } + pos += buf.length; + } + return buffer; + }, "concat"); + function byteLength(string, encoding) { + if (Buffer3.isBuffer(string)) { + return string.length; + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength; + } + if (typeof string !== "string") { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string + ); + } + const len = string.length; + const mustMatch = arguments.length > 2 && arguments[2] === true; + if (!mustMatch && len === 0) return 0; + let loweredCase = false; + for (; ; ) { + switch (encoding) { + case "ascii": + case "latin1": + case "binary": + return len; + case "utf8": + case "utf-8": + return utf8ToBytes(string).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return len * 2; + case "hex": + return len >>> 1; + case "base64": + return base64ToBytes(string).length; + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length; + } + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + } + __name(byteLength, "byteLength"); + Buffer3.byteLength = byteLength; + function slowToString(encoding, start, end) { + let loweredCase = false; + if (start === void 0 || start < 0) { + start = 0; + } + if (start > this.length) { + return ""; + } + if (end === void 0 || end > this.length) { + end = this.length; + } + if (end <= 0) { + return ""; + } + end >>>= 0; + start >>>= 0; + if (end <= start) { + return ""; + } + if (!encoding) encoding = "utf8"; + while (true) { + switch (encoding) { + case "hex": + return hexSlice(this, start, end); + case "utf8": + case "utf-8": + return utf8Slice(this, start, end); + case "ascii": + return asciiSlice(this, start, end); + case "latin1": + case "binary": + return latin1Slice(this, start, end); + case "base64": + return base64Slice(this, start, end); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return utf16leSlice(this, start, end); + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); + encoding = (encoding + "").toLowerCase(); + loweredCase = true; + } + } + } + __name(slowToString, "slowToString"); + Buffer3.prototype._isBuffer = true; + function swap(b, n, m) { + const i = b[n]; + b[n] = b[m]; + b[m] = i; + } + __name(swap, "swap"); + Buffer3.prototype.swap16 = /* @__PURE__ */ __name(function swap16() { + const len = this.length; + if (len % 2 !== 0) { + throw new RangeError("Buffer size must be a multiple of 16-bits"); + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this; + }, "swap16"); + Buffer3.prototype.swap32 = /* @__PURE__ */ __name(function swap32() { + const len = this.length; + if (len % 4 !== 0) { + throw new RangeError("Buffer size must be a multiple of 32-bits"); + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this; + }, "swap32"); + Buffer3.prototype.swap64 = /* @__PURE__ */ __name(function swap64() { + const len = this.length; + if (len % 8 !== 0) { + throw new RangeError("Buffer size must be a multiple of 64-bits"); + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this; + }, "swap64"); + Buffer3.prototype.toString = /* @__PURE__ */ __name(function toString() { + const length = this.length; + if (length === 0) return ""; + if (arguments.length === 0) return utf8Slice(this, 0, length); + return slowToString.apply(this, arguments); + }, "toString"); + Buffer3.prototype.toLocaleString = Buffer3.prototype.toString; + Buffer3.prototype.equals = /* @__PURE__ */ __name(function equals(b) { + if (!Buffer3.isBuffer(b)) throw new TypeError("Argument must be a Buffer"); + if (this === b) return true; + return Buffer3.compare(this, b) === 0; + }, "equals"); + Buffer3.prototype.inspect = /* @__PURE__ */ __name(function inspect() { + let str = ""; + const max = exports.INSPECT_MAX_BYTES; + str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); + if (this.length > max) str += " ... "; + return ""; + }, "inspect"); + if (customInspectSymbol) { + Buffer3.prototype[customInspectSymbol] = Buffer3.prototype.inspect; + } + Buffer3.prototype.compare = /* @__PURE__ */ __name(function compare(target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer3.from(target, target.offset, target.byteLength); + } + if (!Buffer3.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target + ); + } + if (start === void 0) { + start = 0; + } + if (end === void 0) { + end = target ? target.length : 0; + } + if (thisStart === void 0) { + thisStart = 0; + } + if (thisEnd === void 0) { + thisEnd = this.length; + } + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError("out of range index"); + } + if (thisStart >= thisEnd && start >= end) { + return 0; + } + if (thisStart >= thisEnd) { + return -1; + } + if (start >= end) { + return 1; + } + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + if (this === target) return 0; + let x = thisEnd - thisStart; + let y = end - start; + const len = Math.min(x, y); + const thisCopy = this.slice(thisStart, thisEnd); + const targetCopy = target.slice(start, end); + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break; + } + } + if (x < y) return -1; + if (y < x) return 1; + return 0; + }, "compare"); + function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + if (buffer.length === 0) return -1; + if (typeof byteOffset === "string") { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 2147483647) { + byteOffset = 2147483647; + } else if (byteOffset < -2147483648) { + byteOffset = -2147483648; + } + byteOffset = +byteOffset; + if (numberIsNaN(byteOffset)) { + byteOffset = dir ? 0 : buffer.length - 1; + } + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1; + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1; + } + if (typeof val === "string") { + val = Buffer3.from(val, encoding); + } + if (Buffer3.isBuffer(val)) { + if (val.length === 0) { + return -1; + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir); + } else if (typeof val === "number") { + val = val & 255; + if (typeof Uint8Array.prototype.indexOf === "function") { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); + } + throw new TypeError("val must be string, number or Buffer"); + } + __name(bidirectionalIndexOf, "bidirectionalIndexOf"); + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + let indexSize = 1; + let arrLength = arr.length; + let valLength = val.length; + if (encoding !== void 0) { + encoding = String(encoding).toLowerCase(); + if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { + if (arr.length < 2 || val.length < 2) { + return -1; + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + function read(buf, i2) { + if (indexSize === 1) { + return buf[i2]; + } else { + return buf.readUInt16BE(i2 * indexSize); + } + } + __name(read, "read"); + let i; + if (dir) { + let foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + let found = true; + for (let j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break; + } + } + if (found) return i; + } + } + return -1; + } + __name(arrayIndexOf, "arrayIndexOf"); + Buffer3.prototype.includes = /* @__PURE__ */ __name(function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; + }, "includes"); + Buffer3.prototype.indexOf = /* @__PURE__ */ __name(function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); + }, "indexOf"); + Buffer3.prototype.lastIndexOf = /* @__PURE__ */ __name(function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); + }, "lastIndexOf"); + function hexWrite(buf, string, offset, length) { + offset = Number(offset) || 0; + const remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + const strLen = string.length; + if (length > strLen / 2) { + length = strLen / 2; + } + let i; + for (i = 0; i < length; ++i) { + const parsed = parseInt(string.substr(i * 2, 2), 16); + if (numberIsNaN(parsed)) return i; + buf[offset + i] = parsed; + } + return i; + } + __name(hexWrite, "hexWrite"); + function utf8Write(buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); + } + __name(utf8Write, "utf8Write"); + function asciiWrite(buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length); + } + __name(asciiWrite, "asciiWrite"); + function base64Write(buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length); + } + __name(base64Write, "base64Write"); + function ucs2Write(buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); + } + __name(ucs2Write, "ucs2Write"); + Buffer3.prototype.write = /* @__PURE__ */ __name(function write(string, offset, length, encoding) { + if (offset === void 0) { + encoding = "utf8"; + length = this.length; + offset = 0; + } else if (length === void 0 && typeof offset === "string") { + encoding = offset; + length = this.length; + offset = 0; + } else if (isFinite(offset)) { + offset = offset >>> 0; + if (isFinite(length)) { + length = length >>> 0; + if (encoding === void 0) encoding = "utf8"; + } else { + encoding = length; + length = void 0; + } + } else { + throw new Error( + "Buffer.write(string, encoding, offset[, length]) is no longer supported" + ); + } + const remaining = this.length - offset; + if (length === void 0 || length > remaining) length = remaining; + if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { + throw new RangeError("Attempt to write outside buffer bounds"); + } + if (!encoding) encoding = "utf8"; + let loweredCase = false; + for (; ; ) { + switch (encoding) { + case "hex": + return hexWrite(this, string, offset, length); + case "utf8": + case "utf-8": + return utf8Write(this, string, offset, length); + case "ascii": + case "latin1": + case "binary": + return asciiWrite(this, string, offset, length); + case "base64": + return base64Write(this, string, offset, length); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return ucs2Write(this, string, offset, length); + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + }, "write"); + Buffer3.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() { + return { + type: "Buffer", + data: Array.prototype.slice.call(this._arr || this, 0) + }; + }, "toJSON"); + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf); + } else { + return base64.fromByteArray(buf.slice(start, end)); + } + } + __name(base64Slice, "base64Slice"); + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + const res = []; + let i = start; + while (i < end) { + const firstByte = buf[i]; + let codePoint = null; + let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint; + switch (bytesPerSequence) { + case 1: + if (firstByte < 128) { + codePoint = firstByte; + } + break; + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 192) === 128) { + tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; + if (tempCodePoint > 127) { + codePoint = tempCodePoint; + } + } + break; + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; + if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { + codePoint = tempCodePoint; + } + } + break; + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; + if (tempCodePoint > 65535 && tempCodePoint < 1114112) { + codePoint = tempCodePoint; + } + } + } + } + if (codePoint === null) { + codePoint = 65533; + bytesPerSequence = 1; + } else if (codePoint > 65535) { + codePoint -= 65536; + res.push(codePoint >>> 10 & 1023 | 55296); + codePoint = 56320 | codePoint & 1023; + } + res.push(codePoint); + i += bytesPerSequence; + } + return decodeCodePointsArray(res); + } + __name(utf8Slice, "utf8Slice"); + var MAX_ARGUMENTS_LENGTH = 4096; + function decodeCodePointsArray(codePoints) { + const len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); + } + let res = ""; + let i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res; + } + __name(decodeCodePointsArray, "decodeCodePointsArray"); + function asciiSlice(buf, start, end) { + let ret = ""; + end = Math.min(buf.length, end); + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 127); + } + return ret; + } + __name(asciiSlice, "asciiSlice"); + function latin1Slice(buf, start, end) { + let ret = ""; + end = Math.min(buf.length, end); + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret; + } + __name(latin1Slice, "latin1Slice"); + function hexSlice(buf, start, end) { + const len = buf.length; + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + let out = ""; + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]]; + } + return out; + } + __name(hexSlice, "hexSlice"); + function utf16leSlice(buf, start, end) { + const bytes = buf.slice(start, end); + let res = ""; + for (let i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res; + } + __name(utf16leSlice, "utf16leSlice"); + Buffer3.prototype.slice = /* @__PURE__ */ __name(function slice(start, end) { + const len = this.length; + start = ~~start; + end = end === void 0 ? len : ~~end; + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + if (end < start) end = start; + const newBuf = this.subarray(start, end); + Object.setPrototypeOf(newBuf, Buffer3.prototype); + return newBuf; + }, "slice"); + function checkOffset(offset, ext, length) { + if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint"); + if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length"); + } + __name(checkOffset, "checkOffset"); + Buffer3.prototype.readUintLE = Buffer3.prototype.readUIntLE = /* @__PURE__ */ __name(function readUIntLE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) checkOffset(offset, byteLength2, this.length); + let val = this[offset]; + let mul = 1; + let i = 0; + while (++i < byteLength2 && (mul *= 256)) { + val += this[offset + i] * mul; + } + return val; + }, "readUIntLE"); + Buffer3.prototype.readUintBE = Buffer3.prototype.readUIntBE = /* @__PURE__ */ __name(function readUIntBE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength2, this.length); + } + let val = this[offset + --byteLength2]; + let mul = 1; + while (byteLength2 > 0 && (mul *= 256)) { + val += this[offset + --byteLength2] * mul; + } + return val; + }, "readUIntBE"); + Buffer3.prototype.readUint8 = Buffer3.prototype.readUInt8 = /* @__PURE__ */ __name(function readUInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset]; + }, "readUInt8"); + Buffer3.prototype.readUint16LE = Buffer3.prototype.readUInt16LE = /* @__PURE__ */ __name(function readUInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | this[offset + 1] << 8; + }, "readUInt16LE"); + Buffer3.prototype.readUint16BE = Buffer3.prototype.readUInt16BE = /* @__PURE__ */ __name(function readUInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] << 8 | this[offset + 1]; + }, "readUInt16BE"); + Buffer3.prototype.readUint32LE = Buffer3.prototype.readUInt32LE = /* @__PURE__ */ __name(function readUInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; + }, "readUInt32LE"); + Buffer3.prototype.readUint32BE = Buffer3.prototype.readUInt32BE = /* @__PURE__ */ __name(function readUInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); + }, "readUInt32BE"); + Buffer3.prototype.readBigUInt64LE = defineBigIntMethod(/* @__PURE__ */ __name(function readBigUInt64LE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset, this.length - 8); + } + const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24; + const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24; + return BigInt(lo) + (BigInt(hi) << BigInt(32)); + }, "readBigUInt64LE")); + Buffer3.prototype.readBigUInt64BE = defineBigIntMethod(/* @__PURE__ */ __name(function readBigUInt64BE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset, this.length - 8); + } + const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; + const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last; + return (BigInt(hi) << BigInt(32)) + BigInt(lo); + }, "readBigUInt64BE")); + Buffer3.prototype.readIntLE = /* @__PURE__ */ __name(function readIntLE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) checkOffset(offset, byteLength2, this.length); + let val = this[offset]; + let mul = 1; + let i = 0; + while (++i < byteLength2 && (mul *= 256)) { + val += this[offset + i] * mul; + } + mul *= 128; + if (val >= mul) val -= Math.pow(2, 8 * byteLength2); + return val; + }, "readIntLE"); + Buffer3.prototype.readIntBE = /* @__PURE__ */ __name(function readIntBE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) checkOffset(offset, byteLength2, this.length); + let i = byteLength2; + let mul = 1; + let val = this[offset + --i]; + while (i > 0 && (mul *= 256)) { + val += this[offset + --i] * mul; + } + mul *= 128; + if (val >= mul) val -= Math.pow(2, 8 * byteLength2); + return val; + }, "readIntBE"); + Buffer3.prototype.readInt8 = /* @__PURE__ */ __name(function readInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 128)) return this[offset]; + return (255 - this[offset] + 1) * -1; + }, "readInt8"); + Buffer3.prototype.readInt16LE = /* @__PURE__ */ __name(function readInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + const val = this[offset] | this[offset + 1] << 8; + return val & 32768 ? val | 4294901760 : val; + }, "readInt16LE"); + Buffer3.prototype.readInt16BE = /* @__PURE__ */ __name(function readInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + const val = this[offset + 1] | this[offset] << 8; + return val & 32768 ? val | 4294901760 : val; + }, "readInt16BE"); + Buffer3.prototype.readInt32LE = /* @__PURE__ */ __name(function readInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; + }, "readInt32LE"); + Buffer3.prototype.readInt32BE = /* @__PURE__ */ __name(function readInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; + }, "readInt32BE"); + Buffer3.prototype.readBigInt64LE = defineBigIntMethod(/* @__PURE__ */ __name(function readBigInt64LE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset, this.length - 8); + } + const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24); + return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24); + }, "readBigInt64LE")); + Buffer3.prototype.readBigInt64BE = defineBigIntMethod(/* @__PURE__ */ __name(function readBigInt64BE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset, this.length - 8); + } + const val = (first << 24) + // Overflow + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; + return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last); + }, "readBigInt64BE")); + Buffer3.prototype.readFloatLE = /* @__PURE__ */ __name(function readFloatLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, true, 23, 4); + }, "readFloatLE"); + Buffer3.prototype.readFloatBE = /* @__PURE__ */ __name(function readFloatBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, false, 23, 4); + }, "readFloatBE"); + Buffer3.prototype.readDoubleLE = /* @__PURE__ */ __name(function readDoubleLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, true, 52, 8); + }, "readDoubleLE"); + Buffer3.prototype.readDoubleBE = /* @__PURE__ */ __name(function readDoubleBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, false, 52, 8); + }, "readDoubleBE"); + function checkInt(buf, value, offset, ext, max, min) { + if (!Buffer3.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) throw new RangeError("Index out of range"); + } + __name(checkInt, "checkInt"); + Buffer3.prototype.writeUintLE = Buffer3.prototype.writeUIntLE = /* @__PURE__ */ __name(function writeUIntLE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength2) - 1; + checkInt(this, value, offset, byteLength2, maxBytes, 0); + } + let mul = 1; + let i = 0; + this[offset] = value & 255; + while (++i < byteLength2 && (mul *= 256)) { + this[offset + i] = value / mul & 255; + } + return offset + byteLength2; + }, "writeUIntLE"); + Buffer3.prototype.writeUintBE = Buffer3.prototype.writeUIntBE = /* @__PURE__ */ __name(function writeUIntBE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength2) - 1; + checkInt(this, value, offset, byteLength2, maxBytes, 0); + } + let i = byteLength2 - 1; + let mul = 1; + this[offset + i] = value & 255; + while (--i >= 0 && (mul *= 256)) { + this[offset + i] = value / mul & 255; + } + return offset + byteLength2; + }, "writeUIntBE"); + Buffer3.prototype.writeUint8 = Buffer3.prototype.writeUInt8 = /* @__PURE__ */ __name(function writeUInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 1, 255, 0); + this[offset] = value & 255; + return offset + 1; + }, "writeUInt8"); + Buffer3.prototype.writeUint16LE = Buffer3.prototype.writeUInt16LE = /* @__PURE__ */ __name(function writeUInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 65535, 0); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + return offset + 2; + }, "writeUInt16LE"); + Buffer3.prototype.writeUint16BE = Buffer3.prototype.writeUInt16BE = /* @__PURE__ */ __name(function writeUInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 65535, 0); + this[offset] = value >>> 8; + this[offset + 1] = value & 255; + return offset + 2; + }, "writeUInt16BE"); + Buffer3.prototype.writeUint32LE = Buffer3.prototype.writeUInt32LE = /* @__PURE__ */ __name(function writeUInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0); + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 255; + return offset + 4; + }, "writeUInt32LE"); + Buffer3.prototype.writeUint32BE = Buffer3.prototype.writeUInt32BE = /* @__PURE__ */ __name(function writeUInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0); + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 255; + return offset + 4; + }, "writeUInt32BE"); + function wrtBigUInt64LE(buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7); + let lo = Number(value & BigInt(4294967295)); + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + let hi = Number(value >> BigInt(32) & BigInt(4294967295)); + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + return offset; + } + __name(wrtBigUInt64LE, "wrtBigUInt64LE"); + function wrtBigUInt64BE(buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7); + let lo = Number(value & BigInt(4294967295)); + buf[offset + 7] = lo; + lo = lo >> 8; + buf[offset + 6] = lo; + lo = lo >> 8; + buf[offset + 5] = lo; + lo = lo >> 8; + buf[offset + 4] = lo; + let hi = Number(value >> BigInt(32) & BigInt(4294967295)); + buf[offset + 3] = hi; + hi = hi >> 8; + buf[offset + 2] = hi; + hi = hi >> 8; + buf[offset + 1] = hi; + hi = hi >> 8; + buf[offset] = hi; + return offset + 8; + } + __name(wrtBigUInt64BE, "wrtBigUInt64BE"); + Buffer3.prototype.writeBigUInt64LE = defineBigIntMethod(/* @__PURE__ */ __name(function writeBigUInt64LE(value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); + }, "writeBigUInt64LE")); + Buffer3.prototype.writeBigUInt64BE = defineBigIntMethod(/* @__PURE__ */ __name(function writeBigUInt64BE(value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); + }, "writeBigUInt64BE")); + Buffer3.prototype.writeIntLE = /* @__PURE__ */ __name(function writeIntLE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + const limit = Math.pow(2, 8 * byteLength2 - 1); + checkInt(this, value, offset, byteLength2, limit - 1, -limit); + } + let i = 0; + let mul = 1; + let sub = 0; + this[offset] = value & 255; + while (++i < byteLength2 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = (value / mul >> 0) - sub & 255; + } + return offset + byteLength2; + }, "writeIntLE"); + Buffer3.prototype.writeIntBE = /* @__PURE__ */ __name(function writeIntBE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + const limit = Math.pow(2, 8 * byteLength2 - 1); + checkInt(this, value, offset, byteLength2, limit - 1, -limit); + } + let i = byteLength2 - 1; + let mul = 1; + let sub = 0; + this[offset + i] = value & 255; + while (--i >= 0 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = (value / mul >> 0) - sub & 255; + } + return offset + byteLength2; + }, "writeIntBE"); + Buffer3.prototype.writeInt8 = /* @__PURE__ */ __name(function writeInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 1, 127, -128); + if (value < 0) value = 255 + value + 1; + this[offset] = value & 255; + return offset + 1; + }, "writeInt8"); + Buffer3.prototype.writeInt16LE = /* @__PURE__ */ __name(function writeInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + return offset + 2; + }, "writeInt16LE"); + Buffer3.prototype.writeInt16BE = /* @__PURE__ */ __name(function writeInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768); + this[offset] = value >>> 8; + this[offset + 1] = value & 255; + return offset + 2; + }, "writeInt16BE"); + Buffer3.prototype.writeInt32LE = /* @__PURE__ */ __name(function writeInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + return offset + 4; + }, "writeInt32LE"); + Buffer3.prototype.writeInt32BE = /* @__PURE__ */ __name(function writeInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648); + if (value < 0) value = 4294967295 + value + 1; + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 255; + return offset + 4; + }, "writeInt32BE"); + Buffer3.prototype.writeBigInt64LE = defineBigIntMethod(/* @__PURE__ */ __name(function writeBigInt64LE(value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }, "writeBigInt64LE")); + Buffer3.prototype.writeBigInt64BE = defineBigIntMethod(/* @__PURE__ */ __name(function writeBigInt64BE(value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }, "writeBigInt64BE")); + function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError("Index out of range"); + if (offset < 0) throw new RangeError("Index out of range"); + } + __name(checkIEEE754, "checkIEEE754"); + function writeFloat(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22); + } + ieee754.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4; + } + __name(writeFloat, "writeFloat"); + Buffer3.prototype.writeFloatLE = /* @__PURE__ */ __name(function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); + }, "writeFloatLE"); + Buffer3.prototype.writeFloatBE = /* @__PURE__ */ __name(function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); + }, "writeFloatBE"); + function writeDouble(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292); + } + ieee754.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; + } + __name(writeDouble, "writeDouble"); + Buffer3.prototype.writeDoubleLE = /* @__PURE__ */ __name(function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); + }, "writeDoubleLE"); + Buffer3.prototype.writeDoubleBE = /* @__PURE__ */ __name(function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); + }, "writeDoubleBE"); + Buffer3.prototype.copy = /* @__PURE__ */ __name(function copy(target, targetStart, start, end) { + if (!Buffer3.isBuffer(target)) throw new TypeError("argument should be a Buffer"); + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + if (end === start) return 0; + if (target.length === 0 || this.length === 0) return 0; + if (targetStart < 0) { + throw new RangeError("targetStart out of bounds"); + } + if (start < 0 || start >= this.length) throw new RangeError("Index out of range"); + if (end < 0) throw new RangeError("sourceEnd out of bounds"); + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + const len = end - start; + if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { + this.copyWithin(targetStart, start, end); + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ); + } + return len; + }, "copy"); + Buffer3.prototype.fill = /* @__PURE__ */ __name(function fill(val, start, end, encoding) { + if (typeof val === "string") { + if (typeof start === "string") { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === "string") { + encoding = end; + end = this.length; + } + if (encoding !== void 0 && typeof encoding !== "string") { + throw new TypeError("encoding must be a string"); + } + if (typeof encoding === "string" && !Buffer3.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + if (val.length === 1) { + const code = val.charCodeAt(0); + if (encoding === "utf8" && code < 128 || encoding === "latin1") { + val = code; + } + } + } else if (typeof val === "number") { + val = val & 255; + } else if (typeof val === "boolean") { + val = Number(val); + } + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError("Out of range index"); + } + if (end <= start) { + return this; + } + start = start >>> 0; + end = end === void 0 ? this.length : end >>> 0; + if (!val) val = 0; + let i; + if (typeof val === "number") { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + const bytes = Buffer3.isBuffer(val) ? val : Buffer3.from(val, encoding); + const len = bytes.length; + if (len === 0) { + throw new TypeError('The value "' + val + '" is invalid for argument "value"'); + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + return this; + }, "fill"); + var errors = {}; + function E(sym, getMessage, Base) { + errors[sym] = class NodeError extends Base { + static { + __name(this, "NodeError"); + } + constructor() { + super(); + Object.defineProperty(this, "message", { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }); + this.name = `${this.name} [${sym}]`; + this.stack; + delete this.name; + } + get code() { + return sym; + } + set code(value) { + Object.defineProperty(this, "code", { + configurable: true, + enumerable: true, + value, + writable: true + }); + } + toString() { + return `${this.name} [${sym}]: ${this.message}`; + } + }; + } + __name(E, "E"); + E( + "ERR_BUFFER_OUT_OF_BOUNDS", + function(name) { + if (name) { + return `${name} is outside of buffer bounds`; + } + return "Attempt to access memory outside buffer bounds"; + }, + RangeError + ); + E( + "ERR_INVALID_ARG_TYPE", + function(name, actual) { + return `The "${name}" argument must be of type number. Received type ${typeof actual}`; + }, + TypeError + ); + E( + "ERR_OUT_OF_RANGE", + function(str, range, input) { + let msg = `The value of "${str}" is out of range.`; + let received = input; + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)); + } else if (typeof input === "bigint") { + received = String(input); + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received); + } + received += "n"; + } + msg += ` It must be ${range}. Received ${received}`; + return msg; + }, + RangeError + ); + function addNumericalSeparator(val) { + let res = ""; + let i = val.length; + const start = val[0] === "-" ? 1 : 0; + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}`; + } + return `${val.slice(0, i)}${res}`; + } + __name(addNumericalSeparator, "addNumericalSeparator"); + function checkBounds(buf, offset, byteLength2) { + validateNumber(offset, "offset"); + if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) { + boundsError(offset, buf.length - (byteLength2 + 1)); + } + } + __name(checkBounds, "checkBounds"); + function checkIntBI(value, min, max, buf, offset, byteLength2) { + if (value > max || value < min) { + const n = typeof min === "bigint" ? "n" : ""; + let range; + if (byteLength2 > 3) { + if (min === 0 || min === BigInt(0)) { + range = `>= 0${n} and < 2${n} ** ${(byteLength2 + 1) * 8}${n}`; + } else { + range = `>= -(2${n} ** ${(byteLength2 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n}`; + } + } else { + range = `>= ${min}${n} and <= ${max}${n}`; + } + throw new errors.ERR_OUT_OF_RANGE("value", range, value); + } + checkBounds(buf, offset, byteLength2); + } + __name(checkIntBI, "checkIntBI"); + function validateNumber(value, name) { + if (typeof value !== "number") { + throw new errors.ERR_INVALID_ARG_TYPE(name, "number", value); + } + } + __name(validateNumber, "validateNumber"); + function boundsError(value, length, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type); + throw new errors.ERR_OUT_OF_RANGE(type || "offset", "an integer", value); + } + if (length < 0) { + throw new errors.ERR_BUFFER_OUT_OF_BOUNDS(); + } + throw new errors.ERR_OUT_OF_RANGE( + type || "offset", + `>= ${type ? 1 : 0} and <= ${length}`, + value + ); + } + __name(boundsError, "boundsError"); + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + function base64clean(str) { + str = str.split("=")[0]; + str = str.trim().replace(INVALID_BASE64_RE, ""); + if (str.length < 2) return ""; + while (str.length % 4 !== 0) { + str = str + "="; + } + return str; + } + __name(base64clean, "base64clean"); + function utf8ToBytes(string, units) { + units = units || Infinity; + let codePoint; + const length = string.length; + let leadSurrogate = null; + const bytes = []; + for (let i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + if (codePoint > 55295 && codePoint < 57344) { + if (!leadSurrogate) { + if (codePoint > 56319) { + if ((units -= 3) > -1) bytes.push(239, 191, 189); + continue; + } else if (i + 1 === length) { + if ((units -= 3) > -1) bytes.push(239, 191, 189); + continue; + } + leadSurrogate = codePoint; + continue; + } + if (codePoint < 56320) { + if ((units -= 3) > -1) bytes.push(239, 191, 189); + leadSurrogate = codePoint; + continue; + } + codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; + } else if (leadSurrogate) { + if ((units -= 3) > -1) bytes.push(239, 191, 189); + } + leadSurrogate = null; + if (codePoint < 128) { + if ((units -= 1) < 0) break; + bytes.push(codePoint); + } else if (codePoint < 2048) { + if ((units -= 2) < 0) break; + bytes.push( + codePoint >> 6 | 192, + codePoint & 63 | 128 + ); + } else if (codePoint < 65536) { + if ((units -= 3) < 0) break; + bytes.push( + codePoint >> 12 | 224, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else if (codePoint < 1114112) { + if ((units -= 4) < 0) break; + bytes.push( + codePoint >> 18 | 240, + codePoint >> 12 & 63 | 128, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else { + throw new Error("Invalid code point"); + } + } + return bytes; + } + __name(utf8ToBytes, "utf8ToBytes"); + function asciiToBytes(str) { + const byteArray = []; + for (let i = 0; i < str.length; ++i) { + byteArray.push(str.charCodeAt(i) & 255); + } + return byteArray; + } + __name(asciiToBytes, "asciiToBytes"); + function utf16leToBytes(str, units) { + let c, hi, lo; + const byteArray = []; + for (let i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break; + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + return byteArray; + } + __name(utf16leToBytes, "utf16leToBytes"); + function base64ToBytes(str) { + return base64.toByteArray(base64clean(str)); + } + __name(base64ToBytes, "base64ToBytes"); + function blitBuffer(src, dst, offset, length) { + let i; + for (i = 0; i < length; ++i) { + if (i + offset >= dst.length || i >= src.length) break; + dst[i + offset] = src[i]; + } + return i; + } + __name(blitBuffer, "blitBuffer"); + function isInstance(obj, type) { + return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; + } + __name(isInstance, "isInstance"); + function numberIsNaN(obj) { + return obj !== obj; + } + __name(numberIsNaN, "numberIsNaN"); + var hexSliceLookupTable = function() { + const alphabet = "0123456789abcdef"; + const table = new Array(256); + for (let i = 0; i < 16; ++i) { + const i16 = i * 16; + for (let j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j]; + } + } + return table; + }(); + function defineBigIntMethod(fn) { + return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn; + } + __name(defineBigIntMethod, "defineBigIntMethod"); + function BufferBigIntNotDefined() { + throw new Error("BigInt not supported"); + } + __name(BufferBigIntNotDefined, "BufferBigIntNotDefined"); + } +}); + +// shims/shims.js +var global, setImmediate, clearImmediate, crypto, Buffer2, process; +var init_shims = __esm({ + "shims/shims.js"() { + "use strict"; + global = globalThis; + setImmediate = globalThis.setImmediate ?? ((fn) => setTimeout(fn, 0)); + clearImmediate = globalThis.clearImmediate ?? ((id) => clearTimeout(id)); + crypto = globalThis.crypto ?? {}; + crypto.subtle ??= {}; + Buffer2 = typeof globalThis.Buffer === "function" && typeof globalThis.Buffer.allocUnsafe === "function" ? globalThis.Buffer : require_buffer().Buffer; + process = globalThis.process ?? {}; + process.env ??= {}; + try { + process.nextTick(() => void 0); + } catch (err) { + const resolve = Promise.resolve(); + process.nextTick = resolve.then.bind(resolve); + } + } +}); + +// node_modules/events/events.js +var require_events = __commonJS({ + "node_modules/events/events.js"(exports, module) { + "use strict"; + init_shims(); + var R = typeof Reflect === "object" ? Reflect : null; + var ReflectApply = R && typeof R.apply === "function" ? R.apply : /* @__PURE__ */ __name(function ReflectApply2(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + }, "ReflectApply"); + var ReflectOwnKeys; + if (R && typeof R.ownKeys === "function") { + ReflectOwnKeys = R.ownKeys; + } else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = /* @__PURE__ */ __name(function ReflectOwnKeys2(target) { + return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); + }, "ReflectOwnKeys"); + } else { + ReflectOwnKeys = /* @__PURE__ */ __name(function ReflectOwnKeys2(target) { + return Object.getOwnPropertyNames(target); + }, "ReflectOwnKeys"); + } + function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); + } + __name(ProcessEmitWarning, "ProcessEmitWarning"); + var NumberIsNaN = Number.isNaN || /* @__PURE__ */ __name(function NumberIsNaN2(value) { + return value !== value; + }, "NumberIsNaN"); + function EventEmitter2() { + EventEmitter2.init.call(this); + } + __name(EventEmitter2, "EventEmitter"); + module.exports = EventEmitter2; + module.exports.once = once; + EventEmitter2.EventEmitter = EventEmitter2; + EventEmitter2.prototype._events = void 0; + EventEmitter2.prototype._eventsCount = 0; + EventEmitter2.prototype._maxListeners = void 0; + var defaultMaxListeners = 10; + function checkListener(listener) { + if (typeof listener !== "function") { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + } + __name(checkListener, "checkListener"); + Object.defineProperty(EventEmitter2, "defaultMaxListeners", { + enumerable: true, + get: /* @__PURE__ */ __name(function() { + return defaultMaxListeners; + }, "get"), + set: /* @__PURE__ */ __name(function(arg) { + if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); + } + defaultMaxListeners = arg; + }, "set") + }); + EventEmitter2.init = function() { + if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } + this._maxListeners = this._maxListeners || void 0; + }; + EventEmitter2.prototype.setMaxListeners = /* @__PURE__ */ __name(function setMaxListeners(n) { + if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); + } + this._maxListeners = n; + return this; + }, "setMaxListeners"); + function _getMaxListeners(that) { + if (that._maxListeners === void 0) + return EventEmitter2.defaultMaxListeners; + return that._maxListeners; + } + __name(_getMaxListeners, "_getMaxListeners"); + EventEmitter2.prototype.getMaxListeners = /* @__PURE__ */ __name(function getMaxListeners() { + return _getMaxListeners(this); + }, "getMaxListeners"); + EventEmitter2.prototype.emit = /* @__PURE__ */ __name(function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = type === "error"; + var events = this._events; + if (events !== void 0) + doError = doError && events.error === void 0; + else if (!doError) + return false; + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + throw er; + } + var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); + err.context = er; + throw err; + } + var handler = events[type]; + if (handler === void 0) + return false; + if (typeof handler === "function") { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + return true; + }, "emit"); + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + checkListener(listener); + events = target._events; + if (events === void 0) { + events = target._events = /* @__PURE__ */ Object.create(null); + target._eventsCount = 0; + } else { + if (events.newListener !== void 0) { + target.emit( + "newListener", + type, + listener.listener ? listener.listener : listener + ); + events = target._events; + } + existing = events[type]; + } + if (existing === void 0) { + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === "function") { + existing = events[type] = prepend ? [listener, existing] : [existing, listener]; + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); + w.name = "MaxListenersExceededWarning"; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + return target; + } + __name(_addListener, "_addListener"); + EventEmitter2.prototype.addListener = /* @__PURE__ */ __name(function addListener(type, listener) { + return _addListener(this, type, listener, false); + }, "addListener"); + EventEmitter2.prototype.on = EventEmitter2.prototype.addListener; + EventEmitter2.prototype.prependListener = /* @__PURE__ */ __name(function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }, "prependListener"); + function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } + } + __name(onceWrapper, "onceWrapper"); + function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: void 0, target, type, listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; + } + __name(_onceWrap, "_onceWrap"); + EventEmitter2.prototype.once = /* @__PURE__ */ __name(function once2(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; + }, "once"); + EventEmitter2.prototype.prependOnceListener = /* @__PURE__ */ __name(function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }, "prependOnceListener"); + EventEmitter2.prototype.removeListener = /* @__PURE__ */ __name(function removeListener(type, listener) { + var list, events, position, i, originalListener; + checkListener(listener); + events = this._events; + if (events === void 0) + return this; + list = events[type]; + if (list === void 0) + return this; + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = /* @__PURE__ */ Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit("removeListener", type, list.listener || listener); + } + } else if (typeof list !== "function") { + position = -1; + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + if (position < 0) + return this; + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + if (list.length === 1) + events[type] = list[0]; + if (events.removeListener !== void 0) + this.emit("removeListener", type, originalListener || listener); + } + return this; + }, "removeListener"); + EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; + EventEmitter2.prototype.removeAllListeners = /* @__PURE__ */ __name(function removeAllListeners(type) { + var listeners, events, i; + events = this._events; + if (events === void 0) + return this; + if (events.removeListener === void 0) { + if (arguments.length === 0) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== void 0) { + if (--this._eventsCount === 0) + this._events = /* @__PURE__ */ Object.create(null); + else + delete events[type]; + } + return this; + } + if (arguments.length === 0) { + var keys2 = Object.keys(events); + var key; + for (i = 0; i < keys2.length; ++i) { + key = keys2[i]; + if (key === "removeListener") continue; + this.removeAllListeners(key); + } + this.removeAllListeners("removeListener"); + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + return this; + } + listeners = events[type]; + if (typeof listeners === "function") { + this.removeListener(type, listeners); + } else if (listeners !== void 0) { + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + return this; + }, "removeAllListeners"); + function _listeners(target, type, unwrap) { + var events = target._events; + if (events === void 0) + return []; + var evlistener = events[type]; + if (evlistener === void 0) + return []; + if (typeof evlistener === "function") + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); + } + __name(_listeners, "_listeners"); + EventEmitter2.prototype.listeners = /* @__PURE__ */ __name(function listeners(type) { + return _listeners(this, type, true); + }, "listeners"); + EventEmitter2.prototype.rawListeners = /* @__PURE__ */ __name(function rawListeners(type) { + return _listeners(this, type, false); + }, "rawListeners"); + EventEmitter2.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === "function") { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } + }; + EventEmitter2.prototype.listenerCount = listenerCount; + function listenerCount(type) { + var events = this._events; + if (events !== void 0) { + var evlistener = events[type]; + if (typeof evlistener === "function") { + return 1; + } else if (evlistener !== void 0) { + return evlistener.length; + } + } + return 0; + } + __name(listenerCount, "listenerCount"); + EventEmitter2.prototype.eventNames = /* @__PURE__ */ __name(function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; + }, "eventNames"); + function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; + } + __name(arrayClone, "arrayClone"); + function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); + } + __name(spliceOne, "spliceOne"); + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + __name(unwrapListeners, "unwrapListeners"); + function once(emitter, name) { + return new Promise(function(resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } + __name(errorListener, "errorListener"); + function resolver() { + if (typeof emitter.removeListener === "function") { + emitter.removeListener("error", errorListener); + } + resolve([].slice.call(arguments)); + } + __name(resolver, "resolver"); + ; + eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); + if (name !== "error") { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); + } + __name(once, "once"); + function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === "function") { + eventTargetAgnosticAddListener(emitter, "error", handler, flags); + } + } + __name(addErrorHandlerIfEventEmitter, "addErrorHandlerIfEventEmitter"); + function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === "function") { + if (flags.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === "function") { + emitter.addEventListener(name, /* @__PURE__ */ __name(function wrapListener(arg) { + if (flags.once) { + emitter.removeEventListener(name, wrapListener); + } + listener(arg); + }, "wrapListener")); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } + } + __name(eventTargetAgnosticAddListener, "eventTargetAgnosticAddListener"); + } +}); + +// shims/util/index.ts +var util_exports = {}; +__export(util_exports, { + default: () => util_default +}); +var util_default; +var init_util = __esm({ + "shims/util/index.ts"() { + "use strict"; + init_shims(); + util_default = {}; + } +}); + +// shims/crypto/sha256.ts +function sha256(data) { + let h0 = 1779033703, h1 = 3144134277, h2 = 1013904242, h3 = 2773480762, h4 = 1359893119, h5 = 2600822924, h6 = 528734635, h7 = 1541459225, tsz = 0, bp = 0; + const k = [ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 + ], rrot = /* @__PURE__ */ __name((x, n) => x >>> n | x << 32 - n, "rrot"), w = new Uint32Array(64), buf = new Uint8Array(64), process2 = /* @__PURE__ */ __name(() => { + for (let j = 0, r2 = 0; j < 16; j++, r2 += 4) { + w[j] = buf[r2] << 24 | buf[r2 + 1] << 16 | buf[r2 + 2] << 8 | buf[r2 + 3]; + } + for (let j = 16; j < 64; j++) { + let s0 = rrot(w[j - 15], 7) ^ rrot(w[j - 15], 18) ^ w[j - 15] >>> 3; + let s1 = rrot(w[j - 2], 17) ^ rrot(w[j - 2], 19) ^ w[j - 2] >>> 10; + w[j] = w[j - 16] + s0 + w[j - 7] + s1 | 0; + } + let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7; + for (let j = 0; j < 64; j++) { + let S1 = rrot(e, 6) ^ rrot(e, 11) ^ rrot(e, 25), ch = e & f ^ ~e & g, t1 = h + S1 + ch + k[j] + w[j] | 0, S0 = rrot(a, 2) ^ rrot(a, 13) ^ rrot(a, 22), maj = a & b ^ a & c ^ b & c, t2 = S0 + maj | 0; + h = g; + g = f; + f = e; + e = d + t1 | 0; + d = c; + c = b; + b = a; + a = t1 + t2 | 0; + } + h0 = h0 + a | 0; + h1 = h1 + b | 0; + h2 = h2 + c | 0; + h3 = h3 + d | 0; + h4 = h4 + e | 0; + h5 = h5 + f | 0; + h6 = h6 + g | 0; + h7 = h7 + h | 0; + bp = 0; + }, "process"), add = /* @__PURE__ */ __name((data2) => { + if (typeof data2 === "string") { + data2 = new TextEncoder().encode(data2); + } + for (let i = 0; i < data2.length; i++) { + buf[bp++] = data2[i]; + if (bp === 64) process2(); + } + tsz += data2.length; + }, "add"), digest = /* @__PURE__ */ __name(() => { + buf[bp++] = 128; + if (bp == 64) process2(); + if (bp + 8 > 64) { + while (bp < 64) buf[bp++] = 0; + process2(); + } + while (bp < 58) buf[bp++] = 0; + let L = tsz * 8; + buf[bp++] = L / 1099511627776 & 255; + buf[bp++] = L / 4294967296 & 255; + buf[bp++] = L >>> 24; + buf[bp++] = L >>> 16 & 255; + buf[bp++] = L >>> 8 & 255; + buf[bp++] = L & 255; + process2(); + let reply = new Uint8Array(32); + reply[0] = h0 >>> 24; + reply[1] = h0 >>> 16 & 255; + reply[2] = h0 >>> 8 & 255; + reply[3] = h0 & 255; + reply[4] = h1 >>> 24; + reply[5] = h1 >>> 16 & 255; + reply[6] = h1 >>> 8 & 255; + reply[7] = h1 & 255; + reply[8] = h2 >>> 24; + reply[9] = h2 >>> 16 & 255; + reply[10] = h2 >>> 8 & 255; + reply[11] = h2 & 255; + reply[12] = h3 >>> 24; + reply[13] = h3 >>> 16 & 255; + reply[14] = h3 >>> 8 & 255; + reply[15] = h3 & 255; + reply[16] = h4 >>> 24; + reply[17] = h4 >>> 16 & 255; + reply[18] = h4 >>> 8 & 255; + reply[19] = h4 & 255; + reply[20] = h5 >>> 24; + reply[21] = h5 >>> 16 & 255; + reply[22] = h5 >>> 8 & 255; + reply[23] = h5 & 255; + reply[24] = h6 >>> 24; + reply[25] = h6 >>> 16 & 255; + reply[26] = h6 >>> 8 & 255; + reply[27] = h6 & 255; + reply[28] = h7 >>> 24; + reply[29] = h7 >>> 16 & 255; + reply[30] = h7 >>> 8 & 255; + reply[31] = h7 & 255; + return reply; + }, "digest"); + if (data === void 0) return { add, digest }; + add(data); + return digest(); +} +var init_sha256 = __esm({ + "shims/crypto/sha256.ts"() { + "use strict"; + init_shims(); + __name(sha256, "sha256"); + } +}); + +// shims/crypto/md5.ts +var Md5; +var init_md5 = __esm({ + "shims/crypto/md5.ts"() { + "use strict"; + init_shims(); + Md5 = class _Md5 { + static { + __name(this, "Md5"); + } + static hashByteArray(arr, raw = false) { + return this.onePassHasher.start().appendByteArray(arr).end(raw); + } + static hashStr(str, raw = false) { + return this.onePassHasher.start().appendStr(str).end(raw); + } + static hashAsciiStr(str, raw = false) { + return this.onePassHasher.start().appendAsciiStr(str).end(raw); + } + // Private Static Variables + static stateIdentity = new Int32Array([ + 1732584193, + -271733879, + -1732584194, + 271733878 + ]); + static buffer32Identity = new Int32Array([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]); + static hexChars = "0123456789abcdef"; + static hexOut = []; + // Permanent instance is to use for one-call hashing + static onePassHasher = new _Md5(); + static _hex(x) { + const hc = _Md5.hexChars; + const ho = _Md5.hexOut; + let n; + let offset; + let j; + let i; + for (i = 0; i < 4; i += 1) { + offset = i * 8; + n = x[i]; + for (j = 0; j < 8; j += 2) { + ho[offset + 1 + j] = hc.charAt(n & 15); + n >>>= 4; + ho[offset + 0 + j] = hc.charAt(n & 15); + n >>>= 4; + } + } + return ho.join(""); + } + static _md5cycle(x, k) { + let a = x[0]; + let b = x[1]; + let c = x[2]; + let d = x[3]; + a += (b & c | ~b & d) + k[0] - 680876936 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[1] - 389564586 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[2] + 606105819 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[3] - 1044525330 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a += (b & c | ~b & d) + k[4] - 176418897 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[5] + 1200080426 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[6] - 1473231341 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[7] - 45705983 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a += (b & c | ~b & d) + k[8] + 1770035416 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[9] - 1958414417 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[10] - 42063 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[11] - 1990404162 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a += (b & c | ~b & d) + k[12] + 1804603682 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[13] - 40341101 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[14] - 1502002290 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[15] + 1236535329 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a += (b & d | c & ~d) + k[1] - 165796510 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[6] - 1069501632 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[11] + 643717713 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[0] - 373897302 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a += (b & d | c & ~d) + k[5] - 701558691 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[10] + 38016083 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[15] - 660478335 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[4] - 405537848 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a += (b & d | c & ~d) + k[9] + 568446438 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[14] - 1019803690 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[3] - 187363961 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[8] + 1163531501 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a += (b & d | c & ~d) + k[13] - 1444681467 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[2] - 51403784 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[7] + 1735328473 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[12] - 1926607734 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a += (b ^ c ^ d) + k[5] - 378558 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[8] - 2022574463 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[11] + 1839030562 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[14] - 35309556 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a += (b ^ c ^ d) + k[1] - 1530992060 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[4] + 1272893353 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[7] - 155497632 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[10] - 1094730640 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a += (b ^ c ^ d) + k[13] + 681279174 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[0] - 358537222 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[3] - 722521979 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[6] + 76029189 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a += (b ^ c ^ d) + k[9] - 640364487 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[12] - 421815835 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[15] + 530742520 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[2] - 995338651 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a += (c ^ (b | ~d)) + k[0] - 198630844 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[5] - 57434055 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[10] - 1051523 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[15] - 30611744 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a += (c ^ (b | ~d)) + k[4] - 145523070 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[2] + 718787259 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[9] - 343485551 | 0; + b = (b << 21 | b >>> 11) + c | 0; + x[0] = a + x[0] | 0; + x[1] = b + x[1] | 0; + x[2] = c + x[2] | 0; + x[3] = d + x[3] | 0; + } + _dataLength = 0; + _bufferLength = 0; + _state = new Int32Array(4); + _buffer = new ArrayBuffer(68); + _buffer8; + _buffer32; + constructor() { + this._buffer8 = new Uint8Array(this._buffer, 0, 68); + this._buffer32 = new Uint32Array(this._buffer, 0, 17); + this.start(); + } + /** + * Initialise buffer to be hashed + */ + start() { + this._dataLength = 0; + this._bufferLength = 0; + this._state.set(_Md5.stateIdentity); + return this; + } + // Char to code point to to array conversion: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt + // #Example.3A_Fixing_charCodeAt_to_handle_non-Basic-Multilingual-Plane_characters_if_their_presence_earlier_in_the_string_is_unknown + /** + * Append a UTF-8 string to the hash buffer + * @param str String to append + */ + appendStr(str) { + const buf8 = this._buffer8; + const buf32 = this._buffer32; + let bufLen = this._bufferLength; + let code; + let i; + for (i = 0; i < str.length; i += 1) { + code = str.charCodeAt(i); + if (code < 128) { + buf8[bufLen++] = code; + } else if (code < 2048) { + buf8[bufLen++] = (code >>> 6) + 192; + buf8[bufLen++] = code & 63 | 128; + } else if (code < 55296 || code > 56319) { + buf8[bufLen++] = (code >>> 12) + 224; + buf8[bufLen++] = code >>> 6 & 63 | 128; + buf8[bufLen++] = code & 63 | 128; + } else { + code = (code - 55296) * 1024 + (str.charCodeAt(++i) - 56320) + 65536; + if (code > 1114111) { + throw new Error( + "Unicode standard supports code points up to U+10FFFF" + ); + } + buf8[bufLen++] = (code >>> 18) + 240; + buf8[bufLen++] = code >>> 12 & 63 | 128; + buf8[bufLen++] = code >>> 6 & 63 | 128; + buf8[bufLen++] = code & 63 | 128; + } + if (bufLen >= 64) { + this._dataLength += 64; + _Md5._md5cycle(this._state, buf32); + bufLen -= 64; + buf32[0] = buf32[16]; + } + } + this._bufferLength = bufLen; + return this; + } + /** + * Append an ASCII string to the hash buffer + * @param str String to append + */ + appendAsciiStr(str) { + const buf8 = this._buffer8; + const buf32 = this._buffer32; + let bufLen = this._bufferLength; + let i; + let j = 0; + for (; ; ) { + i = Math.min(str.length - j, 64 - bufLen); + while (i--) { + buf8[bufLen++] = str.charCodeAt(j++); + } + if (bufLen < 64) { + break; + } + this._dataLength += 64; + _Md5._md5cycle(this._state, buf32); + bufLen = 0; + } + this._bufferLength = bufLen; + return this; + } + /** + * Append a byte array to the hash buffer + * @param input array to append + */ + appendByteArray(input) { + const buf8 = this._buffer8; + const buf32 = this._buffer32; + let bufLen = this._bufferLength; + let i; + let j = 0; + for (; ; ) { + i = Math.min(input.length - j, 64 - bufLen); + while (i--) { + buf8[bufLen++] = input[j++]; + } + if (bufLen < 64) { + break; + } + this._dataLength += 64; + _Md5._md5cycle(this._state, buf32); + bufLen = 0; + } + this._bufferLength = bufLen; + return this; + } + /** + * Get the state of the hash buffer + */ + getState() { + const s = this._state; + return { + buffer: String.fromCharCode.apply(null, Array.from(this._buffer8)), + buflen: this._bufferLength, + length: this._dataLength, + state: [s[0], s[1], s[2], s[3]] + }; + } + /** + * Override the current state of the hash buffer + * @param state New hash buffer state + */ + setState(state) { + const buf = state.buffer; + const x = state.state; + const s = this._state; + let i; + this._dataLength = state.length; + this._bufferLength = state.buflen; + s[0] = x[0]; + s[1] = x[1]; + s[2] = x[2]; + s[3] = x[3]; + for (i = 0; i < buf.length; i += 1) { + this._buffer8[i] = buf.charCodeAt(i); + } + } + /** + * Hash the current state of the hash buffer and return the result + * @param raw Whether to return the value as an `Int32Array` + */ + end(raw = false) { + const bufLen = this._bufferLength; + const buf8 = this._buffer8; + const buf32 = this._buffer32; + const i = (bufLen >> 2) + 1; + this._dataLength += bufLen; + const dataBitsLen = this._dataLength * 8; + buf8[bufLen] = 128; + buf8[bufLen + 1] = buf8[bufLen + 2] = buf8[bufLen + 3] = 0; + buf32.set(_Md5.buffer32Identity.subarray(i), i); + if (bufLen > 55) { + _Md5._md5cycle(this._state, buf32); + buf32.set(_Md5.buffer32Identity); + } + if (dataBitsLen <= 4294967295) { + buf32[14] = dataBitsLen; + } else { + const matches = dataBitsLen.toString(16).match(/(.*?)(.{0,8})$/); + if (matches === null) { + return; + } + const lo = parseInt(matches[2], 16); + const hi = parseInt(matches[1], 16) || 0; + buf32[14] = lo; + buf32[15] = hi; + } + _Md5._md5cycle(this._state, buf32); + return raw ? this._state : _Md5._hex(this._state); + } + }; + } +}); + +// shims/crypto/index.ts +var crypto_exports = {}; +__export(crypto_exports, { + createHash: () => createHash, + createHmac: () => createHmac, + randomBytes: () => randomBytes +}); +function randomBytes(length) { + return crypto.getRandomValues(Buffer2.alloc(length)); +} +function createHash(type) { + if (type === "sha256") + return { + update: /* @__PURE__ */ __name(function(data) { + return { + digest: /* @__PURE__ */ __name(function() { + return Buffer2.from(sha256(data)); + }, "digest") + }; + }, "update") + }; + if (type === "md5") + return { + update: /* @__PURE__ */ __name(function(data) { + return { + digest: /* @__PURE__ */ __name(function() { + return typeof data === "string" ? Md5.hashStr(data) : Md5.hashByteArray(data); + }, "digest") + }; + }, "update") + }; + throw new Error(`Hash type '${type}' not supported`); +} +function createHmac(type, key) { + if (type !== "sha256") + throw new Error(`Only sha256 is supported (requested: '${type}')`); + return { + update: /* @__PURE__ */ __name(function(data) { + return { + digest: /* @__PURE__ */ __name(function() { + if (typeof key === "string") key = new TextEncoder().encode(key); + if (typeof data === "string") data = new TextEncoder().encode(data); + const keyLen = key.length; + if (keyLen > 64) { + key = sha256(key); + } else if (keyLen < 64) { + const tmp = new Uint8Array(64); + tmp.set(key); + key = tmp; + } + const innerKey = new Uint8Array(64); + const outerKey = new Uint8Array(64); + for (let i = 0; i < 64; i++) { + innerKey[i] = 54 ^ key[i]; + outerKey[i] = 92 ^ key[i]; + } + const msg = new Uint8Array(data.length + 64); + msg.set(innerKey, 0); + msg.set(data, 64); + const result = new Uint8Array(64 + 32); + result.set(outerKey, 0); + result.set(sha256(msg), 64); + return Buffer2.from(sha256(result)); + }, "digest") + }; + }, "update") + }; +} +var init_crypto = __esm({ + "shims/crypto/index.ts"() { + "use strict"; + init_shims(); + init_sha256(); + init_md5(); + __name(randomBytes, "randomBytes"); + __name(createHash, "createHash"); + __name(createHmac, "createHmac"); + } +}); + +// node_modules/pg/node_modules/postgres-array/index.js +var require_postgres_array = __commonJS({ + "node_modules/pg/node_modules/postgres-array/index.js"(exports) { + "use strict"; + init_shims(); + exports.parse = function(source, transform) { + return new ArrayParser(source, transform).parse(); + }; + var ArrayParser = class _ArrayParser { + static { + __name(this, "ArrayParser"); + } + constructor(source, transform) { + this.source = source; + this.transform = transform || identity; + this.position = 0; + this.entries = []; + this.recorded = []; + this.dimension = 0; + } + isEof() { + return this.position >= this.source.length; + } + nextCharacter() { + var character = this.source[this.position++]; + if (character === "\\") { + return { + value: this.source[this.position++], + escaped: true + }; + } + return { + value: character, + escaped: false + }; + } + record(character) { + this.recorded.push(character); + } + newEntry(includeEmpty) { + var entry; + if (this.recorded.length > 0 || includeEmpty) { + entry = this.recorded.join(""); + if (entry === "NULL" && !includeEmpty) { + entry = null; + } + if (entry !== null) entry = this.transform(entry); + this.entries.push(entry); + this.recorded = []; + } + } + consumeDimensions() { + if (this.source[0] === "[") { + while (!this.isEof()) { + var char = this.nextCharacter(); + if (char.value === "=") break; + } + } + } + parse(nested) { + var character, parser, quote; + this.consumeDimensions(); + while (!this.isEof()) { + character = this.nextCharacter(); + if (character.value === "{" && !quote) { + this.dimension++; + if (this.dimension > 1) { + parser = new _ArrayParser(this.source.substr(this.position - 1), this.transform); + this.entries.push(parser.parse(true)); + this.position += parser.position - 2; + } + } else if (character.value === "}" && !quote) { + this.dimension--; + if (!this.dimension) { + this.newEntry(); + if (nested) return this.entries; + } + } else if (character.value === '"' && !character.escaped) { + if (quote) this.newEntry(true); + quote = !quote; + } else if (character.value === "," && !quote) { + this.newEntry(); + } else { + this.record(character.value); + } + } + if (this.dimension !== 0) { + throw new Error("array dimension not balanced"); + } + return this.entries; + } + }; + function identity(value) { + return value; + } + __name(identity, "identity"); + } +}); + +// node_modules/pg/node_modules/pg-types/lib/arrayParser.js +var require_arrayParser = __commonJS({ + "node_modules/pg/node_modules/pg-types/lib/arrayParser.js"(exports, module) { + init_shims(); + var array = require_postgres_array(); + module.exports = { + create: /* @__PURE__ */ __name(function(source, transform) { + return { + parse: /* @__PURE__ */ __name(function() { + return array.parse(source, transform); + }, "parse") + }; + }, "create") + }; + } +}); + +// node_modules/pg/node_modules/postgres-date/index.js +var require_postgres_date = __commonJS({ + "node_modules/pg/node_modules/postgres-date/index.js"(exports, module) { + "use strict"; + init_shims(); + var DATE_TIME = /(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/; + var DATE = /^(\d{1,})-(\d{2})-(\d{2})( BC)?$/; + var TIME_ZONE = /([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/; + var INFINITY = /^-?infinity$/; + module.exports = /* @__PURE__ */ __name(function parseDate(isoDate) { + if (INFINITY.test(isoDate)) { + return Number(isoDate.replace("i", "I")); + } + var matches = DATE_TIME.exec(isoDate); + if (!matches) { + return getDate(isoDate) || null; + } + var isBC = !!matches[8]; + var year = parseInt(matches[1], 10); + if (isBC) { + year = bcYearToNegativeYear(year); + } + var month = parseInt(matches[2], 10) - 1; + var day = matches[3]; + var hour = parseInt(matches[4], 10); + var minute = parseInt(matches[5], 10); + var second = parseInt(matches[6], 10); + var ms = matches[7]; + ms = ms ? 1e3 * parseFloat(ms) : 0; + var date; + var offset = timeZoneOffset(isoDate); + if (offset != null) { + date = new Date(Date.UTC(year, month, day, hour, minute, second, ms)); + if (is0To99(year)) { + date.setUTCFullYear(year); + } + if (offset !== 0) { + date.setTime(date.getTime() - offset); + } + } else { + date = new Date(year, month, day, hour, minute, second, ms); + if (is0To99(year)) { + date.setFullYear(year); + } + } + return date; + }, "parseDate"); + function getDate(isoDate) { + var matches = DATE.exec(isoDate); + if (!matches) { + return; + } + var year = parseInt(matches[1], 10); + var isBC = !!matches[4]; + if (isBC) { + year = bcYearToNegativeYear(year); + } + var month = parseInt(matches[2], 10) - 1; + var day = matches[3]; + var date = new Date(year, month, day); + if (is0To99(year)) { + date.setFullYear(year); + } + return date; + } + __name(getDate, "getDate"); + function timeZoneOffset(isoDate) { + if (isoDate.endsWith("+00")) { + return 0; + } + var zone = TIME_ZONE.exec(isoDate.split(" ")[1]); + if (!zone) return; + var type = zone[1]; + if (type === "Z") { + return 0; + } + var sign = type === "-" ? -1 : 1; + var offset = parseInt(zone[2], 10) * 3600 + parseInt(zone[3] || 0, 10) * 60 + parseInt(zone[4] || 0, 10); + return offset * sign * 1e3; + } + __name(timeZoneOffset, "timeZoneOffset"); + function bcYearToNegativeYear(year) { + return -(year - 1); + } + __name(bcYearToNegativeYear, "bcYearToNegativeYear"); + function is0To99(num) { + return num >= 0 && num < 100; + } + __name(is0To99, "is0To99"); + } +}); + +// node_modules/xtend/mutable.js +var require_mutable = __commonJS({ + "node_modules/xtend/mutable.js"(exports, module) { + init_shims(); + module.exports = extend; + var hasOwnProperty2 = Object.prototype.hasOwnProperty; + function extend(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (hasOwnProperty2.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + } + __name(extend, "extend"); + } +}); + +// node_modules/pg/node_modules/postgres-interval/index.js +var require_postgres_interval = __commonJS({ + "node_modules/pg/node_modules/postgres-interval/index.js"(exports, module) { + "use strict"; + init_shims(); + var extend = require_mutable(); + module.exports = PostgresInterval; + function PostgresInterval(raw) { + if (!(this instanceof PostgresInterval)) { + return new PostgresInterval(raw); + } + extend(this, parse2(raw)); + } + __name(PostgresInterval, "PostgresInterval"); + var properties = ["seconds", "minutes", "hours", "days", "months", "years"]; + PostgresInterval.prototype.toPostgres = function() { + var filtered = properties.filter(this.hasOwnProperty, this); + if (this.milliseconds && filtered.indexOf("seconds") < 0) { + filtered.push("seconds"); + } + if (filtered.length === 0) return "0"; + return filtered.map(function(property) { + var value = this[property] || 0; + if (property === "seconds" && this.milliseconds) { + value = (value + this.milliseconds / 1e3).toFixed(6).replace(/\.?0+$/, ""); + } + return value + " " + property; + }, this).join(" "); + }; + var propertiesISOEquivalent = { + years: "Y", + months: "M", + days: "D", + hours: "H", + minutes: "M", + seconds: "S" + }; + var dateProperties = ["years", "months", "days"]; + var timeProperties = ["hours", "minutes", "seconds"]; + PostgresInterval.prototype.toISOString = PostgresInterval.prototype.toISO = function() { + var datePart = dateProperties.map(buildProperty, this).join(""); + var timePart = timeProperties.map(buildProperty, this).join(""); + return "P" + datePart + "T" + timePart; + function buildProperty(property) { + var value = this[property] || 0; + if (property === "seconds" && this.milliseconds) { + value = (value + this.milliseconds / 1e3).toFixed(6).replace(/0+$/, ""); + } + return value + propertiesISOEquivalent[property]; + } + __name(buildProperty, "buildProperty"); + }; + var NUMBER = "([+-]?\\d+)"; + var YEAR = NUMBER + "\\s+years?"; + var MONTH = NUMBER + "\\s+mons?"; + var DAY = NUMBER + "\\s+days?"; + var TIME = "([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?"; + var INTERVAL = new RegExp([YEAR, MONTH, DAY, TIME].map(function(regexString) { + return "(" + regexString + ")?"; + }).join("\\s*")); + var positions = { + years: 2, + months: 4, + days: 6, + hours: 9, + minutes: 10, + seconds: 11, + milliseconds: 12 + }; + var negatives = ["hours", "minutes", "seconds", "milliseconds"]; + function parseMilliseconds(fraction) { + var microseconds = fraction + "000000".slice(fraction.length); + return parseInt(microseconds, 10) / 1e3; + } + __name(parseMilliseconds, "parseMilliseconds"); + function parse2(interval) { + if (!interval) return {}; + var matches = INTERVAL.exec(interval); + var isNegative = matches[8] === "-"; + return Object.keys(positions).reduce(function(parsed, property) { + var position = positions[property]; + var value = matches[position]; + if (!value) return parsed; + value = property === "milliseconds" ? parseMilliseconds(value) : parseInt(value, 10); + if (!value) return parsed; + if (isNegative && ~negatives.indexOf(property)) { + value *= -1; + } + parsed[property] = value; + return parsed; + }, {}); + } + __name(parse2, "parse"); + } +}); + +// node_modules/pg/node_modules/postgres-bytea/index.js +var require_postgres_bytea = __commonJS({ + "node_modules/pg/node_modules/postgres-bytea/index.js"(exports, module) { + "use strict"; + init_shims(); + module.exports = /* @__PURE__ */ __name(function parseBytea(input) { + if (/^\\x/.test(input)) { + return new Buffer2(input.substr(2), "hex"); + } + var output = ""; + var i = 0; + while (i < input.length) { + if (input[i] !== "\\") { + output += input[i]; + ++i; + } else { + if (/[0-7]{3}/.test(input.substr(i + 1, 3))) { + output += String.fromCharCode(parseInt(input.substr(i + 1, 3), 8)); + i += 4; + } else { + var backslashes = 1; + while (i + backslashes < input.length && input[i + backslashes] === "\\") { + backslashes++; + } + for (var k = 0; k < Math.floor(backslashes / 2); ++k) { + output += "\\"; + } + i += Math.floor(backslashes / 2) * 2; + } + } + } + return new Buffer2(output, "binary"); + }, "parseBytea"); + } +}); + +// node_modules/pg/node_modules/pg-types/lib/textParsers.js +var require_textParsers = __commonJS({ + "node_modules/pg/node_modules/pg-types/lib/textParsers.js"(exports, module) { + init_shims(); + var array = require_postgres_array(); + var arrayParser = require_arrayParser(); + var parseDate = require_postgres_date(); + var parseInterval = require_postgres_interval(); + var parseByteA = require_postgres_bytea(); + function allowNull(fn) { + return /* @__PURE__ */ __name(function nullAllowed(value) { + if (value === null) return value; + return fn(value); + }, "nullAllowed"); + } + __name(allowNull, "allowNull"); + function parseBool(value) { + if (value === null) return value; + return value === "TRUE" || value === "t" || value === "true" || value === "y" || value === "yes" || value === "on" || value === "1"; + } + __name(parseBool, "parseBool"); + function parseBoolArray(value) { + if (!value) return null; + return array.parse(value, parseBool); + } + __name(parseBoolArray, "parseBoolArray"); + function parseBaseTenInt(string) { + return parseInt(string, 10); + } + __name(parseBaseTenInt, "parseBaseTenInt"); + function parseIntegerArray(value) { + if (!value) return null; + return array.parse(value, allowNull(parseBaseTenInt)); + } + __name(parseIntegerArray, "parseIntegerArray"); + function parseBigIntegerArray(value) { + if (!value) return null; + return array.parse(value, allowNull(function(entry) { + return parseBigInteger(entry).trim(); + })); + } + __name(parseBigIntegerArray, "parseBigIntegerArray"); + var parsePointArray = /* @__PURE__ */ __name(function(value) { + if (!value) { + return null; + } + var p2 = arrayParser.create(value, function(entry) { + if (entry !== null) { + entry = parsePoint(entry); + } + return entry; + }); + return p2.parse(); + }, "parsePointArray"); + var parseFloatArray = /* @__PURE__ */ __name(function(value) { + if (!value) { + return null; + } + var p2 = arrayParser.create(value, function(entry) { + if (entry !== null) { + entry = parseFloat(entry); + } + return entry; + }); + return p2.parse(); + }, "parseFloatArray"); + var parseStringArray = /* @__PURE__ */ __name(function(value) { + if (!value) { + return null; + } + var p2 = arrayParser.create(value); + return p2.parse(); + }, "parseStringArray"); + var parseDateArray = /* @__PURE__ */ __name(function(value) { + if (!value) { + return null; + } + var p2 = arrayParser.create(value, function(entry) { + if (entry !== null) { + entry = parseDate(entry); + } + return entry; + }); + return p2.parse(); + }, "parseDateArray"); + var parseIntervalArray = /* @__PURE__ */ __name(function(value) { + if (!value) { + return null; + } + var p2 = arrayParser.create(value, function(entry) { + if (entry !== null) { + entry = parseInterval(entry); + } + return entry; + }); + return p2.parse(); + }, "parseIntervalArray"); + var parseByteAArray = /* @__PURE__ */ __name(function(value) { + if (!value) { + return null; + } + return array.parse(value, allowNull(parseByteA)); + }, "parseByteAArray"); + var parseInteger = /* @__PURE__ */ __name(function(value) { + return parseInt(value, 10); + }, "parseInteger"); + var parseBigInteger = /* @__PURE__ */ __name(function(value) { + var valStr = String(value); + if (/^\d+$/.test(valStr)) { + return valStr; + } + return value; + }, "parseBigInteger"); + var parseJsonArray = /* @__PURE__ */ __name(function(value) { + if (!value) { + return null; + } + return array.parse(value, allowNull(JSON.parse)); + }, "parseJsonArray"); + var parsePoint = /* @__PURE__ */ __name(function(value) { + if (value[0] !== "(") { + return null; + } + value = value.substring(1, value.length - 1).split(","); + return { + x: parseFloat(value[0]), + y: parseFloat(value[1]) + }; + }, "parsePoint"); + var parseCircle = /* @__PURE__ */ __name(function(value) { + if (value[0] !== "<" && value[1] !== "(") { + return null; + } + var point = "("; + var radius = ""; + var pointParsed = false; + for (var i = 2; i < value.length - 1; i++) { + if (!pointParsed) { + point += value[i]; + } + if (value[i] === ")") { + pointParsed = true; + continue; + } else if (!pointParsed) { + continue; + } + if (value[i] === ",") { + continue; + } + radius += value[i]; + } + var result = parsePoint(point); + result.radius = parseFloat(radius); + return result; + }, "parseCircle"); + var init = /* @__PURE__ */ __name(function(register) { + register(20, parseBigInteger); + register(21, parseInteger); + register(23, parseInteger); + register(26, parseInteger); + register(700, parseFloat); + register(701, parseFloat); + register(16, parseBool); + register(1082, parseDate); + register(1114, parseDate); + register(1184, parseDate); + register(600, parsePoint); + register(651, parseStringArray); + register(718, parseCircle); + register(1e3, parseBoolArray); + register(1001, parseByteAArray); + register(1005, parseIntegerArray); + register(1007, parseIntegerArray); + register(1028, parseIntegerArray); + register(1016, parseBigIntegerArray); + register(1017, parsePointArray); + register(1021, parseFloatArray); + register(1022, parseFloatArray); + register(1231, parseFloatArray); + register(1014, parseStringArray); + register(1015, parseStringArray); + register(1008, parseStringArray); + register(1009, parseStringArray); + register(1040, parseStringArray); + register(1041, parseStringArray); + register(1115, parseDateArray); + register(1182, parseDateArray); + register(1185, parseDateArray); + register(1186, parseInterval); + register(1187, parseIntervalArray); + register(17, parseByteA); + register(114, JSON.parse.bind(JSON)); + register(3802, JSON.parse.bind(JSON)); + register(199, parseJsonArray); + register(3807, parseJsonArray); + register(3907, parseStringArray); + register(2951, parseStringArray); + register(791, parseStringArray); + register(1183, parseStringArray); + register(1270, parseStringArray); + }, "init"); + module.exports = { + init + }; + } +}); + +// node_modules/pg-int8/index.js +var require_pg_int8 = __commonJS({ + "node_modules/pg-int8/index.js"(exports, module) { + "use strict"; + init_shims(); + var BASE = 1e6; + function readInt8(buffer) { + var high = buffer.readInt32BE(0); + var low = buffer.readUInt32BE(4); + var sign = ""; + if (high < 0) { + high = ~high + (low === 0); + low = ~low + 1 >>> 0; + sign = "-"; + } + var result = ""; + var carry; + var t; + var digits; + var pad; + var l2; + var i; + { + carry = high % BASE; + high = high / BASE >>> 0; + t = 4294967296 * carry + low; + low = t / BASE >>> 0; + digits = "" + (t - BASE * low); + if (low === 0 && high === 0) { + return sign + digits + result; + } + pad = ""; + l2 = 6 - digits.length; + for (i = 0; i < l2; i++) { + pad += "0"; + } + result = pad + digits + result; + } + { + carry = high % BASE; + high = high / BASE >>> 0; + t = 4294967296 * carry + low; + low = t / BASE >>> 0; + digits = "" + (t - BASE * low); + if (low === 0 && high === 0) { + return sign + digits + result; + } + pad = ""; + l2 = 6 - digits.length; + for (i = 0; i < l2; i++) { + pad += "0"; + } + result = pad + digits + result; + } + { + carry = high % BASE; + high = high / BASE >>> 0; + t = 4294967296 * carry + low; + low = t / BASE >>> 0; + digits = "" + (t - BASE * low); + if (low === 0 && high === 0) { + return sign + digits + result; + } + pad = ""; + l2 = 6 - digits.length; + for (i = 0; i < l2; i++) { + pad += "0"; + } + result = pad + digits + result; + } + { + carry = high % BASE; + t = 4294967296 * carry + low; + digits = "" + t % BASE; + return sign + digits + result; + } + } + __name(readInt8, "readInt8"); + module.exports = readInt8; + } +}); + +// node_modules/pg/node_modules/pg-types/lib/binaryParsers.js +var require_binaryParsers = __commonJS({ + "node_modules/pg/node_modules/pg-types/lib/binaryParsers.js"(exports, module) { + init_shims(); + var parseInt64 = require_pg_int8(); + var parseBits = /* @__PURE__ */ __name(function(data, bits, offset, invert, callback) { + offset = offset || 0; + invert = invert || false; + callback = callback || function(lastValue, newValue, bits2) { + return lastValue * Math.pow(2, bits2) + newValue; + }; + var offsetBytes = offset >> 3; + var inv = /* @__PURE__ */ __name(function(value) { + if (invert) { + return ~value & 255; + } + return value; + }, "inv"); + var mask = 255; + var firstBits = 8 - offset % 8; + if (bits < firstBits) { + mask = 255 << 8 - bits & 255; + firstBits = bits; + } + if (offset) { + mask = mask >> offset % 8; + } + var result = 0; + if (offset % 8 + bits >= 8) { + result = callback(0, inv(data[offsetBytes]) & mask, firstBits); + } + var bytes = bits + offset >> 3; + for (var i = offsetBytes + 1; i < bytes; i++) { + result = callback(result, inv(data[i]), 8); + } + var lastBits = (bits + offset) % 8; + if (lastBits > 0) { + result = callback(result, inv(data[bytes]) >> 8 - lastBits, lastBits); + } + return result; + }, "parseBits"); + var parseFloatFromBits = /* @__PURE__ */ __name(function(data, precisionBits, exponentBits) { + var bias = Math.pow(2, exponentBits - 1) - 1; + var sign = parseBits(data, 1); + var exponent = parseBits(data, exponentBits, 1); + if (exponent === 0) { + return 0; + } + var precisionBitsCounter = 1; + var parsePrecisionBits = /* @__PURE__ */ __name(function(lastValue, newValue, bits) { + if (lastValue === 0) { + lastValue = 1; + } + for (var i = 1; i <= bits; i++) { + precisionBitsCounter /= 2; + if ((newValue & 1 << bits - i) > 0) { + lastValue += precisionBitsCounter; + } + } + return lastValue; + }, "parsePrecisionBits"); + var mantissa = parseBits(data, precisionBits, exponentBits + 1, false, parsePrecisionBits); + if (exponent == Math.pow(2, exponentBits + 1) - 1) { + if (mantissa === 0) { + return sign === 0 ? Infinity : -Infinity; + } + return NaN; + } + return (sign === 0 ? 1 : -1) * Math.pow(2, exponent - bias) * mantissa; + }, "parseFloatFromBits"); + var parseInt16 = /* @__PURE__ */ __name(function(value) { + if (parseBits(value, 1) == 1) { + return -1 * (parseBits(value, 15, 1, true) + 1); + } + return parseBits(value, 15, 1); + }, "parseInt16"); + var parseInt32 = /* @__PURE__ */ __name(function(value) { + if (parseBits(value, 1) == 1) { + return -1 * (parseBits(value, 31, 1, true) + 1); + } + return parseBits(value, 31, 1); + }, "parseInt32"); + var parseFloat32 = /* @__PURE__ */ __name(function(value) { + return parseFloatFromBits(value, 23, 8); + }, "parseFloat32"); + var parseFloat64 = /* @__PURE__ */ __name(function(value) { + return parseFloatFromBits(value, 52, 11); + }, "parseFloat64"); + var parseNumeric = /* @__PURE__ */ __name(function(value) { + var sign = parseBits(value, 16, 32); + if (sign == 49152) { + return NaN; + } + var weight = Math.pow(1e4, parseBits(value, 16, 16)); + var result = 0; + var digits = []; + var ndigits = parseBits(value, 16); + for (var i = 0; i < ndigits; i++) { + result += parseBits(value, 16, 64 + 16 * i) * weight; + weight /= 1e4; + } + var scale = Math.pow(10, parseBits(value, 16, 48)); + return (sign === 0 ? 1 : -1) * Math.round(result * scale) / scale; + }, "parseNumeric"); + var parseDate = /* @__PURE__ */ __name(function(isUTC, value) { + var sign = parseBits(value, 1); + var rawValue = parseBits(value, 63, 1); + var result = new Date((sign === 0 ? 1 : -1) * rawValue / 1e3 + 9466848e5); + if (!isUTC) { + result.setTime(result.getTime() + result.getTimezoneOffset() * 6e4); + } + result.usec = rawValue % 1e3; + result.getMicroSeconds = function() { + return this.usec; + }; + result.setMicroSeconds = function(value2) { + this.usec = value2; + }; + result.getUTCMicroSeconds = function() { + return this.usec; + }; + return result; + }, "parseDate"); + var parseArray = /* @__PURE__ */ __name(function(value) { + var dim = parseBits(value, 32); + var flags = parseBits(value, 32, 32); + var elementType = parseBits(value, 32, 64); + var offset = 96; + var dims = []; + for (var i = 0; i < dim; i++) { + dims[i] = parseBits(value, 32, offset); + offset += 32; + offset += 32; + } + var parseElement = /* @__PURE__ */ __name(function(elementType2) { + var length = parseBits(value, 32, offset); + offset += 32; + if (length == 4294967295) { + return null; + } + var result; + if (elementType2 == 23 || elementType2 == 20) { + result = parseBits(value, length * 8, offset); + offset += length * 8; + return result; + } else if (elementType2 == 25) { + result = value.toString(this.encoding, offset >> 3, (offset += length << 3) >> 3); + return result; + } else { + console.log("ERROR: ElementType not implemented: " + elementType2); + } + }, "parseElement"); + var parse2 = /* @__PURE__ */ __name(function(dimension, elementType2) { + var array = []; + var i2; + if (dimension.length > 1) { + var count = dimension.shift(); + for (i2 = 0; i2 < count; i2++) { + array[i2] = parse2(dimension, elementType2); + } + dimension.unshift(count); + } else { + for (i2 = 0; i2 < dimension[0]; i2++) { + array[i2] = parseElement(elementType2); + } + } + return array; + }, "parse"); + return parse2(dims, elementType); + }, "parseArray"); + var parseText = /* @__PURE__ */ __name(function(value) { + return value.toString("utf8"); + }, "parseText"); + var parseBool = /* @__PURE__ */ __name(function(value) { + if (value === null) return null; + return parseBits(value, 8) > 0; + }, "parseBool"); + var init = /* @__PURE__ */ __name(function(register) { + register(20, parseInt64); + register(21, parseInt16); + register(23, parseInt32); + register(26, parseInt32); + register(1700, parseNumeric); + register(700, parseFloat32); + register(701, parseFloat64); + register(16, parseBool); + register(1114, parseDate.bind(null, false)); + register(1184, parseDate.bind(null, true)); + register(1e3, parseArray); + register(1007, parseArray); + register(1016, parseArray); + register(1008, parseArray); + register(1009, parseArray); + register(25, parseText); + }, "init"); + module.exports = { + init + }; + } +}); + +// node_modules/pg/node_modules/pg-types/lib/builtins.js +var require_builtins = __commonJS({ + "node_modules/pg/node_modules/pg-types/lib/builtins.js"(exports, module) { + init_shims(); + module.exports = { + BOOL: 16, + BYTEA: 17, + CHAR: 18, + INT8: 20, + INT2: 21, + INT4: 23, + REGPROC: 24, + TEXT: 25, + OID: 26, + TID: 27, + XID: 28, + CID: 29, + JSON: 114, + XML: 142, + PG_NODE_TREE: 194, + SMGR: 210, + PATH: 602, + POLYGON: 604, + CIDR: 650, + FLOAT4: 700, + FLOAT8: 701, + ABSTIME: 702, + RELTIME: 703, + TINTERVAL: 704, + CIRCLE: 718, + MACADDR8: 774, + MONEY: 790, + MACADDR: 829, + INET: 869, + ACLITEM: 1033, + BPCHAR: 1042, + VARCHAR: 1043, + DATE: 1082, + TIME: 1083, + TIMESTAMP: 1114, + TIMESTAMPTZ: 1184, + INTERVAL: 1186, + TIMETZ: 1266, + BIT: 1560, + VARBIT: 1562, + NUMERIC: 1700, + REFCURSOR: 1790, + REGPROCEDURE: 2202, + REGOPER: 2203, + REGOPERATOR: 2204, + REGCLASS: 2205, + REGTYPE: 2206, + UUID: 2950, + TXID_SNAPSHOT: 2970, + PG_LSN: 3220, + PG_NDISTINCT: 3361, + PG_DEPENDENCIES: 3402, + TSVECTOR: 3614, + TSQUERY: 3615, + GTSVECTOR: 3642, + REGCONFIG: 3734, + REGDICTIONARY: 3769, + JSONB: 3802, + REGNAMESPACE: 4089, + REGROLE: 4096 + }; + } +}); + +// node_modules/pg/node_modules/pg-types/index.js +var require_pg_types = __commonJS({ + "node_modules/pg/node_modules/pg-types/index.js"(exports) { + init_shims(); + var textParsers = require_textParsers(); + var binaryParsers = require_binaryParsers(); + var arrayParser = require_arrayParser(); + var builtinTypes = require_builtins(); + exports.getTypeParser = getTypeParser; + exports.setTypeParser = setTypeParser; + exports.arrayParser = arrayParser; + exports.builtins = builtinTypes; + var typeParsers = { + text: {}, + binary: {} + }; + function noParse(val) { + return String(val); + } + __name(noParse, "noParse"); + function getTypeParser(oid, format) { + format = format || "text"; + if (!typeParsers[format]) { + return noParse; + } + return typeParsers[format][oid] || noParse; + } + __name(getTypeParser, "getTypeParser"); + function setTypeParser(oid, format, parseFn) { + if (typeof format == "function") { + parseFn = format; + format = "text"; + } + typeParsers[format][oid] = parseFn; + } + __name(setTypeParser, "setTypeParser"); + textParsers.init(function(oid, converter) { + typeParsers.text[oid] = converter; + }); + binaryParsers.init(function(oid, converter) { + typeParsers.binary[oid] = converter; + }); + } +}); + +// node_modules/pg/lib/defaults.js +var require_defaults = __commonJS({ + "node_modules/pg/lib/defaults.js"(exports, module) { + "use strict"; + init_shims(); + module.exports = { + // database host. defaults to localhost + host: "localhost", + // database user's name + user: process.platform === "win32" ? process.env.USERNAME : process.env.USER, + // name of database to connect + database: void 0, + // database user's password + password: null, + // a Postgres connection string to be used instead of setting individual connection items + // NOTE: Setting this value will cause it to override any other value (such as database or user) defined + // in the defaults object. + connectionString: void 0, + // database port + port: 5432, + // number of rows to return at a time from a prepared statement's + // portal. 0 will return all rows at once + rows: 0, + // binary result mode + binary: false, + // Connection pool options - see https://github.com/brianc/node-pg-pool + // number of connections to use in connection pool + // 0 will disable connection pooling + max: 10, + // max milliseconds a client can go unused before it is removed + // from the pool and destroyed + idleTimeoutMillis: 3e4, + client_encoding: "", + ssl: false, + application_name: void 0, + fallback_application_name: void 0, + options: void 0, + parseInputDatesAsUTC: false, + // max milliseconds any query using this connection will execute for before timing out in error. + // false=unlimited + statement_timeout: false, + // Abort any statement that waits longer than the specified duration in milliseconds while attempting to acquire a lock. + // false=unlimited + lock_timeout: false, + // Terminate any session with an open transaction that has been idle for longer than the specified duration in milliseconds + // false=unlimited + idle_in_transaction_session_timeout: false, + // max milliseconds to wait for query to complete (client side) + query_timeout: false, + connect_timeout: 0, + keepalives: 1, + keepalives_idle: 0 + }; + var pgTypes = require_pg_types(); + var parseBigInteger = pgTypes.getTypeParser(20, "text"); + var parseBigIntegerArray = pgTypes.getTypeParser(1016, "text"); + module.exports.__defineSetter__("parseInt8", function(val) { + pgTypes.setTypeParser(20, "text", val ? pgTypes.getTypeParser(23, "text") : parseBigInteger); + pgTypes.setTypeParser(1016, "text", val ? pgTypes.getTypeParser(1007, "text") : parseBigIntegerArray); + }); + } +}); + +// node_modules/pg/lib/utils.js +var require_utils = __commonJS({ + "node_modules/pg/lib/utils.js"(exports, module) { + "use strict"; + init_shims(); + var crypto2 = (init_crypto(), __toCommonJS(crypto_exports)); + var defaults2 = require_defaults(); + function escapeElement(elementRepresentation) { + var escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); + return '"' + escaped + '"'; + } + __name(escapeElement, "escapeElement"); + function arrayString(val) { + var result = "{"; + for (var i = 0; i < val.length; i++) { + if (i > 0) { + result = result + ","; + } + if (val[i] === null || typeof val[i] === "undefined") { + result = result + "NULL"; + } else if (Array.isArray(val[i])) { + result = result + arrayString(val[i]); + } else if (val[i] instanceof Buffer2) { + result += "\\\\x" + val[i].toString("hex"); + } else { + result += escapeElement(prepareValue2(val[i])); + } + } + result = result + "}"; + return result; + } + __name(arrayString, "arrayString"); + var prepareValue2 = /* @__PURE__ */ __name(function(val, seen) { + if (val == null) { + return null; + } + if (val instanceof Buffer2) { + return val; + } + if (ArrayBuffer.isView(val)) { + var buf = Buffer2.from(val.buffer, val.byteOffset, val.byteLength); + if (buf.length === val.byteLength) { + return buf; + } + return buf.slice(val.byteOffset, val.byteOffset + val.byteLength); + } + if (val instanceof Date) { + if (defaults2.parseInputDatesAsUTC) { + return dateToStringUTC(val); + } else { + return dateToString(val); + } + } + if (Array.isArray(val)) { + return arrayString(val); + } + if (typeof val === "object") { + return prepareObject(val, seen); + } + return val.toString(); + }, "prepareValue"); + function prepareObject(val, seen) { + if (val && typeof val.toPostgres === "function") { + seen = seen || []; + if (seen.indexOf(val) !== -1) { + throw new Error('circular reference detected while preparing "' + val + '" for query'); + } + seen.push(val); + return prepareValue2(val.toPostgres(prepareValue2), seen); + } + return JSON.stringify(val); + } + __name(prepareObject, "prepareObject"); + function pad(number, digits) { + number = "" + number; + while (number.length < digits) { + number = "0" + number; + } + return number; + } + __name(pad, "pad"); + function dateToString(date) { + var offset = -date.getTimezoneOffset(); + var year = date.getFullYear(); + var isBCYear = year < 1; + if (isBCYear) year = Math.abs(year) + 1; + var ret = pad(year, 4) + "-" + pad(date.getMonth() + 1, 2) + "-" + pad(date.getDate(), 2) + "T" + pad(date.getHours(), 2) + ":" + pad(date.getMinutes(), 2) + ":" + pad(date.getSeconds(), 2) + "." + pad(date.getMilliseconds(), 3); + if (offset < 0) { + ret += "-"; + offset *= -1; + } else { + ret += "+"; + } + ret += pad(Math.floor(offset / 60), 2) + ":" + pad(offset % 60, 2); + if (isBCYear) ret += " BC"; + return ret; + } + __name(dateToString, "dateToString"); + function dateToStringUTC(date) { + var year = date.getUTCFullYear(); + var isBCYear = year < 1; + if (isBCYear) year = Math.abs(year) + 1; + var ret = pad(year, 4) + "-" + pad(date.getUTCMonth() + 1, 2) + "-" + pad(date.getUTCDate(), 2) + "T" + pad(date.getUTCHours(), 2) + ":" + pad(date.getUTCMinutes(), 2) + ":" + pad(date.getUTCSeconds(), 2) + "." + pad(date.getUTCMilliseconds(), 3); + ret += "+00:00"; + if (isBCYear) ret += " BC"; + return ret; + } + __name(dateToStringUTC, "dateToStringUTC"); + function normalizeQueryConfig(config, values, callback) { + config = typeof config === "string" ? { text: config } : config; + if (values) { + if (typeof values === "function") { + config.callback = values; + } else { + config.values = values; + } + } + if (callback) { + config.callback = callback; + } + return config; + } + __name(normalizeQueryConfig, "normalizeQueryConfig"); + var md5 = /* @__PURE__ */ __name(function(string) { + return crypto2.createHash("md5").update(string, "utf-8").digest("hex"); + }, "md5"); + var postgresMd5PasswordHash = /* @__PURE__ */ __name(function(user, password, salt) { + var inner = md5(password + user); + var outer = md5(Buffer2.concat([Buffer2.from(inner), salt])); + return "md5" + outer; + }, "postgresMd5PasswordHash"); + module.exports = { + prepareValue: /* @__PURE__ */ __name(function prepareValueWrapper(value) { + return prepareValue2(value); + }, "prepareValueWrapper"), + normalizeQueryConfig, + postgresMd5PasswordHash, + md5 + }; + } +}); + +// node_modules/pg/lib/sasl.js +var require_sasl = __commonJS({ + "node_modules/pg/lib/sasl.js"(exports, module) { + "use strict"; + init_shims(); + var crypto2 = (init_crypto(), __toCommonJS(crypto_exports)); + function startSession(mechanisms) { + if (mechanisms.indexOf("SCRAM-SHA-256") === -1) { + throw new Error("SASL: Only mechanism SCRAM-SHA-256 is currently supported"); + } + const clientNonce = crypto2.randomBytes(18).toString("base64"); + return { + mechanism: "SCRAM-SHA-256", + clientNonce, + response: "n,,n=*,r=" + clientNonce, + message: "SASLInitialResponse" + }; + } + __name(startSession, "startSession"); + function continueSession(session, password, serverData) { + if (session.message !== "SASLInitialResponse") { + throw new Error("SASL: Last message was not SASLInitialResponse"); + } + if (typeof password !== "string") { + throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string"); + } + if (typeof serverData !== "string") { + throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string"); + } + const sv = parseServerFirstMessage(serverData); + if (!sv.nonce.startsWith(session.clientNonce)) { + throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce"); + } else if (sv.nonce.length === session.clientNonce.length) { + throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short"); + } + var saltBytes = Buffer2.from(sv.salt, "base64"); + var saltedPassword = Hi(password, saltBytes, sv.iteration); + var clientKey = hmacSha256(saltedPassword, "Client Key"); + var storedKey = sha2562(clientKey); + var clientFirstMessageBare = "n=*,r=" + session.clientNonce; + var serverFirstMessage = "r=" + sv.nonce + ",s=" + sv.salt + ",i=" + sv.iteration; + var clientFinalMessageWithoutProof = "c=biws,r=" + sv.nonce; + var authMessage = clientFirstMessageBare + "," + serverFirstMessage + "," + clientFinalMessageWithoutProof; + var clientSignature = hmacSha256(storedKey, authMessage); + var clientProofBytes = xorBuffers(clientKey, clientSignature); + var clientProof = clientProofBytes.toString("base64"); + var serverKey = hmacSha256(saltedPassword, "Server Key"); + var serverSignatureBytes = hmacSha256(serverKey, authMessage); + session.message = "SASLResponse"; + session.serverSignature = serverSignatureBytes.toString("base64"); + session.response = clientFinalMessageWithoutProof + ",p=" + clientProof; + } + __name(continueSession, "continueSession"); + function finalizeSession(session, serverData) { + if (session.message !== "SASLResponse") { + throw new Error("SASL: Last message was not SASLResponse"); + } + if (typeof serverData !== "string") { + throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string"); + } + const { serverSignature } = parseServerFinalMessage(serverData); + if (serverSignature !== session.serverSignature) { + throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match"); + } + } + __name(finalizeSession, "finalizeSession"); + function isPrintableChars(text) { + if (typeof text !== "string") { + throw new TypeError("SASL: text must be a string"); + } + return text.split("").map((_2, i) => text.charCodeAt(i)).every((c) => c >= 33 && c <= 43 || c >= 45 && c <= 126); + } + __name(isPrintableChars, "isPrintableChars"); + function isBase64(text) { + return /^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(text); + } + __name(isBase64, "isBase64"); + function parseAttributePairs(text) { + if (typeof text !== "string") { + throw new TypeError("SASL: attribute pairs text must be a string"); + } + return new Map( + text.split(",").map((attrValue) => { + if (!/^.=/.test(attrValue)) { + throw new Error("SASL: Invalid attribute pair entry"); + } + const name = attrValue[0]; + const value = attrValue.substring(2); + return [name, value]; + }) + ); + } + __name(parseAttributePairs, "parseAttributePairs"); + function parseServerFirstMessage(data) { + const attrPairs = parseAttributePairs(data); + const nonce = attrPairs.get("r"); + if (!nonce) { + throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing"); + } else if (!isPrintableChars(nonce)) { + throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters"); + } + const salt = attrPairs.get("s"); + if (!salt) { + throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing"); + } else if (!isBase64(salt)) { + throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64"); + } + const iterationText = attrPairs.get("i"); + if (!iterationText) { + throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing"); + } else if (!/^[1-9][0-9]*$/.test(iterationText)) { + throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count"); + } + const iteration = parseInt(iterationText, 10); + return { + nonce, + salt, + iteration + }; + } + __name(parseServerFirstMessage, "parseServerFirstMessage"); + function parseServerFinalMessage(serverData) { + const attrPairs = parseAttributePairs(serverData); + const serverSignature = attrPairs.get("v"); + if (!serverSignature) { + throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing"); + } else if (!isBase64(serverSignature)) { + throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64"); + } + return { + serverSignature + }; + } + __name(parseServerFinalMessage, "parseServerFinalMessage"); + function xorBuffers(a, b) { + if (!Buffer2.isBuffer(a)) { + throw new TypeError("first argument must be a Buffer"); + } + if (!Buffer2.isBuffer(b)) { + throw new TypeError("second argument must be a Buffer"); + } + if (a.length !== b.length) { + throw new Error("Buffer lengths must match"); + } + if (a.length === 0) { + throw new Error("Buffers cannot be empty"); + } + return Buffer2.from(a.map((_2, i) => a[i] ^ b[i])); + } + __name(xorBuffers, "xorBuffers"); + function sha2562(text) { + return crypto2.createHash("sha256").update(text).digest(); + } + __name(sha2562, "sha256"); + function hmacSha256(key, msg) { + return crypto2.createHmac("sha256", key).update(msg).digest(); + } + __name(hmacSha256, "hmacSha256"); + function Hi(password, saltBytes, iterations) { + var ui1 = hmacSha256(password, Buffer2.concat([saltBytes, Buffer2.from([0, 0, 0, 1])])); + var ui = ui1; + for (var i = 0; i < iterations - 1; i++) { + ui1 = hmacSha256(password, ui1); + ui = xorBuffers(ui, ui1); + } + return ui; + } + __name(Hi, "Hi"); + module.exports = { + startSession, + continueSession, + finalizeSession + }; + } +}); + +// shims/path/index.ts +var path_exports = {}; +__export(path_exports, { + join: () => join +}); +function join(...args) { + return args.join("/"); +} +var init_path = __esm({ + "shims/path/index.ts"() { + "use strict"; + init_shims(); + __name(join, "join"); + } +}); + +// shims/fs/index.ts +var fs_exports = {}; +__export(fs_exports, { + stat: () => stat +}); +function stat(file, cb) { + cb(new Error("No filesystem")); +} +var init_fs = __esm({ + "shims/fs/index.ts"() { + "use strict"; + init_shims(); + __name(stat, "stat"); + } +}); + +// shims/stream/index.ts +var stream_exports = {}; +__export(stream_exports, { + default: () => stream_default +}); +var stream_default; +var init_stream = __esm({ + "shims/stream/index.ts"() { + "use strict"; + init_shims(); + stream_default = {}; + } +}); + +// shims/string_decoder/index.ts +var string_decoder_exports = {}; +__export(string_decoder_exports, { + StringDecoder: () => StringDecoder +}); +var StringDecoder; +var init_string_decoder = __esm({ + "shims/string_decoder/index.ts"() { + "use strict"; + init_shims(); + StringDecoder = class { + static { + __name(this, "StringDecoder"); + } + td; + constructor(encoding) { + this.td = new TextDecoder(encoding); + } + write(data) { + return this.td.decode(data, { stream: true }); + } + end(data) { + return this.td.decode(data); + } + }; + } +}); + +// node_modules/split2/index.js +var require_split2 = __commonJS({ + "node_modules/split2/index.js"(exports, module) { + "use strict"; + init_shims(); + var { Transform } = (init_stream(), __toCommonJS(stream_exports)); + var { StringDecoder: StringDecoder2 } = (init_string_decoder(), __toCommonJS(string_decoder_exports)); + var kLast = Symbol("last"); + var kDecoder = Symbol("decoder"); + function transform(chunk, enc, cb) { + let list; + if (this.overflow) { + const buf = this[kDecoder].write(chunk); + list = buf.split(this.matcher); + if (list.length === 1) return cb(); + list.shift(); + this.overflow = false; + } else { + this[kLast] += this[kDecoder].write(chunk); + list = this[kLast].split(this.matcher); + } + this[kLast] = list.pop(); + for (let i = 0; i < list.length; i++) { + try { + push(this, this.mapper(list[i])); + } catch (error) { + return cb(error); + } + } + this.overflow = this[kLast].length > this.maxLength; + if (this.overflow && !this.skipOverflow) { + cb(new Error("maximum buffer reached")); + return; + } + cb(); + } + __name(transform, "transform"); + function flush(cb) { + this[kLast] += this[kDecoder].end(); + if (this[kLast]) { + try { + push(this, this.mapper(this[kLast])); + } catch (error) { + return cb(error); + } + } + cb(); + } + __name(flush, "flush"); + function push(self, val) { + if (val !== void 0) { + self.push(val); + } + } + __name(push, "push"); + function noop(incoming) { + return incoming; + } + __name(noop, "noop"); + function split(matcher, mapper, options) { + matcher = matcher || /\r?\n/; + mapper = mapper || noop; + options = options || {}; + switch (arguments.length) { + case 1: + if (typeof matcher === "function") { + mapper = matcher; + matcher = /\r?\n/; + } else if (typeof matcher === "object" && !(matcher instanceof RegExp) && !matcher[Symbol.split]) { + options = matcher; + matcher = /\r?\n/; + } + break; + case 2: + if (typeof matcher === "function") { + options = mapper; + mapper = matcher; + matcher = /\r?\n/; + } else if (typeof mapper === "object") { + options = mapper; + mapper = noop; + } + } + options = Object.assign({}, options); + options.autoDestroy = true; + options.transform = transform; + options.flush = flush; + options.readableObjectMode = true; + const stream = new Transform(options); + stream[kLast] = ""; + stream[kDecoder] = new StringDecoder2("utf8"); + stream.matcher = matcher; + stream.mapper = mapper; + stream.maxLength = options.maxLength; + stream.skipOverflow = options.skipOverflow || false; + stream.overflow = false; + stream._destroy = function(err, cb) { + this._writableState.errorEmitted = false; + cb(err); + }; + return stream; + } + __name(split, "split"); + module.exports = split; + } +}); + +// node_modules/pgpass/lib/helper.js +var require_helper = __commonJS({ + "node_modules/pgpass/lib/helper.js"(exports, module) { + "use strict"; + init_shims(); + var path = (init_path(), __toCommonJS(path_exports)); + var Stream = (init_stream(), __toCommonJS(stream_exports)).Stream; + var split = require_split2(); + var util = (init_util(), __toCommonJS(util_exports)); + var defaultPort = 5432; + var isWin = process.platform === "win32"; + var warnStream = process.stderr; + var S_IRWXG = 56; + var S_IRWXO = 7; + var S_IFMT = 61440; + var S_IFREG = 32768; + function isRegFile(mode) { + return (mode & S_IFMT) == S_IFREG; + } + __name(isRegFile, "isRegFile"); + var fieldNames = ["host", "port", "database", "user", "password"]; + var nrOfFields = fieldNames.length; + var passKey = fieldNames[nrOfFields - 1]; + function warn() { + var isWritable = warnStream instanceof Stream && true === warnStream.writable; + if (isWritable) { + var args = Array.prototype.slice.call(arguments).concat("\n"); + warnStream.write(util.format.apply(util, args)); + } + } + __name(warn, "warn"); + Object.defineProperty(module.exports, "isWin", { + get: /* @__PURE__ */ __name(function() { + return isWin; + }, "get"), + set: /* @__PURE__ */ __name(function(val) { + isWin = val; + }, "set") + }); + module.exports.warnTo = function(stream) { + var old = warnStream; + warnStream = stream; + return old; + }; + module.exports.getFileName = function(rawEnv) { + var env = rawEnv || process.env; + var file = env.PGPASSFILE || (isWin ? path.join(env.APPDATA || "./", "postgresql", "pgpass.conf") : path.join(env.HOME || "./", ".pgpass")); + return file; + }; + module.exports.usePgPass = function(stats, fname) { + if (Object.prototype.hasOwnProperty.call(process.env, "PGPASSWORD")) { + return false; + } + if (isWin) { + return true; + } + fname = fname || ""; + if (!isRegFile(stats.mode)) { + warn('WARNING: password file "%s" is not a plain file', fname); + return false; + } + if (stats.mode & (S_IRWXG | S_IRWXO)) { + warn('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less', fname); + return false; + } + return true; + }; + var matcher = module.exports.match = function(connInfo, entry) { + return fieldNames.slice(0, -1).reduce(function(prev, field, idx) { + if (idx == 1) { + if (Number(connInfo[field] || defaultPort) === Number(entry[field])) { + return prev && true; + } + } + return prev && (entry[field] === "*" || entry[field] === connInfo[field]); + }, true); + }; + module.exports.getPassword = function(connInfo, stream, cb) { + var pass; + var lineStream = stream.pipe(split()); + function onLine(line) { + var entry = parseLine(line); + if (entry && isValidEntry(entry) && matcher(connInfo, entry)) { + pass = entry[passKey]; + lineStream.end(); + } + } + __name(onLine, "onLine"); + var onEnd = /* @__PURE__ */ __name(function() { + stream.destroy(); + cb(pass); + }, "onEnd"); + var onErr = /* @__PURE__ */ __name(function(err) { + stream.destroy(); + warn("WARNING: error on reading file: %s", err); + cb(void 0); + }, "onErr"); + stream.on("error", onErr); + lineStream.on("data", onLine).on("end", onEnd).on("error", onErr); + }; + var parseLine = module.exports.parseLine = function(line) { + if (line.length < 11 || line.match(/^\s+#/)) { + return null; + } + var curChar = ""; + var prevChar = ""; + var fieldIdx = 0; + var startIdx = 0; + var endIdx = 0; + var obj = {}; + var isLastField = false; + var addToObj = /* @__PURE__ */ __name(function(idx, i0, i1) { + var field = line.substring(i0, i1); + if (!Object.hasOwnProperty.call(process.env, "PGPASS_NO_DEESCAPE")) { + field = field.replace(/\\([:\\])/g, "$1"); + } + obj[fieldNames[idx]] = field; + }, "addToObj"); + for (var i = 0; i < line.length - 1; i += 1) { + curChar = line.charAt(i + 1); + prevChar = line.charAt(i); + isLastField = fieldIdx == nrOfFields - 1; + if (isLastField) { + addToObj(fieldIdx, startIdx); + break; + } + if (i >= 0 && curChar == ":" && prevChar !== "\\") { + addToObj(fieldIdx, startIdx, i + 1); + startIdx = i + 2; + fieldIdx += 1; + } + } + obj = Object.keys(obj).length === nrOfFields ? obj : null; + return obj; + }; + var isValidEntry = module.exports.isValidEntry = function(entry) { + var rules = { + // host + 0: function(x) { + return x.length > 0; + }, + // port + 1: function(x) { + if (x === "*") { + return true; + } + x = Number(x); + return isFinite(x) && x > 0 && x < 9007199254740992 && Math.floor(x) === x; + }, + // database + 2: function(x) { + return x.length > 0; + }, + // username + 3: function(x) { + return x.length > 0; + }, + // password + 4: function(x) { + return x.length > 0; + } + }; + for (var idx = 0; idx < fieldNames.length; idx += 1) { + var rule = rules[idx]; + var value = entry[fieldNames[idx]] || ""; + var res = rule(value); + if (!res) { + return false; + } + } + return true; + }; + } +}); + +// node_modules/pgpass/lib/index.js +var require_lib = __commonJS({ + "node_modules/pgpass/lib/index.js"(exports, module) { + "use strict"; + init_shims(); + var path = (init_path(), __toCommonJS(path_exports)); + var fs = (init_fs(), __toCommonJS(fs_exports)); + var helper = require_helper(); + module.exports = function(connInfo, cb) { + var file = helper.getFileName(); + fs.stat(file, function(err, stat2) { + if (err || !helper.usePgPass(stat2, file)) { + return cb(void 0); + } + var st2 = fs.createReadStream(file); + helper.getPassword(connInfo, st2, cb); + }); + }; + module.exports.warnTo = helper.warnTo; + } +}); + +// node_modules/pg/lib/type-overrides.js +var require_type_overrides = __commonJS({ + "node_modules/pg/lib/type-overrides.js"(exports, module) { + "use strict"; + init_shims(); + var types2 = require_pg_types(); + function TypeOverrides2(userTypes) { + this._types = userTypes || types2; + this.text = {}; + this.binary = {}; + } + __name(TypeOverrides2, "TypeOverrides"); + TypeOverrides2.prototype.getOverrides = function(format) { + switch (format) { + case "text": + return this.text; + case "binary": + return this.binary; + default: + return {}; + } + }; + TypeOverrides2.prototype.setTypeParser = function(oid, format, parseFn) { + if (typeof format === "function") { + parseFn = format; + format = "text"; + } + this.getOverrides(format)[oid] = parseFn; + }; + TypeOverrides2.prototype.getTypeParser = function(oid, format) { + format = format || "text"; + return this.getOverrides(format)[oid] || this._types.getTypeParser(oid, format); + }; + module.exports = TypeOverrides2; + } +}); + +// shims/dns/index.ts +var dns_exports = {}; +__export(dns_exports, { + default: () => dns_default +}); +var dns_default; +var init_dns = __esm({ + "shims/dns/index.ts"() { + "use strict"; + init_shims(); + dns_default = {}; + } +}); + +// shims/url/index.ts +var url_exports = {}; +__export(url_exports, { + parse: () => parse +}); +function parse(url, parseQueryString = false) { + const { protocol } = new URL(url); + const httpUrl = "http:" + url.substring(protocol.length); + let { + username, + password, + host, + hostname, + port, + pathname, + search, + searchParams, + hash + } = new URL(httpUrl); + password = decodeURIComponent(password); + username = decodeURIComponent(username); + pathname = decodeURIComponent(pathname); + const auth = username + ":" + password; + const query = parseQueryString ? Object.fromEntries(searchParams.entries()) : search; + return { + href: url, + protocol, + auth, + username, + password, + host, + hostname, + port, + pathname, + search, + query, + hash + }; +} +var init_url = __esm({ + "shims/url/index.ts"() { + "use strict"; + init_shims(); + __name(parse, "parse"); + } +}); + +// node_modules/pg-connection-string/index.js +var require_pg_connection_string = __commonJS({ + "node_modules/pg-connection-string/index.js"(exports, module) { + "use strict"; + init_shims(); + var url = (init_url(), __toCommonJS(url_exports)); + var fs = (init_fs(), __toCommonJS(fs_exports)); + function parse2(str) { + if (str.charAt(0) === "/") { + var config = str.split(" "); + return { host: config[0], database: config[1] }; + } + var result = url.parse( + / |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str) ? encodeURI(str).replace(/\%25(\d\d)/g, "%$1") : str, + true + ); + var config = result.query; + for (var k in config) { + if (Array.isArray(config[k])) { + config[k] = config[k][config[k].length - 1]; + } + } + var auth = (result.auth || ":").split(":"); + config.user = auth[0]; + config.password = auth.splice(1).join(":"); + config.port = result.port; + if (result.protocol == "socket:") { + config.host = decodeURI(result.pathname); + config.database = result.query.db; + config.client_encoding = result.query.encoding; + return config; + } + if (!config.host) { + config.host = result.hostname; + } + var pathname = result.pathname; + if (!config.host && pathname && /^%2f/i.test(pathname)) { + var pathnameSplit = pathname.split("/"); + config.host = decodeURIComponent(pathnameSplit[0]); + pathname = pathnameSplit.splice(1).join("/"); + } + if (pathname && pathname.charAt(0) === "/") { + pathname = pathname.slice(1) || null; + } + config.database = pathname && decodeURI(pathname); + if (config.ssl === "true" || config.ssl === "1") { + config.ssl = true; + } + if (config.ssl === "0") { + config.ssl = false; + } + if (config.sslcert || config.sslkey || config.sslrootcert || config.sslmode) { + config.ssl = {}; + } + if (config.sslcert) { + config.ssl.cert = fs.readFileSync(config.sslcert).toString(); + } + if (config.sslkey) { + config.ssl.key = fs.readFileSync(config.sslkey).toString(); + } + if (config.sslrootcert) { + config.ssl.ca = fs.readFileSync(config.sslrootcert).toString(); + } + switch (config.sslmode) { + case "disable": { + config.ssl = false; + break; + } + case "prefer": + case "require": + case "verify-ca": + case "verify-full": { + break; + } + case "no-verify": { + config.ssl.rejectUnauthorized = false; + break; + } + } + return config; + } + __name(parse2, "parse"); + module.exports = parse2; + parse2.parse = parse2; + } +}); + +// node_modules/pg/lib/connection-parameters.js +var require_connection_parameters = __commonJS({ + "node_modules/pg/lib/connection-parameters.js"(exports, module) { + "use strict"; + init_shims(); + var dns = (init_dns(), __toCommonJS(dns_exports)); + var defaults2 = require_defaults(); + var parse2 = require_pg_connection_string().parse; + var val = /* @__PURE__ */ __name(function(key, config, envVar) { + if (envVar === void 0) { + envVar = process.env["PG" + key.toUpperCase()]; + } else if (envVar === false) { + } else { + envVar = process.env[envVar]; + } + return config[key] || envVar || defaults2[key]; + }, "val"); + var readSSLConfigFromEnvironment = /* @__PURE__ */ __name(function() { + switch (process.env.PGSSLMODE) { + case "disable": + return false; + case "prefer": + case "require": + case "verify-ca": + case "verify-full": + return true; + case "no-verify": + return { rejectUnauthorized: false }; + } + return defaults2.ssl; + }, "readSSLConfigFromEnvironment"); + var quoteParamValue = /* @__PURE__ */ __name(function(value) { + return "'" + ("" + value).replace(/\\/g, "\\\\").replace(/'/g, "\\'") + "'"; + }, "quoteParamValue"); + var add = /* @__PURE__ */ __name(function(params, config, paramName) { + var value = config[paramName]; + if (value !== void 0 && value !== null) { + params.push(paramName + "=" + quoteParamValue(value)); + } + }, "add"); + var ConnectionParameters2 = class { + static { + __name(this, "ConnectionParameters"); + } + constructor(config) { + config = typeof config === "string" ? parse2(config) : config || {}; + if (config.connectionString) { + config = Object.assign({}, config, parse2(config.connectionString)); + } + this.user = val("user", config); + this.database = val("database", config); + if (this.database === void 0) { + this.database = this.user; + } + this.port = parseInt(val("port", config), 10); + this.host = val("host", config); + Object.defineProperty(this, "password", { + configurable: true, + enumerable: false, + writable: true, + value: val("password", config) + }); + this.binary = val("binary", config); + this.options = val("options", config); + this.ssl = typeof config.ssl === "undefined" ? readSSLConfigFromEnvironment() : config.ssl; + if (typeof this.ssl === "string") { + if (this.ssl === "true") { + this.ssl = true; + } + } + if (this.ssl === "no-verify") { + this.ssl = { rejectUnauthorized: false }; + } + if (this.ssl && this.ssl.key) { + Object.defineProperty(this.ssl, "key", { + enumerable: false + }); + } + this.client_encoding = val("client_encoding", config); + this.replication = val("replication", config); + this.isDomainSocket = !(this.host || "").indexOf("/"); + this.application_name = val("application_name", config, "PGAPPNAME"); + this.fallback_application_name = val("fallback_application_name", config, false); + this.statement_timeout = val("statement_timeout", config, false); + this.lock_timeout = val("lock_timeout", config, false); + this.idle_in_transaction_session_timeout = val("idle_in_transaction_session_timeout", config, false); + this.query_timeout = val("query_timeout", config, false); + if (config.connectionTimeoutMillis === void 0) { + this.connect_timeout = process.env.PGCONNECT_TIMEOUT || 0; + } else { + this.connect_timeout = Math.floor(config.connectionTimeoutMillis / 1e3); + } + if (config.keepAlive === false) { + this.keepalives = 0; + } else if (config.keepAlive === true) { + this.keepalives = 1; + } + if (typeof config.keepAliveInitialDelayMillis === "number") { + this.keepalives_idle = Math.floor(config.keepAliveInitialDelayMillis / 1e3); + } + } + getLibpqConnectionString(cb) { + var params = []; + add(params, this, "user"); + add(params, this, "password"); + add(params, this, "port"); + add(params, this, "application_name"); + add(params, this, "fallback_application_name"); + add(params, this, "connect_timeout"); + add(params, this, "options"); + var ssl = typeof this.ssl === "object" ? this.ssl : this.ssl ? { sslmode: this.ssl } : {}; + add(params, ssl, "sslmode"); + add(params, ssl, "sslca"); + add(params, ssl, "sslkey"); + add(params, ssl, "sslcert"); + add(params, ssl, "sslrootcert"); + if (this.database) { + params.push("dbname=" + quoteParamValue(this.database)); + } + if (this.replication) { + params.push("replication=" + quoteParamValue(this.replication)); + } + if (this.host) { + params.push("host=" + quoteParamValue(this.host)); + } + if (this.isDomainSocket) { + return cb(null, params.join(" ")); + } + if (this.client_encoding) { + params.push("client_encoding=" + quoteParamValue(this.client_encoding)); + } + dns.lookup(this.host, function(err, address) { + if (err) return cb(err, null); + params.push("hostaddr=" + quoteParamValue(address)); + return cb(null, params.join(" ")); + }); + } + }; + module.exports = ConnectionParameters2; + } +}); + +// node_modules/pg/lib/result.js +var require_result = __commonJS({ + "node_modules/pg/lib/result.js"(exports, module) { + "use strict"; + init_shims(); + var types2 = require_pg_types(); + var matchRegexp = /^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/; + var Result = class { + static { + __name(this, "Result"); + } + constructor(rowMode, types3) { + this.command = null; + this.rowCount = null; + this.oid = null; + this.rows = []; + this.fields = []; + this._parsers = void 0; + this._types = types3; + this.RowCtor = null; + this.rowAsArray = rowMode === "array"; + if (this.rowAsArray) { + this.parseRow = this._parseRowAsArray; + } + } + // adds a command complete message + addCommandComplete(msg) { + var match; + if (msg.text) { + match = matchRegexp.exec(msg.text); + } else { + match = matchRegexp.exec(msg.command); + } + if (match) { + this.command = match[1]; + if (match[3]) { + this.oid = parseInt(match[2], 10); + this.rowCount = parseInt(match[3], 10); + } else if (match[2]) { + this.rowCount = parseInt(match[2], 10); + } + } + } + _parseRowAsArray(rowData) { + var row = new Array(rowData.length); + for (var i = 0, len = rowData.length; i < len; i++) { + var rawValue = rowData[i]; + if (rawValue !== null) { + row[i] = this._parsers[i](rawValue); + } else { + row[i] = null; + } + } + return row; + } + parseRow(rowData) { + var row = {}; + for (var i = 0, len = rowData.length; i < len; i++) { + var rawValue = rowData[i]; + var field = this.fields[i].name; + if (rawValue !== null) { + row[field] = this._parsers[i](rawValue); + } else { + row[field] = null; + } + } + return row; + } + addRow(row) { + this.rows.push(row); + } + addFields(fieldDescriptions) { + this.fields = fieldDescriptions; + if (this.fields.length) { + this._parsers = new Array(fieldDescriptions.length); + } + for (var i = 0; i < fieldDescriptions.length; i++) { + var desc = fieldDescriptions[i]; + if (this._types) { + this._parsers[i] = this._types.getTypeParser(desc.dataTypeID, desc.format || "text"); + } else { + this._parsers[i] = types2.getTypeParser(desc.dataTypeID, desc.format || "text"); + } + } + } + }; + module.exports = Result; + } +}); + +// node_modules/pg/lib/query.js +var require_query = __commonJS({ + "node_modules/pg/lib/query.js"(exports, module) { + "use strict"; + init_shims(); + var { EventEmitter: EventEmitter2 } = require_events(); + var Result = require_result(); + var utils = require_utils(); + var Query2 = class extends EventEmitter2 { + static { + __name(this, "Query"); + } + constructor(config, values, callback) { + super(); + config = utils.normalizeQueryConfig(config, values, callback); + this.text = config.text; + this.values = config.values; + this.rows = config.rows; + this.types = config.types; + this.name = config.name; + this.binary = config.binary; + this.portal = config.portal || ""; + this.callback = config.callback; + this._rowMode = config.rowMode; + if (process.domain && config.callback) { + this.callback = process.domain.bind(config.callback); + } + this._result = new Result(this._rowMode, this.types); + this._results = this._result; + this.isPreparedStatement = false; + this._canceledDueToError = false; + this._promise = null; + } + requiresPreparation() { + if (this.name) { + return true; + } + if (this.rows) { + return true; + } + if (!this.text) { + return false; + } + if (!this.values) { + return false; + } + return this.values.length > 0; + } + _checkForMultirow() { + if (this._result.command) { + if (!Array.isArray(this._results)) { + this._results = [this._result]; + } + this._result = new Result(this._rowMode, this.types); + this._results.push(this._result); + } + } + // associates row metadata from the supplied + // message with this query object + // metadata used when parsing row results + handleRowDescription(msg) { + this._checkForMultirow(); + this._result.addFields(msg.fields); + this._accumulateRows = this.callback || !this.listeners("row").length; + } + handleDataRow(msg) { + let row; + if (this._canceledDueToError) { + return; + } + try { + row = this._result.parseRow(msg.fields); + } catch (err) { + this._canceledDueToError = err; + return; + } + this.emit("row", row, this._result); + if (this._accumulateRows) { + this._result.addRow(row); + } + } + handleCommandComplete(msg, connection) { + this._checkForMultirow(); + this._result.addCommandComplete(msg); + if (this.rows) { + connection.sync(); + } + } + // if a named prepared statement is created with empty query text + // the backend will send an emptyQuery message but *not* a command complete message + // since we pipeline sync immediately after execute we don't need to do anything here + // unless we have rows specified, in which case we did not pipeline the intial sync call + handleEmptyQuery(connection) { + if (this.rows) { + connection.sync(); + } + } + handleError(err, connection) { + if (this._canceledDueToError) { + err = this._canceledDueToError; + this._canceledDueToError = false; + } + if (this.callback) { + return this.callback(err); + } + this.emit("error", err); + } + handleReadyForQuery(con) { + if (this._canceledDueToError) { + return this.handleError(this._canceledDueToError, con); + } + if (this.callback) { + try { + this.callback(null, this._results); + } catch (err) { + process.nextTick(() => { + throw err; + }); + } + } + this.emit("end", this._results); + } + submit(connection) { + if (typeof this.text !== "string" && typeof this.name !== "string") { + return new Error("A query must have either text or a name. Supplying neither is unsupported."); + } + const previous = connection.parsedStatements[this.name]; + if (this.text && previous && this.text !== previous) { + return new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`); + } + if (this.values && !Array.isArray(this.values)) { + return new Error("Query values must be an array"); + } + if (this.requiresPreparation()) { + this.prepare(connection); + } else { + connection.query(this.text); + } + return null; + } + hasBeenParsed(connection) { + return this.name && connection.parsedStatements[this.name]; + } + handlePortalSuspended(connection) { + this._getRows(connection, this.rows); + } + _getRows(connection, rows) { + connection.execute({ + portal: this.portal, + rows + }); + if (!rows) { + connection.sync(); + } else { + connection.flush(); + } + } + // http://developer.postgresql.org/pgdocs/postgres/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY + prepare(connection) { + this.isPreparedStatement = true; + if (!this.hasBeenParsed(connection)) { + connection.parse({ + text: this.text, + name: this.name, + types: this.types + }); + } + try { + connection.bind({ + portal: this.portal, + statement: this.name, + values: this.values, + binary: this.binary, + valueMapper: utils.prepareValue + }); + } catch (err) { + this.handleError(err, connection); + return; + } + connection.describe({ + type: "P", + name: this.portal || "" + }); + this._getRows(connection, this.rows); + } + handleCopyInResponse(connection) { + connection.sendCopyFail("No source stream defined"); + } + // eslint-disable-next-line no-unused-vars + handleCopyData(msg, connection) { + } + }; + module.exports = Query2; + } +}); + +// shims/net/index.ts +var net_exports = {}; +__export(net_exports, { + Socket: () => Socket, + isIP: () => isIP +}); +function hexDump(data) { + return `${data.length} bytes` + data.reduce( + (memo, byte) => memo + " " + byte.toString(16).padStart(2, "0"), + "\nhex:" + ) + "\nstr: " + new TextDecoder().decode(data); +} +function log(...args) { + console.log( + ...args.map( + (arg) => arg instanceof Uint8Array ? hexDump(arg) : arg instanceof ArrayBuffer ? hexDump(new Uint8Array(arg)) : arg + ) + ); +} +function isIP(input) { + return 0; +} +var import_events, FIRST_WORD_REGEX, Socket; +var init_net = __esm({ + "shims/net/index.ts"() { + "use strict"; + init_shims(); + import_events = __toESM(require_events(), 1); + __name(hexDump, "hexDump"); + __name(log, "log"); + __name(isIP, "isIP"); + FIRST_WORD_REGEX = /^[^.]+\./; + Socket = class _Socket extends import_events.EventEmitter { + static { + __name(this, "Socket"); + } + static defaults = { + // these options relate to the fetch transport and take effect *only* when set globally + poolQueryViaFetch: false, + fetchEndpoint: /* @__PURE__ */ __name((host, _port, options) => { + let newHost; + if (options?.jwtAuth) { + newHost = host.replace(FIRST_WORD_REGEX, "apiauth."); + } else { + newHost = host.replace(FIRST_WORD_REGEX, "api."); + } + return "https://" + newHost + "/sql"; + }, "fetchEndpoint"), + fetchConnectionCache: true, + fetchFunction: void 0, + // these options relate to the WebSocket transport + webSocketConstructor: void 0, + wsProxy: /* @__PURE__ */ __name((host) => host + "/v2", "wsProxy"), + useSecureWebSocket: true, + forceDisablePgSSL: true, + coalesceWrites: true, + pipelineConnect: "password", + // these options apply only to Postgres-native TLS over WebSockets (when forceDisablePgSSL === false) + subtls: void 0, + rootCerts: "", + pipelineTLS: false, + disableSNI: false + }; + static opts = {}; + opts = {}; + static get poolQueryViaFetch() { + return _Socket.opts.poolQueryViaFetch ?? _Socket.defaults.poolQueryViaFetch; + } + static set poolQueryViaFetch(newValue) { + _Socket.opts.poolQueryViaFetch = newValue; + } + static get fetchEndpoint() { + return _Socket.opts.fetchEndpoint ?? _Socket.defaults.fetchEndpoint; + } + static set fetchEndpoint(newValue) { + _Socket.opts.fetchEndpoint = newValue; + } + static get fetchConnectionCache() { + return true; + } + static set fetchConnectionCache(newValue) { + console.warn( + "The `fetchConnectionCache` option is deprecated (now always `true`)" + ); + } + static get fetchFunction() { + return _Socket.opts.fetchFunction ?? _Socket.defaults.fetchFunction; + } + static set fetchFunction(newValue) { + _Socket.opts.fetchFunction = newValue; + } + static get webSocketConstructor() { + return _Socket.opts.webSocketConstructor ?? _Socket.defaults.webSocketConstructor; + } + static set webSocketConstructor(newValue) { + _Socket.opts.webSocketConstructor = newValue; + } + get webSocketConstructor() { + return this.opts.webSocketConstructor ?? _Socket.webSocketConstructor; + } + set webSocketConstructor(newValue) { + this.opts.webSocketConstructor = newValue; + } + static get wsProxy() { + return _Socket.opts.wsProxy ?? _Socket.defaults.wsProxy; + } + static set wsProxy(newValue) { + _Socket.opts.wsProxy = newValue; + } + get wsProxy() { + return this.opts.wsProxy ?? _Socket.wsProxy; + } + set wsProxy(newValue) { + this.opts.wsProxy = newValue; + } + static get coalesceWrites() { + return _Socket.opts.coalesceWrites ?? _Socket.defaults.coalesceWrites; + } + static set coalesceWrites(newValue) { + _Socket.opts.coalesceWrites = newValue; + } + get coalesceWrites() { + return this.opts.coalesceWrites ?? _Socket.coalesceWrites; + } + set coalesceWrites(newValue) { + this.opts.coalesceWrites = newValue; + } + static get useSecureWebSocket() { + return _Socket.opts.useSecureWebSocket ?? _Socket.defaults.useSecureWebSocket; + } + static set useSecureWebSocket(newValue) { + _Socket.opts.useSecureWebSocket = newValue; + } + get useSecureWebSocket() { + return this.opts.useSecureWebSocket ?? _Socket.useSecureWebSocket; + } + set useSecureWebSocket(newValue) { + this.opts.useSecureWebSocket = newValue; + } + static get forceDisablePgSSL() { + return _Socket.opts.forceDisablePgSSL ?? _Socket.defaults.forceDisablePgSSL; + } + static set forceDisablePgSSL(newValue) { + _Socket.opts.forceDisablePgSSL = newValue; + } + get forceDisablePgSSL() { + return this.opts.forceDisablePgSSL ?? _Socket.forceDisablePgSSL; + } + set forceDisablePgSSL(newValue) { + this.opts.forceDisablePgSSL = newValue; + } + static get disableSNI() { + return _Socket.opts.disableSNI ?? _Socket.defaults.disableSNI; + } + static set disableSNI(newValue) { + _Socket.opts.disableSNI = newValue; + } + get disableSNI() { + return this.opts.disableSNI ?? _Socket.disableSNI; + } + set disableSNI(newValue) { + this.opts.disableSNI = newValue; + } + static get pipelineConnect() { + return _Socket.opts.pipelineConnect ?? _Socket.defaults.pipelineConnect; + } + static set pipelineConnect(newValue) { + _Socket.opts.pipelineConnect = newValue; + } + get pipelineConnect() { + return this.opts.pipelineConnect ?? _Socket.pipelineConnect; + } + set pipelineConnect(newValue) { + this.opts.pipelineConnect = newValue; + } + static get subtls() { + return _Socket.opts.subtls ?? _Socket.defaults.subtls; + } + static set subtls(newValue) { + _Socket.opts.subtls = newValue; + } + get subtls() { + return this.opts.subtls ?? _Socket.subtls; + } + set subtls(newValue) { + this.opts.subtls = newValue; + } + static get pipelineTLS() { + return _Socket.opts.pipelineTLS ?? _Socket.defaults.pipelineTLS; + } + static set pipelineTLS(newValue) { + _Socket.opts.pipelineTLS = newValue; + } + get pipelineTLS() { + return this.opts.pipelineTLS ?? _Socket.pipelineTLS; + } + set pipelineTLS(newValue) { + this.opts.pipelineTLS = newValue; + } + static get rootCerts() { + return _Socket.opts.rootCerts ?? _Socket.defaults.rootCerts; + } + static set rootCerts(newValue) { + _Socket.opts.rootCerts = newValue; + } + get rootCerts() { + return this.opts.rootCerts ?? _Socket.rootCerts; + } + set rootCerts(newValue) { + this.opts.rootCerts = newValue; + } + wsProxyAddrForHost(host, port) { + const wsProxy = this.wsProxy; + if (wsProxy === void 0) { + throw new Error( + `No WebSocket proxy is configured. Please see https://github.com/neondatabase/serverless/blob/main/CONFIG.md#wsproxy-string--host-string-port-number--string--string` + ); + } + return typeof wsProxy === "function" ? wsProxy(host, port) : `${wsProxy}?address=${host}:${port}`; + } + connecting = false; + pending = true; + writable = true; + encrypted = false; + authorized = false; + destroyed = false; + ws = null; + writeBuffer; + // used only if coalesceWrites === true + tlsState = 0 /* None */; + tlsRead; + tlsWrite; + setNoDelay() { + log("setNoDelay (no-op)"); + return this; + } + setKeepAlive() { + log("setKeepAlive (no-op)"); + return this; + } + ref() { + log("ref (no-op)"); + return this; + } + unref() { + log("unref (no-op)"); + return this; + } + connect(port, host, connectListener) { + this.connecting = true; + if (connectListener) this.once("connect", connectListener); + const handleWebSocketOpen = /* @__PURE__ */ __name(() => { + log("socket ready"); + this.connecting = false; + this.pending = false; + this.emit("connect"); + this.emit("ready"); + }, "handleWebSocketOpen"); + const configureWebSocket = /* @__PURE__ */ __name((ws, immediateOpen = false) => { + ws.binaryType = "arraybuffer"; + ws.addEventListener("error", (err) => { + log("websocket error", err); + this.emit("error", err); + this.emit("close"); + }); + ws.addEventListener("message", (msg) => { + log("socket received:", msg.data); + if (this.tlsState === 0 /* None */) { + log("emitting received data"); + const buffer = Buffer2.from(msg.data); + this.emit("data", buffer); + } + }); + ws.addEventListener("close", () => { + log("websocket closed"); + this.emit("close"); + }); + if (immediateOpen) handleWebSocketOpen(); + else ws.addEventListener("open", handleWebSocketOpen); + }, "configureWebSocket"); + let wsAddr; + try { + wsAddr = this.wsProxyAddrForHost( + host, + typeof port === "string" ? parseInt(port, 10) : port + ); + } catch (err) { + this.emit("error", err); + this.emit("close"); + return; + } + try { + const wsProtocol = this.useSecureWebSocket ? "wss:" : "ws:"; + const wsAddrFull = wsProtocol + "//" + wsAddr; + if (this.webSocketConstructor !== void 0) { + this.ws = new this.webSocketConstructor(wsAddrFull); + configureWebSocket(this.ws); + } else { + try { + this.ws = new WebSocket(wsAddrFull); + configureWebSocket(this.ws); + } catch (err) { + log("new WebSocket() failed"); + this.ws = new __unstable_WebSocket(wsAddrFull); + configureWebSocket(this.ws); + } + } + } catch (err) { + log("WebSocket constructors failed"); + const wsProtocol = this.useSecureWebSocket ? "https:" : "http:"; + const fetchAddrFull = wsProtocol + "//" + wsAddr; + fetch(fetchAddrFull, { headers: { Upgrade: "websocket" } }).then((resp) => { + this.ws = resp.webSocket; + if (this.ws == null) throw err; + this.ws.accept(); + configureWebSocket(this.ws, true); + log("Cloudflare WebSocket opened"); + }).catch((err2) => { + log(`fetch() with { Upgrade: "websocket" } failed`); + this.emit( + "error", + new Error( + `All attempts to open a WebSocket to connect to the database failed. Please refer to https://github.com/neondatabase/serverless/blob/main/CONFIG.md#websocketconstructor-typeof-websocket--undefined. Details: ${err2.message}` + ) + ); + this.emit("close"); + }); + } + } + async startTls(host) { + log("starting TLS"); + if (this.subtls === void 0) + throw new Error( + "For Postgres SSL connections, you must set `neonConfig.subtls` to the subtls library. See https://github.com/neondatabase/serverless/blob/main/CONFIG.md for more information." + ); + this.tlsState = 1 /* Handshake */; + const rootCerts = this.subtls.TrustedCert.fromPEM(this.rootCerts); + const readQueue = new this.subtls.WebSocketReadQueue(this.ws); + const networkRead = readQueue.read.bind(readQueue); + const networkWrite = this.rawWrite.bind(this); + const [tlsRead, tlsWrite] = await this.subtls.startTls( + host, + rootCerts, + networkRead, + networkWrite, + { + useSNI: !this.disableSNI, + expectPreData: this.pipelineTLS ? new Uint8Array([83]) : void 0 + // expect (and discard) an 'S' before the TLS response if pipelineTLS is set + } + ); + this.tlsRead = tlsRead; + this.tlsWrite = tlsWrite; + log("TLS connection established"); + this.tlsState = 2 /* Established */; + this.encrypted = true; + this.authorized = true; + this.emit("secureConnection", this); + this.tlsReadLoop(); + } + async tlsReadLoop() { + while (true) { + log("awaiting TLS data ..."); + const data = await this.tlsRead(); + if (data === void 0) { + log("no TLS data, breaking loop"); + break; + } else { + log("emitting decrypted TLS data:", data); + const buffer = Buffer2.from(data); + this.emit("data", buffer); + } + } + } + rawWrite(data) { + if (!this.coalesceWrites) { + this.ws.send(data); + return; + } + if (this.writeBuffer === void 0) { + this.writeBuffer = data; + setTimeout(() => { + this.ws.send(this.writeBuffer); + this.writeBuffer = void 0; + }, 0); + } else { + const newBuffer = new Uint8Array(this.writeBuffer.length + data.length); + newBuffer.set(this.writeBuffer); + newBuffer.set(data, this.writeBuffer.length); + this.writeBuffer = newBuffer; + } + } + write(data, encoding = "utf8", callback = (err) => { + }) { + if (data.length === 0) { + callback(); + return true; + } + if (typeof data === "string") + data = Buffer2.from(data, encoding); + if (this.tlsState === 0 /* None */) { + log("sending data direct:", data); + this.rawWrite(data); + callback(); + } else if (this.tlsState === 1 /* Handshake */) { + log("TLS handshake in progress, queueing data:", data); + this.once("secureConnection", () => { + this.write(data, encoding, callback); + }); + } else { + log("encrypting data:", data); + this.tlsWrite(data); + callback(); + } + return true; + } + end(data = Buffer2.alloc(0), encoding = "utf8", callback = () => { + }) { + log("ending socket"); + this.write(data, encoding, () => { + this.ws.close(); + callback(); + }); + return this; + } + destroy() { + this.destroyed = true; + return this.end(); + } + }; + } +}); + +// node_modules/pg-protocol/dist/messages.js +var require_messages = __commonJS({ + "node_modules/pg-protocol/dist/messages.js"(exports) { + "use strict"; + init_shims(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoticeMessage = exports.DataRowMessage = exports.CommandCompleteMessage = exports.ReadyForQueryMessage = exports.NotificationResponseMessage = exports.BackendKeyDataMessage = exports.AuthenticationMD5Password = exports.ParameterStatusMessage = exports.ParameterDescriptionMessage = exports.RowDescriptionMessage = exports.Field = exports.CopyResponse = exports.CopyDataMessage = exports.DatabaseError = exports.copyDone = exports.emptyQuery = exports.replicationStart = exports.portalSuspended = exports.noData = exports.closeComplete = exports.bindComplete = exports.parseComplete = void 0; + exports.parseComplete = { + name: "parseComplete", + length: 5 + }; + exports.bindComplete = { + name: "bindComplete", + length: 5 + }; + exports.closeComplete = { + name: "closeComplete", + length: 5 + }; + exports.noData = { + name: "noData", + length: 5 + }; + exports.portalSuspended = { + name: "portalSuspended", + length: 5 + }; + exports.replicationStart = { + name: "replicationStart", + length: 4 + }; + exports.emptyQuery = { + name: "emptyQuery", + length: 4 + }; + exports.copyDone = { + name: "copyDone", + length: 4 + }; + var DatabaseError2 = class extends Error { + static { + __name(this, "DatabaseError"); + } + constructor(message, length, name) { + super(message); + this.length = length; + this.name = name; + } + }; + exports.DatabaseError = DatabaseError2; + var CopyDataMessage = class { + static { + __name(this, "CopyDataMessage"); + } + constructor(length, chunk) { + this.length = length; + this.chunk = chunk; + this.name = "copyData"; + } + }; + exports.CopyDataMessage = CopyDataMessage; + var CopyResponse = class { + static { + __name(this, "CopyResponse"); + } + constructor(length, name, binary, columnCount) { + this.length = length; + this.name = name; + this.binary = binary; + this.columnTypes = new Array(columnCount); + } + }; + exports.CopyResponse = CopyResponse; + var Field = class { + static { + __name(this, "Field"); + } + constructor(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, format) { + this.name = name; + this.tableID = tableID; + this.columnID = columnID; + this.dataTypeID = dataTypeID; + this.dataTypeSize = dataTypeSize; + this.dataTypeModifier = dataTypeModifier; + this.format = format; + } + }; + exports.Field = Field; + var RowDescriptionMessage = class { + static { + __name(this, "RowDescriptionMessage"); + } + constructor(length, fieldCount) { + this.length = length; + this.fieldCount = fieldCount; + this.name = "rowDescription"; + this.fields = new Array(this.fieldCount); + } + }; + exports.RowDescriptionMessage = RowDescriptionMessage; + var ParameterDescriptionMessage = class { + static { + __name(this, "ParameterDescriptionMessage"); + } + constructor(length, parameterCount) { + this.length = length; + this.parameterCount = parameterCount; + this.name = "parameterDescription"; + this.dataTypeIDs = new Array(this.parameterCount); + } + }; + exports.ParameterDescriptionMessage = ParameterDescriptionMessage; + var ParameterStatusMessage = class { + static { + __name(this, "ParameterStatusMessage"); + } + constructor(length, parameterName, parameterValue) { + this.length = length; + this.parameterName = parameterName; + this.parameterValue = parameterValue; + this.name = "parameterStatus"; + } + }; + exports.ParameterStatusMessage = ParameterStatusMessage; + var AuthenticationMD5Password = class { + static { + __name(this, "AuthenticationMD5Password"); + } + constructor(length, salt) { + this.length = length; + this.salt = salt; + this.name = "authenticationMD5Password"; + } + }; + exports.AuthenticationMD5Password = AuthenticationMD5Password; + var BackendKeyDataMessage = class { + static { + __name(this, "BackendKeyDataMessage"); + } + constructor(length, processID, secretKey) { + this.length = length; + this.processID = processID; + this.secretKey = secretKey; + this.name = "backendKeyData"; + } + }; + exports.BackendKeyDataMessage = BackendKeyDataMessage; + var NotificationResponseMessage = class { + static { + __name(this, "NotificationResponseMessage"); + } + constructor(length, processId, channel, payload) { + this.length = length; + this.processId = processId; + this.channel = channel; + this.payload = payload; + this.name = "notification"; + } + }; + exports.NotificationResponseMessage = NotificationResponseMessage; + var ReadyForQueryMessage = class { + static { + __name(this, "ReadyForQueryMessage"); + } + constructor(length, status) { + this.length = length; + this.status = status; + this.name = "readyForQuery"; + } + }; + exports.ReadyForQueryMessage = ReadyForQueryMessage; + var CommandCompleteMessage = class { + static { + __name(this, "CommandCompleteMessage"); + } + constructor(length, text) { + this.length = length; + this.text = text; + this.name = "commandComplete"; + } + }; + exports.CommandCompleteMessage = CommandCompleteMessage; + var DataRowMessage = class { + static { + __name(this, "DataRowMessage"); + } + constructor(length, fields) { + this.length = length; + this.fields = fields; + this.name = "dataRow"; + this.fieldCount = fields.length; + } + }; + exports.DataRowMessage = DataRowMessage; + var NoticeMessage = class { + static { + __name(this, "NoticeMessage"); + } + constructor(length, message) { + this.length = length; + this.message = message; + this.name = "notice"; + } + }; + exports.NoticeMessage = NoticeMessage; + } +}); + +// node_modules/pg-protocol/dist/buffer-writer.js +var require_buffer_writer = __commonJS({ + "node_modules/pg-protocol/dist/buffer-writer.js"(exports) { + "use strict"; + init_shims(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Writer = void 0; + var Writer = class { + static { + __name(this, "Writer"); + } + constructor(size = 256) { + this.size = size; + this.offset = 5; + this.headerPosition = 0; + this.buffer = Buffer2.allocUnsafe(size); + } + ensure(size) { + var remaining = this.buffer.length - this.offset; + if (remaining < size) { + var oldBuffer = this.buffer; + var newSize = oldBuffer.length + (oldBuffer.length >> 1) + size; + this.buffer = Buffer2.allocUnsafe(newSize); + oldBuffer.copy(this.buffer); + } + } + addInt32(num) { + this.ensure(4); + this.buffer[this.offset++] = num >>> 24 & 255; + this.buffer[this.offset++] = num >>> 16 & 255; + this.buffer[this.offset++] = num >>> 8 & 255; + this.buffer[this.offset++] = num >>> 0 & 255; + return this; + } + addInt16(num) { + this.ensure(2); + this.buffer[this.offset++] = num >>> 8 & 255; + this.buffer[this.offset++] = num >>> 0 & 255; + return this; + } + addCString(string) { + if (!string) { + this.ensure(1); + } else { + var len = Buffer2.byteLength(string); + this.ensure(len + 1); + this.buffer.write(string, this.offset, "utf-8"); + this.offset += len; + } + this.buffer[this.offset++] = 0; + return this; + } + addString(string = "") { + var len = Buffer2.byteLength(string); + this.ensure(len); + this.buffer.write(string, this.offset); + this.offset += len; + return this; + } + add(otherBuffer) { + this.ensure(otherBuffer.length); + otherBuffer.copy(this.buffer, this.offset); + this.offset += otherBuffer.length; + return this; + } + join(code) { + if (code) { + this.buffer[this.headerPosition] = code; + const length = this.offset - (this.headerPosition + 1); + this.buffer.writeInt32BE(length, this.headerPosition + 1); + } + return this.buffer.slice(code ? 0 : 5, this.offset); + } + flush(code) { + var result = this.join(code); + this.offset = 5; + this.headerPosition = 0; + this.buffer = Buffer2.allocUnsafe(this.size); + return result; + } + }; + exports.Writer = Writer; + } +}); + +// node_modules/pg-protocol/dist/serializer.js +var require_serializer = __commonJS({ + "node_modules/pg-protocol/dist/serializer.js"(exports) { + "use strict"; + init_shims(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.serialize = void 0; + var buffer_writer_1 = require_buffer_writer(); + var writer = new buffer_writer_1.Writer(); + var startup = /* @__PURE__ */ __name((opts) => { + writer.addInt16(3).addInt16(0); + for (const key of Object.keys(opts)) { + writer.addCString(key).addCString(opts[key]); + } + writer.addCString("client_encoding").addCString("UTF8"); + var bodyBuffer = writer.addCString("").flush(); + var length = bodyBuffer.length + 4; + return new buffer_writer_1.Writer().addInt32(length).add(bodyBuffer).flush(); + }, "startup"); + var requestSsl = /* @__PURE__ */ __name(() => { + const response = Buffer2.allocUnsafe(8); + response.writeInt32BE(8, 0); + response.writeInt32BE(80877103, 4); + return response; + }, "requestSsl"); + var password = /* @__PURE__ */ __name((password2) => { + return writer.addCString(password2).flush( + 112 + /* code.startup */ + ); + }, "password"); + var sendSASLInitialResponseMessage = /* @__PURE__ */ __name(function(mechanism, initialResponse) { + writer.addCString(mechanism).addInt32(Buffer2.byteLength(initialResponse)).addString(initialResponse); + return writer.flush( + 112 + /* code.startup */ + ); + }, "sendSASLInitialResponseMessage"); + var sendSCRAMClientFinalMessage = /* @__PURE__ */ __name(function(additionalData) { + return writer.addString(additionalData).flush( + 112 + /* code.startup */ + ); + }, "sendSCRAMClientFinalMessage"); + var query = /* @__PURE__ */ __name((text) => { + return writer.addCString(text).flush( + 81 + /* code.query */ + ); + }, "query"); + var emptyArray = []; + var parse2 = /* @__PURE__ */ __name((query2) => { + const name = query2.name || ""; + if (name.length > 63) { + console.error("Warning! Postgres only supports 63 characters for query names."); + console.error("You supplied %s (%s)", name, name.length); + console.error("This can cause conflicts and silent errors executing queries"); + } + const types2 = query2.types || emptyArray; + var len = types2.length; + var buffer = writer.addCString(name).addCString(query2.text).addInt16(len); + for (var i = 0; i < len; i++) { + buffer.addInt32(types2[i]); + } + return writer.flush( + 80 + /* code.parse */ + ); + }, "parse"); + var paramWriter = new buffer_writer_1.Writer(); + var writeValues = /* @__PURE__ */ __name(function(values, valueMapper) { + for (let i = 0; i < values.length; i++) { + const mappedVal = valueMapper ? valueMapper(values[i], i) : values[i]; + if (mappedVal == null) { + writer.addInt16( + 0 + /* ParamType.STRING */ + ); + paramWriter.addInt32(-1); + } else if (mappedVal instanceof Buffer2) { + writer.addInt16( + 1 + /* ParamType.BINARY */ + ); + paramWriter.addInt32(mappedVal.length); + paramWriter.add(mappedVal); + } else { + writer.addInt16( + 0 + /* ParamType.STRING */ + ); + paramWriter.addInt32(Buffer2.byteLength(mappedVal)); + paramWriter.addString(mappedVal); + } + } + }, "writeValues"); + var bind = /* @__PURE__ */ __name((config = {}) => { + const portal = config.portal || ""; + const statement = config.statement || ""; + const binary = config.binary || false; + const values = config.values || emptyArray; + const len = values.length; + writer.addCString(portal).addCString(statement); + writer.addInt16(len); + writeValues(values, config.valueMapper); + writer.addInt16(len); + writer.add(paramWriter.flush()); + writer.addInt16( + binary ? 1 : 0 + /* ParamType.STRING */ + ); + return writer.flush( + 66 + /* code.bind */ + ); + }, "bind"); + var emptyExecute = Buffer2.from([69, 0, 0, 0, 9, 0, 0, 0, 0, 0]); + var execute = /* @__PURE__ */ __name((config) => { + if (!config || !config.portal && !config.rows) { + return emptyExecute; + } + const portal = config.portal || ""; + const rows = config.rows || 0; + const portalLength = Buffer2.byteLength(portal); + const len = 4 + portalLength + 1 + 4; + const buff = Buffer2.allocUnsafe(1 + len); + buff[0] = 69; + buff.writeInt32BE(len, 1); + buff.write(portal, 5, "utf-8"); + buff[portalLength + 5] = 0; + buff.writeUInt32BE(rows, buff.length - 4); + return buff; + }, "execute"); + var cancel = /* @__PURE__ */ __name((processID, secretKey) => { + const buffer = Buffer2.allocUnsafe(16); + buffer.writeInt32BE(16, 0); + buffer.writeInt16BE(1234, 4); + buffer.writeInt16BE(5678, 6); + buffer.writeInt32BE(processID, 8); + buffer.writeInt32BE(secretKey, 12); + return buffer; + }, "cancel"); + var cstringMessage = /* @__PURE__ */ __name((code, string) => { + const stringLen = Buffer2.byteLength(string); + const len = 4 + stringLen + 1; + const buffer = Buffer2.allocUnsafe(1 + len); + buffer[0] = code; + buffer.writeInt32BE(len, 1); + buffer.write(string, 5, "utf-8"); + buffer[len] = 0; + return buffer; + }, "cstringMessage"); + var emptyDescribePortal = writer.addCString("P").flush( + 68 + /* code.describe */ + ); + var emptyDescribeStatement = writer.addCString("S").flush( + 68 + /* code.describe */ + ); + var describe = /* @__PURE__ */ __name((msg) => { + return msg.name ? cstringMessage(68, `${msg.type}${msg.name || ""}`) : msg.type === "P" ? emptyDescribePortal : emptyDescribeStatement; + }, "describe"); + var close = /* @__PURE__ */ __name((msg) => { + const text = `${msg.type}${msg.name || ""}`; + return cstringMessage(67, text); + }, "close"); + var copyData = /* @__PURE__ */ __name((chunk) => { + return writer.add(chunk).flush( + 100 + /* code.copyFromChunk */ + ); + }, "copyData"); + var copyFail = /* @__PURE__ */ __name((message) => { + return cstringMessage(102, message); + }, "copyFail"); + var codeOnlyBuffer = /* @__PURE__ */ __name((code) => Buffer2.from([code, 0, 0, 0, 4]), "codeOnlyBuffer"); + var flushBuffer = codeOnlyBuffer( + 72 + /* code.flush */ + ); + var syncBuffer = codeOnlyBuffer( + 83 + /* code.sync */ + ); + var endBuffer = codeOnlyBuffer( + 88 + /* code.end */ + ); + var copyDoneBuffer = codeOnlyBuffer( + 99 + /* code.copyDone */ + ); + var serialize = { + startup, + password, + requestSsl, + sendSASLInitialResponseMessage, + sendSCRAMClientFinalMessage, + query, + parse: parse2, + bind, + execute, + describe, + close, + flush: /* @__PURE__ */ __name(() => flushBuffer, "flush"), + sync: /* @__PURE__ */ __name(() => syncBuffer, "sync"), + end: /* @__PURE__ */ __name(() => endBuffer, "end"), + copyData, + copyDone: /* @__PURE__ */ __name(() => copyDoneBuffer, "copyDone"), + copyFail, + cancel + }; + exports.serialize = serialize; + } +}); + +// node_modules/pg-protocol/dist/buffer-reader.js +var require_buffer_reader = __commonJS({ + "node_modules/pg-protocol/dist/buffer-reader.js"(exports) { + "use strict"; + init_shims(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BufferReader = void 0; + var emptyBuffer = Buffer2.allocUnsafe(0); + var BufferReader = class { + static { + __name(this, "BufferReader"); + } + constructor(offset = 0) { + this.offset = offset; + this.buffer = emptyBuffer; + this.encoding = "utf-8"; + } + setBuffer(offset, buffer) { + this.offset = offset; + this.buffer = buffer; + } + int16() { + const result = this.buffer.readInt16BE(this.offset); + this.offset += 2; + return result; + } + byte() { + const result = this.buffer[this.offset]; + this.offset++; + return result; + } + int32() { + const result = this.buffer.readInt32BE(this.offset); + this.offset += 4; + return result; + } + string(length) { + const result = this.buffer.toString(this.encoding, this.offset, this.offset + length); + this.offset += length; + return result; + } + cstring() { + const start = this.offset; + let end = start; + while (this.buffer[end++] !== 0) { + } + this.offset = end; + return this.buffer.toString(this.encoding, start, end - 1); + } + bytes(length) { + const result = this.buffer.slice(this.offset, this.offset + length); + this.offset += length; + return result; + } + }; + exports.BufferReader = BufferReader; + } +}); + +// node_modules/pg-protocol/dist/parser.js +var require_parser = __commonJS({ + "node_modules/pg-protocol/dist/parser.js"(exports) { + "use strict"; + init_shims(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Parser = void 0; + var messages_1 = require_messages(); + var buffer_reader_1 = require_buffer_reader(); + var CODE_LENGTH = 1; + var LEN_LENGTH = 4; + var HEADER_LENGTH = CODE_LENGTH + LEN_LENGTH; + var emptyBuffer = Buffer2.allocUnsafe(0); + var Parser = class { + static { + __name(this, "Parser"); + } + constructor(opts) { + this.buffer = emptyBuffer; + this.bufferLength = 0; + this.bufferOffset = 0; + this.reader = new buffer_reader_1.BufferReader(); + if ((opts === null || opts === void 0 ? void 0 : opts.mode) === "binary") { + throw new Error("Binary mode not supported yet"); + } + this.mode = (opts === null || opts === void 0 ? void 0 : opts.mode) || "text"; + } + parse(buffer, callback) { + this.mergeBuffer(buffer); + const bufferFullLength = this.bufferOffset + this.bufferLength; + let offset = this.bufferOffset; + while (offset + HEADER_LENGTH <= bufferFullLength) { + const code = this.buffer[offset]; + const length = this.buffer.readUInt32BE(offset + CODE_LENGTH); + const fullMessageLength = CODE_LENGTH + length; + if (fullMessageLength + offset <= bufferFullLength) { + const message = this.handlePacket(offset + HEADER_LENGTH, code, length, this.buffer); + callback(message); + offset += fullMessageLength; + } else { + break; + } + } + if (offset === bufferFullLength) { + this.buffer = emptyBuffer; + this.bufferLength = 0; + this.bufferOffset = 0; + } else { + this.bufferLength = bufferFullLength - offset; + this.bufferOffset = offset; + } + } + mergeBuffer(buffer) { + if (this.bufferLength > 0) { + const newLength = this.bufferLength + buffer.byteLength; + const newFullLength = newLength + this.bufferOffset; + if (newFullLength > this.buffer.byteLength) { + let newBuffer; + if (newLength <= this.buffer.byteLength && this.bufferOffset >= this.bufferLength) { + newBuffer = this.buffer; + } else { + let newBufferLength = this.buffer.byteLength * 2; + while (newLength >= newBufferLength) { + newBufferLength *= 2; + } + newBuffer = Buffer2.allocUnsafe(newBufferLength); + } + this.buffer.copy(newBuffer, 0, this.bufferOffset, this.bufferOffset + this.bufferLength); + this.buffer = newBuffer; + this.bufferOffset = 0; + } + buffer.copy(this.buffer, this.bufferOffset + this.bufferLength); + this.bufferLength = newLength; + } else { + this.buffer = buffer; + this.bufferOffset = 0; + this.bufferLength = buffer.byteLength; + } + } + handlePacket(offset, code, length, bytes) { + switch (code) { + case 50: + return messages_1.bindComplete; + case 49: + return messages_1.parseComplete; + case 51: + return messages_1.closeComplete; + case 110: + return messages_1.noData; + case 115: + return messages_1.portalSuspended; + case 99: + return messages_1.copyDone; + case 87: + return messages_1.replicationStart; + case 73: + return messages_1.emptyQuery; + case 68: + return this.parseDataRowMessage(offset, length, bytes); + case 67: + return this.parseCommandCompleteMessage(offset, length, bytes); + case 90: + return this.parseReadyForQueryMessage(offset, length, bytes); + case 65: + return this.parseNotificationMessage(offset, length, bytes); + case 82: + return this.parseAuthenticationResponse(offset, length, bytes); + case 83: + return this.parseParameterStatusMessage(offset, length, bytes); + case 75: + return this.parseBackendKeyData(offset, length, bytes); + case 69: + return this.parseErrorMessage(offset, length, bytes, "error"); + case 78: + return this.parseErrorMessage(offset, length, bytes, "notice"); + case 84: + return this.parseRowDescriptionMessage(offset, length, bytes); + case 116: + return this.parseParameterDescriptionMessage(offset, length, bytes); + case 71: + return this.parseCopyInMessage(offset, length, bytes); + case 72: + return this.parseCopyOutMessage(offset, length, bytes); + case 100: + return this.parseCopyData(offset, length, bytes); + default: + return new messages_1.DatabaseError("received invalid response: " + code.toString(16), length, "error"); + } + } + parseReadyForQueryMessage(offset, length, bytes) { + this.reader.setBuffer(offset, bytes); + const status = this.reader.string(1); + return new messages_1.ReadyForQueryMessage(length, status); + } + parseCommandCompleteMessage(offset, length, bytes) { + this.reader.setBuffer(offset, bytes); + const text = this.reader.cstring(); + return new messages_1.CommandCompleteMessage(length, text); + } + parseCopyData(offset, length, bytes) { + const chunk = bytes.slice(offset, offset + (length - 4)); + return new messages_1.CopyDataMessage(length, chunk); + } + parseCopyInMessage(offset, length, bytes) { + return this.parseCopyMessage(offset, length, bytes, "copyInResponse"); + } + parseCopyOutMessage(offset, length, bytes) { + return this.parseCopyMessage(offset, length, bytes, "copyOutResponse"); + } + parseCopyMessage(offset, length, bytes, messageName) { + this.reader.setBuffer(offset, bytes); + const isBinary = this.reader.byte() !== 0; + const columnCount = this.reader.int16(); + const message = new messages_1.CopyResponse(length, messageName, isBinary, columnCount); + for (let i = 0; i < columnCount; i++) { + message.columnTypes[i] = this.reader.int16(); + } + return message; + } + parseNotificationMessage(offset, length, bytes) { + this.reader.setBuffer(offset, bytes); + const processId = this.reader.int32(); + const channel = this.reader.cstring(); + const payload = this.reader.cstring(); + return new messages_1.NotificationResponseMessage(length, processId, channel, payload); + } + parseRowDescriptionMessage(offset, length, bytes) { + this.reader.setBuffer(offset, bytes); + const fieldCount = this.reader.int16(); + const message = new messages_1.RowDescriptionMessage(length, fieldCount); + for (let i = 0; i < fieldCount; i++) { + message.fields[i] = this.parseField(); + } + return message; + } + parseField() { + const name = this.reader.cstring(); + const tableID = this.reader.int32(); + const columnID = this.reader.int16(); + const dataTypeID = this.reader.int32(); + const dataTypeSize = this.reader.int16(); + const dataTypeModifier = this.reader.int32(); + const mode = this.reader.int16() === 0 ? "text" : "binary"; + return new messages_1.Field(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, mode); + } + parseParameterDescriptionMessage(offset, length, bytes) { + this.reader.setBuffer(offset, bytes); + const parameterCount = this.reader.int16(); + const message = new messages_1.ParameterDescriptionMessage(length, parameterCount); + for (let i = 0; i < parameterCount; i++) { + message.dataTypeIDs[i] = this.reader.int32(); + } + return message; + } + parseDataRowMessage(offset, length, bytes) { + this.reader.setBuffer(offset, bytes); + const fieldCount = this.reader.int16(); + const fields = new Array(fieldCount); + for (let i = 0; i < fieldCount; i++) { + const len = this.reader.int32(); + fields[i] = len === -1 ? null : this.reader.string(len); + } + return new messages_1.DataRowMessage(length, fields); + } + parseParameterStatusMessage(offset, length, bytes) { + this.reader.setBuffer(offset, bytes); + const name = this.reader.cstring(); + const value = this.reader.cstring(); + return new messages_1.ParameterStatusMessage(length, name, value); + } + parseBackendKeyData(offset, length, bytes) { + this.reader.setBuffer(offset, bytes); + const processID = this.reader.int32(); + const secretKey = this.reader.int32(); + return new messages_1.BackendKeyDataMessage(length, processID, secretKey); + } + parseAuthenticationResponse(offset, length, bytes) { + this.reader.setBuffer(offset, bytes); + const code = this.reader.int32(); + const message = { + name: "authenticationOk", + length + }; + switch (code) { + case 0: + break; + case 3: + if (message.length === 8) { + message.name = "authenticationCleartextPassword"; + } + break; + case 5: + if (message.length === 12) { + message.name = "authenticationMD5Password"; + const salt = this.reader.bytes(4); + return new messages_1.AuthenticationMD5Password(length, salt); + } + break; + case 10: + message.name = "authenticationSASL"; + message.mechanisms = []; + let mechanism; + do { + mechanism = this.reader.cstring(); + if (mechanism) { + message.mechanisms.push(mechanism); + } + } while (mechanism); + break; + case 11: + message.name = "authenticationSASLContinue"; + message.data = this.reader.string(length - 8); + break; + case 12: + message.name = "authenticationSASLFinal"; + message.data = this.reader.string(length - 8); + break; + default: + throw new Error("Unknown authenticationOk message type " + code); + } + return message; + } + parseErrorMessage(offset, length, bytes, name) { + this.reader.setBuffer(offset, bytes); + const fields = {}; + let fieldType = this.reader.string(1); + while (fieldType !== "\0") { + fields[fieldType] = this.reader.cstring(); + fieldType = this.reader.string(1); + } + const messageValue = fields.M; + const message = name === "notice" ? new messages_1.NoticeMessage(length, messageValue) : new messages_1.DatabaseError(messageValue, length, name); + message.severity = fields.S; + message.code = fields.C; + message.detail = fields.D; + message.hint = fields.H; + message.position = fields.P; + message.internalPosition = fields.p; + message.internalQuery = fields.q; + message.where = fields.W; + message.schema = fields.s; + message.table = fields.t; + message.column = fields.c; + message.dataType = fields.d; + message.constraint = fields.n; + message.file = fields.F; + message.line = fields.L; + message.routine = fields.R; + return message; + } + }; + exports.Parser = Parser; + } +}); + +// node_modules/pg-protocol/dist/index.js +var require_dist = __commonJS({ + "node_modules/pg-protocol/dist/index.js"(exports) { + "use strict"; + init_shims(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DatabaseError = exports.serialize = exports.parse = void 0; + var messages_1 = require_messages(); + Object.defineProperty(exports, "DatabaseError", { enumerable: true, get: /* @__PURE__ */ __name(function() { + return messages_1.DatabaseError; + }, "get") }); + var serializer_1 = require_serializer(); + Object.defineProperty(exports, "serialize", { enumerable: true, get: /* @__PURE__ */ __name(function() { + return serializer_1.serialize; + }, "get") }); + var parser_1 = require_parser(); + function parse2(stream, callback) { + const parser = new parser_1.Parser(); + stream.on("data", (buffer) => parser.parse(buffer, callback)); + return new Promise((resolve) => stream.on("end", () => resolve())); + } + __name(parse2, "parse"); + exports.parse = parse2; + } +}); + +// shims/tls/index.ts +var tls_exports = {}; +__export(tls_exports, { + connect: () => connect +}); +function connect({ + socket, + servername +}) { + socket.startTls(servername); + return socket; +} +var init_tls = __esm({ + "shims/tls/index.ts"() { + "use strict"; + init_shims(); + __name(connect, "connect"); + } +}); + +// node_modules/pg/lib/connection.js +var require_connection = __commonJS({ + "node_modules/pg/lib/connection.js"(exports, module) { + "use strict"; + init_shims(); + var net = (init_net(), __toCommonJS(net_exports)); + var EventEmitter2 = require_events().EventEmitter; + var { parse: parse2, serialize } = require_dist(); + var flushBuffer = serialize.flush(); + var syncBuffer = serialize.sync(); + var endBuffer = serialize.end(); + var Connection3 = class extends EventEmitter2 { + static { + __name(this, "Connection"); + } + constructor(config) { + super(); + config = config || {}; + this.stream = config.stream || new net.Socket(); + this._keepAlive = config.keepAlive; + this._keepAliveInitialDelayMillis = config.keepAliveInitialDelayMillis; + this.lastBuffer = false; + this.parsedStatements = {}; + this.ssl = config.ssl || false; + this._ending = false; + this._emitMessage = false; + var self = this; + this.on("newListener", function(eventName) { + if (eventName === "message") { + self._emitMessage = true; + } + }); + } + connect(port, host) { + var self = this; + this._connecting = true; + this.stream.setNoDelay(true); + this.stream.connect(port, host); + this.stream.once("connect", function() { + if (self._keepAlive) { + self.stream.setKeepAlive(true, self._keepAliveInitialDelayMillis); + } + self.emit("connect"); + }); + const reportStreamError = /* @__PURE__ */ __name(function(error) { + if (self._ending && (error.code === "ECONNRESET" || error.code === "EPIPE")) { + return; + } + self.emit("error", error); + }, "reportStreamError"); + this.stream.on("error", reportStreamError); + this.stream.on("close", function() { + self.emit("end"); + }); + if (!this.ssl) { + return this.attachListeners(this.stream); + } + this.stream.once("data", function(buffer) { + var responseCode = buffer.toString("utf8"); + switch (responseCode) { + case "S": + break; + case "N": + self.stream.end(); + return self.emit("error", new Error("The server does not support SSL connections")); + default: + self.stream.end(); + return self.emit("error", new Error("There was an error establishing an SSL connection")); + } + var tls = (init_tls(), __toCommonJS(tls_exports)); + const options = { + socket: self.stream + }; + if (self.ssl !== true) { + Object.assign(options, self.ssl); + if ("key" in self.ssl) { + options.key = self.ssl.key; + } + } + if (net.isIP(host) === 0) { + options.servername = host; + } + try { + self.stream = tls.connect(options); + } catch (err) { + return self.emit("error", err); + } + self.attachListeners(self.stream); + self.stream.on("error", reportStreamError); + self.emit("sslconnect"); + }); + } + attachListeners(stream) { + stream.on("end", () => { + this.emit("end"); + }); + parse2(stream, (msg) => { + var eventName = msg.name === "error" ? "errorMessage" : msg.name; + if (this._emitMessage) { + this.emit("message", msg); + } + this.emit(eventName, msg); + }); + } + requestSsl() { + this.stream.write(serialize.requestSsl()); + } + startup(config) { + this.stream.write(serialize.startup(config)); + } + cancel(processID, secretKey) { + this._send(serialize.cancel(processID, secretKey)); + } + password(password) { + this._send(serialize.password(password)); + } + sendSASLInitialResponseMessage(mechanism, initialResponse) { + this._send(serialize.sendSASLInitialResponseMessage(mechanism, initialResponse)); + } + sendSCRAMClientFinalMessage(additionalData) { + this._send(serialize.sendSCRAMClientFinalMessage(additionalData)); + } + _send(buffer) { + if (!this.stream.writable) { + return false; + } + return this.stream.write(buffer); + } + query(text) { + this._send(serialize.query(text)); + } + // send parse message + parse(query) { + this._send(serialize.parse(query)); + } + // send bind message + bind(config) { + this._send(serialize.bind(config)); + } + // send execute message + execute(config) { + this._send(serialize.execute(config)); + } + flush() { + if (this.stream.writable) { + this.stream.write(flushBuffer); + } + } + sync() { + this._ending = true; + this._send(flushBuffer); + this._send(syncBuffer); + } + ref() { + this.stream.ref(); + } + unref() { + this.stream.unref(); + } + end() { + this._ending = true; + if (!this._connecting || !this.stream.writable) { + this.stream.end(); + return; + } + return this.stream.write(endBuffer, () => { + this.stream.end(); + }); + } + close(msg) { + this._send(serialize.close(msg)); + } + describe(msg) { + this._send(serialize.describe(msg)); + } + sendCopyFromChunk(chunk) { + this._send(serialize.copyData(chunk)); + } + endCopyFrom() { + this._send(serialize.copyDone()); + } + sendCopyFail(msg) { + this._send(serialize.copyFail(msg)); + } + }; + module.exports = Connection3; + } +}); + +// node_modules/pg/lib/client.js +var require_client = __commonJS({ + "node_modules/pg/lib/client.js"(exports, module) { + "use strict"; + init_shims(); + var EventEmitter2 = require_events().EventEmitter; + var util = (init_util(), __toCommonJS(util_exports)); + var utils = require_utils(); + var sasl = require_sasl(); + var pgPass = require_lib(); + var TypeOverrides2 = require_type_overrides(); + var ConnectionParameters2 = require_connection_parameters(); + var Query2 = require_query(); + var defaults2 = require_defaults(); + var Connection3 = require_connection(); + var Client3 = class extends EventEmitter2 { + static { + __name(this, "Client"); + } + constructor(config) { + super(); + this.connectionParameters = new ConnectionParameters2(config); + this.user = this.connectionParameters.user; + this.database = this.connectionParameters.database; + this.port = this.connectionParameters.port; + this.host = this.connectionParameters.host; + Object.defineProperty(this, "password", { + configurable: true, + enumerable: false, + writable: true, + value: this.connectionParameters.password + }); + this.replication = this.connectionParameters.replication; + var c = config || {}; + this._Promise = c.Promise || global.Promise; + this._types = new TypeOverrides2(c.types); + this._ending = false; + this._connecting = false; + this._connected = false; + this._connectionError = false; + this._queryable = true; + this.connection = c.connection || new Connection3({ + stream: c.stream, + ssl: this.connectionParameters.ssl, + keepAlive: c.keepAlive || false, + keepAliveInitialDelayMillis: c.keepAliveInitialDelayMillis || 0, + encoding: this.connectionParameters.client_encoding || "utf8" + }); + this.queryQueue = []; + this.binary = c.binary || defaults2.binary; + this.processID = null; + this.secretKey = null; + this.ssl = this.connectionParameters.ssl || false; + if (this.ssl && this.ssl.key) { + Object.defineProperty(this.ssl, "key", { + enumerable: false + }); + } + this._connectionTimeoutMillis = c.connectionTimeoutMillis || 0; + } + _errorAllQueries(err) { + const enqueueError = /* @__PURE__ */ __name((query) => { + process.nextTick(() => { + query.handleError(err, this.connection); + }); + }, "enqueueError"); + if (this.activeQuery) { + enqueueError(this.activeQuery); + this.activeQuery = null; + } + this.queryQueue.forEach(enqueueError); + this.queryQueue.length = 0; + } + _connect(callback) { + var self = this; + var con = this.connection; + this._connectionCallback = callback; + if (this._connecting || this._connected) { + const err = new Error("Client has already been connected. You cannot reuse a client."); + process.nextTick(() => { + callback(err); + }); + return; + } + this._connecting = true; + this.connectionTimeoutHandle; + if (this._connectionTimeoutMillis > 0) { + this.connectionTimeoutHandle = setTimeout(() => { + con._ending = true; + con.stream.destroy(new Error("timeout expired")); + }, this._connectionTimeoutMillis); + } + if (this.host && this.host.indexOf("/") === 0) { + con.connect(this.host + "/.s.PGSQL." + this.port); + } else { + con.connect(this.port, this.host); + } + con.on("connect", function() { + if (self.ssl) { + con.requestSsl(); + } else { + con.startup(self.getStartupConf()); + } + }); + con.on("sslconnect", function() { + con.startup(self.getStartupConf()); + }); + this._attachListeners(con); + con.once("end", () => { + const error = this._ending ? new Error("Connection terminated") : new Error("Connection terminated unexpectedly"); + clearTimeout(this.connectionTimeoutHandle); + this._errorAllQueries(error); + if (!this._ending) { + if (this._connecting && !this._connectionError) { + if (this._connectionCallback) { + this._connectionCallback(error); + } else { + this._handleErrorEvent(error); + } + } else if (!this._connectionError) { + this._handleErrorEvent(error); + } + } + process.nextTick(() => { + this.emit("end"); + }); + }); + } + connect(callback) { + if (callback) { + this._connect(callback); + return; + } + return new this._Promise((resolve, reject) => { + this._connect((error) => { + if (error) { + reject(error); + } else { + resolve(); + } + }); + }); + } + _attachListeners(con) { + con.on("authenticationCleartextPassword", this._handleAuthCleartextPassword.bind(this)); + con.on("authenticationMD5Password", this._handleAuthMD5Password.bind(this)); + con.on("authenticationSASL", this._handleAuthSASL.bind(this)); + con.on("authenticationSASLContinue", this._handleAuthSASLContinue.bind(this)); + con.on("authenticationSASLFinal", this._handleAuthSASLFinal.bind(this)); + con.on("backendKeyData", this._handleBackendKeyData.bind(this)); + con.on("error", this._handleErrorEvent.bind(this)); + con.on("errorMessage", this._handleErrorMessage.bind(this)); + con.on("readyForQuery", this._handleReadyForQuery.bind(this)); + con.on("notice", this._handleNotice.bind(this)); + con.on("rowDescription", this._handleRowDescription.bind(this)); + con.on("dataRow", this._handleDataRow.bind(this)); + con.on("portalSuspended", this._handlePortalSuspended.bind(this)); + con.on("emptyQuery", this._handleEmptyQuery.bind(this)); + con.on("commandComplete", this._handleCommandComplete.bind(this)); + con.on("parseComplete", this._handleParseComplete.bind(this)); + con.on("copyInResponse", this._handleCopyInResponse.bind(this)); + con.on("copyData", this._handleCopyData.bind(this)); + con.on("notification", this._handleNotification.bind(this)); + } + // TODO(bmc): deprecate pgpass "built in" integration since this.password can be a function + // it can be supplied by the user if required - this is a breaking change! + _checkPgPass(cb) { + const con = this.connection; + if (typeof this.password === "function") { + this._Promise.resolve().then(() => this.password()).then((pass) => { + if (pass !== void 0) { + if (typeof pass !== "string") { + con.emit("error", new TypeError("Password must be a string")); + return; + } + this.connectionParameters.password = this.password = pass; + } else { + this.connectionParameters.password = this.password = null; + } + cb(); + }).catch((err) => { + con.emit("error", err); + }); + } else if (this.password !== null) { + cb(); + } else { + pgPass(this.connectionParameters, (pass) => { + if (void 0 !== pass) { + this.connectionParameters.password = this.password = pass; + } + cb(); + }); + } + } + _handleAuthCleartextPassword(msg) { + this._checkPgPass(() => { + this.connection.password(this.password); + }); + } + _handleAuthMD5Password(msg) { + this._checkPgPass(() => { + const hashedPassword = utils.postgresMd5PasswordHash(this.user, this.password, msg.salt); + this.connection.password(hashedPassword); + }); + } + _handleAuthSASL(msg) { + this._checkPgPass(() => { + this.saslSession = sasl.startSession(msg.mechanisms); + this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism, this.saslSession.response); + }); + } + _handleAuthSASLContinue(msg) { + sasl.continueSession(this.saslSession, this.password, msg.data); + this.connection.sendSCRAMClientFinalMessage(this.saslSession.response); + } + _handleAuthSASLFinal(msg) { + sasl.finalizeSession(this.saslSession, msg.data); + this.saslSession = null; + } + _handleBackendKeyData(msg) { + this.processID = msg.processID; + this.secretKey = msg.secretKey; + } + _handleReadyForQuery(msg) { + if (this._connecting) { + this._connecting = false; + this._connected = true; + clearTimeout(this.connectionTimeoutHandle); + if (this._connectionCallback) { + this._connectionCallback(null, this); + this._connectionCallback = null; + } + this.emit("connect"); + } + const { activeQuery } = this; + this.activeQuery = null; + this.readyForQuery = true; + if (activeQuery) { + activeQuery.handleReadyForQuery(this.connection); + } + this._pulseQueryQueue(); + } + // if we receieve an error event or error message + // during the connection process we handle it here + _handleErrorWhileConnecting(err) { + if (this._connectionError) { + return; + } + this._connectionError = true; + clearTimeout(this.connectionTimeoutHandle); + if (this._connectionCallback) { + return this._connectionCallback(err); + } + this.emit("error", err); + } + // if we're connected and we receive an error event from the connection + // this means the socket is dead - do a hard abort of all queries and emit + // the socket error on the client as well + _handleErrorEvent(err) { + if (this._connecting) { + return this._handleErrorWhileConnecting(err); + } + this._queryable = false; + this._errorAllQueries(err); + this.emit("error", err); + } + // handle error messages from the postgres backend + _handleErrorMessage(msg) { + if (this._connecting) { + return this._handleErrorWhileConnecting(msg); + } + const activeQuery = this.activeQuery; + if (!activeQuery) { + this._handleErrorEvent(msg); + return; + } + this.activeQuery = null; + activeQuery.handleError(msg, this.connection); + } + _handleRowDescription(msg) { + this.activeQuery.handleRowDescription(msg); + } + _handleDataRow(msg) { + this.activeQuery.handleDataRow(msg); + } + _handlePortalSuspended(msg) { + this.activeQuery.handlePortalSuspended(this.connection); + } + _handleEmptyQuery(msg) { + this.activeQuery.handleEmptyQuery(this.connection); + } + _handleCommandComplete(msg) { + this.activeQuery.handleCommandComplete(msg, this.connection); + } + _handleParseComplete(msg) { + if (this.activeQuery.name) { + this.connection.parsedStatements[this.activeQuery.name] = this.activeQuery.text; + } + } + _handleCopyInResponse(msg) { + this.activeQuery.handleCopyInResponse(this.connection); + } + _handleCopyData(msg) { + this.activeQuery.handleCopyData(msg, this.connection); + } + _handleNotification(msg) { + this.emit("notification", msg); + } + _handleNotice(msg) { + this.emit("notice", msg); + } + getStartupConf() { + var params = this.connectionParameters; + var data = { + user: params.user, + database: params.database + }; + var appName = params.application_name || params.fallback_application_name; + if (appName) { + data.application_name = appName; + } + if (params.replication) { + data.replication = "" + params.replication; + } + if (params.statement_timeout) { + data.statement_timeout = String(parseInt(params.statement_timeout, 10)); + } + if (params.lock_timeout) { + data.lock_timeout = String(parseInt(params.lock_timeout, 10)); + } + if (params.idle_in_transaction_session_timeout) { + data.idle_in_transaction_session_timeout = String(parseInt(params.idle_in_transaction_session_timeout, 10)); + } + if (params.options) { + data.options = params.options; + } + return data; + } + cancel(client, query) { + if (client.activeQuery === query) { + var con = this.connection; + if (this.host && this.host.indexOf("/") === 0) { + con.connect(this.host + "/.s.PGSQL." + this.port); + } else { + con.connect(this.port, this.host); + } + con.on("connect", function() { + con.cancel(client.processID, client.secretKey); + }); + } else if (client.queryQueue.indexOf(query) !== -1) { + client.queryQueue.splice(client.queryQueue.indexOf(query), 1); + } + } + setTypeParser(oid, format, parseFn) { + return this._types.setTypeParser(oid, format, parseFn); + } + getTypeParser(oid, format) { + return this._types.getTypeParser(oid, format); + } + // Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c + escapeIdentifier(str) { + return '"' + str.replace(/"/g, '""') + '"'; + } + // Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c + escapeLiteral(str) { + var hasBackslash = false; + var escaped = "'"; + for (var i = 0; i < str.length; i++) { + var c = str[i]; + if (c === "'") { + escaped += c + c; + } else if (c === "\\") { + escaped += c + c; + hasBackslash = true; + } else { + escaped += c; + } + } + escaped += "'"; + if (hasBackslash === true) { + escaped = " E" + escaped; + } + return escaped; + } + _pulseQueryQueue() { + if (this.readyForQuery === true) { + this.activeQuery = this.queryQueue.shift(); + if (this.activeQuery) { + this.readyForQuery = false; + this.hasExecuted = true; + const queryError = this.activeQuery.submit(this.connection); + if (queryError) { + process.nextTick(() => { + this.activeQuery.handleError(queryError, this.connection); + this.readyForQuery = true; + this._pulseQueryQueue(); + }); + } + } else if (this.hasExecuted) { + this.activeQuery = null; + this.emit("drain"); + } + } + } + query(config, values, callback) { + var query; + var result; + var readTimeout; + var readTimeoutTimer; + var queryCallback; + if (config === null || config === void 0) { + throw new TypeError("Client was passed a null or undefined query"); + } else if (typeof config.submit === "function") { + readTimeout = config.query_timeout || this.connectionParameters.query_timeout; + result = query = config; + if (typeof values === "function") { + query.callback = query.callback || values; + } + } else { + readTimeout = this.connectionParameters.query_timeout; + query = new Query2(config, values, callback); + if (!query.callback) { + result = new this._Promise((resolve, reject) => { + query.callback = (err, res) => err ? reject(err) : resolve(res); + }); + } + } + if (readTimeout) { + queryCallback = query.callback; + readTimeoutTimer = setTimeout(() => { + var error = new Error("Query read timeout"); + process.nextTick(() => { + query.handleError(error, this.connection); + }); + queryCallback(error); + query.callback = () => { + }; + var index = this.queryQueue.indexOf(query); + if (index > -1) { + this.queryQueue.splice(index, 1); + } + this._pulseQueryQueue(); + }, readTimeout); + query.callback = (err, res) => { + clearTimeout(readTimeoutTimer); + queryCallback(err, res); + }; + } + if (this.binary && !query.binary) { + query.binary = true; + } + if (query._result && !query._result._types) { + query._result._types = this._types; + } + if (!this._queryable) { + process.nextTick(() => { + query.handleError(new Error("Client has encountered a connection error and is not queryable"), this.connection); + }); + return result; + } + if (this._ending) { + process.nextTick(() => { + query.handleError(new Error("Client was closed and is not queryable"), this.connection); + }); + return result; + } + this.queryQueue.push(query); + this._pulseQueryQueue(); + return result; + } + ref() { + this.connection.ref(); + } + unref() { + this.connection.unref(); + } + end(cb) { + this._ending = true; + if (!this.connection._connecting) { + if (cb) { + cb(); + } else { + return this._Promise.resolve(); + } + } + if (this.activeQuery || !this._queryable) { + this.connection.stream.destroy(); + } else { + this.connection.end(); + } + if (cb) { + this.connection.once("end", cb); + } else { + return new this._Promise((resolve) => { + this.connection.once("end", resolve); + }); + } + } + }; + Client3.Query = Query2; + module.exports = Client3; + } +}); + +// node_modules/pg-pool/index.js +var require_pg_pool = __commonJS({ + "node_modules/pg-pool/index.js"(exports, module) { + "use strict"; + init_shims(); + var EventEmitter2 = require_events().EventEmitter; + var NOOP = /* @__PURE__ */ __name(function() { + }, "NOOP"); + var removeWhere = /* @__PURE__ */ __name((list, predicate) => { + const i = list.findIndex(predicate); + return i === -1 ? void 0 : list.splice(i, 1)[0]; + }, "removeWhere"); + var IdleItem = class { + static { + __name(this, "IdleItem"); + } + constructor(client, idleListener, timeoutId) { + this.client = client; + this.idleListener = idleListener; + this.timeoutId = timeoutId; + } + }; + var PendingItem = class { + static { + __name(this, "PendingItem"); + } + constructor(callback) { + this.callback = callback; + } + }; + function throwOnDoubleRelease() { + throw new Error("Release called on client which has already been released to the pool."); + } + __name(throwOnDoubleRelease, "throwOnDoubleRelease"); + function promisify2(Promise2, callback) { + if (callback) { + return { callback, result: void 0 }; + } + let rej; + let res; + const cb = /* @__PURE__ */ __name(function(err, client) { + err ? rej(err) : res(client); + }, "cb"); + const result = new Promise2(function(resolve, reject) { + res = resolve; + rej = reject; + }).catch((err) => { + Error.captureStackTrace(err); + throw err; + }); + return { callback: cb, result }; + } + __name(promisify2, "promisify"); + function makeIdleListener(pool, client) { + return /* @__PURE__ */ __name(function idleListener(err) { + err.client = client; + client.removeListener("error", idleListener); + client.on("error", () => { + pool.log("additional client error after disconnection due to error", err); + }); + pool._remove(client); + pool.emit("error", err, client); + }, "idleListener"); + } + __name(makeIdleListener, "makeIdleListener"); + var Pool2 = class extends EventEmitter2 { + static { + __name(this, "Pool"); + } + constructor(options, Client3) { + super(); + this.options = Object.assign({}, options); + if (options != null && "password" in options) { + Object.defineProperty(this.options, "password", { + configurable: true, + enumerable: false, + writable: true, + value: options.password + }); + } + if (options != null && options.ssl && options.ssl.key) { + Object.defineProperty(this.options.ssl, "key", { + enumerable: false + }); + } + this.options.max = this.options.max || this.options.poolSize || 10; + this.options.maxUses = this.options.maxUses || Infinity; + this.options.allowExitOnIdle = this.options.allowExitOnIdle || false; + this.options.maxLifetimeSeconds = this.options.maxLifetimeSeconds || 0; + this.log = this.options.log || function() { + }; + this.Client = this.options.Client || Client3 || require_lib2().Client; + this.Promise = this.options.Promise || global.Promise; + if (typeof this.options.idleTimeoutMillis === "undefined") { + this.options.idleTimeoutMillis = 1e4; + } + this._clients = []; + this._idle = []; + this._expired = /* @__PURE__ */ new WeakSet(); + this._pendingQueue = []; + this._endCallback = void 0; + this.ending = false; + this.ended = false; + } + _isFull() { + return this._clients.length >= this.options.max; + } + _pulseQueue() { + this.log("pulse queue"); + if (this.ended) { + this.log("pulse queue ended"); + return; + } + if (this.ending) { + this.log("pulse queue on ending"); + if (this._idle.length) { + this._idle.slice().map((item) => { + this._remove(item.client); + }); + } + if (!this._clients.length) { + this.ended = true; + this._endCallback(); + } + return; + } + if (!this._pendingQueue.length) { + this.log("no queued requests"); + return; + } + if (!this._idle.length && this._isFull()) { + return; + } + const pendingItem = this._pendingQueue.shift(); + if (this._idle.length) { + const idleItem = this._idle.pop(); + clearTimeout(idleItem.timeoutId); + const client = idleItem.client; + client.ref && client.ref(); + const idleListener = idleItem.idleListener; + return this._acquireClient(client, pendingItem, idleListener, false); + } + if (!this._isFull()) { + return this.newClient(pendingItem); + } + throw new Error("unexpected condition"); + } + _remove(client) { + const removed = removeWhere(this._idle, (item) => item.client === client); + if (removed !== void 0) { + clearTimeout(removed.timeoutId); + } + this._clients = this._clients.filter((c) => c !== client); + client.end(); + this.emit("remove", client); + } + connect(cb) { + if (this.ending) { + const err = new Error("Cannot use a pool after calling end on the pool"); + return cb ? cb(err) : this.Promise.reject(err); + } + const response = promisify2(this.Promise, cb); + const result = response.result; + if (this._isFull() || this._idle.length) { + if (this._idle.length) { + process.nextTick(() => this._pulseQueue()); + } + if (!this.options.connectionTimeoutMillis) { + this._pendingQueue.push(new PendingItem(response.callback)); + return result; + } + const queueCallback = /* @__PURE__ */ __name((err, res, done) => { + clearTimeout(tid); + response.callback(err, res, done); + }, "queueCallback"); + const pendingItem = new PendingItem(queueCallback); + const tid = setTimeout(() => { + removeWhere(this._pendingQueue, (i) => i.callback === queueCallback); + pendingItem.timedOut = true; + response.callback(new Error("timeout exceeded when trying to connect")); + }, this.options.connectionTimeoutMillis); + this._pendingQueue.push(pendingItem); + return result; + } + this.newClient(new PendingItem(response.callback)); + return result; + } + newClient(pendingItem) { + const client = new this.Client(this.options); + this._clients.push(client); + const idleListener = makeIdleListener(this, client); + this.log("checking client timeout"); + let tid; + let timeoutHit = false; + if (this.options.connectionTimeoutMillis) { + tid = setTimeout(() => { + this.log("ending client due to timeout"); + timeoutHit = true; + client.connection ? client.connection.stream.destroy() : client.end(); + }, this.options.connectionTimeoutMillis); + } + this.log("connecting new client"); + client.connect((err) => { + if (tid) { + clearTimeout(tid); + } + client.on("error", idleListener); + if (err) { + this.log("client failed to connect", err); + this._clients = this._clients.filter((c) => c !== client); + if (timeoutHit) { + err.message = "Connection terminated due to connection timeout"; + } + this._pulseQueue(); + if (!pendingItem.timedOut) { + pendingItem.callback(err, void 0, NOOP); + } + } else { + this.log("new client connected"); + if (this.options.maxLifetimeSeconds !== 0) { + const maxLifetimeTimeout = setTimeout(() => { + this.log("ending client due to expired lifetime"); + this._expired.add(client); + const idleIndex = this._idle.findIndex((idleItem) => idleItem.client === client); + if (idleIndex !== -1) { + this._acquireClient( + client, + new PendingItem((err2, client2, clientRelease) => clientRelease()), + idleListener, + false + ); + } + }, this.options.maxLifetimeSeconds * 1e3); + maxLifetimeTimeout.unref(); + client.once("end", () => clearTimeout(maxLifetimeTimeout)); + } + return this._acquireClient(client, pendingItem, idleListener, true); + } + }); + } + // acquire a client for a pending work item + _acquireClient(client, pendingItem, idleListener, isNew) { + if (isNew) { + this.emit("connect", client); + } + this.emit("acquire", client); + client.release = this._releaseOnce(client, idleListener); + client.removeListener("error", idleListener); + if (!pendingItem.timedOut) { + if (isNew && this.options.verify) { + this.options.verify(client, (err) => { + if (err) { + client.release(err); + return pendingItem.callback(err, void 0, NOOP); + } + pendingItem.callback(void 0, client, client.release); + }); + } else { + pendingItem.callback(void 0, client, client.release); + } + } else { + if (isNew && this.options.verify) { + this.options.verify(client, client.release); + } else { + client.release(); + } + } + } + // returns a function that wraps _release and throws if called more than once + _releaseOnce(client, idleListener) { + let released = false; + return (err) => { + if (released) { + throwOnDoubleRelease(); + } + released = true; + this._release(client, idleListener, err); + }; + } + // release a client back to the poll, include an error + // to remove it from the pool + _release(client, idleListener, err) { + client.on("error", idleListener); + client._poolUseCount = (client._poolUseCount || 0) + 1; + this.emit("release", err, client); + if (err || this.ending || !client._queryable || client._ending || client._poolUseCount >= this.options.maxUses) { + if (client._poolUseCount >= this.options.maxUses) { + this.log("remove expended client"); + } + this._remove(client); + this._pulseQueue(); + return; + } + const isExpired = this._expired.has(client); + if (isExpired) { + this.log("remove expired client"); + this._expired.delete(client); + this._remove(client); + this._pulseQueue(); + return; + } + let tid; + if (this.options.idleTimeoutMillis) { + tid = setTimeout(() => { + this.log("remove idle client"); + this._remove(client); + }, this.options.idleTimeoutMillis); + if (this.options.allowExitOnIdle) { + tid.unref(); + } + } + if (this.options.allowExitOnIdle) { + client.unref(); + } + this._idle.push(new IdleItem(client, idleListener, tid)); + this._pulseQueue(); + } + query(text, values, cb) { + if (typeof text === "function") { + const response2 = promisify2(this.Promise, text); + setImmediate(function() { + return response2.callback(new Error("Passing a function as the first parameter to pool.query is not supported")); + }); + return response2.result; + } + if (typeof values === "function") { + cb = values; + values = void 0; + } + const response = promisify2(this.Promise, cb); + cb = response.callback; + this.connect((err, client) => { + if (err) { + return cb(err); + } + let clientReleased = false; + const onError = /* @__PURE__ */ __name((err2) => { + if (clientReleased) { + return; + } + clientReleased = true; + client.release(err2); + cb(err2); + }, "onError"); + client.once("error", onError); + this.log("dispatching query"); + try { + client.query(text, values, (err2, res) => { + this.log("query dispatched"); + client.removeListener("error", onError); + if (clientReleased) { + return; + } + clientReleased = true; + client.release(err2); + if (err2) { + return cb(err2); + } + return cb(void 0, res); + }); + } catch (err2) { + client.release(err2); + return cb(err2); + } + }); + return response.result; + } + end(cb) { + this.log("ending"); + if (this.ending) { + const err = new Error("Called end on pool more than once"); + return cb ? cb(err) : this.Promise.reject(err); + } + this.ending = true; + const promised = promisify2(this.Promise, cb); + this._endCallback = promised.callback; + this._pulseQueue(); + return promised.result; + } + get waitingCount() { + return this._pendingQueue.length; + } + get idleCount() { + return this._idle.length; + } + get expiredCount() { + return this._clients.reduce((acc, client) => acc + (this._expired.has(client) ? 1 : 0), 0); + } + get totalCount() { + return this._clients.length; + } + }; + module.exports = Pool2; + } +}); + +// shims/pg-native/index.js +var pg_native_exports = {}; +__export(pg_native_exports, { + default: () => pg_native_default +}); +var pg_native_default; +var init_pg_native = __esm({ + "shims/pg-native/index.js"() { + "use strict"; + init_shims(); + pg_native_default = {}; + } +}); + +// node_modules/pg/package.json +var require_package = __commonJS({ + "node_modules/pg/package.json"(exports, module) { + module.exports = { + name: "pg", + version: "8.8.0", + description: "PostgreSQL client - pure javascript & libpq with the same API", + keywords: [ + "database", + "libpq", + "pg", + "postgre", + "postgres", + "postgresql", + "rdbms" + ], + homepage: "https://github.com/brianc/node-postgres", + repository: { + type: "git", + url: "git://github.com/brianc/node-postgres.git", + directory: "packages/pg" + }, + author: "Brian Carlson ", + main: "./lib", + dependencies: { + "buffer-writer": "2.0.0", + "packet-reader": "1.0.0", + "pg-connection-string": "^2.5.0", + "pg-pool": "^3.5.2", + "pg-protocol": "^1.5.0", + "pg-types": "^2.1.0", + pgpass: "1.x" + }, + devDependencies: { + async: "2.6.4", + bluebird: "3.5.2", + co: "4.6.0", + "pg-copy-streams": "0.3.0" + }, + peerDependencies: { + "pg-native": ">=3.0.1" + }, + peerDependenciesMeta: { + "pg-native": { + optional: true + } + }, + scripts: { + test: "make test-all" + }, + files: [ + "lib", + "SPONSORS.md" + ], + license: "MIT", + engines: { + node: ">= 8.0.0" + }, + gitHead: "c99fb2c127ddf8d712500db2c7b9a5491a178655" + }; + } +}); + +// node_modules/pg/lib/native/query.js +var require_query2 = __commonJS({ + "node_modules/pg/lib/native/query.js"(exports, module) { + "use strict"; + init_shims(); + var EventEmitter2 = require_events().EventEmitter; + var util = (init_util(), __toCommonJS(util_exports)); + var utils = require_utils(); + var NativeQuery = module.exports = function(config, values, callback) { + EventEmitter2.call(this); + config = utils.normalizeQueryConfig(config, values, callback); + this.text = config.text; + this.values = config.values; + this.name = config.name; + this.callback = config.callback; + this.state = "new"; + this._arrayMode = config.rowMode === "array"; + this._emitRowEvents = false; + this.on( + "newListener", + function(event) { + if (event === "row") this._emitRowEvents = true; + }.bind(this) + ); + }; + util.inherits(NativeQuery, EventEmitter2); + var errorFieldMap = { + /* eslint-disable quote-props */ + sqlState: "code", + statementPosition: "position", + messagePrimary: "message", + context: "where", + schemaName: "schema", + tableName: "table", + columnName: "column", + dataTypeName: "dataType", + constraintName: "constraint", + sourceFile: "file", + sourceLine: "line", + sourceFunction: "routine" + }; + NativeQuery.prototype.handleError = function(err) { + var fields = this.native.pq.resultErrorFields(); + if (fields) { + for (var key in fields) { + var normalizedFieldName = errorFieldMap[key] || key; + err[normalizedFieldName] = fields[key]; + } + } + if (this.callback) { + this.callback(err); + } else { + this.emit("error", err); + } + this.state = "error"; + }; + NativeQuery.prototype.then = function(onSuccess, onFailure) { + return this._getPromise().then(onSuccess, onFailure); + }; + NativeQuery.prototype.catch = function(callback) { + return this._getPromise().catch(callback); + }; + NativeQuery.prototype._getPromise = function() { + if (this._promise) return this._promise; + this._promise = new Promise( + function(resolve, reject) { + this._once("end", resolve); + this._once("error", reject); + }.bind(this) + ); + return this._promise; + }; + NativeQuery.prototype.submit = function(client) { + this.state = "running"; + var self = this; + this.native = client.native; + client.native.arrayMode = this._arrayMode; + var after = /* @__PURE__ */ __name(function(err, rows, results) { + client.native.arrayMode = false; + setImmediate(function() { + self.emit("_done"); + }); + if (err) { + return self.handleError(err); + } + if (self._emitRowEvents) { + if (results.length > 1) { + rows.forEach((rowOfRows, i) => { + rowOfRows.forEach((row) => { + self.emit("row", row, results[i]); + }); + }); + } else { + rows.forEach(function(row) { + self.emit("row", row, results); + }); + } + } + self.state = "end"; + self.emit("end", results); + if (self.callback) { + self.callback(null, results); + } + }, "after"); + if (process.domain) { + after = process.domain.bind(after); + } + if (this.name) { + if (this.name.length > 63) { + console.error("Warning! Postgres only supports 63 characters for query names."); + console.error("You supplied %s (%s)", this.name, this.name.length); + console.error("This can cause conflicts and silent errors executing queries"); + } + var values = (this.values || []).map(utils.prepareValue); + if (client.namedQueries[this.name]) { + if (this.text && client.namedQueries[this.name] !== this.text) { + const err = new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`); + return after(err); + } + return client.native.execute(this.name, values, after); + } + return client.native.prepare(this.name, this.text, values.length, function(err) { + if (err) return after(err); + client.namedQueries[self.name] = self.text; + return self.native.execute(self.name, values, after); + }); + } else if (this.values) { + if (!Array.isArray(this.values)) { + const err = new Error("Query values must be an array"); + return after(err); + } + var vals = this.values.map(utils.prepareValue); + client.native.query(this.text, vals, after); + } else { + client.native.query(this.text, after); + } + }; + } +}); + +// node_modules/pg/lib/native/client.js +var require_client2 = __commonJS({ + "node_modules/pg/lib/native/client.js"(exports, module) { + "use strict"; + init_shims(); + var Native = (init_pg_native(), __toCommonJS(pg_native_exports)); + var TypeOverrides2 = require_type_overrides(); + var pkg = require_package(); + var EventEmitter2 = require_events().EventEmitter; + var util = (init_util(), __toCommonJS(util_exports)); + var ConnectionParameters2 = require_connection_parameters(); + var NativeQuery = require_query2(); + var Client3 = module.exports = function(config) { + EventEmitter2.call(this); + config = config || {}; + this._Promise = config.Promise || global.Promise; + this._types = new TypeOverrides2(config.types); + this.native = new Native({ + types: this._types + }); + this._queryQueue = []; + this._ending = false; + this._connecting = false; + this._connected = false; + this._queryable = true; + var cp = this.connectionParameters = new ConnectionParameters2(config); + this.user = cp.user; + Object.defineProperty(this, "password", { + configurable: true, + enumerable: false, + writable: true, + value: cp.password + }); + this.database = cp.database; + this.host = cp.host; + this.port = cp.port; + this.namedQueries = {}; + }; + Client3.Query = NativeQuery; + util.inherits(Client3, EventEmitter2); + Client3.prototype._errorAllQueries = function(err) { + const enqueueError = /* @__PURE__ */ __name((query) => { + process.nextTick(() => { + query.native = this.native; + query.handleError(err); + }); + }, "enqueueError"); + if (this._hasActiveQuery()) { + enqueueError(this._activeQuery); + this._activeQuery = null; + } + this._queryQueue.forEach(enqueueError); + this._queryQueue.length = 0; + }; + Client3.prototype._connect = function(cb) { + var self = this; + if (this._connecting) { + process.nextTick(() => cb(new Error("Client has already been connected. You cannot reuse a client."))); + return; + } + this._connecting = true; + this.connectionParameters.getLibpqConnectionString(function(err, conString) { + if (err) return cb(err); + self.native.connect(conString, function(err2) { + if (err2) { + self.native.end(); + return cb(err2); + } + self._connected = true; + self.native.on("error", function(err3) { + self._queryable = false; + self._errorAllQueries(err3); + self.emit("error", err3); + }); + self.native.on("notification", function(msg) { + self.emit("notification", { + channel: msg.relname, + payload: msg.extra + }); + }); + self.emit("connect"); + self._pulseQueryQueue(true); + cb(); + }); + }); + }; + Client3.prototype.connect = function(callback) { + if (callback) { + this._connect(callback); + return; + } + return new this._Promise((resolve, reject) => { + this._connect((error) => { + if (error) { + reject(error); + } else { + resolve(); + } + }); + }); + }; + Client3.prototype.query = function(config, values, callback) { + var query; + var result; + var readTimeout; + var readTimeoutTimer; + var queryCallback; + if (config === null || config === void 0) { + throw new TypeError("Client was passed a null or undefined query"); + } else if (typeof config.submit === "function") { + readTimeout = config.query_timeout || this.connectionParameters.query_timeout; + result = query = config; + if (typeof values === "function") { + config.callback = values; + } + } else { + readTimeout = this.connectionParameters.query_timeout; + query = new NativeQuery(config, values, callback); + if (!query.callback) { + let resolveOut, rejectOut; + result = new this._Promise((resolve, reject) => { + resolveOut = resolve; + rejectOut = reject; + }); + query.callback = (err, res) => err ? rejectOut(err) : resolveOut(res); + } + } + if (readTimeout) { + queryCallback = query.callback; + readTimeoutTimer = setTimeout(() => { + var error = new Error("Query read timeout"); + process.nextTick(() => { + query.handleError(error, this.connection); + }); + queryCallback(error); + query.callback = () => { + }; + var index = this._queryQueue.indexOf(query); + if (index > -1) { + this._queryQueue.splice(index, 1); + } + this._pulseQueryQueue(); + }, readTimeout); + query.callback = (err, res) => { + clearTimeout(readTimeoutTimer); + queryCallback(err, res); + }; + } + if (!this._queryable) { + query.native = this.native; + process.nextTick(() => { + query.handleError(new Error("Client has encountered a connection error and is not queryable")); + }); + return result; + } + if (this._ending) { + query.native = this.native; + process.nextTick(() => { + query.handleError(new Error("Client was closed and is not queryable")); + }); + return result; + } + this._queryQueue.push(query); + this._pulseQueryQueue(); + return result; + }; + Client3.prototype.end = function(cb) { + var self = this; + this._ending = true; + if (!this._connected) { + this.once("connect", this.end.bind(this, cb)); + } + var result; + if (!cb) { + result = new this._Promise(function(resolve, reject) { + cb = /* @__PURE__ */ __name((err) => err ? reject(err) : resolve(), "cb"); + }); + } + this.native.end(function() { + self._errorAllQueries(new Error("Connection terminated")); + process.nextTick(() => { + self.emit("end"); + if (cb) cb(); + }); + }); + return result; + }; + Client3.prototype._hasActiveQuery = function() { + return this._activeQuery && this._activeQuery.state !== "error" && this._activeQuery.state !== "end"; + }; + Client3.prototype._pulseQueryQueue = function(initialConnection) { + if (!this._connected) { + return; + } + if (this._hasActiveQuery()) { + return; + } + var query = this._queryQueue.shift(); + if (!query) { + if (!initialConnection) { + this.emit("drain"); + } + return; + } + this._activeQuery = query; + query.submit(this); + var self = this; + query.once("_done", function() { + self._pulseQueryQueue(); + }); + }; + Client3.prototype.cancel = function(query) { + if (this._activeQuery === query) { + this.native.cancel(function() { + }); + } else if (this._queryQueue.indexOf(query) !== -1) { + this._queryQueue.splice(this._queryQueue.indexOf(query), 1); + } + }; + Client3.prototype.ref = function() { + }; + Client3.prototype.unref = function() { + }; + Client3.prototype.setTypeParser = function(oid, format, parseFn) { + return this._types.setTypeParser(oid, format, parseFn); + }; + Client3.prototype.getTypeParser = function(oid, format) { + return this._types.getTypeParser(oid, format); + }; + } +}); + +// node_modules/pg/lib/native/index.js +var require_native = __commonJS({ + "node_modules/pg/lib/native/index.js"(exports, module) { + "use strict"; + init_shims(); + module.exports = require_client2(); + } +}); + +// node_modules/pg/lib/index.js +var require_lib2 = __commonJS({ + "node_modules/pg/lib/index.js"(exports, module) { + "use strict"; + init_shims(); + var Client3 = require_client(); + var defaults2 = require_defaults(); + var Connection3 = require_connection(); + var Pool2 = require_pg_pool(); + var { DatabaseError: DatabaseError2 } = require_dist(); + var poolFactory = /* @__PURE__ */ __name((Client4) => { + return class BoundPool extends Pool2 { + static { + __name(this, "BoundPool"); + } + constructor(options) { + super(options, Client4); + } + }; + }, "poolFactory"); + var PG = /* @__PURE__ */ __name(function(clientConstructor) { + this.defaults = defaults2; + this.Client = clientConstructor; + this.Query = this.Client.Query; + this.Pool = poolFactory(this.Client); + this._pools = []; + this.Connection = Connection3; + this.types = require_pg_types(); + this.DatabaseError = DatabaseError2; + }, "PG"); + if (typeof process.env.NODE_PG_FORCE_NATIVE !== "undefined") { + module.exports = new PG(require_native()); + } else { + module.exports = new PG(Client3); + Object.defineProperty(module.exports, "native", { + configurable: true, + enumerable: false, + get() { + var native = null; + try { + native = new PG(require_native()); + } catch (err) { + if (err.code !== "MODULE_NOT_FOUND") { + throw err; + } + } + Object.defineProperty(module.exports, "native", { + value: native + }); + return native; + } + }); + } + } +}); + +// src/index.ts +init_shims(); + +// node_modules/subtls/index.js +var subtls_exports = {}; +__export(subtls_exports, { + SocketReadQueue: () => Lt, + TrustedCert: () => st, + WebSocketReadQueue: () => vt, + startTls: () => he +}); +init_shims(); +function p(...r2) { + if (r2.length === 1 && r2[0] instanceof Uint8Array) return r2[0]; + let e = r2.reduce((n, a) => n + a.length, 0), t = new Uint8Array(e), i = 0; + for (let n of r2) t.set(n, i), i += n.length; + return t; +} +__name(p, "p"); +function O(r2, e) { + let t = r2.length; + if (t !== e.length) return false; + for (let i = 0; i < t; i++) if (r2[i] !== e[i]) return false; + return true; +} +__name(O, "O"); +var it = "\xB7\xB7 "; +var Nt = new TextEncoder(); +var Yt = new TextDecoder(); +var N = class { + static { + __name(this, "N"); + } + offset; + dataView; + data; + comments; + indents; + indent; + constructor(e) { + this.offset = 0, this.data = typeof e == "number" ? new Uint8Array(e) : e, this.dataView = new DataView( + this.data.buffer, + this.data.byteOffset, + this.data.byteLength + ), this.comments = {}, this.indents = {}, this.indent = 0; + } + extend(e) { + let t = typeof e == "number" ? new Uint8Array(e) : e; + this.data = p(this.data, t), this.dataView = new DataView( + this.data.buffer, + this.data.byteOffset, + this.data.byteLength + ); + } + remaining() { + return this.data.length - this.offset; + } + subarray(e) { + return this.data.subarray(this.offset, this.offset += e); + } + skip(e, t) { + return this.offset += e, t && this.comment(t), this; + } + comment(e, t = this.offset) { + throw new Error("No comments should be emitted outside of chatty mode"); + } + readBytes(e) { + return this.data.slice(this.offset, this.offset += e); + } + readUTF8String(e) { + let t = this.subarray(e); + return Yt.decode( + t + ); + } + readUTF8StringNullTerminated() { + let e = this.offset; + for (; this.data[e] !== 0; ) e++; + let t = this.readUTF8String(e - this.offset); + return this.expectUint8(0, "end of string"), t; + } + readUint8(e) { + let t = this.dataView.getUint8(this.offset); + return this.offset += 1, t; + } + readUint16(e) { + let t = this.dataView.getUint16(this.offset); + return this.offset += 2, t; + } + readUint24(e) { + let t = this.readUint8(), i = this.readUint16(); + return (t << 16) + i; + } + readUint32(e) { + let t = this.dataView.getUint32(this.offset); + return this.offset += 4, t; + } + expectBytes(e, t) { + let i = this.readBytes(e.length); + if (!O(i, e)) throw new Error("Unexpected bytes"); + } + expectUint8(e, t) { + let i = this.readUint8(); + if (i !== e) throw new Error(`Expected ${e}, got ${i}`); + } + expectUint16(e, t) { + let i = this.readUint16(); + if (i !== e) throw new Error(`Expected ${e}, got ${i}`); + } + expectUint24(e, t) { + let i = this.readUint24(); + if (i !== e) throw new Error(`Expected ${e}, got ${i}`); + } + expectUint32(e, t) { + let i = this.readUint32(); + if (i !== e) throw new Error(`Expected ${e}, got ${i}`); + } + expectLength(e, t = 1) { + let i = this.offset, n = i + e; + if (n > this.data.length) throw new Error("Expected length exceeds remaining data length"); + return this.indent += t, this.indents[i] = this.indent, [() => { + if (this.indent -= t, this.indents[this.offset] = this.indent, this.offset !== n) throw new Error( + `${e} bytes expected but ${this.offset - i} read` + ); + }, () => n - this.offset]; + } + expectLengthUint8(e) { + let t = this.readUint8(); + return this.expectLength(t); + } + expectLengthUint16(e) { + let t = this.readUint16(); + return this.expectLength(t); + } + expectLengthUint24(e) { + let t = this.readUint24(); + return this.expectLength(t); + } + expectLengthUint32(e) { + let t = this.readUint32(); + return this.expectLength(t); + } + expectLengthUint8Incl(e) { + let t = this.readUint8(); + return this.expectLength( + t - 1 + ); + } + expectLengthUint16Incl(e) { + let t = this.readUint16(); + return this.expectLength( + t - 2 + ); + } + expectLengthUint24Incl(e) { + let t = this.readUint24(); + return this.expectLength( + t - 3 + ); + } + expectLengthUint32Incl(e) { + let t = this.readUint32(); + return this.expectLength( + t - 4 + ); + } + writeBytes(e) { + return this.data.set(e, this.offset), this.offset += e.length, this; + } + writeUTF8String(e) { + let t = Nt.encode(e); + return this.writeBytes(t), this; + } + writeUTF8StringNullTerminated(e) { + let t = Nt.encode(e); + return this.writeBytes(t), this.writeUint8(0), this; + } + writeUint8(e, t) { + return this.dataView.setUint8(this.offset, e), this.offset += 1, this; + } + writeUint16(e, t) { + return this.dataView.setUint16(this.offset, e), this.offset += 2, this; + } + writeUint24(e, t) { + return this.writeUint8((e & 16711680) >> 16), this.writeUint16(e & 65535, t), this; + } + writeUint32(e, t) { + return this.dataView.setUint32(this.offset, e), this.offset += 4, this; + } + _writeLengthGeneric(e, t, i) { + let n = this.offset; + this.offset += e; + let a = this.offset; + return this.indent += 1, this.indents[a] = this.indent, () => { + let c = this.offset - (t ? n : a); + if (e === 1) this.dataView.setUint8(n, c); + else if (e === 2) this.dataView.setUint16(n, c); + else if (e === 3) this.dataView.setUint8(n, (c & 16711680) >> 16), this.dataView.setUint16(n + 1, c & 65535); + else if (e === 4) this.dataView.setUint32( + n, + c + ); + else throw new Error(`Invalid length for length field: ${e}`); + this.indent -= 1, this.indents[this.offset] = this.indent; + }; + } + writeLengthUint8(e) { + return this._writeLengthGeneric( + 1, + false, + e + ); + } + writeLengthUint16(e) { + return this._writeLengthGeneric(2, false, e); + } + writeLengthUint24(e) { + return this._writeLengthGeneric(3, false, e); + } + writeLengthUint32(e) { + return this._writeLengthGeneric( + 4, + false, + e + ); + } + writeLengthUint8Incl(e) { + return this._writeLengthGeneric(1, true, e); + } + writeLengthUint16Incl(e) { + return this._writeLengthGeneric(2, true, e); + } + writeLengthUint24Incl(e) { + return this._writeLengthGeneric( + 3, + true, + e + ); + } + writeLengthUint32Incl(e) { + return this._writeLengthGeneric(4, true, e); + } + array() { + return this.data.subarray(0, this.offset); + } + commentedString(e = false) { + let t = this.indents[0] !== void 0 ? it.repeat(this.indents[0]) : "", i = this.indents[0] ?? 0, n = e ? this.data.length : this.offset; + for (let a = 0; a < n; a++) { + t += this.data[a].toString(16).padStart(2, "0") + " "; + let c = this.comments[a + 1]; + this.indents[a + 1] !== void 0 && (i = this.indents[a + 1]), c && (t += ` ${c} +${it.repeat(i)}`); + } + return t; + } +}; +function St(r2, e, t, i = true) { + let n = new N(1024); + n.writeUint8(22, 0), n.writeUint16(769, 0); + let a = n.writeLengthUint16(); + n.writeUint8(1, 0); + let c = n.writeLengthUint24(); + n.writeUint16( + 771, + 0 + ), crypto.getRandomValues(n.subarray(32)); + let s = n.writeLengthUint8(0); + n.writeBytes( + t + ), s(); + let o = n.writeLengthUint16(0); + n.writeUint16(4865, 0), o(); + let h = n.writeLengthUint8( + 0 + ); + n.writeUint8(0, 0), h(); + let y = n.writeLengthUint16(0); + if (i) { + n.writeUint16(0, 0); + let q = n.writeLengthUint16(0), G = n.writeLengthUint16(0); + n.writeUint8(0, 0); + let D = n.writeLengthUint16( + 0 + ); + n.writeUTF8String(r2), D(), G(), q(); + } + n.writeUint16(11, 0); + let d = n.writeLengthUint16( + 0 + ), m = n.writeLengthUint8(0); + n.writeUint8(0, 0), m(), d(), n.writeUint16(10, 0); + let g = n.writeLengthUint16(0), A = n.writeLengthUint16(0); + n.writeUint16(23, 0), A(), g(), n.writeUint16( + 13, + 0 + ); + let L = n.writeLengthUint16(0), f = n.writeLengthUint16(0); + n.writeUint16(1027, 0), n.writeUint16(2052, 0), f(), L(), n.writeUint16(43, 0); + let u = n.writeLengthUint16(0), x = n.writeLengthUint8(0); + n.writeUint16(772, 0), x(), u(), n.writeUint16(51, 0); + let T = n.writeLengthUint16( + 0 + ), $ = n.writeLengthUint16(0); + n.writeUint16(23, 0); + let P = n.writeLengthUint16(0); + return n.writeBytes(new Uint8Array(e)), P(), $(), T(), y(), c(), a(), n; +} +__name(St, "St"); +function K(r2, e = "") { + return [...r2].map((t) => t.toString(16).padStart(2, "0")).join(e); +} +__name(K, "K"); +function Ut(r2, e) { + let t, i, [n] = r2.expectLength(r2.remaining()); + r2.expectUint8(2, 0); + let [ + a + ] = r2.expectLengthUint24(0); + r2.expectUint16(771, 0); + let c = r2.readBytes(32); + if (O(c, [ + 207, + 33, + 173, + 116, + 229, + 154, + 97, + 17, + 190, + 29, + 140, + 2, + 30, + 101, + 184, + 145, + 194, + 162, + 17, + 22, + 122, + 187, + 140, + 94, + 7, + 158, + 9, + 226, + 200, + 168, + 51, + 156 + ])) throw new Error("Unexpected HelloRetryRequest"); + r2.expectUint8( + e.length, + 0 + ), r2.expectBytes(e, 0), r2.expectUint16(4865, 0), r2.expectUint8(0, 0); + let [s, o] = r2.expectLengthUint16(0); + for (; o() > 0; ) { + let h = r2.readUint16(0), [y] = r2.expectLengthUint16( + 0 + ); + if (h === 43) r2.expectUint16(772, 0), i = true; + else if (h === 51) r2.expectUint16(23, 0), r2.expectUint16( + 65 + ), t = r2.readBytes(65); + else throw new Error(`Unexpected extension 0x${K([h])}`); + y(); + } + if (s(), a(), n(), i !== true) throw new Error("No TLS version provided"); + if (t === void 0) throw new Error( + "No key provided" + ); + return t; +} +__name(Ut, "Ut"); +var Ce = new RegExp(` .+|^(${it})+`, "gm"); +var rt = 16384; +var te = rt + 1 + 255; +async function ht(r2, e, t = rt) { + let n = await r2(5); + if (n === void 0) + return; + if (n.length < 5) throw new Error("TLS record header truncated"); + let a = new N( + n + ), c = a.readUint8(); + if (c < 20 || c > 24) throw new Error(`Illegal TLS record type 0x${c.toString(16)}`); + if (e !== void 0 && c !== e) throw new Error(`Unexpected TLS record type 0x${c.toString(16).padStart(2, "0")} (expected 0x${e.toString(16).padStart(2, "0")})`); + a.expectUint16(771, "TLS record version 1.2 (middlebox compatibility)"); + let s = a.readUint16(0); + if (s > t) throw new Error(`Record too long: ${s} bytes`); + let o = await r2( + s + ); + if (o === void 0 || o.length < s) throw new Error("TLS record content truncated"); + return { + headerData: n, + header: a, + type: c, + length: s, + content: o + }; +} +__name(ht, "ht"); +async function dt(r2, e, t) { + let i = await ht( + r2, + 23, + te + ); + if (i === void 0) return; + let n = new N(i.content), [a] = n.expectLength(n.remaining()); + n.skip(i.length - 16, 0), n.skip(16, 0), a(); + let c = await e.process(i.content, 16, i.headerData), s = c.length - 1; + for (; c[s] === 0; ) s -= 1; + if (s < 0) throw new Error("Decrypted message has no record type indicator (all zeroes)"); + let o = c[s], h = c.subarray(0, s); + if (!(o === 21 && h.length === 2 && h[0] === 1 && h[1] === 0)) { + if (o === 22 && h[0] === 4) return dt(r2, e, t); + if (t !== void 0 && o !== t) throw new Error(`Unexpected TLS record type 0x${o.toString(16).padStart( + 2, + "0" + )} (expected 0x${t.toString(16).padStart(2, "0")})`); + return h; + } +} +__name(dt, "dt"); +async function ee(r2, e, t) { + let i = p(r2, [t]), n = 5, s = i.length + 16, o = new N(n + s); + o.writeUint8(23, 0), o.writeUint16( + 771, + 0 + ), o.writeUint16(s, `${s} bytes follow`); + let [h] = o.expectLength(s), y = o.array(), d = await e.process(i, 16, y); + return o.writeBytes(d.subarray(0, d.length - 16)), o.writeBytes(d.subarray( + d.length - 16 + )), h(), o.array(); +} +__name(ee, "ee"); +async function At(r2, e, t) { + let i = Math.ceil(r2.length / rt), n = []; + for (let a = 0; a < i; a++) { + let c = r2.subarray(a * rt, (a + 1) * rt), s = await ee(c, e, t); + n.push( + s + ); + } + return n; +} +__name(At, "At"); +var l = crypto.subtle; +var Ht = new TextEncoder(); +async function lt(r2, e, t) { + let i = await l.importKey( + "raw", + r2, + { name: "HMAC", hash: { name: `SHA-${t}` } }, + false, + ["sign"] + ); + var n = new Uint8Array(await l.sign( + "HMAC", + i, + e + )); + return n; +} +__name(lt, "lt"); +async function ne(r2, e, t, i) { + let n = i >> 3, a = Math.ceil(t / n), c = new Uint8Array( + a * n + ), s = await l.importKey("raw", r2, { name: "HMAC", hash: { name: `SHA-${i}` } }, false, ["sign"]), o = new Uint8Array(0); + for (let h = 0; h < a; h++) { + let y = p(o, e, [h + 1]), d = await l.sign( + "HMAC", + s, + y + ), m = new Uint8Array(d); + c.set(m, n * h), o = m; + } + return c.subarray(0, t); +} +__name(ne, "ne"); +var Rt = Ht.encode( + "tls13 " +); +async function S(r2, e, t, i, n) { + let a = Ht.encode(e), c = p( + [(i & 65280) >> 8, i & 255], + [Rt.length + a.length], + Rt, + a, + [t.length], + t + ); + return ne(r2, c, i, n); +} +__name(S, "S"); +async function Kt(r2, e, t, i, n) { + let a = i >>> 3, c = new Uint8Array(a), s = await l.importKey( + "raw", + r2, + { name: "ECDH", namedCurve: "P-256" }, + false, + [] + ), o = await l.deriveBits({ + name: "ECDH", + public: s + }, e, 256), h = new Uint8Array(o), y = await l.digest("SHA-256", t), d = new Uint8Array( + y + ), m = await lt(new Uint8Array(1), c, i), g = await l.digest(`SHA-${i}`, new Uint8Array( + 0 + )), A = new Uint8Array(g), L = await S(m, "derived", A, a, i), f = await lt(L, h, i), u = await S( + f, + "c hs traffic", + d, + a, + i + ), x = await S(f, "s hs traffic", d, a, i), T = await S(u, "key", new Uint8Array( + 0 + ), n, i), $ = await S(x, "key", new Uint8Array(0), n, i), P = await S(u, "iv", new Uint8Array( + 0 + ), 12, i), q = await S(x, "iv", new Uint8Array(0), 12, i); + return { + serverHandshakeKey: $, + serverHandshakeIV: q, + clientHandshakeKey: T, + clientHandshakeIV: P, + handshakeSecret: f, + clientSecret: u, + serverSecret: x + }; +} +__name(Kt, "Kt"); +async function Tt(r2, e, t, i) { + let n = t >>> 3, a = new Uint8Array(n), c = await l.digest(`SHA-${t}`, new Uint8Array(0)), s = new Uint8Array(c), o = await S(r2, "derived", s, n, t), h = await lt( + o, + a, + t + ), y = await S(h, "c ap traffic", e, n, t), d = await S(h, "s ap traffic", e, n, t), m = await S( + y, + "key", + new Uint8Array(0), + i, + t + ), g = await S(d, "key", new Uint8Array(0), i, t), A = await S( + y, + "iv", + new Uint8Array(0), + 12, + t + ), L = await S(d, "iv", new Uint8Array(0), 12, t); + return { + serverApplicationKey: g, + serverApplicationIV: L, + clientApplicationKey: m, + clientApplicationIV: A + }; +} +__name(Tt, "Tt"); +var Z = class { + static { + __name(this, "Z"); + } + constructor(e, t, i) { + this.mode = e; + this.key = t; + this.initialIv = i; + } + recordsProcessed = 0n; + priorPromise = Promise.resolve(new Uint8Array()); + async process(e, t, i) { + let n = this.processUnsequenced(e, t, i); + return this.priorPromise = this.priorPromise.then(() => n); + } + async processUnsequenced(e, t, i) { + let n = this.recordsProcessed; + this.recordsProcessed += 1n; + let a = this.initialIv.slice(), c = BigInt(a.length), s = c - 1n; + for (let m = 0n; m < c; m++) { + let g = n >> (m << 3n); + if (g === 0n) break; + a[Number(s - m)] ^= Number(g & 0xffn); + } + let o = t << 3, h = { name: "AES-GCM", iv: a, tagLength: o, additionalData: i }, y = await l[this.mode](h, this.key, e); + return new Uint8Array(y); + } +}; +function yt(r2) { + return r2 > 64 && r2 < 91 ? r2 - 65 : r2 > 96 && r2 < 123 ? r2 - 71 : r2 > 47 && r2 < 58 ? r2 + 4 : r2 === 43 ? 62 : r2 === 47 ? 63 : r2 === 61 ? 64 : void 0; +} +__name(yt, "yt"); +function Dt(r2) { + let e = r2.length, t = 0, i = 0, n = 64, a = 64, c = 64, s = 64, o = new Uint8Array(e * 0.75); + for (; t < e; ) n = yt(r2.charCodeAt(t++)), a = yt(r2.charCodeAt( + t++ + )), c = yt(r2.charCodeAt(t++)), s = yt(r2.charCodeAt(t++)), o[i++] = n << 2 | a >> 4, o[i++] = (a & 15) << 4 | c >> 2, o[i++] = (c & 3) << 6 | s; + let h = a === 64 ? 0 : c === 64 ? 2 : s === 64 ? 1 : 0; + return o.subarray( + 0, + i - h + ); +} +__name(Dt, "Dt"); +var M = class extends N { + static { + __name(this, "M"); + } + readASN1Length(e) { + let t = this.readUint8(); + if (t < 128) return t; + let i = t & 127, n = 0; + if (i === 1) return this.readUint8(n); + if (i === 2) return this.readUint16( + n + ); + if (i === 3) return this.readUint24(n); + if (i === 4) return this.readUint32(n); + throw new Error( + `ASN.1 length fields are only supported up to 4 bytes (this one is ${i} bytes)` + ); + } + expectASN1Length(e) { + let t = this.readASN1Length(e); + return this.expectLength(t); + } + readASN1OID() { + let [e, t] = this.expectASN1Length(0), i = this.readUint8(), n = `${Math.floor(i / 40)}.${i % 40}`; + for (; t() > 0; ) { + let a = 0; + for (; ; ) { + let c = this.readUint8(); + if (a <<= 7, a += c & 127, c < 128) break; + } + n += `.${a}`; + } + return e(), n; + } + readASN1Boolean() { + let [e, t] = this.expectASN1Length(0), i = t(); + if (i !== 1) + throw new Error(`Boolean has weird length: ${i}`); + let n = this.readUint8(), a; + if (n === 255) a = true; + else if (n === 0) a = false; + else throw new Error(`Boolean has weird value: 0x${K( + [n] + )}`); + return e(), a; + } + readASN1UTCTime() { + let [e, t] = this.expectASN1Length(0), n = this.readUTF8String(t()).match(/^(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)Z$/); + if (!n) throw new Error( + "Unrecognised ASN.1 UTC time format" + ); + let [, a, c, s, o, h, y] = n, d = parseInt(a, 10), m = d + (d >= 50 ? 1900 : 2e3), g = /* @__PURE__ */ new Date(`${m}-${c}-${s}T${o}:${h}:${y}Z`); + return e(), g; + } + readASN1BitString() { + let [e, t] = this.expectASN1Length(0), i = this.readUint8(0), n = t(), a = this.readBytes(n); + if (i > 7) throw new Error(`Invalid right pad value: ${i}`); + if (i > 0) { + let c = 8 - i; + for (let s = n - 1; s > 0; s--) a[s] = 255 & a[s - 1] << c | a[s] >>> i; + a[0] = a[0] >>> i; + } + return e(), a; + } +}; +function mt(r2, e = (i, n) => n, t) { + return JSON.stringify(r2, (n, a) => e(n, typeof a != "object" || a === null || Array.isArray(a) ? a : Object.fromEntries(Object.entries(a).sort(([c], [s]) => c < s ? -1 : c > s ? 1 : 0))), t); +} +__name(mt, "mt"); +var gt = 1; +var tt = 2; +var U = 48; +var ie = 49; +var Q = 6; +var re = 19; +var se = 12; +var bt = 23; +var ft = 5; +var _ = 4; +var ut = 3; +var $t = 163; +var W = 128; +var ae = { + "2.5.4.6": "C", + "2.5.4.10": "O", + "2.5.4.11": "OU", + "2.5.4.3": "CN", + "2.5.4.7": "L", + "2.5.4.8": "ST", + "2.5.4.12": "T", + "2.5.4.42": "GN", + "2.5.4.43": "I", + "2.5.4.4": "SN", + "1.2.840.113549.1.9.1": "E-mail" +}; +function qt(r2) { + let { length: e } = r2; + if (e > 4) throw new Error(`Bit string length ${e} would overflow JS bit operators`); + let t = 0, i = 0; + for (let n = r2.length - 1; n >= 0; n--) t |= r2[n] << i, i += 8; + return t; +} +__name(qt, "qt"); +function Ct(r2, e) { + let t = {}; + r2.expectUint8(U, 0); + let [i, n] = r2.expectASN1Length( + 0 + ); + for (; n() > 0; ) { + r2.expectUint8(ie, 0); + let [a] = r2.expectASN1Length(0); + r2.expectUint8( + U, + 0 + ); + let [c] = r2.expectASN1Length(0); + r2.expectUint8(Q, 0); + let s = r2.readASN1OID(), o = ae[s] ?? s, h = r2.readUint8(); + if (h !== re) { + if (h !== se) throw new Error(`Unexpected item type in certificate ${e}: 0x${K([h])}`); + } + let [y, d] = r2.expectASN1Length(0), m = r2.readUTF8String( + d() + ); + if (y(), c(), a(), t[o] !== void 0) throw new Error(`Duplicate OID ${o} in certificate ${e}`); + t[o] = m; + } + return i(), t; +} +__name(Ct, "Ct"); +function Bt(r2, e = 0) { + let t = [], [i, n] = r2.expectASN1Length( + 0 + ); + for (; n() > 0; ) { + let a = r2.readUint8(0), [c, s] = r2.expectASN1Length(0), o; + a === (e | 2) ? o = r2.readUTF8String(s()) : o = r2.readBytes(s()), t.push({ name: o, type: a }), c(); + } + return i(), t; +} +__name(Bt, "Bt"); +function Ft(r2) { + let e = { + "1.2.840.113549.1.1.1": { name: "RSAES-PKCS1-v1_5" }, + "1.2.840.113549.1.1.5": { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-1" } }, + "1.2.840.113549.1.1.11": { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } }, + "1.2.840.113549.1.1.12": { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-384" } }, + "1.2.840.113549.1.1.13": { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-512" } }, + "1.2.840.113549.1.1.10": { name: "RSA-PSS" }, + "1.2.840.113549.1.1.7": { name: "RSA-OAEP" }, + "1.2.840.10045.2.1": { name: "ECDSA", hash: { name: "SHA-1" } }, + "1.2.840.10045.4.1": { name: "ECDSA", hash: { name: "SHA-1" } }, + "1.2.840.10045.4.3.2": { name: "ECDSA", hash: { name: "SHA-256" } }, + "1.2.840.10045.4.3.3": { name: "ECDSA", hash: { + name: "SHA-384" + } }, + "1.2.840.10045.4.3.4": { name: "ECDSA", hash: { name: "SHA-512" } }, + "1.3.133.16.840.63.0.2": { name: "ECDH", kdf: "SHA-1" }, + "1.3.132.1.11.1": { name: "ECDH", kdf: "SHA-256" }, + "1.3.132.1.11.2": { name: "ECDH", kdf: "SHA-384" }, + "1.3.132.1.11.3": { name: "ECDH", kdf: "SHA-512" }, + "2.16.840.1.101.3.4.1.2": { name: "AES-CBC", length: 128 }, + "2.16.840.1.101.3.4.1.22": { name: "AES-CBC", length: 192 }, + "2.16.840.1.101.3.4.1.42": { name: "AES-CBC", length: 256 }, + "2.16.840.1.101.3.4.1.6": { name: "AES-GCM", length: 128 }, + "2.16.840.1.101.3.4.1.26": { name: "AES-GCM", length: 192 }, + "2.16.840.1.101.3.4.1.46": { name: "AES-GCM", length: 256 }, + "2.16.840.1.101.3.4.1.4": { name: "AES-CFB", length: 128 }, + "2.16.840.1.101.3.4.1.24": { name: "AES-CFB", length: 192 }, + "2.16.840.1.101.3.4.1.44": { name: "AES-CFB", length: 256 }, + "2.16.840.1.101.3.4.1.5": { name: "AES-KW", length: 128 }, + "2.16.840.1.101.3.4.1.25": { name: "AES-KW", length: 192 }, + "2.16.840.1.101.3.4.1.45": { name: "AES-KW", length: 256 }, + "1.2.840.113549.2.7": { name: "HMAC", hash: { name: "SHA-1" } }, + "1.2.840.113549.2.9": { name: "HMAC", hash: { name: "SHA-256" } }, + "1.2.840.113549.2.10": { name: "HMAC", hash: { name: "SHA-384" } }, + "1.2.840.113549.2.11": { name: "HMAC", hash: { name: "SHA-512" } }, + "1.2.840.113549.1.9.16.3.5": { name: "DH" }, + "1.3.14.3.2.26": { name: "SHA-1" }, + "2.16.840.1.101.3.4.2.1": { name: "SHA-256" }, + "2.16.840.1.101.3.4.2.2": { name: "SHA-384" }, + "2.16.840.1.101.3.4.2.3": { name: "SHA-512" }, + "1.2.840.113549.1.5.12": { name: "PBKDF2" }, + "1.2.840.10045.3.1.7": { name: "P-256" }, + "1.3.132.0.34": { name: "P-384" }, + "1.3.132.0.35": { + name: "P-521" + } + }[r2]; + if (e === void 0) throw new Error(`Unsupported algorithm identifier: ${r2}`); + return e; +} +__name(Ft, "Ft"); +function Ot(r2, e = []) { + return Object.values(r2).forEach((t) => { + typeof t == "string" ? e = [...e, t] : e = Ot(t, e); + }), e; +} +__name(Ot, "Ot"); +function Pt(r2) { + return Ot(r2).join(" / "); +} +__name(Pt, "Pt"); +var ce = [ + "digitalSignature", + "nonRepudiation", + "keyEncipherment", + "dataEncipherment", + "keyAgreement", + "keyCertSign", + "cRLSign", + "encipherOnly", + "decipherOnly" +]; +var X = class r { + static { + __name(this, "r"); + } + serialNumber; + algorithm; + issuer; + validityPeriod; + subject; + publicKey; + signature; + keyUsage; + subjectAltNames; + extKeyUsage; + authorityKeyIdentifier; + subjectKeyIdentifier; + basicConstraints; + signedData; + static distinguishedNamesAreEqual(e, t) { + return mt(e) === mt(t); + } + static readableDN(e) { + return Object.entries(e).map((t) => t.join( + "=" + )).join(", "); + } + constructor(e) { + let t = e instanceof M ? e : new M(e); + t.expectUint8( + U, + 0 + ); + let [i] = t.expectASN1Length(0), n = t.offset; + t.expectUint8(U, 0); + let [a] = t.expectASN1Length( + 0 + ); + t.expectBytes([160, 3, 2, 1, 2], 0), t.expectUint8(tt, 0); + let [c, s] = t.expectASN1Length( + 0 + ); + this.serialNumber = t.subarray(s()), c(), t.expectUint8(U, 0); + let [o, h] = t.expectASN1Length( + 0 + ); + t.expectUint8(Q, 0), this.algorithm = t.readASN1OID(), h() > 0 && (t.expectUint8(ft, 0), t.expectUint8(0, 0)), o(), this.issuer = Ct(t, "issuer"), t.expectUint8(U, 0); + let [y] = t.expectASN1Length( + 0 + ); + t.expectUint8(bt, 0); + let d = t.readASN1UTCTime(); + t.expectUint8(bt, 0); + let m = t.readASN1UTCTime(); + this.validityPeriod = { notBefore: d, notAfter: m }, y(), this.subject = Ct(t, "subject"); + let g = t.offset; + t.expectUint8(U, 0); + let [A] = t.expectASN1Length(0); + t.expectUint8(U, 0); + let [ + L, + f + ] = t.expectASN1Length(0), u = []; + for (; f() > 0; ) { + let H = t.readUint8(); + if (H === Q) { + let z = t.readASN1OID(); + u.push(z); + } else H === ft && t.expectUint8(0, 0); + } + L(), t.expectUint8(ut, 0); + let x = t.readASN1BitString(); + this.publicKey = { identifiers: u, data: x, all: t.data.subarray( + g, + t.offset + ) }, A(), t.expectUint8($t, 0); + let [T] = t.expectASN1Length(); + t.expectUint8( + U, + 0 + ); + let [$, P] = t.expectASN1Length(0); + for (; P() > 0; ) { + t.expectUint8(U, 0); + let [H, z] = t.expectASN1Length(); + t.expectUint8(Q, 0); + let B = t.readASN1OID(); + if (B === "2.5.29.17") { + t.expectUint8(_, 0); + let [k] = t.expectASN1Length(0); + t.expectUint8(U, 0); + let b = Bt(t, W); + this.subjectAltNames = b.filter((C) => C.type === (2 | W)).map((C) => C.name), k(); + } else if (B === "2.5.29.15") { + t.expectUint8( + gt, + 0 + ); + let k = t.readASN1Boolean(); + t.expectUint8(_, 0); + let [b] = t.expectASN1Length(0); + t.expectUint8(ut, 0); + let C = t.readASN1BitString(), E = qt(C), I = new Set(ce.filter((w, j) => E & 1 << j)); + b(), this.keyUsage = { critical: k, usages: I }; + } else if (B === "2.5.29.37") { + this.extKeyUsage = {}, t.expectUint8(_, 0); + let [k] = t.expectASN1Length(0); + t.expectUint8(U, 0); + let [b, C] = t.expectASN1Length(0); + for (; C() > 0; ) { + t.expectUint8(Q, 0); + let E = t.readASN1OID(); + E === "1.3.6.1.5.5.7.3.1" && (this.extKeyUsage.serverTls = true), E === "1.3.6.1.5.5.7.3.2" && (this.extKeyUsage.clientTls = true); + } + b(), k(); + } else if (B === "2.5.29.35") { + t.expectUint8(_, 0); + let [ + k + ] = t.expectASN1Length(0); + t.expectUint8(U, 0); + let [b, C] = t.expectASN1Length(0); + for (; C() > 0; ) { + let E = t.readUint8(); + if (E === (W | 0)) { + let [I, w] = t.expectASN1Length(0); + this.authorityKeyIdentifier = t.readBytes(w()), I(); + } else if (E === (W | 1)) { + let [I, w] = t.expectASN1Length(0); + t.skip( + w(), + 0 + ), I(); + } else if (E === (W | 2)) { + let [I, w] = t.expectASN1Length(0); + t.skip(w(), 0), I(); + } else if (E === (W | 33)) { + let [I, w] = t.expectASN1Length(0); + t.skip(w(), 0), I(); + } else throw new Error(`Unexpected data type ${E} in authorityKeyIdentifier certificate extension`); + } + b(), k(); + } else if (B === "2.5.29.14") { + t.expectUint8(_, 0); + let [k] = t.expectASN1Length(0); + t.expectUint8(_, 0); + let [b, C] = t.expectASN1Length(0); + this.subjectKeyIdentifier = t.readBytes(C()), b(), k(); + } else if (B === "2.5.29.19") { + let k, b = t.readUint8(); + if (b === gt && (k = t.readASN1Boolean(), b = t.readUint8()), b !== _) throw new Error("Unexpected type in certificate basic constraints"); + let [C] = t.expectASN1Length(0); + t.expectUint8(U, 0); + let [E, I] = t.expectASN1Length(), w; + I() > 0 && (t.expectUint8(gt, 0), w = t.readASN1Boolean()); + let j; + if (I() > 0) { + t.expectUint8(tt, 0); + let J = t.readASN1Length(0); + if (j = J === 1 ? t.readUint8() : J === 2 ? t.readUint16() : J === 3 ? t.readUint24() : void 0, j === void 0) throw new Error("Too many bytes in max path length in certificate basicConstraints"); + } + E(), C(), this.basicConstraints = { critical: k, ca: w, pathLength: j }; + } else + t.skip(z(), 0); + H(); + } + $(), T(), a(), this.signedData = t.data.subarray(n, t.offset), t.expectUint8( + U, + 0 + ); + let [q, G] = t.expectASN1Length(0); + t.expectUint8(Q, 0); + let D = t.readASN1OID(); + if (G() > 0 && (t.expectUint8(ft, 0), t.expectUint8(0, 0)), q(), D !== this.algorithm) throw new Error( + `Certificate specifies different signature algorithms inside (${this.algorithm}) and out (${D})` + ); + t.expectUint8(ut, 0), this.signature = t.readASN1BitString(), i(); + } + static fromPEM(e) { + let t = "[A-Z0-9 ]+", i = new RegExp(`-{5}BEGIN ${t}-{5}([a-zA-Z0-9=+\\/\\n\\r]+)-{5}END ${t}-{5}`, "g"), n = [], a = null; + for (; a = i.exec(e); ) { + let c = a[1].replace(/[\r\n]/g, ""), s = Dt(c), o = new this(s); + n.push(o); + } + return n; + } + subjectAltNameMatchingHost(e) { + let t = /[.][^.]+[.][^.]+$/; + return (this.subjectAltNames ?? []).find((i) => { + let n = i, a = e; + if (t.test(e) && t.test(n) && n.startsWith("*.") && (n = n.slice(1), a = a.slice(a.indexOf("."))), n === a) return true; + }); + } + isValidAtMoment(e = /* @__PURE__ */ new Date()) { + return e >= this.validityPeriod.notBefore && e <= this.validityPeriod.notAfter; + } + description() { + return "subject: " + r.readableDN(this.subject) + (this.subjectAltNames ? ` +subject alt names: ` + this.subjectAltNames.join(", ") : "") + (this.subjectKeyIdentifier ? ` +subject key id: ${K(this.subjectKeyIdentifier, " ")}` : "") + ` +issuer: ` + r.readableDN(this.issuer) + (this.authorityKeyIdentifier ? ` +authority key id: ${K(this.authorityKeyIdentifier, " ")}` : "") + ` +validity: ` + this.validityPeriod.notBefore.toISOString() + " \u2013 " + this.validityPeriod.notAfter.toISOString() + ` (${this.isValidAtMoment() ? "currently valid" : "not valid"})` + (this.keyUsage ? ` +key usage (${this.keyUsage.critical ? "critical" : "non-critical"}): ` + [...this.keyUsage.usages].join(", ") : "") + (this.extKeyUsage ? ` +extended key usage: TLS server \u2014\xA0${this.extKeyUsage.serverTls}, TLS client \u2014\xA0${this.extKeyUsage.clientTls}` : "") + (this.basicConstraints ? ` +basic constraints (${this.basicConstraints.critical ? "critical" : "non-critical"}): CA \u2014\xA0${this.basicConstraints.ca}, path length \u2014 ${this.basicConstraints.pathLength}` : "") + ` +signature algorithm: ` + Pt(Ft(this.algorithm)); + } + toJSON() { + return { + serialNumber: [...this.serialNumber], + algorithm: this.algorithm, + issuer: this.issuer, + validityPeriod: { notBefore: this.validityPeriod.notBefore.toISOString(), notAfter: this.validityPeriod.notAfter.toISOString() }, + subject: this.subject, + publicKey: { identifiers: this.publicKey.identifiers, data: [...this.publicKey.data], all: [...this.publicKey.all] }, + signature: [...this.signature], + keyUsage: { + critical: this.keyUsage?.critical, + usages: [...this.keyUsage?.usages ?? []] + }, + subjectAltNames: this.subjectAltNames, + extKeyUsage: this.extKeyUsage, + authorityKeyIdentifier: this.authorityKeyIdentifier && [...this.authorityKeyIdentifier], + subjectKeyIdentifier: this.subjectKeyIdentifier && [...this.subjectKeyIdentifier], + basicConstraints: this.basicConstraints, + signedData: [ + ...this.signedData + ] + }; + } +}; +var st = class extends X { + static { + __name(this, "st"); + } +}; +async function pt(r2, e, t, i, n) { + r2.expectUint8(U, 0); + let [a] = r2.expectASN1Length(0); + r2.expectUint8( + tt, + 0 + ); + let [c, s] = r2.expectASN1Length(0), o = r2.readBytes(s()); + c(), r2.expectUint8(tt, 0); + let [h, y] = r2.expectASN1Length(0), d = r2.readBytes(y()); + h(), a(); + let m = /* @__PURE__ */ __name((u, x) => u.length > x ? u.subarray(u.length - x) : u.length < x ? p(new Uint8Array(x - u.length), u) : u, "m"), g = i === "P-256" ? 32 : 48, A = p(m(o, g), m(d, g)), L = await l.importKey( + "spki", + e, + { name: "ECDSA", namedCurve: i }, + false, + ["verify"] + ); + if (await l.verify({ name: "ECDSA", hash: n }, L, A, t) !== true) throw new Error( + "ECDSA-SECP256R1-SHA256 certificate verify failed" + ); +} +__name(pt, "pt"); +async function jt(r2, e, t, i = true, n = true) { + for (let h of e) ; + let a = e[0]; + if (a.subjectAltNameMatchingHost( + r2 + ) === void 0) throw new Error(`No matching subjectAltName for ${r2}`); + if (!a.isValidAtMoment()) + throw new Error("End-user certificate is not valid now"); + if (i && !a.extKeyUsage?.serverTls) + throw new Error("End-user certificate has no TLS server extKeyUsage"); + let o = false; + for (let h of t) + ; + for (let h = 0, y = e.length; h < y; h++) { + let d = e[h], m = d.authorityKeyIdentifier, g; + if (m === void 0 ? g = t.find((f) => X.distinguishedNamesAreEqual(f.subject, d.issuer)) : g = t.find((f) => f.subjectKeyIdentifier !== void 0 && O(f.subjectKeyIdentifier, m)), g === void 0 && (g = e[h + 1]), g === void 0) throw new Error("Ran out of certificates before reaching trusted root"); + let A = g instanceof st; + if (g.isValidAtMoment() !== true) throw new Error("Signing certificate is not valid now"); + if (n && g.keyUsage?.usages.has("digitalSignature") !== true) + throw new Error("Signing certificate keyUsage does not include digital signatures"); + if (g.basicConstraints?.ca !== true) throw new Error("Signing certificate basicConstraints do not indicate a CA certificate"); + let { pathLength: L } = g.basicConstraints; + if (L !== void 0 && L < h) throw new Error("Exceeded certificate pathLength"); + if (d.algorithm === "1.2.840.10045.4.3.2" || d.algorithm === "1.2.840.10045.4.3.3") { + let f = d.algorithm === "1.2.840.10045.4.3.2" ? "SHA-256" : "SHA-384", u = g.publicKey.identifiers, x = u.includes( + "1.2.840.10045.3.1.7" + ) ? "P-256" : u.includes("1.3.132.0.34") ? "P-384" : void 0; + if (x === void 0) throw new Error("Unsupported signing key curve"); + let T = new M(d.signature); + await pt(T, g.publicKey.all, d.signedData, x, f); + } else if (d.algorithm === "1.2.840.113549.1.1.11" || d.algorithm === "1.2.840.113549.1.1.12") { + let f = d.algorithm === "1.2.840.113549.1.1.11" ? "SHA-256" : "SHA-384", u = await l.importKey("spki", g.publicKey.all, { name: "RSASSA-PKCS1-v1_5", hash: f }, false, ["verify"]); + if (await l.verify({ name: "RSASSA-PKCS1-v1_5" }, u, d.signature, d.signedData) !== true) throw new Error("RSASSA_PKCS1-v1_5-SHA256 certificate verify failed"); + } else throw new Error("Unsupported signing algorithm"); + if (A) { + o = true; + break; + } + } + return o; +} +__name(jt, "jt"); +var oe = new TextEncoder(); +async function Vt(r2, e, t, i, n, a = true, c = true) { + let s = new M(await e()); + s.expectUint8(8, 0); + let [o] = s.expectLengthUint24(), [h, y] = s.expectLengthUint16(0); + for (; y() > 0; ) { + let R = s.readUint16(0); + if (R === 0) s.expectUint16(0, 0); + else if (R === 10) { + let [V, F] = s.expectLengthUint16("groups data"); + s.skip(F(), 0), V(); + } else throw new Error(`Unsupported server encrypted extension type 0x${K([R]).padStart(4, "0")}`); + } + h(), o(), s.remaining() === 0 && s.extend(await e()); + let d = false, m = s.readUint8(); + if (m === 13) { + d = true; + let [R] = s.expectLengthUint24( + "certificate request data" + ); + s.expectUint8(0, 0); + let [V, F] = s.expectLengthUint16("certificate request extensions"); + s.skip(F(), 0), V(), R(), s.remaining() === 0 && s.extend( + await e() + ), m = s.readUint8(); + } + if (m !== 11) throw new Error(`Unexpected handshake message type 0x${K([m])}`); + let [g] = s.expectLengthUint24(0); + s.expectUint8(0, 0); + let [A, L] = s.expectLengthUint24(0), f = []; + for (; L() > 0; ) { + let [R] = s.expectLengthUint24(0), V = new X(s); + f.push(V), R(); + let [F, et] = s.expectLengthUint16(), wt = s.subarray(et()); + F(); + } + if (A(), g(), f.length === 0) throw new Error("No certificates supplied"); + let u = f[0], x = s.data.subarray( + 0, + s.offset + ), T = p(i, x), $ = await l.digest("SHA-256", T), P = new Uint8Array($), q = p(oe.encode( + " ".repeat(64) + "TLS 1.3, server CertificateVerify" + ), [0], P); + s.remaining() === 0 && s.extend(await e()), s.expectUint8(15, 0); + let [G] = s.expectLengthUint24(0), D = s.readUint16(); + if (D === 1027) { + let [R] = s.expectLengthUint16(); + await pt( + s, + u.publicKey.all, + q, + "P-256", + "SHA-256" + ), R(); + } else if (D === 2052) { + let [R, V] = s.expectLengthUint16(), F = s.subarray(V()); + R(); + let et = await l.importKey("spki", u.publicKey.all, { name: "RSA-PSS", hash: "SHA-256" }, false, ["verify"]); + if (await l.verify({ name: "RSA-PSS", saltLength: 32 }, et, F, q) !== true) + throw new Error("RSA-PSS-RSAE-SHA256 certificate verify failed"); + } else throw new Error( + `Unsupported certificate verify signature type 0x${K([D]).padStart(4, "0")}` + ); + G(); + let H = s.data.subarray(0, s.offset), z = p(i, H), B = await S(t, "finished", new Uint8Array( + 0 + ), 32, 256), k = await l.digest("SHA-256", z), b = await l.importKey("raw", B, { + name: "HMAC", + hash: { name: "SHA-256" } + }, false, ["sign"]), C = await l.sign("HMAC", b, k), E = new Uint8Array( + C + ); + s.remaining() === 0 && s.extend(await e()), s.expectUint8(20, 0); + let [I, w] = s.expectLengthUint24( + 0 + ), j = s.readBytes(w()); + if (I(), s.remaining() !== 0) throw new Error("Unexpected extra bytes in server handshake"); + if (O(j, E) !== true) throw new Error("Invalid server verify hash"); + if (!await jt(r2, f, n, a, c)) throw new Error("Validated certificate chain did not end in a trusted root"); + return [s.data, d]; +} +__name(Vt, "Vt"); +async function he(r2, e, t, i, { + useSNI: n, + requireServerTlsExtKeyUsage: a, + requireDigitalSigKeyUsage: c, + writePreData: s, + expectPreData: o, + commentPreData: h +} = {}) { + n ??= true, a ??= true, c ??= true; + let y = await l.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, ["deriveKey", "deriveBits"]), d = await l.exportKey("raw", y.publicKey), m = new Uint8Array(32); + crypto.getRandomValues(m); + let A = St( + r2, + d, + m, + n + ).array(), L = s ? p(s, A) : A; + if (i(L), o) { + let v = await t(o.length); + if (!v || !O(v, o)) + throw new Error("Pre data did not match expectation"); + } + let f = await ht(t, 22); + if (f === void 0) throw new Error("Connection closed while awaiting server hello"); + let u = new N( + f.content + ), x = Ut(u, m), T = await ht(t, 20); + if (T === void 0) throw new Error("Connection closed awaiting server cipher change"); + let $ = new N(T.content), [P] = $.expectLength( + 1 + ); + $.expectUint8(1, 0), P(); + let q = A.subarray(5), G = f.content, D = p(q, G), H = await Kt( + x, + y.privateKey, + D, + 256, + 16 + ), z = await l.importKey("raw", H.serverHandshakeKey, { name: "AES-GCM" }, false, ["decrypt"]), B = new Z("decrypt", z, H.serverHandshakeIV), k = await l.importKey( + "raw", + H.clientHandshakeKey, + { name: "AES-GCM" }, + false, + ["encrypt"] + ), b = new Z( + "encrypt", + k, + H.clientHandshakeIV + ), C = /* @__PURE__ */ __name(async () => { + let v = await dt(t, B, 22); + if (v === void 0) throw new Error( + "Premature end of encrypted server handshake" + ); + return v; + }, "C"), [E, I] = await Vt( + r2, + C, + H.serverSecret, + D, + e, + a, + c + ), w = new N(6); + w.writeUint8(20, 0), w.writeUint16(771, 0); + let j = w.writeLengthUint16(); + w.writeUint8(1, 0), j(); + let J = w.array(), Y = new Uint8Array(0); + if (I) { + let v = new N(8); + v.writeUint8(11, 0); + let nt = v.writeLengthUint24("client certificate data"); + v.writeUint8( + 0, + 0 + ), v.writeUint24(0, 0), nt(), Y = v.array(); + } + let R = p(D, E, Y), V = await l.digest("SHA-256", R), F = new Uint8Array(V), et = await S( + H.clientSecret, + "finished", + new Uint8Array(0), + 32, + 256 + ), wt = await l.importKey("raw", et, { name: "HMAC", hash: { name: "SHA-256" } }, false, ["sign"]), Mt = await l.sign("HMAC", wt, F), _t = new Uint8Array(Mt), at = new N(36); + at.writeUint8( + 20, + 0 + ); + let Gt = at.writeLengthUint24(0); + at.writeBytes(_t), Gt(); + let zt = at.array(), kt = await At( + p(Y, zt), + b, + 22 + ), Et = F; + if (Y.length > 0) { + let v = R.subarray(0, R.length - Y.length), nt = await l.digest("SHA-256", v); + Et = new Uint8Array(nt); + } + let ct = await Tt( + H.handshakeSecret, + Et, + 256, + 16 + ), Jt = await l.importKey("raw", ct.clientApplicationKey, { name: "AES-GCM" }, true, ["encrypt"]), Zt = new Z("encrypt", Jt, ct.clientApplicationIV), Qt = await l.importKey( + "raw", + ct.serverApplicationKey, + { name: "AES-GCM" }, + true, + ["decrypt"] + ), Wt = new Z("decrypt", Qt, ct.serverApplicationIV), ot = false; + return [() => { + if (!ot) { + let v = p(J, ...kt); + i(v), ot = true; + } + return dt( + t, + Wt + ); + }, async (v) => { + let nt = ot; + ot = true; + let It = await At(v, Zt, 23), Xt = nt ? p(...It) : p( + J, + ...kt, + ...It + ); + i(Xt); + }]; +} +__name(he, "he"); +var xt = class { + static { + __name(this, "xt"); + } + queue; + outstandingRequest; + constructor() { + this.queue = []; + } + enqueue(e) { + this.queue.push(e), this.dequeue(); + } + dequeue() { + if (this.outstandingRequest === void 0) return; + let { resolve: e, bytes: t } = this.outstandingRequest, i = this.bytesInQueue(); + if (i < t && this.socketIsNotClosed()) return; + if (t = Math.min(t, i), t === 0) return e(void 0); + this.outstandingRequest = void 0; + let n = this.queue[0], a = n.length; + if (a === t) return this.queue.shift(), e(n); + if (a > t) return this.queue[0] = n.subarray(t), e(n.subarray(0, t)); + { + let c = new Uint8Array(t), s = t, o = 0; + for (; s > 0; ) { + let h = this.queue[0], y = h.length; + y <= s ? (this.queue.shift(), c.set( + h, + o + ), o += y, s -= y) : (this.queue[0] = h.subarray(s), c.set(h.subarray(0, s), o), s -= s, o += s); + } + return e(c); + } + } + bytesInQueue() { + return this.queue.reduce((e, t) => e + t.length, 0); + } + async read(e) { + if (this.outstandingRequest !== void 0) throw new Error("Can\u2019t read while already awaiting read"); + return new Promise((t) => { + this.outstandingRequest = { resolve: t, bytes: e }, this.dequeue(); + }); + } +}; +var vt = class extends xt { + static { + __name(this, "vt"); + } + constructor(t) { + super(); + this.socket = t; + t.addEventListener( + "message", + (i) => this.enqueue(new Uint8Array(i.data)) + ), t.addEventListener("close", () => this.dequeue()); + } + socketIsNotClosed() { + let { socket: t } = this, { readyState: i } = t; + return i <= 1; + } +}; +var Lt = class extends xt { + static { + __name(this, "Lt"); + } + constructor(t) { + super(); + this.socket = t; + t.on("data", (i) => this.enqueue( + new Uint8Array(i) + )), t.on("close", () => this.dequeue()); + } + socketIsNotClosed() { + let { socket: t } = this, { readyState: i } = t; + return i === "opening" || i === "open"; + } +}; + +// src/isrgrootx1.pem +var isrgrootx1_default = "-----BEGIN CERTIFICATE-----\nMIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\nTzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\ncmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\nWhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\nZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\nMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\nh77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\nA5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\nT8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\nB5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\nB5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\nKBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\nOlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\njh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\nqHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\nrU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\nHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\nhkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\nubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\nNFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\nORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\nTkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\njNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\noyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\nmRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\nemyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n-----END CERTIFICATE-----\n"; + +// node_modules/fast-equals/dist/esm/index.mjs +init_shims(); +var getOwnPropertyNames = Object.getOwnPropertyNames; +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +function combineComparators(comparatorA, comparatorB) { + return /* @__PURE__ */ __name(function isEqual(a, b, state) { + return comparatorA(a, b, state) && comparatorB(a, b, state); + }, "isEqual"); +} +__name(combineComparators, "combineComparators"); +function createIsCircular(areItemsEqual) { + return /* @__PURE__ */ __name(function isCircular(a, b, state) { + if (!a || !b || typeof a !== "object" || typeof b !== "object") { + return areItemsEqual(a, b, state); + } + var cache = state.cache; + var cachedA = cache.get(a); + var cachedB = cache.get(b); + if (cachedA && cachedB) { + return cachedA === b && cachedB === a; + } + cache.set(a, b); + cache.set(b, a); + var result = areItemsEqual(a, b, state); + cache.delete(a); + cache.delete(b); + return result; + }, "isCircular"); +} +__name(createIsCircular, "createIsCircular"); +function getStrictProperties(object) { + return getOwnPropertyNames(object).concat(getOwnPropertySymbols(object)); +} +__name(getStrictProperties, "getStrictProperties"); +var hasOwn = Object.hasOwn || function(object, property) { + return hasOwnProperty.call(object, property); +}; +function sameValueZeroEqual(a, b) { + return a || b ? a === b : a === b || a !== a && b !== b; +} +__name(sameValueZeroEqual, "sameValueZeroEqual"); +var OWNER = "_owner"; +var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +var keys = Object.keys; +function areArraysEqual(a, b, state) { + var index = a.length; + if (b.length !== index) { + return false; + } + while (index-- > 0) { + if (!state.equals(a[index], b[index], index, index, a, b, state)) { + return false; + } + } + return true; +} +__name(areArraysEqual, "areArraysEqual"); +function areDatesEqual(a, b) { + return sameValueZeroEqual(a.getTime(), b.getTime()); +} +__name(areDatesEqual, "areDatesEqual"); +function areMapsEqual(a, b, state) { + if (a.size !== b.size) { + return false; + } + var matchedIndices = {}; + var aIterable = a.entries(); + var index = 0; + var aResult; + var bResult; + while (aResult = aIterable.next()) { + if (aResult.done) { + break; + } + var bIterable = b.entries(); + var hasMatch = false; + var matchIndex = 0; + while (bResult = bIterable.next()) { + if (bResult.done) { + break; + } + var _a = aResult.value, aKey = _a[0], aValue = _a[1]; + var _b = bResult.value, bKey = _b[0], bValue = _b[1]; + if (!hasMatch && !matchedIndices[matchIndex] && (hasMatch = state.equals(aKey, bKey, index, matchIndex, a, b, state) && state.equals(aValue, bValue, aKey, bKey, a, b, state))) { + matchedIndices[matchIndex] = true; + } + matchIndex++; + } + if (!hasMatch) { + return false; + } + index++; + } + return true; +} +__name(areMapsEqual, "areMapsEqual"); +function areObjectsEqual(a, b, state) { + var properties = keys(a); + var index = properties.length; + if (keys(b).length !== index) { + return false; + } + var property; + while (index-- > 0) { + property = properties[index]; + if (property === OWNER && (a.$$typeof || b.$$typeof) && a.$$typeof !== b.$$typeof) { + return false; + } + if (!hasOwn(b, property) || !state.equals(a[property], b[property], property, property, a, b, state)) { + return false; + } + } + return true; +} +__name(areObjectsEqual, "areObjectsEqual"); +function areObjectsEqualStrict(a, b, state) { + var properties = getStrictProperties(a); + var index = properties.length; + if (getStrictProperties(b).length !== index) { + return false; + } + var property; + var descriptorA; + var descriptorB; + while (index-- > 0) { + property = properties[index]; + if (property === OWNER && (a.$$typeof || b.$$typeof) && a.$$typeof !== b.$$typeof) { + return false; + } + if (!hasOwn(b, property)) { + return false; + } + if (!state.equals(a[property], b[property], property, property, a, b, state)) { + return false; + } + descriptorA = getOwnPropertyDescriptor(a, property); + descriptorB = getOwnPropertyDescriptor(b, property); + if ((descriptorA || descriptorB) && (!descriptorA || !descriptorB || descriptorA.configurable !== descriptorB.configurable || descriptorA.enumerable !== descriptorB.enumerable || descriptorA.writable !== descriptorB.writable)) { + return false; + } + } + return true; +} +__name(areObjectsEqualStrict, "areObjectsEqualStrict"); +function arePrimitiveWrappersEqual(a, b) { + return sameValueZeroEqual(a.valueOf(), b.valueOf()); +} +__name(arePrimitiveWrappersEqual, "arePrimitiveWrappersEqual"); +function areRegExpsEqual(a, b) { + return a.source === b.source && a.flags === b.flags; +} +__name(areRegExpsEqual, "areRegExpsEqual"); +function areSetsEqual(a, b, state) { + if (a.size !== b.size) { + return false; + } + var matchedIndices = {}; + var aIterable = a.values(); + var aResult; + var bResult; + while (aResult = aIterable.next()) { + if (aResult.done) { + break; + } + var bIterable = b.values(); + var hasMatch = false; + var matchIndex = 0; + while (bResult = bIterable.next()) { + if (bResult.done) { + break; + } + if (!hasMatch && !matchedIndices[matchIndex] && (hasMatch = state.equals(aResult.value, bResult.value, aResult.value, bResult.value, a, b, state))) { + matchedIndices[matchIndex] = true; + } + matchIndex++; + } + if (!hasMatch) { + return false; + } + } + return true; +} +__name(areSetsEqual, "areSetsEqual"); +function areTypedArraysEqual(a, b) { + var index = a.length; + if (b.length !== index) { + return false; + } + while (index-- > 0) { + if (a[index] !== b[index]) { + return false; + } + } + return true; +} +__name(areTypedArraysEqual, "areTypedArraysEqual"); +var ARGUMENTS_TAG = "[object Arguments]"; +var BOOLEAN_TAG = "[object Boolean]"; +var DATE_TAG = "[object Date]"; +var MAP_TAG = "[object Map]"; +var NUMBER_TAG = "[object Number]"; +var OBJECT_TAG = "[object Object]"; +var REG_EXP_TAG = "[object RegExp]"; +var SET_TAG = "[object Set]"; +var STRING_TAG = "[object String]"; +var isArray = Array.isArray; +var isTypedArray = typeof ArrayBuffer === "function" && ArrayBuffer.isView ? ArrayBuffer.isView : null; +var assign = Object.assign; +var getTag = Object.prototype.toString.call.bind(Object.prototype.toString); +function createEqualityComparator(_a) { + var areArraysEqual2 = _a.areArraysEqual, areDatesEqual2 = _a.areDatesEqual, areMapsEqual2 = _a.areMapsEqual, areObjectsEqual2 = _a.areObjectsEqual, arePrimitiveWrappersEqual2 = _a.arePrimitiveWrappersEqual, areRegExpsEqual2 = _a.areRegExpsEqual, areSetsEqual2 = _a.areSetsEqual, areTypedArraysEqual2 = _a.areTypedArraysEqual; + return /* @__PURE__ */ __name(function comparator(a, b, state) { + if (a === b) { + return true; + } + if (a == null || b == null || typeof a !== "object" || typeof b !== "object") { + return a !== a && b !== b; + } + var constructor = a.constructor; + if (constructor !== b.constructor) { + return false; + } + if (constructor === Object) { + return areObjectsEqual2(a, b, state); + } + if (isArray(a)) { + return areArraysEqual2(a, b, state); + } + if (isTypedArray != null && isTypedArray(a)) { + return areTypedArraysEqual2(a, b, state); + } + if (constructor === Date) { + return areDatesEqual2(a, b, state); + } + if (constructor === RegExp) { + return areRegExpsEqual2(a, b, state); + } + if (constructor === Map) { + return areMapsEqual2(a, b, state); + } + if (constructor === Set) { + return areSetsEqual2(a, b, state); + } + var tag = getTag(a); + if (tag === DATE_TAG) { + return areDatesEqual2(a, b, state); + } + if (tag === REG_EXP_TAG) { + return areRegExpsEqual2(a, b, state); + } + if (tag === MAP_TAG) { + return areMapsEqual2(a, b, state); + } + if (tag === SET_TAG) { + return areSetsEqual2(a, b, state); + } + if (tag === OBJECT_TAG) { + return typeof a.then !== "function" && typeof b.then !== "function" && areObjectsEqual2(a, b, state); + } + if (tag === ARGUMENTS_TAG) { + return areObjectsEqual2(a, b, state); + } + if (tag === BOOLEAN_TAG || tag === NUMBER_TAG || tag === STRING_TAG) { + return arePrimitiveWrappersEqual2(a, b, state); + } + return false; + }, "comparator"); +} +__name(createEqualityComparator, "createEqualityComparator"); +function createEqualityComparatorConfig(_a) { + var circular = _a.circular, createCustomConfig = _a.createCustomConfig, strict = _a.strict; + var config = { + areArraysEqual: strict ? areObjectsEqualStrict : areArraysEqual, + areDatesEqual, + areMapsEqual: strict ? combineComparators(areMapsEqual, areObjectsEqualStrict) : areMapsEqual, + areObjectsEqual: strict ? areObjectsEqualStrict : areObjectsEqual, + arePrimitiveWrappersEqual, + areRegExpsEqual, + areSetsEqual: strict ? combineComparators(areSetsEqual, areObjectsEqualStrict) : areSetsEqual, + areTypedArraysEqual: strict ? areObjectsEqualStrict : areTypedArraysEqual + }; + if (createCustomConfig) { + config = assign({}, config, createCustomConfig(config)); + } + if (circular) { + var areArraysEqual$1 = createIsCircular(config.areArraysEqual); + var areMapsEqual$1 = createIsCircular(config.areMapsEqual); + var areObjectsEqual$1 = createIsCircular(config.areObjectsEqual); + var areSetsEqual$1 = createIsCircular(config.areSetsEqual); + config = assign({}, config, { + areArraysEqual: areArraysEqual$1, + areMapsEqual: areMapsEqual$1, + areObjectsEqual: areObjectsEqual$1, + areSetsEqual: areSetsEqual$1 + }); + } + return config; +} +__name(createEqualityComparatorConfig, "createEqualityComparatorConfig"); +function createInternalEqualityComparator(compare) { + return function(a, b, _indexOrKeyA, _indexOrKeyB, _parentA, _parentB, state) { + return compare(a, b, state); + }; +} +__name(createInternalEqualityComparator, "createInternalEqualityComparator"); +function createIsEqual(_a) { + var circular = _a.circular, comparator = _a.comparator, createState = _a.createState, equals = _a.equals, strict = _a.strict; + if (createState) { + return /* @__PURE__ */ __name(function isEqual(a, b) { + var _a2 = createState(), _b = _a2.cache, cache = _b === void 0 ? circular ? /* @__PURE__ */ new WeakMap() : void 0 : _b, meta = _a2.meta; + return comparator(a, b, { + cache, + equals, + meta, + strict + }); + }, "isEqual"); + } + if (circular) { + return /* @__PURE__ */ __name(function isEqual(a, b) { + return comparator(a, b, { + cache: /* @__PURE__ */ new WeakMap(), + equals, + meta: void 0, + strict + }); + }, "isEqual"); + } + var state = { + cache: void 0, + equals, + meta: void 0, + strict + }; + return /* @__PURE__ */ __name(function isEqual(a, b) { + return comparator(a, b, state); + }, "isEqual"); +} +__name(createIsEqual, "createIsEqual"); +var deepEqual = createCustomEqual(); +var strictDeepEqual = createCustomEqual({ strict: true }); +var circularDeepEqual = createCustomEqual({ circular: true }); +var strictCircularDeepEqual = createCustomEqual({ + circular: true, + strict: true +}); +var shallowEqual = createCustomEqual({ + createInternalComparator: /* @__PURE__ */ __name(function() { + return sameValueZeroEqual; + }, "createInternalComparator") +}); +var strictShallowEqual = createCustomEqual({ + strict: true, + createInternalComparator: /* @__PURE__ */ __name(function() { + return sameValueZeroEqual; + }, "createInternalComparator") +}); +var circularShallowEqual = createCustomEqual({ + circular: true, + createInternalComparator: /* @__PURE__ */ __name(function() { + return sameValueZeroEqual; + }, "createInternalComparator") +}); +var strictCircularShallowEqual = createCustomEqual({ + circular: true, + createInternalComparator: /* @__PURE__ */ __name(function() { + return sameValueZeroEqual; + }, "createInternalComparator"), + strict: true +}); +function createCustomEqual(options) { + if (options === void 0) { + options = {}; + } + var _a = options.circular, circular = _a === void 0 ? false : _a, createCustomInternalComparator = options.createInternalComparator, createState = options.createState, _b = options.strict, strict = _b === void 0 ? false : _b; + var config = createEqualityComparatorConfig(options); + var comparator = createEqualityComparator(config); + var equals = createCustomInternalComparator ? createCustomInternalComparator(comparator) : createInternalEqualityComparator(comparator); + return createIsEqual({ circular, comparator, createState, equals, strict }); +} +__name(createCustomEqual, "createCustomEqual"); + +// export/index.ts +init_shims(); +var import_pg = __toESM(require_lib2()); +init_net(); + +// export/httpQuery.ts +init_shims(); +init_url(); +init_net(); +var import_utils = __toESM(require_utils()); +var import_type_overrides = __toESM(require_type_overrides()); +var NeonDbError = class extends Error { + static { + __name(this, "NeonDbError"); + } + name = "NeonDbError"; + severity; + code; + detail; + hint; + position; + internalPosition; + internalQuery; + where; + schema; + table; + column; + dataType; + constraint; + file; + line; + routine; + sourceError; +}; +var txnArgErrMsg = "transaction() expects an array of queries, or a function returning an array of queries"; +var errorFields = [ + "severity", + "code", + "detail", + "hint", + "position", + "internalPosition", + "internalQuery", + "where", + "schema", + "table", + "column", + "dataType", + "constraint", + "file", + "line", + "routine" +]; +function neon(connectionString, { + arrayMode: neonOptArrayMode, + fullResults: neonOptFullResults, + fetchOptions: neonOptFetchOptions, + isolationLevel: neonOptIsolationLevel, + readOnly: neonOptReadOnly, + deferrable: neonOptDeferrable, + queryCallback, + resultCallback, + authToken +} = {}) { + if (!connectionString) + throw new Error( + "No database connection string was provided to `neon()`. Perhaps an environment variable has not been set?" + ); + let db; + try { + db = parse(connectionString); + } catch { + throw new Error( + "Database connection string provided to `neon()` is not a valid URL. Connection string: " + String(connectionString) + ); + } + const { protocol, username, password, hostname, port, pathname } = db; + if (protocol !== "postgres:" && protocol !== "postgresql:" || !username || !hostname || !pathname) { + throw new Error( + "Database connection string format for `neon()` should be: postgresql://user:password@host.tld/dbname?option=value" + ); + } + function resolve(strings, ...params) { + let query; + let queryOpts; + if (typeof strings === "string") { + query = strings; + queryOpts = params[1]; + params = params[0] ?? []; + } else { + query = ""; + for (let i = 0; i < strings.length; i++) { + query += strings[i]; + if (i < params.length) query += "$" + (i + 1); + } + } + params = params.map((param) => (0, import_utils.prepareValue)(param)); + const parameterizedQuery = { query, params }; + if (queryCallback) queryCallback(parameterizedQuery); + return createNeonQueryPromise(execute, parameterizedQuery, queryOpts); + } + __name(resolve, "resolve"); + resolve.transaction = async (queries2, txnOpts) => { + if (typeof queries2 === "function") queries2 = queries2(resolve); + if (!Array.isArray(queries2)) throw new Error(txnArgErrMsg); + queries2.forEach((query) => { + if (query[Symbol.toStringTag] !== "NeonQueryPromise") + throw new Error(txnArgErrMsg); + }); + const parameterizedQueries = queries2.map( + (query) => query.parameterizedQuery + ); + const opts = queries2.map((query) => query.opts ?? {}); + return execute(parameterizedQueries, opts, txnOpts); + }; + async function execute(parameterizedQuery, allSqlOpts, txnOpts) { + const { fetchEndpoint, fetchFunction } = Socket; + const url = typeof fetchEndpoint === "function" ? fetchEndpoint(hostname, port, { + jwtAuth: authToken !== void 0 + }) : fetchEndpoint; + const bodyData = Array.isArray(parameterizedQuery) ? { queries: parameterizedQuery } : parameterizedQuery; + let resolvedFetchOptions = neonOptFetchOptions ?? {}; + let resolvedArrayMode = neonOptArrayMode ?? false; + let resolvedFullResults = neonOptFullResults ?? false; + let resolvedIsolationLevel = neonOptIsolationLevel; + let resolvedReadOnly = neonOptReadOnly; + let resolvedDeferrable = neonOptDeferrable; + if (txnOpts !== void 0) { + if (txnOpts.fetchOptions !== void 0) + resolvedFetchOptions = { + ...resolvedFetchOptions, + ...txnOpts.fetchOptions + }; + if (txnOpts.arrayMode !== void 0) + resolvedArrayMode = txnOpts.arrayMode; + if (txnOpts.fullResults !== void 0) + resolvedFullResults = txnOpts.fullResults; + if (txnOpts.isolationLevel !== void 0) + resolvedIsolationLevel = txnOpts.isolationLevel; + if (txnOpts.readOnly !== void 0) resolvedReadOnly = txnOpts.readOnly; + if (txnOpts.deferrable !== void 0) + resolvedDeferrable = txnOpts.deferrable; + } + if (allSqlOpts !== void 0 && !Array.isArray(allSqlOpts) && allSqlOpts.fetchOptions !== void 0) { + resolvedFetchOptions = { + ...resolvedFetchOptions, + ...allSqlOpts.fetchOptions + }; + } + const headers = { + "Neon-Connection-String": connectionString, + "Neon-Raw-Text-Output": "true", + // because we do our own parsing with node-postgres + "Neon-Array-Mode": "true" + // this saves data and post-processing even if we return objects, not arrays + }; + if (typeof authToken === "string") { + headers["Authorization"] = `Bearer ${authToken}`; + } else if (typeof authToken === "function") { + headers["Authorization"] = `Bearer ${Promise.resolve(authToken())}`; + } + if (Array.isArray(parameterizedQuery)) { + if (resolvedIsolationLevel !== void 0) + headers["Neon-Batch-Isolation-Level"] = resolvedIsolationLevel; + if (resolvedReadOnly !== void 0) + headers["Neon-Batch-Read-Only"] = String(resolvedReadOnly); + if (resolvedDeferrable !== void 0) + headers["Neon-Batch-Deferrable"] = String(resolvedDeferrable); + } + let response; + try { + response = await (fetchFunction ?? fetch)(url, { + method: "POST", + body: JSON.stringify(bodyData), + // TODO: use json-custom-numbers to allow BigInts? + headers, + ...resolvedFetchOptions + // this is last, so it gets the final say + }); + } catch (err) { + const connectErr = new NeonDbError( + `Error connecting to database: ${err.message}` + ); + connectErr.sourceError = err; + throw connectErr; + } + if (response.ok) { + const rawResults = await response.json(); + if (Array.isArray(parameterizedQuery)) { + const resultArray = rawResults.results; + if (!Array.isArray(resultArray)) + throw new NeonDbError( + "Neon internal error: unexpected result format" + ); + return resultArray.map((result, i) => { + let sqlOpts = allSqlOpts[i] ?? {}; + let arrayMode = sqlOpts.arrayMode ?? resolvedArrayMode; + let fullResults = sqlOpts.fullResults ?? resolvedFullResults; + return processQueryResult(result, { + arrayMode, + fullResults, + parameterizedQuery: parameterizedQuery[i], + resultCallback, + types: sqlOpts.types + }); + }); + } else { + let sqlOpts = allSqlOpts ?? {}; + let arrayMode = sqlOpts.arrayMode ?? resolvedArrayMode; + let fullResults = sqlOpts.fullResults ?? resolvedFullResults; + return processQueryResult(rawResults, { + arrayMode, + fullResults, + parameterizedQuery, + resultCallback, + types: sqlOpts.types + }); + } + } else { + const { status } = response; + if (status === 400) { + const json = await response.json(); + const dbError = new NeonDbError(json.message); + for (const field of errorFields) + dbError[field] = json[field] ?? void 0; + throw dbError; + } else { + const text = await response.text(); + throw new NeonDbError(`Server error (HTTP status ${status}): ${text}`); + } + } + } + __name(execute, "execute"); + return resolve; +} +__name(neon, "neon"); +function createNeonQueryPromise(execute, parameterizedQuery, opts) { + return { + [Symbol.toStringTag]: "NeonQueryPromise", + parameterizedQuery, + opts, + then: /* @__PURE__ */ __name((resolve, reject) => execute(parameterizedQuery, opts).then(resolve, reject), "then"), + catch: /* @__PURE__ */ __name((reject) => execute(parameterizedQuery, opts).catch(reject), "catch"), + finally: /* @__PURE__ */ __name((finallyFn) => execute(parameterizedQuery, opts).finally(finallyFn), "finally") + }; +} +__name(createNeonQueryPromise, "createNeonQueryPromise"); +function processQueryResult(rawResults, { + arrayMode, + fullResults, + parameterizedQuery, + resultCallback, + types: customTypes +}) { + const types2 = new import_type_overrides.default(customTypes); + const colNames = rawResults.fields.map((field) => field.name); + const parsers = rawResults.fields.map( + (field) => types2.getTypeParser(field.dataTypeID) + ); + const rows = arrayMode === true ? ( + // maintain array-of-arrays structure + rawResults.rows.map( + (row) => row.map( + (col, i) => col === null ? null : parsers[i](col) + ) + ) + ) : ( + // turn into an object + rawResults.rows.map((row) => { + return Object.fromEntries( + row.map((col, i) => [ + colNames[i], + col === null ? null : parsers[i](col) + ]) + ); + }) + ); + if (resultCallback) + resultCallback(parameterizedQuery, rawResults, rows, { + arrayMode, + fullResults + }); + if (fullResults) { + rawResults.viaNeonFetch = true; + rawResults.rowAsArray = arrayMode; + rawResults.rows = rows; + rawResults._parsers = parsers; + rawResults._types = types2; + return rawResults; + } + return rows; +} +__name(processQueryResult, "processQueryResult"); + +// export/index.ts +var import_connection_parameters = __toESM(require_connection_parameters()); +var import_pg2 = __toESM(require_lib2()); +var NeonClient = class extends import_pg.Client { + constructor(config) { + super(config); + this.config = config; + } + static { + __name(this, "NeonClient"); + } + get neonConfig() { + return this.connection.stream; + } + connect(callback) { + const { neonConfig } = this; + if (neonConfig.forceDisablePgSSL) { + this.ssl = this.connection.ssl = false; + } + if (this.ssl && neonConfig.useSecureWebSocket) { + console.warn( + `SSL is enabled for both Postgres (e.g. ?sslmode=require in the connection string + forceDisablePgSSL = false) and the WebSocket tunnel (useSecureWebSocket = true). Double encryption will increase latency and CPU usage. It may be appropriate to disable SSL in the Postgres connection parameters or set forceDisablePgSSL = true.` + ); + } + const hasConfiguredHost = this.config?.host !== void 0 || this.config?.connectionString !== void 0 || process.env.PGHOST !== void 0; + const defaultUser = process.env.USER ?? process.env.USERNAME; + if (!hasConfiguredHost && this.host === "localhost" && this.user === defaultUser && this.database === defaultUser && this.password === null) + throw new Error( + `No database host or connection string was set, and key parameters have default values (host: localhost, user: ${defaultUser}, db: ${defaultUser}, password: null). Is an environment variable missing? Alternatively, if you intended to connect with these parameters, please set the host to 'localhost' explicitly.` + ); + const result = super.connect(callback); + const pipelineTLS = neonConfig.pipelineTLS && this.ssl; + const pipelineConnect = neonConfig.pipelineConnect === "password"; + if (!pipelineTLS && !neonConfig.pipelineConnect) return result; + const con = this.connection; + if (pipelineTLS) { + con.on("connect", () => con.stream.emit("data", "S")); + } + if (pipelineConnect) { + con.removeAllListeners("authenticationCleartextPassword"); + con.removeAllListeners("readyForQuery"); + con.once( + "readyForQuery", + () => con.on("readyForQuery", this._handleReadyForQuery.bind(this)) + ); + const connectEvent = this.ssl ? "sslconnect" : "connect"; + con.on(connectEvent, () => { + this._handleAuthCleartextPassword(); + this._handleReadyForQuery(); + }); + } + return result; + } + async _handleAuthSASLContinue(msg) { + const session = this.saslSession; + const password = this.password; + const serverData = msg.data; + if (session.message !== "SASLInitialResponse" || typeof password !== "string" || typeof serverData !== "string") + throw new Error("SASL: protocol error"); + const attrPairs = Object.fromEntries( + serverData.split(",").map((attrValue) => { + if (!/^.=/.test(attrValue)) + throw new Error("SASL: Invalid attribute pair entry"); + const name = attrValue[0]; + const value = attrValue.substring(2); + return [name, value]; + }) + ); + const nonce = attrPairs.r; + const salt = attrPairs.s; + const iterationText = attrPairs.i; + if (!nonce || !/^[!-+--~]+$/.test(nonce)) + throw new Error( + "SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing/unprintable" + ); + if (!salt || !/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test( + salt + )) + throw new Error( + "SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing/not base64" + ); + if (!iterationText || !/^[1-9][0-9]*$/.test(iterationText)) + throw new Error( + "SASL: SCRAM-SERVER-FIRST-MESSAGE: missing/invalid iteration count" + ); + if (!nonce.startsWith(session.clientNonce)) + throw new Error( + "SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce" + ); + if (nonce.length === session.clientNonce.length) + throw new Error( + "SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short" + ); + const iterations = parseInt(iterationText, 10); + const saltBytes = Buffer2.from(salt, "base64"); + const enc = new TextEncoder(); + const passwordBytes = enc.encode(password); + const iterHmacKey = await crypto.subtle.importKey( + "raw", + passwordBytes, + { name: "HMAC", hash: { name: "SHA-256" } }, + false, + ["sign"] + ); + let ui1 = new Uint8Array( + await crypto.subtle.sign( + "HMAC", + iterHmacKey, + Buffer2.concat([saltBytes, Buffer2.from([0, 0, 0, 1])]) + ) + ); + let ui = ui1; + for (var i = 0; i < iterations - 1; i++) { + ui1 = new Uint8Array(await crypto.subtle.sign("HMAC", iterHmacKey, ui1)); + ui = Buffer2.from(ui.map((_2, i2) => ui[i2] ^ ui1[i2])); + } + const saltedPassword = ui; + const ckHmacKey = await crypto.subtle.importKey( + "raw", + saltedPassword, + { name: "HMAC", hash: { name: "SHA-256" } }, + false, + ["sign"] + ); + const clientKey = new Uint8Array( + await crypto.subtle.sign("HMAC", ckHmacKey, enc.encode("Client Key")) + ); + const storedKey = await crypto.subtle.digest("SHA-256", clientKey); + const clientFirstMessageBare = "n=*,r=" + session.clientNonce; + const serverFirstMessage = "r=" + nonce + ",s=" + salt + ",i=" + iterations; + const clientFinalMessageWithoutProof = "c=biws,r=" + nonce; + const authMessage = clientFirstMessageBare + "," + serverFirstMessage + "," + clientFinalMessageWithoutProof; + const csHmacKey = await crypto.subtle.importKey( + "raw", + storedKey, + { name: "HMAC", hash: { name: "SHA-256" } }, + false, + ["sign"] + ); + var clientSignature = new Uint8Array( + await crypto.subtle.sign("HMAC", csHmacKey, enc.encode(authMessage)) + ); + var clientProofBytes = Buffer2.from( + clientKey.map((_2, i2) => clientKey[i2] ^ clientSignature[i2]) + ); + var clientProof = clientProofBytes.toString("base64"); + const skHmacKey = await crypto.subtle.importKey( + "raw", + saltedPassword, + { name: "HMAC", hash: { name: "SHA-256" } }, + false, + ["sign"] + ); + const serverKey = await crypto.subtle.sign( + "HMAC", + skHmacKey, + enc.encode("Server Key") + ); + const ssbHmacKey = await crypto.subtle.importKey( + "raw", + serverKey, + { name: "HMAC", hash: { name: "SHA-256" } }, + false, + ["sign"] + ); + var serverSignatureBytes = Buffer2.from( + await crypto.subtle.sign("HMAC", ssbHmacKey, enc.encode(authMessage)) + ); + session.message = "SASLResponse"; + session.serverSignature = serverSignatureBytes.toString("base64"); + session.response = clientFinalMessageWithoutProof + ",p=" + clientProof; + this.connection.sendSCRAMClientFinalMessage(this.saslSession.response); + } +}; +function promisify(Promise2, callback) { + if (callback) return { callback, result: void 0 }; + let rej, res; + const cb = /* @__PURE__ */ __name(function(err, client) { + err ? rej(err) : res(client); + }, "cb"); + const result = new Promise2(function(resolve, reject) { + res = resolve; + rej = reject; + }); + return { callback: cb, result }; +} +__name(promisify, "promisify"); +var NeonPool = class extends import_pg.Pool { + static { + __name(this, "NeonPool"); + } + Client = NeonClient; + hasFetchUnsupportedListeners = false; + on(event, listener) { + if (event !== "error") this.hasFetchUnsupportedListeners = true; + return super.on(event, listener); + } + // @ts-ignore -- is it even possible to make TS happy with these overloaded function types? + query(config, values, cb) { + if (!Socket.poolQueryViaFetch || this.hasFetchUnsupportedListeners || typeof config === "function") { + return super.query(config, values, cb); + } + if (typeof values === "function") { + cb = values; + values = void 0; + } + const response = promisify(this.Promise, cb); + cb = response.callback; + try { + const cp = new import_connection_parameters.default( + this.options + ); + const euc = encodeURIComponent, eu = encodeURI; + const connectionString = `postgresql://${euc(cp.user)}:${euc(cp.password)}@${euc(cp.host)}/${eu(cp.database)}`; + const queryText = typeof config === "string" ? config : config.text; + const queryValues = values ?? config.values ?? []; + const sql = neon(connectionString, { + fullResults: true, + arrayMode: config.rowMode === "array" + }); + sql(queryText, queryValues, { + types: config.types ?? this.options?.types + }).then((result) => cb(void 0, result)).catch((err) => cb(err)); + } catch (err) { + cb(err); + } + return response.result; + } +}; + +// src/util.ts +init_shims(); +async function timed(f) { + const t0 = Date.now(); + const result = await f(); + const t = Date.now() - t0; + return [t, result]; +} +__name(timed, "timed"); +async function timedRepeats(n, f, timeListener = (ms, result) => { +}) { + const results = []; + for (let i = 0; i < n; i++) { + const tPlusResult = await timed(f); + const [t, result] = tPlusResult; + timeListener(t, result); + results.push(tPlusResult); + } + const total = results.reduce((memo, [t]) => memo + t, 0); + return [total, results]; +} +__name(timedRepeats, "timedRepeats"); +async function runQuery(queryable, query) { + const { sql, test } = query; + const { rows } = await (typeof queryable === "function" ? queryable(sql) : queryable.query(sql)); + if (!test(rows)) + throw new Error( + `Result fails test +Query: ${sql} +Result: ${JSON.stringify(rows)}` + ); + return rows; +} +__name(runQuery, "runQuery"); +async function clientRunQuery(n, client, ctx2, query) { + await client.connect(); + const tPlusResults = await timedRepeats(n, () => runQuery(client, query)); + ctx2.waitUntil(client.end()); + return tPlusResults; +} +__name(clientRunQuery, "clientRunQuery"); +async function poolRunQuery(n, dbUrl, ctx2, query) { + const pool = new NeonPool({ connectionString: dbUrl }); + const tPlusResults = await timedRepeats(n, () => runQuery(pool, query)); + ctx2.waitUntil(pool.end()); + return tPlusResults; +} +__name(poolRunQuery, "poolRunQuery"); +async function httpRunQuery(n, dbUrl, ctx2, query) { + const sql = neon(dbUrl, { fullResults: true }); + const tPlusResults = await timedRepeats(n, () => runQuery(sql, query)); + return tPlusResults; +} +__name(httpRunQuery, "httpRunQuery"); + +// src/queries.ts +init_shims(); +var queries = [ + { + sql: "SELECT * FROM employees LIMIT 10", + test: /* @__PURE__ */ __name((rows) => rows.length > 1 && typeof rows[0].first_name === "string", "test") + }, + { + sql: "SELECT now()", + test: /* @__PURE__ */ __name((rows) => /^2\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d+Z$/.test(rows[0].now.toISOString()), "test") + } +]; + +// src/index.ts +async function cf(request, env, ctx2) { + let results = []; + for (const query of queries) { + const [, [[, result]]] = await poolRunQuery(1, env.NEON_DB_URL, ctx2, query); + results.push(result); + } + for (const query of queries) { + const [, [[, result]]] = await httpRunQuery(1, env.NEON_DB_URL, ctx2, query); + results.push(result); + } + return new Response(JSON.stringify(results, null, 2), { + headers: { "Content-Type": "application/json" } + }); +} +__name(cf, "cf"); +var ctx = { + waitUntil(promise) { + }, + passThroughOnException() { + } +}; +async function batchQueryTest(env, log2 = (...s) => { +}) { + const sql = neon(env.NEON_DB_URL); + const [[ra], [rb]] = await sql.transaction([ + sql`SELECT ${1}::int AS "batchInt"`, + sql`SELECT ${"hello"} AS "batchStr"` + ]); + log2("batch results:", JSON.stringify(ra), JSON.stringify(rb), "\n"); + if (ra.batchInt !== 1 || rb.batchStr !== "hello") + throw new Error("Batch query problem"); + const [[r1], [r2]] = await sql.transaction((txn) => [ + txn`SELECT ${1}::int AS "batchInt"`, + txn`SELECT ${"hello"} AS "batchStr"` + ]); + log2("batch results:", JSON.stringify(r1), JSON.stringify(r2), "\n"); + if (r1.batchInt !== 1 || r2.batchStr !== "hello") + throw new Error("Batch query problem"); + const emptyResult = await sql.transaction((txn) => []); + log2("empty txn result:", JSON.stringify(emptyResult), "\n"); + const [[[r3]], [[r4]]] = await sql.transaction( + (txn) => [ + txn`SELECT ${1}::int AS "batchInt"`, + txn`SELECT ${"hello"} AS "batchStr"` + ], + { arrayMode: true, isolationLevel: "Serializable", readOnly: true } + ); + log2( + "array mode (via transaction options) batch results:", + JSON.stringify(r3), + JSON.stringify(r4), + "\n" + ); + if (r3 !== 1 || r4 !== "hello") throw new Error("Batch query problem"); + const sqlArr = neon(env.NEON_DB_URL, { + arrayMode: true, + isolationLevel: "RepeatableRead" + }); + const [[[r5]], [[r6]]] = await sqlArr.transaction((txn) => [ + txn`SELECT ${1}::int AS "batchInt"`, + txn`SELECT ${"hello"} AS "batchStr"` + ]); + log2( + "array mode (via neon options) batch results:", + JSON.stringify(r5), + JSON.stringify(r6), + "\n" + ); + if (r5 !== 1 || r6 !== "hello") throw new Error("Batch query problem"); + const sqlArr2 = neon(env.NEON_DB_URL, { arrayMode: true }); + const [[r7], [r8]] = await sqlArr2.transaction( + (txn) => [ + txn`SELECT ${1}::int AS "batchInt"`, + txn`SELECT ${"hello"} AS "batchStr"` + ], + { arrayMode: false } + ); + log2( + "ordinary (via overridden options) batch results:", + JSON.stringify(r7), + JSON.stringify(r8), + "\n" + ); + if (r7.batchInt !== 1 || r8.batchStr !== "hello") + throw new Error("Batch query problem"); + const [[r9], [r10]] = await sql.transaction((txn) => [ + txn`SELECT ${1}::int AS "batchInt"`, + txn('SELECT $1 AS "batchStr"', ["hello"], { arrayMode: true }) + ]); + log2( + "query options on individual batch queries:", + JSON.stringify(r9), + JSON.stringify(r10), + "\n" + ); + if (r9.batchInt !== 1 || r10[0] !== "hello") + throw new Error("Batch query problem"); + let queryErr = void 0; + try { + await sql.transaction((txn) => [ + txn`SELECT ${1}::int AS "batchInt"`, + `SELECT 'hello' AS "batchStr"` + ]); + } catch (err) { + queryErr = err; + } + if (queryErr === void 0) + throw new Error( + "Error should have been raised for string passed to `transaction()`" + ); + log2("successfully caught invalid query passed to `transaction()`\n"); + let connErr; + try { + const urlWithBadPassword = env.NEON_DB_URL.replace(/@/, "x@"); + await neon(urlWithBadPassword).transaction((txn) => [ + txn`SELECT 'never' AS this_should_be_seen_precisely` + ]); + } catch (err) { + connErr = err; + } + if (connErr === void 0) + throw new Error("Error should have been raised for bad password"); + log2("successfully caught invalid password passed to `neon()`\n"); +} +__name(batchQueryTest, "batchQueryTest"); +async function latencies(env, useSubtls, log2 = (...s) => { +}) { + const queryRepeats = [1, 3]; + const connectRepeats = 9; + log2("Warm-up ...\n\n"); + await poolRunQuery(1, env.NEON_DB_URL, ctx, queries[0]); + let counter = 0; + log2(` ===== SQL-over-HTTP tests ===== -`);let a=new Set(["command","rowCount","rows","fields"]),u=await new De({connectionString:r. -NEON_DB_URL}),c=be(r.NEON_DB_URL,{resultCallback:o(async(w,b,U,v)=>{let C=await u. -query({text:w.query,values:w.params,...v.arrayMode?{rowMode:"array"}:{}}),E=b.command=== -C.command,S=b.rowCount===C.rowCount,x=_r(b.fields.map(F=>F.dataTypeID),C.fields. -map(F=>F.dataTypeID)),N=_r(U,C.rows);t(E&&S&&N&&x?"\u2713":"X",JSON.stringify(w), -` - -> us:`,JSON.stringify(U),` - -> pg:`,JSON.stringify(C.rows),` -`)},"resultCallback")}),l=new Date;await c`SELECT ${1} AS int_uncast`,await c`SELECT ${1}::int AS int`, -await c`SELECT ${1}::int8 AS int8num`,await c`SELECT ${1}::decimal AS decimalnum`, -await c`SELECT ${"[1,4)"}::int4range AS int4range`,await c`SELECT ${"hello"} AS str`, -await c`SELECT ${["a","b","c"]} AS arrstr_uncast`,await c`SELECT ${[[1,2],[3,4]]}::int[][] AS arrnumnested`, -await c`SELECT ${l}::timestamptz AS timestamptznow`,await c`SELECT ${"16:17:18+0\ -1:00"}::timetz AS timetz`,await c`SELECT ${"17:18:19"}::time AS time`,await c`SELECT ${l}::date AS datenow`, -await c`SELECT ${{x:"y"}} AS obj_uncast`,await c`SELECT ${"11:22:33:44:55:66"}::macaddr AS macaddr`, -await c`SELECT ${"\\xDEADBEEF"}::bytea AS bytea`,await c`SELECT ${"(2, 3)"}::point AS point`, -await c`SELECT ${"<(2, 3), 1>"}::circle AS circle`,await c`SELECT ${"10.10.10.0/\ -24"}::cidr AS cidr`,await c`SELECT ${!0} AS bool_uncast`,await c`SELECT ${"hello"} || ' ' || ${"\ -world"} AS greeting`,await c`SELECT ${[1,2,3]}::int[] AS arrnum`,await c`SELECT ${[ -"a","b","c"]}::text[] AS arrstr`,await c`SELECT ${{x:"y"}}::jsonb AS jsonb_obj`, -await c`SELECT ${{x:"y"}}::json AS json_obj`,await c`SELECT ${["11:22:33:44:55:6\ -6"]}::macaddr[] AS arrmacaddr`,await c`SELECT ${["10.10.10.0/24"]}::cidr[] AS arrcidr`, -await c`SELECT ${!0}::boolean AS bool`,await c`SELECT ${[l]}::timestamptz[] AS arrtstz`, -await c`SELECT ${["(2, 3)"]}::point[] AS arrpoint`,await c`SELECT ${["<(2, 3), 1\ ->"]}::circle[] AS arrcircle`,await c`SELECT ${["\\xDEADBEEF","\\xDEADBEEF"]}::bytea[] AS arrbytea`, -await c`SELECT null AS null`,await c`SELECT ${null} AS null`,await c`SELECT ${"N\ -ULL"} AS null_str`,await c`SELECT ${[1,2,3]} AS arrnum_uncast`,await c`SELECT ${[ -[1,2],[3,4]]} AS arrnumnested_uncast`,await c`SELECT ${l} AS timenow_uncast`,await c`SELECT ${l}::timestamp AS timestampnow`, -await c("SELECT $1::timestamp AS timestampnow",[l]),await c("SELECT $1 || ' ' ||\ - $2 AS greeting",["hello","world"]),await c("SELECT 123 AS num"),await c("SELECT\ - 123 AS num",[],{arrayMode:!0,fullResults:!0});function h(w,b,U=3){return async function(v,...C){ -let E="";for(let S=0;Sx.abort("fetch timed out"),b);try{let{ -signal:P}=x;return await w(E,C,{fetchOptions:{signal:P}})}catch(P){if(!(P.sourceError&& -P.sourceError instanceof DOMException&&P.sourceError.name==="AbortError")||S>=U) -throw P}finally{clearTimeout(N)}}}}o(h,"sqlWithRetries"),await h(c,5e3)`SELECT ${"\ -did this time out?"} AS str`,await Uh(r,t),we.fetchFunction=(w,b)=>(console.log( -"custom fetch:",w,b),fetch(w,b)),await c`SELECT ${"customFetch"} AS str`;let y="\ -SELECT 123::int[] WHERE x";try{await c(y)}catch(w){console.log("Fields of this e\ -xpected error should match the following error, except for having no `length` fi\ -eld"),console.log(w)}try{await Ct(1,r.NEON_DB_URL,Be,{sql:y,test:o(()=>!0,"test")})}catch(w){ -console.log("Fields of this expected error should match the previous error, exce\ -pt for having an additional `length` field"),console.log(w)}await new Promise(w=>setTimeout( -w,1e3)),u.end(),t(` +`); + const pgShowKeys = /* @__PURE__ */ new Set(["command", "rowCount", "rows", "fields"]); + const pool = await new NeonPool({ connectionString: env.NEON_DB_URL }); + const sql = neon(env.NEON_DB_URL, { + resultCallback: /* @__PURE__ */ __name(async (query, result, rows, opts) => { + const pgRes = await pool.query({ + text: query.query, + values: query.params, + ...opts.arrayMode ? { rowMode: "array" } : {} + }); + const commandMatches = result.command === pgRes.command; + const rowCountMatches = result.rowCount === pgRes.rowCount; + const dataTypesMatch = deepEqual( + result.fields.map((f) => f.dataTypeID), + pgRes.fields.map((f) => f.dataTypeID) + ); + const rowsMatch = deepEqual(rows, pgRes.rows); + const ok = commandMatches && rowCountMatches && rowsMatch && dataTypesMatch; + log2( + ok ? "\u2713" : "X", + JSON.stringify(query), + "\n -> us:", + JSON.stringify(rows), + "\n -> pg:", + JSON.stringify(pgRes.rows), + "\n" + ); + }, "resultCallback") + }); + const now = /* @__PURE__ */ new Date(); + await sql`SELECT ${1} AS int_uncast`; + await sql`SELECT ${1}::int AS int`; + await sql`SELECT ${1}::int8 AS int8num`; + await sql`SELECT ${1}::decimal AS decimalnum`; + await sql`SELECT ${"[1,4)"}::int4range AS int4range`; + await sql`SELECT ${"hello"} AS str`; + await sql`SELECT ${["a", "b", "c"]} AS arrstr_uncast`; + await sql`SELECT ${[[2], [4]]}::int[][] AS arrnumnested`; + await sql`SELECT ${now}::timestamptz AS timestamptznow`; + await sql`SELECT ${"16:17:18+01:00"}::timetz AS timetz`; + await sql`SELECT ${"17:18:19"}::time AS time`; + await sql`SELECT ${now}::date AS datenow`; + await sql`SELECT ${{ x: "y" }} AS obj_uncast`; + await sql`SELECT ${"11:22:33:44:55:66"}::macaddr AS macaddr`; + await sql`SELECT ${"\\xDEADBEEF"}::bytea AS bytea`; + await sql`SELECT ${"(2, 3)"}::point AS point`; + await sql`SELECT ${"<(2, 3), 1>"}::circle AS circle`; + await sql`SELECT ${"10.10.10.0/24"}::cidr AS cidr`; + await sql`SELECT ${true} AS bool_uncast`; + await sql`SELECT ${"hello"} || ' ' || ${"world"} AS greeting`; + await sql`SELECT ${[1, 2, 3]}::int[] AS arrnum`; + await sql`SELECT ${["a", "b", "c"]}::text[] AS arrstr`; + await sql`SELECT ${{ x: "y" }}::jsonb AS jsonb_obj`; + await sql`SELECT ${{ x: "y" }}::json AS json_obj`; + await sql`SELECT ${["11:22:33:44:55:66"]}::macaddr[] AS arrmacaddr`; + await sql`SELECT ${["10.10.10.0/24"]}::cidr[] AS arrcidr`; + await sql`SELECT ${true}::boolean AS bool`; + await sql`SELECT ${[now]}::timestamptz[] AS arrtstz`; + await sql`SELECT ${["(2, 3)"]}::point[] AS arrpoint`; + await sql`SELECT ${["<(2, 3), 1>"]}::circle[] AS arrcircle`; + await sql`SELECT ${["\\xDEADBEEF", "\\xDEADBEEF"]}::bytea[] AS arrbytea`; + await sql`SELECT null AS null`; + await sql`SELECT ${null} AS null`; + await sql`SELECT ${"NULL"} AS null_str`; + await sql`SELECT ${[1, 2, 3]} AS arrnum_uncast`; + await sql`SELECT ${[[2], [4]]} AS arrnumnested_uncast`; + await sql`SELECT ${now} AS timenow_uncast`; + await sql`SELECT ${now}::timestamp AS timestampnow`; + await sql("SELECT $1::timestamp AS timestampnow", [now]); + await sql("SELECT $1 || ' ' || $2 AS greeting", ["hello", "world"]); + await sql("SELECT 123 AS num"); + await sql("SELECT 123 AS num", [], { arrayMode: true, fullResults: true }); + function sqlWithRetries(sql2, timeoutMs, attempts = 3) { + return async function(strings, ...params) { + let query = ""; + for (let i = 0; i < strings.length; i++) { + query += strings[i]; + if (i < params.length) query += "$" + (i + 1); + } + for (let i = 1; ; i++) { + const abortController = new AbortController(); + const timeout = setTimeout( + () => abortController.abort("fetch timed out"), + timeoutMs + ); + try { + const { signal } = abortController; + const result = await sql2(query, params, { fetchOptions: { signal } }); + return result; + } catch (err) { + const timedOut = err.sourceError && err.sourceError instanceof DOMException && err.sourceError.name === "AbortError"; + if (!timedOut || i >= attempts) throw err; + } finally { + clearTimeout(timeout); + } + } + }; + } + __name(sqlWithRetries, "sqlWithRetries"); + const sqlRetry = sqlWithRetries(sql, 5e3); + await sqlRetry`SELECT ${"did this time out?"} AS str`; + await batchQueryTest(env, log2); + Socket.fetchFunction = (url, options) => { + console.log("custom fetch:", url, options); + return fetch(url, options); + }; + await sql`SELECT ${"customFetch"} AS str`; + const errstatement = "SELECT 123::int[] WHERE x"; + try { + await sql(errstatement); + } catch (err) { + console.log( + "Fields of this expected error should match the following error, except for having no `length` field" + ); + console.log(err); + } + try { + await poolRunQuery(1, env.NEON_DB_URL, ctx, { + sql: errstatement, + test: /* @__PURE__ */ __name(() => true, "test") + }); + } catch (err) { + console.log( + "Fields of this expected error should match the previous error, except for having an additional `length` field" + ); + console.log(err); + } + await new Promise((resolve) => setTimeout(resolve, 1e3)); + pool.end(); + log2(` ===== Pool/Client tests ===== -`);for(let w of _t){t(` ------ ${w.sql} ----- - -`);async function b(v,C){let E=String.fromCharCode(s+(s>25?23:65));t(`${E} -`);try{await fetch(`http://localhost:443/${E}`)}catch{}t('Liv\ -e: ');let[,S]=await rt(i,()=>C(v),x=>t(`${x.toFixed()}\ -ms `));t(` -Sorted: `),S.map(([x])=>x).sort((x,N)=>x-N).forEach((x,N)=>{t(N===(i-1)/2?`${x.toFixed()}ms `:`${x.toFixed()}ms `)}),t(` - -`),s+=1}o(b,"section");async function U(v,C){t(`----- ${v} ----- - -`);for(let E of n)t(`${E} quer${E===1?"y":"ies"} \u2013 `),await b(E,C)}o(U,"sec\ -tions"),await U("Neon/wss, no pipelining",async v=>{let C=new Pe(r.NEON_DB_URL); -C.neonConfig.pipelineConnect=!1,await vt(v,C,Be,w)}),await U("Neon/wss, pipeline\ -d connect (default)",async v=>{let C=new Pe(r.NEON_DB_URL);await vt(v,C,Be,w)}), -await U("Neon/wss, pipelined connect, no coalescing",async v=>{let C=new Pe(r.NEON_DB_URL); -C.neonConfig.coalesceWrites=!1,await vt(v,C,Be,w)}),await U("Neon/wss, pipelined\ - connect using Pool.query",async v=>{await Ct(v,r.NEON_DB_URL,Be,w)}),await U("N\ -eon/wss, pipelined connect using Pool.connect",async v=>{let C=new De({connectionString:r. -NEON_DB_URL}),E=await C.connect();await rt(v,()=>At(E,w)),E.release(),Be.waitUntil( -C.end())}),e&&(we.subtls=Cr,we.rootCerts=Si,await U("pg/subtls, pipelined connec\ -t",async v=>{let C=new Pe(r.NEON_DB_URL);C.neonConfig.wsProxy=(E,S)=>`subtls-wsp\ -roxy.jawj.workers.dev/?address=${E}:${S}`,C.neonConfig.forceDisablePgSSL=C.neonConfig. -useSecureWebSocket=!1,C.neonConfig.pipelineTLS=!1,C.neonConfig.pipelineConnect=!1; -try{await vt(v,C,Be,w)}catch(E){console.error(` -*** ${E.message}`)}}))}}o(u0,"latencies");export{Uh as batchQueryTest,o0 as cf,u0 as latencies,we as neonConfig}; +`); + for (const query of queries) { + log2(` +----- ${query.sql} ----- + +`); + async function section(queryRepeat, f) { + const marker = String.fromCharCode( + counter + (counter > 25 ? 49 - 26 : 65) + ); + log2(`${marker} +`); + try { + await fetch(`http://localhost:443/${marker}`); + } catch { + } + log2(`Live: `); + const [, results] = await timedRepeats( + connectRepeats, + () => f(queryRepeat), + (t) => log2(`${t.toFixed()}ms `) + ); + log2("\nSorted: "); + results.map(([t]) => t).sort((a, b) => a - b).forEach((t, i) => { + log2( + i === (connectRepeats - 1) / 2 ? `${t.toFixed()}ms ` : `${t.toFixed()}ms ` + ); + }); + log2("\n\n"); + counter += 1; + } + __name(section, "section"); + async function sections(title, f) { + log2(`----- ${title} ----- + +`); + for (let queryRepeat of queryRepeats) { + log2(`${queryRepeat} quer${queryRepeat === 1 ? "y" : "ies"} \u2013 `); + await section(queryRepeat, f); + } + } + __name(sections, "sections"); + await sections("Neon/wss, no pipelining", async (n) => { + const client = new NeonClient(env.NEON_DB_URL); + client.neonConfig.pipelineConnect = false; + await clientRunQuery(n, client, ctx, query); + }); + await sections("Neon/wss, pipelined connect (default)", async (n) => { + const client = new NeonClient(env.NEON_DB_URL); + await clientRunQuery(n, client, ctx, query); + }); + await sections("Neon/wss, pipelined connect, no coalescing", async (n) => { + const client = new NeonClient(env.NEON_DB_URL); + client.neonConfig.coalesceWrites = false; + await clientRunQuery(n, client, ctx, query); + }); + await sections( + "Neon/wss, pipelined connect using Pool.query", + async (n) => { + await poolRunQuery(n, env.NEON_DB_URL, ctx, query); + } + ); + await sections( + "Neon/wss, pipelined connect using Pool.connect", + async (n) => { + const pool2 = new NeonPool({ connectionString: env.NEON_DB_URL }); + const poolClient = await pool2.connect(); + await timedRepeats(n, () => runQuery(poolClient, query)); + poolClient.release(); + ctx.waitUntil(pool2.end()); + } + ); + if (useSubtls) { + Socket.subtls = subtls_exports; + Socket.rootCerts = isrgrootx1_default; + await sections("pg/subtls, pipelined connect", async (n) => { + const client = new NeonClient(env.NEON_DB_URL); + client.neonConfig.wsProxy = (host, port) => `subtls-wsproxy.jawj.workers.dev/?address=${host}:${port}`; + client.neonConfig.forceDisablePgSSL = client.neonConfig.useSecureWebSocket = false; + client.neonConfig.pipelineTLS = false; + client.neonConfig.pipelineConnect = false; + try { + await clientRunQuery(n, client, ctx, query); + } catch (err) { + console.error(` +*** ${err.message}`); + } + }); + } + } +} +__name(latencies, "latencies"); +export { + batchQueryTest, + cf, + latencies, + Socket as neonConfig +}; /*! Bundled license information: ieee754/index.js: diff --git a/export/httpQuery.ts b/export/httpQuery.ts index 6fa9e90..f4e74f6 100644 --- a/export/httpQuery.ts +++ b/export/httpQuery.ts @@ -51,7 +51,7 @@ interface HTTPQueryOptions { // JWT auth token to be passed as the Bearer token in the Authorization // header - authToken?: string | (() => string); + authToken?: string | (() => Promise | string); } interface HTTPTransactionOptions extends HTTPQueryOptions { @@ -152,7 +152,6 @@ export function neon( if ( (protocol !== 'postgres:' && protocol !== 'postgresql:') || !username || - !password || !hostname || !pathname ) { @@ -224,7 +223,7 @@ export function neon( const url = typeof fetchEndpoint === 'function' ? fetchEndpoint(hostname, port, { - jwtAuth: Boolean(authToken), + jwtAuth: authToken !== undefined, }) : fetchEndpoint; @@ -282,7 +281,7 @@ export function neon( if (typeof authToken === 'string') { headers['Authorization'] = `Bearer ${authToken}`; } else if (typeof authToken === 'function') { - headers['Authorization'] = `Bearer ${authToken()}`; + headers['Authorization'] = `Bearer ${Promise.resolve(authToken())}`; } if (Array.isArray(parameterizedQuery)) { diff --git a/shims/net/index.ts b/shims/net/index.ts index 90cb8a3..2136263 100644 --- a/shims/net/index.ts +++ b/shims/net/index.ts @@ -87,6 +87,8 @@ type GlobalOnlyDefaults = | 'fetchConnectionCache' | 'fetchFunction'; +const FIRST_WORD_REGEX = /^[^.]+\./; + export class Socket extends EventEmitter { static defaults: SocketDefaults = { // these options relate to the fetch transport and take effect *only* when set globally @@ -97,9 +99,9 @@ export class Socket extends EventEmitter { // If the caller sends in a JWT, we need to use the Neon Authorize API // endpoint instead (this goes to the Auth Broker instead of the Neon // Proxy). - newHost = host.replace(/^[^.]+\./, 'apiauth.'); + newHost = host.replace(FIRST_WORD_REGEX, 'apiauth.'); } else { - newHost = host.replace(/^[^.]+\./, 'api.'); + newHost = host.replace(FIRST_WORD_REGEX, 'api.'); } return 'https://' + newHost + '/sql';