@powersync/web 1.23.1 → 1.23.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2452,7 +2452,7 @@ read:function(l,n,u,e,t){var r,i,s=8*t-e-1,o=(1<<s)-1,a=o>>1,c=-7,h=u?t-1:0,d=u?
2452
2452
  * @author Feross Aboukhadijeh <https://feross.org>
2453
2453
  * @license MIT
2454
2454
  */
2455
- !function(l){var n=V,u=nl,e="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;l.Buffer=i,l.SlowBuffer=function(l){+l!=l&&(l=0);return i.alloc(+l)},l.INSPECT_MAX_BYTES=50;var t=2147483647;function r(l){if(l>t)throw new RangeError('The value "'+l+'" is invalid for option "size"');var n=new Uint8Array(l);return Object.setPrototypeOf(n,i.prototype),n}function i(l,n,u){if("number"==typeof l){if("string"==typeof n)throw new TypeError('The "string" argument must be of type string. Received type number');return a(l)}return s(l,n,u)}function s(l,n,u){if("string"==typeof l)return function(l,n){"string"==typeof n&&""!==n||(n="utf8");if(!i.isEncoding(n))throw new TypeError("Unknown encoding: "+n);var u=0|f(l,n),e=r(u),t=e.write(l,n);t!==u&&(e=e.slice(0,t));return e}(l,n);if(ArrayBuffer.isView(l))return function(l){if(B(l,Uint8Array)){var n=new Uint8Array(l);return h(n.buffer,n.byteOffset,n.byteLength)}return c(l)}(l);if(null==l)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof l);if(B(l,ArrayBuffer)||l&&B(l.buffer,ArrayBuffer))return h(l,n,u);if("undefined"!=typeof SharedArrayBuffer&&(B(l,SharedArrayBuffer)||l&&B(l.buffer,SharedArrayBuffer)))return h(l,n,u);if("number"==typeof l)throw new TypeError('The "value" argument must not be of type number. Received type number');var e=l.valueOf&&l.valueOf();if(null!=e&&e!==l)return i.from(e,n,u);var t=function(l){if(i.isBuffer(l)){var n=0|d(l.length),u=r(n);return 0===u.length||l.copy(u,0,0,n),u}if(void 0!==l.length)return"number"!=typeof l.length||q(l.length)?r(0):c(l);if("Buffer"===l.type&&Array.isArray(l.data))return c(l.data)}(l);if(t)return t;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof l[Symbol.toPrimitive])return i.from(l[Symbol.toPrimitive]("string"),n,u);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof l)}function o(l){if("number"!=typeof l)throw new TypeError('"size" argument must be of type number');if(l<0)throw new RangeError('The value "'+l+'" is invalid for option "size"')}function a(l){return o(l),r(l<0?0:0|d(l))}function c(l){for(var n=l.length<0?0:0|d(l.length),u=r(n),e=0;e<n;e+=1)u[e]=255&l[e];return u}function h(l,n,u){if(n<0||l.byteLength<n)throw new RangeError('"offset" is outside of buffer bounds');if(l.byteLength<n+(u||0))throw new RangeError('"length" is outside of buffer bounds');var e;return e=void 0===n&&void 0===u?new Uint8Array(l):void 0===u?new Uint8Array(l,n):new Uint8Array(l,n,u),Object.setPrototypeOf(e,i.prototype),e}function d(l){if(l>=t)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+t.toString(16)+" bytes");return 0|l}function f(l,n){if(i.isBuffer(l))return l.length;if(ArrayBuffer.isView(l)||B(l,ArrayBuffer))return l.byteLength;if("string"!=typeof l)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof l);var u=l.length,e=arguments.length>2&&!0===arguments[2];if(!e&&0===u)return 0;for(var t=!1;;)switch(n){case"ascii":case"latin1":case"binary":return u;case"utf8":case"utf-8":return P(l).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*u;case"hex":return u>>>1;case"base64":return D(l).length;default:if(t)return e?-1:P(l).length;n=(""+n).toLowerCase(),t=!0}}function p(l,n,u){var e=!1;if((void 0===n||n<0)&&(n=0),n>this.length)return"";if((void 0===u||u>this.length)&&(u=this.length),u<=0)return"";if((u>>>=0)<=(n>>>=0))return"";for(l||(l="utf8");;)switch(l){case"hex":return F(this,n,u);case"utf8":case"utf-8":return R(this,n,u);case"ascii":return A(this,n,u);case"latin1":case"binary":return O(this,n,u);case"base64":return T(this,n,u);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,n,u);default:if(e)throw new TypeError("Unknown encoding: "+l);l=(l+"").toLowerCase(),e=!0}}function y(l,n,u){var e=l[n];l[n]=l[u],l[u]=e}function m(l,n,u,e,t){if(0===l.length)return-1;if("string"==typeof u?(e=u,u=0):u>2147483647?u=2147483647:u<-2147483648&&(u=-2147483648),q(u=+u)&&(u=t?0:l.length-1),u<0&&(u=l.length+u),u>=l.length){if(t)return-1;u=l.length-1}else if(u<0){if(!t)return-1;u=0}if("string"==typeof n&&(n=i.from(n,e)),i.isBuffer(n))return 0===n.length?-1:g(l,n,u,e,t);if("number"==typeof n)return n&=255,"function"==typeof Uint8Array.prototype.indexOf?t?Uint8Array.prototype.indexOf.call(l,n,u):Uint8Array.prototype.lastIndexOf.call(l,n,u):g(l,[n],u,e,t);throw new TypeError("val must be string, number or Buffer")}function g(l,n,u,e,t){var r,i=1,s=l.length,o=n.length;if(void 0!==e&&("ucs2"===(e=String(e).toLowerCase())||"ucs-2"===e||"utf16le"===e||"utf-16le"===e)){if(l.length<2||n.length<2)return-1;i=2,s/=2,o/=2,u/=2}function a(l,n){return 1===i?l[n]:l.readUInt16BE(n*i)}if(t){var c=-1;for(r=u;r<s;r++)if(a(l,r)===a(n,-1===c?0:r-c)){if(-1===c&&(c=r),r-c+1===o)return c*i}else-1!==c&&(r-=r-c),c=-1}else for(u+o>s&&(u=s-o),r=u;r>=0;r--){for(var h=!0,d=0;d<o;d++)if(a(l,r+d)!==a(n,d)){h=!1;break}if(h)return r}return-1}function E(l,n,u,e){u=Number(u)||0;var t=l.length-u;e?(e=Number(e))>t&&(e=t):e=t;var r=n.length;e>r/2&&(e=r/2);for(var i=0;i<e;++i){var s=parseInt(n.substr(2*i,2),16);if(q(s))return i;l[u+i]=s}return i}function w(l,n,u,e){return M(P(n,l.length-u),l,u,e)}function v(l,n,u,e){return M(function(l){for(var n=[],u=0;u<l.length;++u)n.push(255&l.charCodeAt(u));return n}(n),l,u,e)}function b(l,n,u,e){return M(D(n),l,u,e)}function S(l,n,u,e){return M(function(l,n){for(var u,e,t,r=[],i=0;i<l.length&&!((n-=2)<0);++i)e=(u=l.charCodeAt(i))>>8,t=u%256,r.push(t),r.push(e);return r}(n,l.length-u),l,u,e)}function T(l,u,e){return 0===u&&e===l.length?n.fromByteArray(l):n.fromByteArray(l.slice(u,e))}function R(l,n,u){u=Math.min(l.length,u);for(var e=[],t=n;t<u;){var r,i,s,o,a=l[t],c=null,h=a>239?4:a>223?3:a>191?2:1;if(t+h<=u)switch(h){case 1:a<128&&(c=a);break;case 2:128==(192&(r=l[t+1]))&&(o=(31&a)<<6|63&r)>127&&(c=o);break;case 3:r=l[t+1],i=l[t+2],128==(192&r)&&128==(192&i)&&(o=(15&a)<<12|(63&r)<<6|63&i)>2047&&(o<55296||o>57343)&&(c=o);break;case 4:r=l[t+1],i=l[t+2],s=l[t+3],128==(192&r)&&128==(192&i)&&128==(192&s)&&(o=(15&a)<<18|(63&r)<<12|(63&i)<<6|63&s)>65535&&o<1114112&&(c=o)}null===c?(c=65533,h=1):c>65535&&(c-=65536,e.push(c>>>10&1023|55296),c=56320|1023&c),e.push(c),t+=h}return function(l){var n=l.length;if(n<=_)return String.fromCharCode.apply(String,l);var u="",e=0;for(;e<n;)u+=String.fromCharCode.apply(String,l.slice(e,e+=_));return u}(e)}l.kMaxLength=t,i.TYPED_ARRAY_SUPPORT=function(){try{var l=new Uint8Array(1),n={foo:function(){return 42}};return Object.setPrototypeOf(n,Uint8Array.prototype),Object.setPrototypeOf(l,n),42===l.foo()}catch(l){return!1}}(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||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."),Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}}),i.poolSize=8192,i.from=function(l,n,u){return s(l,n,u)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array),i.alloc=function(l,n,u){return function(l,n,u){return o(l),l<=0?r(l):void 0!==n?"string"==typeof u?r(l).fill(n,u):r(l).fill(n):r(l)}(l,n,u)},i.allocUnsafe=function(l){return a(l)},i.allocUnsafeSlow=function(l){return a(l)},i.isBuffer=function(l){return null!=l&&!0===l._isBuffer&&l!==i.prototype},i.compare=function(l,n){if(B(l,Uint8Array)&&(l=i.from(l,l.offset,l.byteLength)),B(n,Uint8Array)&&(n=i.from(n,n.offset,n.byteLength)),!i.isBuffer(l)||!i.isBuffer(n))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(l===n)return 0;for(var u=l.length,e=n.length,t=0,r=Math.min(u,e);t<r;++t)if(l[t]!==n[t]){u=l[t],e=n[t];break}return u<e?-1:e<u?1:0},i.isEncoding=function(l){switch(String(l).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!0;default:return!1}},i.concat=function(l,n){if(!Array.isArray(l))throw new TypeError('"list" argument must be an Array of Buffers');if(0===l.length)return i.alloc(0);var u;if(void 0===n)for(n=0,u=0;u<l.length;++u)n+=l[u].length;var e=i.allocUnsafe(n),t=0;for(u=0;u<l.length;++u){var r=l[u];if(B(r,Uint8Array))t+r.length>e.length?i.from(r).copy(e,t):Uint8Array.prototype.set.call(e,r,t);else{if(!i.isBuffer(r))throw new TypeError('"list" argument must be an Array of Buffers');r.copy(e,t)}t+=r.length}return e},i.byteLength=f,i.prototype._isBuffer=!0,i.prototype.swap16=function(){var l=this.length;if(l%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var n=0;n<l;n+=2)y(this,n,n+1);return this},i.prototype.swap32=function(){var l=this.length;if(l%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var n=0;n<l;n+=4)y(this,n,n+3),y(this,n+1,n+2);return this},i.prototype.swap64=function(){var l=this.length;if(l%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var n=0;n<l;n+=8)y(this,n,n+7),y(this,n+1,n+6),y(this,n+2,n+5),y(this,n+3,n+4);return this},i.prototype.toString=function(){var l=this.length;return 0===l?"":0===arguments.length?R(this,0,l):p.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(l){if(!i.isBuffer(l))throw new TypeError("Argument must be a Buffer");return this===l||0===i.compare(this,l)},i.prototype.inspect=function(){var n="",u=l.INSPECT_MAX_BYTES;return n=this.toString("hex",0,u).replace(/(.{2})/g,"$1 ").trim(),this.length>u&&(n+=" ... "),"<Buffer "+n+">"},e&&(i.prototype[e]=i.prototype.inspect),i.prototype.compare=function(l,n,u,e,t){if(B(l,Uint8Array)&&(l=i.from(l,l.offset,l.byteLength)),!i.isBuffer(l))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof l);if(void 0===n&&(n=0),void 0===u&&(u=l?l.length:0),void 0===e&&(e=0),void 0===t&&(t=this.length),n<0||u>l.length||e<0||t>this.length)throw new RangeError("out of range index");if(e>=t&&n>=u)return 0;if(e>=t)return-1;if(n>=u)return 1;if(this===l)return 0;for(var r=(t>>>=0)-(e>>>=0),s=(u>>>=0)-(n>>>=0),o=Math.min(r,s),a=this.slice(e,t),c=l.slice(n,u),h=0;h<o;++h)if(a[h]!==c[h]){r=a[h],s=c[h];break}return r<s?-1:s<r?1:0},i.prototype.includes=function(l,n,u){return-1!==this.indexOf(l,n,u)},i.prototype.indexOf=function(l,n,u){return m(this,l,n,u,!0)},i.prototype.lastIndexOf=function(l,n,u){return m(this,l,n,u,!1)},i.prototype.write=function(l,n,u,e){if(void 0===n)e="utf8",u=this.length,n=0;else if(void 0===u&&"string"==typeof n)e=n,u=this.length,n=0;else{if(!isFinite(n))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");n>>>=0,isFinite(u)?(u>>>=0,void 0===e&&(e="utf8")):(e=u,u=void 0)}var t=this.length-n;if((void 0===u||u>t)&&(u=t),l.length>0&&(u<0||n<0)||n>this.length)throw new RangeError("Attempt to write outside buffer bounds");e||(e="utf8");for(var r=!1;;)switch(e){case"hex":return E(this,l,n,u);case"utf8":case"utf-8":return w(this,l,n,u);case"ascii":case"latin1":case"binary":return v(this,l,n,u);case"base64":return b(this,l,n,u);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,l,n,u);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(""+e).toLowerCase(),r=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var _=4096;function A(l,n,u){var e="";u=Math.min(l.length,u);for(var t=n;t<u;++t)e+=String.fromCharCode(127&l[t]);return e}function O(l,n,u){var e="";u=Math.min(l.length,u);for(var t=n;t<u;++t)e+=String.fromCharCode(l[t]);return e}function F(l,n,u){var e=l.length;(!n||n<0)&&(n=0),(!u||u<0||u>e)&&(u=e);for(var t="",r=n;r<u;++r)t+=j[l[r]];return t}function C(l,n,u){for(var e=l.slice(n,u),t="",r=0;r<e.length-1;r+=2)t+=String.fromCharCode(e[r]+256*e[r+1]);return t}function I(l,n,u){if(l%1!=0||l<0)throw new RangeError("offset is not uint");if(l+n>u)throw new RangeError("Trying to access beyond buffer length")}function k(l,n,u,e,t,r){if(!i.isBuffer(l))throw new TypeError('"buffer" argument must be a Buffer instance');if(n>t||n<r)throw new RangeError('"value" argument is out of bounds');if(u+e>l.length)throw new RangeError("Index out of range")}function L(l,n,u,e,t,r){if(u+e>l.length)throw new RangeError("Index out of range");if(u<0)throw new RangeError("Index out of range")}function N(l,n,e,t,r){return n=+n,e>>>=0,r||L(l,0,e,4),u.write(l,n,e,t,23,4),e+4}function U(l,n,e,t,r){return n=+n,e>>>=0,r||L(l,0,e,8),u.write(l,n,e,t,52,8),e+8}i.prototype.slice=function(l,n){var u=this.length;(l=~~l)<0?(l+=u)<0&&(l=0):l>u&&(l=u),(n=void 0===n?u:~~n)<0?(n+=u)<0&&(n=0):n>u&&(n=u),n<l&&(n=l);var e=this.subarray(l,n);return Object.setPrototypeOf(e,i.prototype),e},i.prototype.readUintLE=i.prototype.readUIntLE=function(l,n,u){l>>>=0,n>>>=0,u||I(l,n,this.length);for(var e=this[l],t=1,r=0;++r<n&&(t*=256);)e+=this[l+r]*t;return e},i.prototype.readUintBE=i.prototype.readUIntBE=function(l,n,u){l>>>=0,n>>>=0,u||I(l,n,this.length);for(var e=this[l+--n],t=1;n>0&&(t*=256);)e+=this[l+--n]*t;return e},i.prototype.readUint8=i.prototype.readUInt8=function(l,n){return l>>>=0,n||I(l,1,this.length),this[l]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(l,n){return l>>>=0,n||I(l,2,this.length),this[l]|this[l+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(l,n){return l>>>=0,n||I(l,2,this.length),this[l]<<8|this[l+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(l,n){return l>>>=0,n||I(l,4,this.length),(this[l]|this[l+1]<<8|this[l+2]<<16)+16777216*this[l+3]},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(l,n){return l>>>=0,n||I(l,4,this.length),16777216*this[l]+(this[l+1]<<16|this[l+2]<<8|this[l+3])},i.prototype.readIntLE=function(l,n,u){l>>>=0,n>>>=0,u||I(l,n,this.length);for(var e=this[l],t=1,r=0;++r<n&&(t*=256);)e+=this[l+r]*t;return e>=(t*=128)&&(e-=Math.pow(2,8*n)),e},i.prototype.readIntBE=function(l,n,u){l>>>=0,n>>>=0,u||I(l,n,this.length);for(var e=n,t=1,r=this[l+--e];e>0&&(t*=256);)r+=this[l+--e]*t;return r>=(t*=128)&&(r-=Math.pow(2,8*n)),r},i.prototype.readInt8=function(l,n){return l>>>=0,n||I(l,1,this.length),128&this[l]?-1*(255-this[l]+1):this[l]},i.prototype.readInt16LE=function(l,n){l>>>=0,n||I(l,2,this.length);var u=this[l]|this[l+1]<<8;return 32768&u?4294901760|u:u},i.prototype.readInt16BE=function(l,n){l>>>=0,n||I(l,2,this.length);var u=this[l+1]|this[l]<<8;return 32768&u?4294901760|u:u},i.prototype.readInt32LE=function(l,n){return l>>>=0,n||I(l,4,this.length),this[l]|this[l+1]<<8|this[l+2]<<16|this[l+3]<<24},i.prototype.readInt32BE=function(l,n){return l>>>=0,n||I(l,4,this.length),this[l]<<24|this[l+1]<<16|this[l+2]<<8|this[l+3]},i.prototype.readFloatLE=function(l,n){return l>>>=0,n||I(l,4,this.length),u.read(this,l,!0,23,4)},i.prototype.readFloatBE=function(l,n){return l>>>=0,n||I(l,4,this.length),u.read(this,l,!1,23,4)},i.prototype.readDoubleLE=function(l,n){return l>>>=0,n||I(l,8,this.length),u.read(this,l,!0,52,8)},i.prototype.readDoubleBE=function(l,n){return l>>>=0,n||I(l,8,this.length),u.read(this,l,!1,52,8)},i.prototype.writeUintLE=i.prototype.writeUIntLE=function(l,n,u,e){(l=+l,n>>>=0,u>>>=0,e)||k(this,l,n,u,Math.pow(2,8*u)-1,0);var t=1,r=0;for(this[n]=255&l;++r<u&&(t*=256);)this[n+r]=l/t&255;return n+u},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(l,n,u,e){(l=+l,n>>>=0,u>>>=0,e)||k(this,l,n,u,Math.pow(2,8*u)-1,0);var t=u-1,r=1;for(this[n+t]=255&l;--t>=0&&(r*=256);)this[n+t]=l/r&255;return n+u},i.prototype.writeUint8=i.prototype.writeUInt8=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,1,255,0),this[n]=255&l,n+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,2,65535,0),this[n]=255&l,this[n+1]=l>>>8,n+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,2,65535,0),this[n]=l>>>8,this[n+1]=255&l,n+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,4,4294967295,0),this[n+3]=l>>>24,this[n+2]=l>>>16,this[n+1]=l>>>8,this[n]=255&l,n+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,4,4294967295,0),this[n]=l>>>24,this[n+1]=l>>>16,this[n+2]=l>>>8,this[n+3]=255&l,n+4},i.prototype.writeIntLE=function(l,n,u,e){if(l=+l,n>>>=0,!e){var t=Math.pow(2,8*u-1);k(this,l,n,u,t-1,-t)}var r=0,i=1,s=0;for(this[n]=255&l;++r<u&&(i*=256);)l<0&&0===s&&0!==this[n+r-1]&&(s=1),this[n+r]=(l/i|0)-s&255;return n+u},i.prototype.writeIntBE=function(l,n,u,e){if(l=+l,n>>>=0,!e){var t=Math.pow(2,8*u-1);k(this,l,n,u,t-1,-t)}var r=u-1,i=1,s=0;for(this[n+r]=255&l;--r>=0&&(i*=256);)l<0&&0===s&&0!==this[n+r+1]&&(s=1),this[n+r]=(l/i|0)-s&255;return n+u},i.prototype.writeInt8=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,1,127,-128),l<0&&(l=255+l+1),this[n]=255&l,n+1},i.prototype.writeInt16LE=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,2,32767,-32768),this[n]=255&l,this[n+1]=l>>>8,n+2},i.prototype.writeInt16BE=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,2,32767,-32768),this[n]=l>>>8,this[n+1]=255&l,n+2},i.prototype.writeInt32LE=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,4,2147483647,-2147483648),this[n]=255&l,this[n+1]=l>>>8,this[n+2]=l>>>16,this[n+3]=l>>>24,n+4},i.prototype.writeInt32BE=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,4,2147483647,-2147483648),l<0&&(l=4294967295+l+1),this[n]=l>>>24,this[n+1]=l>>>16,this[n+2]=l>>>8,this[n+3]=255&l,n+4},i.prototype.writeFloatLE=function(l,n,u){return N(this,l,n,!0,u)},i.prototype.writeFloatBE=function(l,n,u){return N(this,l,n,!1,u)},i.prototype.writeDoubleLE=function(l,n,u){return U(this,l,n,!0,u)},i.prototype.writeDoubleBE=function(l,n,u){return U(this,l,n,!1,u)},i.prototype.copy=function(l,n,u,e){if(!i.isBuffer(l))throw new TypeError("argument should be a Buffer");if(u||(u=0),e||0===e||(e=this.length),n>=l.length&&(n=l.length),n||(n=0),e>0&&e<u&&(e=u),e===u)return 0;if(0===l.length||0===this.length)return 0;if(n<0)throw new RangeError("targetStart out of bounds");if(u<0||u>=this.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("sourceEnd out of bounds");e>this.length&&(e=this.length),l.length-n<e-u&&(e=l.length-n+u);var t=e-u;return this===l&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(n,u,e):Uint8Array.prototype.set.call(l,this.subarray(u,e),n),t},i.prototype.fill=function(l,n,u,e){if("string"==typeof l){if("string"==typeof n?(e=n,n=0,u=this.length):"string"==typeof u&&(e=u,u=this.length),void 0!==e&&"string"!=typeof e)throw new TypeError("encoding must be a string");if("string"==typeof e&&!i.isEncoding(e))throw new TypeError("Unknown encoding: "+e);if(1===l.length){var t=l.charCodeAt(0);("utf8"===e&&t<128||"latin1"===e)&&(l=t)}}else"number"==typeof l?l&=255:"boolean"==typeof l&&(l=Number(l));if(n<0||this.length<n||this.length<u)throw new RangeError("Out of range index");if(u<=n)return this;var r;if(n>>>=0,u=void 0===u?this.length:u>>>0,l||(l=0),"number"==typeof l)for(r=n;r<u;++r)this[r]=l;else{var s=i.isBuffer(l)?l:i.from(l,e),o=s.length;if(0===o)throw new TypeError('The value "'+l+'" is invalid for argument "value"');for(r=0;r<u-n;++r)this[r+n]=s[r%o]}return this};var x=/[^+/0-9A-Za-z-_]/g;function P(l,n){var u;n=n||1/0;for(var e=l.length,t=null,r=[],i=0;i<e;++i){if((u=l.charCodeAt(i))>55295&&u<57344){if(!t){if(u>56319){(n-=3)>-1&&r.push(239,191,189);continue}if(i+1===e){(n-=3)>-1&&r.push(239,191,189);continue}t=u;continue}if(u<56320){(n-=3)>-1&&r.push(239,191,189),t=u;continue}u=65536+(t-55296<<10|u-56320)}else t&&(n-=3)>-1&&r.push(239,191,189);if(t=null,u<128){if((n-=1)<0)break;r.push(u)}else if(u<2048){if((n-=2)<0)break;r.push(u>>6|192,63&u|128)}else if(u<65536){if((n-=3)<0)break;r.push(u>>12|224,u>>6&63|128,63&u|128)}else{if(!(u<1114112))throw new Error("Invalid code point");if((n-=4)<0)break;r.push(u>>18|240,u>>12&63|128,u>>6&63|128,63&u|128)}}return r}function D(l){return n.toByteArray(function(l){if((l=(l=l.split("=")[0]).trim().replace(x,"")).length<2)return"";for(;l.length%4!=0;)l+="=";return l}(l))}function M(l,n,u,e){for(var t=0;t<e&&!(t+u>=n.length||t>=l.length);++t)n[t+u]=l[t];return t}function B(l,n){return l instanceof n||null!=l&&null!=l.constructor&&null!=l.constructor.name&&l.constructor.name===n.name}function q(l){return l!=l}var j=function(){for(var l="0123456789abcdef",n=new Array(256),u=0;u<16;++u)for(var e=16*u,t=0;t<16;++t)n[e+t]=l[u]+l[t];return n}()}(el);var tl={},rl={};!function(l){var n,u,e,t;Object.defineProperty(l,"__esModule",{value:!0}),l.Frame=l.Lengths=l.Flags=l.FrameTypes=void 0,function(l){l[l.RESERVED=0]="RESERVED",l[l.SETUP=1]="SETUP",l[l.LEASE=2]="LEASE",l[l.KEEPALIVE=3]="KEEPALIVE",l[l.REQUEST_RESPONSE=4]="REQUEST_RESPONSE",l[l.REQUEST_FNF=5]="REQUEST_FNF",l[l.REQUEST_STREAM=6]="REQUEST_STREAM",l[l.REQUEST_CHANNEL=7]="REQUEST_CHANNEL",l[l.REQUEST_N=8]="REQUEST_N",l[l.CANCEL=9]="CANCEL",l[l.PAYLOAD=10]="PAYLOAD",l[l.ERROR=11]="ERROR",l[l.METADATA_PUSH=12]="METADATA_PUSH",l[l.RESUME=13]="RESUME",l[l.RESUME_OK=14]="RESUME_OK",l[l.EXT=63]="EXT"}(n=l.FrameTypes||(l.FrameTypes={})),(u=l.Flags||(l.Flags={}))[u.NONE=0]="NONE",u[u.COMPLETE=64]="COMPLETE",u[u.FOLLOWS=128]="FOLLOWS",u[u.IGNORE=512]="IGNORE",u[u.LEASE=64]="LEASE",u[u.METADATA=256]="METADATA",u[u.NEXT=32]="NEXT",u[u.RESPOND=128]="RESPOND",u[u.RESUME_ENABLE=128]="RESUME_ENABLE",function(l){l.hasMetadata=function(n){return(n&l.METADATA)===l.METADATA},l.hasComplete=function(n){return(n&l.COMPLETE)===l.COMPLETE},l.hasNext=function(n){return(n&l.NEXT)===l.NEXT},l.hasFollows=function(n){return(n&l.FOLLOWS)===l.FOLLOWS},l.hasIgnore=function(n){return(n&l.IGNORE)===l.IGNORE},l.hasRespond=function(n){return(n&l.RESPOND)===l.RESPOND},l.hasLease=function(n){return(n&l.LEASE)===l.LEASE},l.hasResume=function(n){return(n&l.RESUME_ENABLE)===l.RESUME_ENABLE}}(l.Flags||(l.Flags={})),(e=l.Lengths||(l.Lengths={}))[e.FRAME=3]="FRAME",e[e.HEADER=6]="HEADER",e[e.METADATA=3]="METADATA",e[e.REQUEST=3]="REQUEST",(t=l.Frame||(l.Frame={})).isConnection=function(l){return 0===l.streamId},t.isRequest=function(l){return n.REQUEST_RESPONSE<=l.type&&l.type<=n.REQUEST_CHANNEL}}(rl),function(l){var n=r&&r.__generator||function(l,n){var u,e,t,r,i={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function s(r){return function(s){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;i;)try{if(u=1,e&&(t=2&r[0]?e.return:r[0]?e.throw||((t=e.return)&&t.call(e),0):e.next)&&!(t=t.call(e,r[1])).done)return t;switch(e=0,t&&(r=[2&r[0],t.value]),r[0]){case 0:case 1:t=r;break;case 4:return i.label++,{value:r[1],done:!1};case 5:i.label++,e=r[1],r=[0];continue;case 7:r=i.ops.pop(),i.trys.pop();continue;default:if(!(t=i.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){i=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){i.label=r[1];break}if(6===r[0]&&i.label<t[1]){i.label=t[1],t=r;break}if(t&&i.label<t[2]){i.label=t[2],i.ops.push(r);break}t[2]&&i.ops.pop(),i.trys.pop();continue}r=n.call(l,i)}catch(l){r=[6,l],e=0}finally{u=t=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,s])}}};Object.defineProperty(l,"__esModule",{value:!0}),l.Deserializer=l.sizeOfFrame=l.serializeFrame=l.deserializeFrame=l.serializeFrameWithLength=l.deserializeFrames=l.deserializeFrameWithLength=l.writeUInt64BE=l.readUInt64BE=l.writeUInt24BE=l.readUInt24BE=l.MAX_VERSION=l.MAX_TTL=l.MAX_STREAM_ID=l.MAX_RESUME_LENGTH=l.MAX_REQUEST_N=l.MAX_REQUEST_COUNT=l.MAX_MIME_LENGTH=l.MAX_METADATA_LENGTH=l.MAX_LIFETIME=l.MAX_KEEPALIVE=l.MAX_CODE=l.FRAME_TYPE_OFFFSET=l.FLAGS_MASK=void 0;var u=rl;l.FLAGS_MASK=1023,l.FRAME_TYPE_OFFFSET=10,l.MAX_CODE=2147483647,l.MAX_KEEPALIVE=2147483647,l.MAX_LIFETIME=2147483647,l.MAX_METADATA_LENGTH=16777215,l.MAX_MIME_LENGTH=255,l.MAX_REQUEST_COUNT=2147483647,l.MAX_REQUEST_N=2147483647,l.MAX_RESUME_LENGTH=65535,l.MAX_STREAM_ID=2147483647,l.MAX_TTL=2147483647,l.MAX_VERSION=65535;var e=4294967296;function t(l,n){return l.readUInt8(n)<<16|l.readUInt8(n+1)<<8|l.readUInt8(n+2)}function i(l,n,u){return u=l.writeUInt8(n>>>16,u),u=l.writeUInt8(n>>>8&255,u),l.writeUInt8(255&n,u)}function s(l,n){var u=l.readUInt32BE(n),t=l.readUInt32BE(n+4);return u*e+t}function o(l,n,u){var t=n/e|0,r=n%e;return u=l.writeUInt32BE(t,u),l.writeUInt32BE(r,u)}l.readUInt24BE=t,l.writeUInt24BE=i,l.readUInt64BE=s,l.writeUInt64BE=o;function a(l){var n=t(l,0);return h(l.slice(3,3+n))}function c(l){var u,e,r,i,s;return n(this,(function(n){switch(n.label){case 0:u=0,n.label=1;case 1:return u+3<l.length?(e=t(l,u),(i=(r=u+3)+e)>l.length?[3,3]:(s=l.slice(r,i),[4,[h(s),u=i]])):[3,3];case 2:return n.sent(),[3,1];case 3:return[2]}}))}function h(n){var e=0,t=n.readInt32BE(e);e+=4;var r=n.readUInt16BE(e);e+=2;var i=r>>>l.FRAME_TYPE_OFFFSET,o=r&l.FLAGS_MASK;switch(i){case u.FrameTypes.SETUP:return function(l,n,e){l.length;var t=6,r=l.readUInt16BE(t);t+=2;var i=l.readUInt16BE(t);t+=2;var s=l.readInt32BE(t);t+=4;var o=l.readInt32BE(t);t+=4;var a=null;if(e&u.Flags.RESUME_ENABLE){var c=l.readInt16BE(t);t+=2,a=l.slice(t,t+c),t+=c}var h=l.readUInt8(t);t+=1;var d=l.toString("ascii",t,t+h);t+=h;var f=l.readUInt8(t);t+=1;var p=l.toString("ascii",t,t+f);t+=f;var y={data:null,dataMimeType:p,flags:e,keepAlive:s,lifetime:o,majorVersion:r,metadata:null,metadataMimeType:d,minorVersion:i,resumeToken:a,streamId:0,type:u.FrameTypes.SETUP};return _(l,y,t),y}(n,0,o);case u.FrameTypes.PAYLOAD:return function(l,n,e){l.length;var t={data:null,flags:e,metadata:null,streamId:n,type:u.FrameTypes.PAYLOAD};return _(l,t,6),t}(n,t,o);case u.FrameTypes.ERROR:return function(l,n,e){l.length;var t=6,r=l.readInt32BE(t);t+=4;var i=l.length-t,s="";i>0&&(s=l.toString("utf8",t,t+i),t+=i);return{code:r,flags:e,message:s,streamId:n,type:u.FrameTypes.ERROR}}(n,t,o);case u.FrameTypes.KEEPALIVE:return function(l,n,e){l.length;var t=6,r=s(l,t);t+=8;var i=null;t<l.length&&(i=l.slice(t,l.length));return{data:i,flags:e,lastReceivedPosition:r,streamId:0,type:u.FrameTypes.KEEPALIVE}}(n,0,o);case u.FrameTypes.REQUEST_FNF:return function(l,n,e){l.length;var t={data:null,flags:e,metadata:null,streamId:n,type:u.FrameTypes.REQUEST_FNF};return _(l,t,6),t}(n,t,o);case u.FrameTypes.REQUEST_RESPONSE:return function(l,n,e){var t={data:null,flags:e,metadata:null,streamId:n,type:u.FrameTypes.REQUEST_RESPONSE};return _(l,t,6),t}(n,t,o);case u.FrameTypes.REQUEST_STREAM:return function(l,n,e){l.length;var t=6,r=l.readInt32BE(t);t+=4;var i={data:null,flags:e,metadata:null,requestN:r,streamId:n,type:u.FrameTypes.REQUEST_STREAM};return _(l,i,t),i}(n,t,o);case u.FrameTypes.REQUEST_CHANNEL:return function(l,n,e){l.length;var t=6,r=l.readInt32BE(t);t+=4;var i={data:null,flags:e,metadata:null,requestN:r,streamId:n,type:u.FrameTypes.REQUEST_CHANNEL};return _(l,i,t),i}(n,t,o);case u.FrameTypes.METADATA_PUSH:return function(l,n,e){return{flags:e,metadata:6===length?null:l.slice(6,length),streamId:0,type:u.FrameTypes.METADATA_PUSH}}(n,0,o);case u.FrameTypes.REQUEST_N:return function(l,n,e){l.length;var t=l.readInt32BE(6);return{flags:e,requestN:t,streamId:n,type:u.FrameTypes.REQUEST_N}}(n,t,o);case u.FrameTypes.RESUME:return function(l,n,e){l.length;var t=6,r=l.readUInt16BE(t);t+=2;var i=l.readUInt16BE(t);t+=2;var o=l.readInt16BE(t);t+=2;var a=l.slice(t,t+o);t+=o;var c=s(l,t);t+=8;var h=s(l,t);return t+=8,{clientPosition:h,flags:e,majorVersion:r,minorVersion:i,resumeToken:a,serverPosition:c,streamId:0,type:u.FrameTypes.RESUME}}(n,0,o);case u.FrameTypes.RESUME_OK:return function(l,n,e){l.length;var t=s(l,6);return{clientPosition:t,flags:e,streamId:0,type:u.FrameTypes.RESUME_OK}}(n,0,o);case u.FrameTypes.CANCEL:return function(l,n,e){return l.length,{flags:e,streamId:n,type:u.FrameTypes.CANCEL}}(n,t,o);case u.FrameTypes.LEASE:return function(l,n,e){var t=6,r=l.readUInt32BE(t);t+=4;var i=l.readUInt32BE(t);t+=4;var s=null;t<l.length&&(s=l.slice(t,l.length));return{flags:e,metadata:s,requestCount:i,streamId:0,ttl:r,type:u.FrameTypes.LEASE}}(n,0,o)}}function d(l){switch(l.type){case u.FrameTypes.SETUP:return function(l){var n=null!=l.resumeToken?l.resumeToken.byteLength:0,e=null!=l.metadataMimeType?el.Buffer.byteLength(l.metadataMimeType,"ascii"):0,t=null!=l.dataMimeType?el.Buffer.byteLength(l.dataMimeType,"ascii"):0,r=T(l),i=el.Buffer.allocUnsafe(6+f+(n?p+n:0)+e+t+r),s=S(l,i);s=i.writeUInt16BE(l.majorVersion,s),s=i.writeUInt16BE(l.minorVersion,s),s=i.writeUInt32BE(l.keepAlive,s),s=i.writeUInt32BE(l.lifetime,s),l.flags&u.Flags.RESUME_ENABLE&&(s=i.writeUInt16BE(n,s),null!=l.resumeToken&&(s+=l.resumeToken.copy(i,s)));s=i.writeUInt8(e,s),null!=l.metadataMimeType&&(s+=i.write(l.metadataMimeType,s,s+e,"ascii"));s=i.writeUInt8(t,s),null!=l.dataMimeType&&(s+=i.write(l.dataMimeType,s,s+t,"ascii"));return R(l,i,s),i}(l);case u.FrameTypes.PAYLOAD:return function(l){var n=T(l),u=el.Buffer.allocUnsafe(6+n),e=S(l,u);return R(l,u,e),u}(l);case u.FrameTypes.ERROR:return function(l){var n=null!=l.message?el.Buffer.byteLength(l.message,"utf8"):0,u=el.Buffer.allocUnsafe(6+y+n),e=S(l,u);e=u.writeUInt32BE(l.code,e),null!=l.message&&u.write(l.message,e,e+n,"utf8");return u}(l);case u.FrameTypes.KEEPALIVE:return function(l){var n=null!=l.data?l.data.byteLength:0,u=el.Buffer.allocUnsafe(6+m+n),e=S(l,u);e=o(u,l.lastReceivedPosition,e),null!=l.data&&l.data.copy(u,e);return u}(l);case u.FrameTypes.REQUEST_FNF:case u.FrameTypes.REQUEST_RESPONSE:return function(l){var n=T(l),u=el.Buffer.allocUnsafe(6+n),e=S(l,u);return R(l,u,e),u}(l);case u.FrameTypes.REQUEST_STREAM:case u.FrameTypes.REQUEST_CHANNEL:return function(l){var n=T(l),u=el.Buffer.allocUnsafe(6+E+n),e=S(l,u);return e=u.writeUInt32BE(l.requestN,e),R(l,u,e),u}(l);case u.FrameTypes.METADATA_PUSH:return function(l){var n=l.metadata;if(null!=n){var u=S(l,e=el.Buffer.allocUnsafe(6+n.byteLength));return n.copy(e,u),e}var e;return S(l,e=el.Buffer.allocUnsafe(6)),e}(l);case u.FrameTypes.REQUEST_N:return function(l){var n=el.Buffer.allocUnsafe(6+w),u=S(l,n);return n.writeUInt32BE(l.requestN,u),n}(l);case u.FrameTypes.RESUME:return function(l){var n=l.resumeToken.byteLength,u=el.Buffer.allocUnsafe(6+v+n),e=S(l,u);return e=u.writeUInt16BE(l.majorVersion,e),e=u.writeUInt16BE(l.minorVersion,e),e=u.writeUInt16BE(n,e),e+=l.resumeToken.copy(u,e),e=o(u,l.serverPosition,e),o(u,l.clientPosition,e),u}(l);case u.FrameTypes.RESUME_OK:return function(l){var n=el.Buffer.allocUnsafe(6+b),u=S(l,n);return o(n,l.clientPosition,u),n}(l);case u.FrameTypes.CANCEL:return function(l){var n=el.Buffer.allocUnsafe(6);return S(l,n),n}(l);case u.FrameTypes.LEASE:return function(l){var n=null!=l.metadata?l.metadata.byteLength:0,u=el.Buffer.allocUnsafe(6+g+n),e=S(l,u);e=u.writeUInt32BE(l.ttl,e),e=u.writeUInt32BE(l.requestCount,e),null!=l.metadata&&l.metadata.copy(u,e);return u}(l)}}l.deserializeFrameWithLength=a,l.deserializeFrames=c,l.serializeFrameWithLength=function(l){var n=d(l),u=el.Buffer.allocUnsafe(n.length+3);return i(u,n.length,0),n.copy(u,3),u},l.deserializeFrame=h,l.serializeFrame=d,l.sizeOfFrame=function(l){switch(l.type){case u.FrameTypes.SETUP:return function(l){var n=null!=l.resumeToken?l.resumeToken.byteLength:0,u=null!=l.metadataMimeType?el.Buffer.byteLength(l.metadataMimeType,"ascii"):0,e=null!=l.dataMimeType?el.Buffer.byteLength(l.dataMimeType,"ascii"):0,t=T(l);return 6+f+(n?p+n:0)+u+e+t}(l);case u.FrameTypes.PAYLOAD:return function(l){var n=T(l);return 6+n}(l);case u.FrameTypes.ERROR:return function(l){var n=null!=l.message?el.Buffer.byteLength(l.message,"utf8"):0;return 6+y+n}(l);case u.FrameTypes.KEEPALIVE:return function(l){var n=null!=l.data?l.data.byteLength:0;return 6+m+n}(l);case u.FrameTypes.REQUEST_FNF:case u.FrameTypes.REQUEST_RESPONSE:return function(l){var n=T(l);return 6+n}(l);case u.FrameTypes.REQUEST_STREAM:case u.FrameTypes.REQUEST_CHANNEL:return function(l){var n=T(l);return 6+E+n}(l);case u.FrameTypes.METADATA_PUSH:return function(l){return 6+(null!=l.metadata?l.metadata.byteLength:0)}(l);case u.FrameTypes.REQUEST_N:return 6+w;case u.FrameTypes.RESUME:return function(l){var n=l.resumeToken.byteLength;return 6+v+n}(l);case u.FrameTypes.RESUME_OK:return 6+b;case u.FrameTypes.CANCEL:return 6;case u.FrameTypes.LEASE:return function(l){var n=null!=l.metadata?l.metadata.byteLength:0;return 6+g+n}(l)}};var f=14,p=2;var y=4;var m=8;var g=8;var E=4;var w=4;var v=22;var b=8;function S(n,u){var e=u.writeInt32BE(n.streamId,0);return u.writeUInt16BE(n.type<<l.FRAME_TYPE_OFFFSET|n.flags&l.FLAGS_MASK,e)}function T(l){var n=0;return null!=l.data&&(n+=l.data.byteLength),u.Flags.hasMetadata(l.flags)&&(n+=3,null!=l.metadata&&(n+=l.metadata.byteLength)),n}function R(l,n,e){u.Flags.hasMetadata(l.flags)&&(null!=l.metadata?(e=i(n,l.metadata.byteLength,e),e+=l.metadata.copy(n,e)):e=i(n,0,e));null!=l.data&&l.data.copy(n,e)}function _(l,n,e){if(u.Flags.hasMetadata(n.flags)){var r=t(l,e);e+=3,r>0&&(n.metadata=l.slice(e,e+r),e+=r)}e<l.length&&(n.data=l.slice(e,l.length))}var A=function(){function l(){}return l.prototype.deserializeFrame=function(l){return h(l)},l.prototype.deserializeFrameWithLength=function(l){return a(l)},l.prototype.deserializeFrames=function(l){return c(l)},l}();l.Deserializer=A}(tl);var il={};Object.defineProperty(il,"__esModule",{value:!0});var sl={},ol=r&&r.__values||function(l){var n="function"==typeof Symbol&&Symbol.iterator,u=n&&l[n],e=0;if(u)return u.call(l);if(l&&"number"==typeof l.length)return{next:function(){return l&&e>=l.length&&(l=void 0),{value:l&&l[e++],done:!l}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(sl,"__esModule",{value:!0}),sl.Deferred=void 0;var al=function(){function l(){this._done=!1,this.onCloseCallbacks=[]}return Object.defineProperty(l.prototype,"done",{get:function(){return this._done},enumerable:!1,configurable:!0}),l.prototype.close=function(l){var n,u,e,t;if(this.done)console.warn("Trying to close for the second time. ".concat(l?"Dropping error [".concat(l,"]."):""));else if(this._done=!0,this._error=l,l)try{for(var r=ol(this.onCloseCallbacks),i=r.next();!i.done;i=r.next()){(0,i.value)(l)}}catch(l){n={error:l}}finally{try{i&&!i.done&&(u=r.return)&&u.call(r)}finally{if(n)throw n.error}}else try{for(var s=ol(this.onCloseCallbacks),o=s.next();!o.done;o=s.next()){(0,o.value)()}}catch(l){e={error:l}}finally{try{o&&!o.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}},l.prototype.onClose=function(l){this._done?l(this._error):this.onCloseCallbacks.push(l)},l}();sl.Deferred=al;var cl={};!function(l){var n,u=r&&r.__extends||(n=function(l,u){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(l,n){l.__proto__=n}||function(l,n){for(var u in n)Object.prototype.hasOwnProperty.call(n,u)&&(l[u]=n[u])},n(l,u)},function(l,u){if("function"!=typeof u&&null!==u)throw new TypeError("Class extends value "+String(u)+" is not a constructor or null");function e(){this.constructor=l}n(l,u),l.prototype=null===u?Object.create(u):(e.prototype=u.prototype,new e)});Object.defineProperty(l,"__esModule",{value:!0}),l.ErrorCodes=l.RSocketError=void 0;var e,t=function(l){function n(n,u){var e=l.call(this,u)||this;return e.code=n,e}return u(n,l),n}(Error);l.RSocketError=t,(e=l.ErrorCodes||(l.ErrorCodes={}))[e.RESERVED=0]="RESERVED",e[e.INVALID_SETUP=1]="INVALID_SETUP",e[e.UNSUPPORTED_SETUP=2]="UNSUPPORTED_SETUP",e[e.REJECTED_SETUP=3]="REJECTED_SETUP",e[e.REJECTED_RESUME=4]="REJECTED_RESUME",e[e.CONNECTION_CLOSE=258]="CONNECTION_CLOSE",e[e.CONNECTION_ERROR=257]="CONNECTION_ERROR",e[e.APPLICATION_ERROR=513]="APPLICATION_ERROR",e[e.REJECTED=514]="REJECTED",e[e.CANCELED=515]="CANCELED",e[e.INVALID=516]="INVALID",e[e.RESERVED_EXTENSION=4294967295]="RESERVED_EXTENSION"}(cl);var hl={};Object.defineProperty(hl,"__esModule",{value:!0});var dl,fl={},pl={};function yl(){return dl||(dl=1,function(l){var n,u=r&&r.__extends||(n=function(l,u){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(l,n){l.__proto__=n}||function(l,n){for(var u in n)Object.prototype.hasOwnProperty.call(n,u)&&(l[u]=n[u])},n(l,u)},function(l,u){if("function"!=typeof u&&null!==u)throw new TypeError("Class extends value "+String(u)+" is not a constructor or null");function e(){this.constructor=l}n(l,u),l.prototype=null===u?Object.create(u):(e.prototype=u.prototype,new e)}),e=r&&r.__awaiter||function(l,n,u,e){return new(u||(u=Promise))((function(t,r){function i(l){try{o(e.next(l))}catch(l){r(l)}}function s(l){try{o(e.throw(l))}catch(l){r(l)}}function o(l){var n;l.done?t(l.value):(n=l.value,n instanceof u?n:new u((function(l){l(n)}))).then(i,s)}o((e=e.apply(l,n||[])).next())}))},t=r&&r.__generator||function(l,n){var u,e,t,r,i={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function s(r){return function(s){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;i;)try{if(u=1,e&&(t=2&r[0]?e.return:r[0]?e.throw||((t=e.return)&&t.call(e),0):e.next)&&!(t=t.call(e,r[1])).done)return t;switch(e=0,t&&(r=[2&r[0],t.value]),r[0]){case 0:case 1:t=r;break;case 4:return i.label++,{value:r[1],done:!1};case 5:i.label++,e=r[1],r=[0];continue;case 7:r=i.ops.pop(),i.trys.pop();continue;default:if(!(t=i.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){i=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){i.label=r[1];break}if(6===r[0]&&i.label<t[1]){i.label=t[1],t=r;break}if(t&&i.label<t[2]){i.label=t[2],i.ops.push(r);break}t[2]&&i.ops.pop(),i.trys.pop();continue}r=n.call(l,i)}catch(l){r=[6,l],e=0}finally{u=t=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,s])}}};Object.defineProperty(l,"__esModule",{value:!0}),l.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer=l.ResumableClientServerInputMultiplexerDemultiplexer=l.ClientServerInputMultiplexerDemultiplexer=l.StreamIdGenerator=void 0;var i=Pn(),s=sl,o=cl,a=rl;!function(l){l.create=function(l){return new n(l)};var n=function(){function l(l){this.currentId=l}return l.prototype.next=function(l){var n=this.currentId+2;l(n)&&(this.currentId=n)},l}()}(l.StreamIdGenerator||(l.StreamIdGenerator={}));var c=function(l){function n(n,u,e){var t=l.call(this)||this;return t.streamIdSupplier=n,t.outbound=u,t.closeable=e,t.registry={},e.onClose(t.close.bind(t)),t}return u(n,l),n.prototype.handle=function(l){if(a.Frame.isConnection(l)){if(l.type===i.FrameTypes.RESERVED)return;this.connectionFramesHandler.handle(l)}else if(a.Frame.isRequest(l)){if(this.registry[l.streamId])return;this.requestFramesHandler.handle(l,this)}else{var n=this.registry[l.streamId];if(!n)return;n.handle(l)}},n.prototype.connectionInbound=function(l){if(this.connectionFramesHandler)throw new Error("Connection frame handler has already been installed");this.connectionFramesHandler=l},n.prototype.handleRequestStream=function(l){if(this.requestFramesHandler)throw new Error("Stream handler has already been installed");this.requestFramesHandler=l},n.prototype.send=function(l){this.outbound.send(l)},Object.defineProperty(n.prototype,"connectionOutbound",{get:function(){return this},enumerable:!1,configurable:!0}),n.prototype.createRequestStream=function(l){var n=this;if(this.done)l.handleReject(new Error("Already closed"));else{var u=this.registry;this.streamIdSupplier.next((function(u){return l.handleReady(u,n)}),Object.keys(u))}},n.prototype.connect=function(l){this.registry[l.streamId]=l},n.prototype.disconnect=function(l){delete this.registry[l.streamId]},n.prototype.close=function(n){if(this.done)l.prototype.close.call(this,n);else{for(var u in this.registry){this.registry[u].close(new Error("Closed. ".concat(n?"Original cause [".concat(n,"]."):"")))}l.prototype.close.call(this,n)}},n}(s.Deferred);l.ClientServerInputMultiplexerDemultiplexer=c;var h=function(l){function n(n,u,e,t,r,i,o){var a=l.call(this,n,u,new s.Deferred)||this;return a.frameStore=t,a.token=r,a.sessionTimeout=o,i instanceof Function?a.reconnector=i:a.sessionStore=i,e.onClose(a.handleConnectionClose.bind(a)),a}return u(n,l),n.prototype.send=function(n){if(a.Frame.isConnection(n)){if(n.type===i.FrameTypes.KEEPALIVE)n.lastReceivedPosition=this.frameStore.lastReceivedFramePosition;else if(n.type===i.FrameTypes.ERROR)return this.outbound.send(n),this.sessionStore&&delete this.sessionStore[this.token],void l.prototype.close.call(this,new o.RSocketError(n.code,n.message))}else this.frameStore.store(n);this.outbound.send(n)},n.prototype.handle=function(n){if(a.Frame.isConnection(n)){if(n.type===i.FrameTypes.KEEPALIVE)try{this.frameStore.dropTo(n.lastReceivedPosition)}catch(l){this.outbound.send({type:i.FrameTypes.ERROR,streamId:0,flags:i.Flags.NONE,code:l.code,message:l.message}),this.close(l)}else if(n.type===i.FrameTypes.ERROR)return l.prototype.handle.call(this,n),this.sessionStore&&delete this.sessionStore[this.token],void l.prototype.close.call(this,new o.RSocketError(n.code,n.message))}else this.frameStore.record(n);l.prototype.handle.call(this,n)},n.prototype.resume=function(l,n,u){switch(this.outbound=n,l.type){case i.FrameTypes.RESUME:if(clearTimeout(this.timeoutId),this.frameStore.lastReceivedFramePosition<l.clientPosition){var e=new o.RSocketError(i.ErrorCodes.REJECTED_RESUME,"Impossible to resume since first available client frame position is greater than last received server frame position");return this.outbound.send({type:i.FrameTypes.ERROR,streamId:0,flags:i.Flags.NONE,code:e.code,message:e.message}),void this.close(e)}try{this.frameStore.dropTo(l.serverPosition)}catch(l){return this.outbound.send({type:i.FrameTypes.ERROR,streamId:0,flags:i.Flags.NONE,code:l.code,message:l.message}),void this.close(l)}this.outbound.send({type:i.FrameTypes.RESUME_OK,streamId:0,flags:i.Flags.NONE,clientPosition:this.frameStore.lastReceivedFramePosition});break;case i.FrameTypes.RESUME_OK:try{this.frameStore.dropTo(l.clientPosition)}catch(l){this.outbound.send({type:i.FrameTypes.ERROR,streamId:0,flags:i.Flags.NONE,code:l.code,message:l.message}),this.close(l)}}this.frameStore.drain(this.outbound.send.bind(this.outbound)),u.onClose(this.handleConnectionClose.bind(this)),this.connectionFramesHandler.resume()},n.prototype.handleConnectionClose=function(l){return e(this,void 0,void 0,(function(){var l;return t(this,(function(n){switch(n.label){case 0:if(this.connectionFramesHandler.pause(),!this.reconnector)return[3,5];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.reconnector(this,this.frameStore)];case 2:return n.sent(),[3,4];case 3:return l=n.sent(),this.close(l),[3,4];case 4:return[3,6];case 5:this.timeoutId=setTimeout(this.close.bind(this),this.sessionTimeout),n.label=6;case 6:return[2]}}))}))},n}(c);l.ResumableClientServerInputMultiplexerDemultiplexer=h;var d=function(){function l(l,n,u){this.outbound=l,this.closeable=n,this.delegate=u,this.resumed=!1}return l.prototype.close=function(){this.delegate.close()},l.prototype.onClose=function(l){this.delegate.onClose(l)},Object.defineProperty(l.prototype,"connectionOutbound",{get:function(){return this.delegate.connectionOutbound},enumerable:!1,configurable:!0}),l.prototype.createRequestStream=function(l){this.delegate.createRequestStream(l)},l.prototype.connectionInbound=function(l){this.delegate.connectionInbound(l)},l.prototype.handleRequestStream=function(l){this.delegate.handleRequestStream(l)},l.prototype.handle=function(l){var n=this;if(!this.resumed)return l.type===i.FrameTypes.RESUME_OK?(this.resumed=!0,void this.delegate.resume(l,this.outbound,this.closeable)):(this.outbound.send({type:i.FrameTypes.ERROR,streamId:0,code:i.ErrorCodes.CONNECTION_ERROR,message:"Incomplete RESUME handshake. Unexpected frame ".concat(l.type," received"),flags:i.Flags.NONE}),this.closeable.close(),void this.closeable.onClose((function(){return n.delegate.close(new o.RSocketError(i.ErrorCodes.CONNECTION_ERROR,"Incomplete RESUME handshake. Unexpected frame ".concat(l.type," received")))})));this.delegate.handle(l)},l}();l.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer=d}(pl)),pl}var ml={},gl={},El={},wl=r&&r.__generator||function(l,n){var u,e,t,r,i={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function s(r){return function(s){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;i;)try{if(u=1,e&&(t=2&r[0]?e.return:r[0]?e.throw||((t=e.return)&&t.call(e),0):e.next)&&!(t=t.call(e,r[1])).done)return t;switch(e=0,t&&(r=[2&r[0],t.value]),r[0]){case 0:case 1:t=r;break;case 4:return i.label++,{value:r[1],done:!1};case 5:i.label++,e=r[1],r=[0];continue;case 7:r=i.ops.pop(),i.trys.pop();continue;default:if(!(t=i.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){i=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){i.label=r[1];break}if(6===r[0]&&i.label<t[1]){i.label=t[1],t=r;break}if(t&&i.label<t[2]){i.label=t[2],i.ops.push(r);break}t[2]&&i.ops.pop(),i.trys.pop();continue}r=n.call(l,i)}catch(l){r=[6,l],e=0}finally{u=t=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,s])}}};Object.defineProperty(El,"__esModule",{value:!0}),El.fragmentWithRequestN=El.fragment=El.isFragmentable=void 0;var vl=rl;El.isFragmentable=function(l,n,u){return 0!==n&&l.data.byteLength+(l.metadata?l.metadata.byteLength+vl.Lengths.METADATA:0)+(u==vl.FrameTypes.REQUEST_STREAM||u==vl.FrameTypes.REQUEST_CHANNEL?vl.Lengths.REQUEST:0)>n},El.fragment=function(l,n,u,e,t){var r,i,s,o,a,c,h,d,f,p,y,m;return void 0===t&&(t=!1),wl(this,(function(g){switch(g.label){case 0:return r=null!==(m=null===(y=n.data)||void 0===y?void 0:y.byteLength)&&void 0!==m?m:0,i=e!==vl.FrameTypes.PAYLOAD,s=u,n.metadata?0!==(a=n.metadata.byteLength)?[3,1]:(s-=vl.Lengths.METADATA,o=el.Buffer.allocUnsafe(0),[3,6]):[3,6];case 1:return c=0,i?(s-=vl.Lengths.METADATA,h=Math.min(a,c+s),o=n.metadata.slice(c,h),s-=o.byteLength,c=h,0!==s?[3,3]:(i=!1,[4,{type:e,flags:vl.Flags.FOLLOWS|vl.Flags.METADATA,data:void 0,metadata:o,streamId:l}])):[3,3];case 2:g.sent(),o=void 0,s=u,g.label=3;case 3:return c<a?(s-=vl.Lengths.METADATA,h=Math.min(a,c+s),o=n.metadata.slice(c,h),s-=o.byteLength,c=h,0!==s&&0!==r?[3,5]:[4,{type:vl.FrameTypes.PAYLOAD,flags:vl.Flags.NEXT|vl.Flags.METADATA|(c===a&&t&&0===r?vl.Flags.COMPLETE:vl.Flags.FOLLOWS),data:void 0,metadata:o,streamId:l}]):[3,6];case 4:g.sent(),o=void 0,s=u,g.label=5;case 5:return[3,3];case 6:return d=0,i?(p=Math.min(r,d+s),f=n.data.slice(d,p),s-=f.byteLength,d=p,[4,{type:e,flags:vl.Flags.FOLLOWS|(o?vl.Flags.METADATA:vl.Flags.NONE),data:f,metadata:o,streamId:l}]):[3,8];case 7:g.sent(),o=void 0,f=void 0,s=u,g.label=8;case 8:return d<r?(p=Math.min(r,d+s),f=n.data.slice(d,p),s-=f.byteLength,d=p,[4,{type:vl.FrameTypes.PAYLOAD,flags:d===r?(t?vl.Flags.COMPLETE:vl.Flags.NONE)|vl.Flags.NEXT|(o?vl.Flags.METADATA:0):vl.Flags.FOLLOWS|vl.Flags.NEXT|(o?vl.Flags.METADATA:0),data:f,metadata:o,streamId:l}]):[3,10];case 9:return g.sent(),o=void 0,f=void 0,s=u,[3,8];case 10:return[2]}}))},El.fragmentWithRequestN=function(l,n,u,e,t,r){var i,s,o,a,c,h,d,f,p,y,m,g;return void 0===r&&(r=!1),wl(this,(function(E){switch(E.label){case 0:return i=null!==(g=null===(m=n.data)||void 0===m?void 0:m.byteLength)&&void 0!==g?g:0,s=!0,o=u,n.metadata?0!==(c=n.metadata.byteLength)?[3,1]:(o-=vl.Lengths.METADATA,a=el.Buffer.allocUnsafe(0),[3,6]):[3,6];case 1:return h=0,s?(o-=vl.Lengths.METADATA+vl.Lengths.REQUEST,d=Math.min(c,h+o),a=n.metadata.slice(h,d),o-=a.byteLength,h=d,0!==o?[3,3]:(s=!1,[4,{type:e,flags:vl.Flags.FOLLOWS|vl.Flags.METADATA,data:void 0,requestN:t,metadata:a,streamId:l}])):[3,3];case 2:E.sent(),a=void 0,o=u,E.label=3;case 3:return h<c?(o-=vl.Lengths.METADATA,d=Math.min(c,h+o),a=n.metadata.slice(h,d),o-=a.byteLength,h=d,0!==o&&0!==i?[3,5]:[4,{type:vl.FrameTypes.PAYLOAD,flags:vl.Flags.NEXT|vl.Flags.METADATA|(h===c&&r&&0===i?vl.Flags.COMPLETE:vl.Flags.FOLLOWS),data:void 0,metadata:a,streamId:l}]):[3,6];case 4:E.sent(),a=void 0,o=u,E.label=5;case 5:return[3,3];case 6:return f=0,s?(o-=vl.Lengths.REQUEST,y=Math.min(i,f+o),p=n.data.slice(f,y),o-=p.byteLength,f=y,[4,{type:e,flags:vl.Flags.FOLLOWS|(a?vl.Flags.METADATA:vl.Flags.NONE),data:p,requestN:t,metadata:a,streamId:l}]):[3,8];case 7:E.sent(),a=void 0,p=void 0,o=u,E.label=8;case 8:return f<i?(y=Math.min(i,f+o),p=n.data.slice(f,y),o-=p.byteLength,f=y,[4,{type:vl.FrameTypes.PAYLOAD,flags:f===i?(r?vl.Flags.COMPLETE:vl.Flags.NONE)|vl.Flags.NEXT|(a?vl.Flags.METADATA:0):vl.Flags.FOLLOWS|vl.Flags.NEXT|(a?vl.Flags.METADATA:0),data:p,metadata:a,streamId:l}]):[3,10];case 9:return E.sent(),a=void 0,p=void 0,o=u,[3,8];case 10:return[2]}}))};var bl={};Object.defineProperty(bl,"__esModule",{value:!0}),bl.cancel=bl.reassemble=bl.add=void 0,bl.add=function(l,n,u){return l.hasFragments?(l.data=l.data?el.Buffer.concat([l.data,n]):n,l.metadata&&u&&(l.metadata=el.Buffer.concat([l.metadata,u])),!0):(l.hasFragments=!0,l.data=n,u&&(l.metadata=u),!0)},bl.reassemble=function(l,n,u){l.hasFragments=!1;var e=l.data?el.Buffer.concat([l.data,n]):n;if(l.data=void 0,l.metadata){var t=u?el.Buffer.concat([l.metadata,u]):l.metadata;return l.metadata=void 0,{data:e,metadata:t}}return{data:e}},bl.cancel=function(l){l.hasFragments=!1,l.data=void 0,l.metadata=void 0};var Sl=r&&r.__createBinding||(Object.create?function(l,n,u,e){void 0===e&&(e=u),Object.defineProperty(l,e,{enumerable:!0,get:function(){return n[u]}})}:function(l,n,u,e){void 0===e&&(e=u),l[e]=n[u]}),Tl=r&&r.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),Rl=r&&r.__importStar||function(l){if(l&&l.__esModule)return l;var n={};if(null!=l)for(var u in l)"default"!==u&&Object.prototype.hasOwnProperty.call(l,u)&&Sl(n,l,u);return Tl(n,l),n},_l=r&&r.__values||function(l){var n="function"==typeof Symbol&&Symbol.iterator,u=n&&l[n],e=0;if(u)return u.call(l);if(l&&"number"==typeof l.length)return{next:function(){return l&&e>=l.length&&(l=void 0),{value:l&&l[e++],done:!l}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(gl,"__esModule",{value:!0}),gl.RequestChannelResponderStream=gl.RequestChannelRequesterStream=void 0;var Al=cl,Ol=El,Fl=rl,Cl=Rl(bl),Il=function(){function l(l,n,u,e,t,r){this.payload=l,this.isComplete=n,this.receiver=u,this.fragmentSize=e,this.initialRequestN=t,this.leaseManager=r,this.streamType=Fl.FrameTypes.REQUEST_CHANNEL}return l.prototype.handleReady=function(l,n){var u,e;if(this.outboundDone)return!1;this.streamId=l,this.stream=n,n.connect(this);var t=this.isComplete;if(t&&(this.outboundDone=t),(0,Ol.isFragmentable)(this.payload,this.fragmentSize,Fl.FrameTypes.REQUEST_CHANNEL))try{for(var r=_l((0,Ol.fragmentWithRequestN)(l,this.payload,this.fragmentSize,Fl.FrameTypes.REQUEST_CHANNEL,this.initialRequestN,t)),i=r.next();!i.done;i=r.next()){var s=i.value;this.stream.send(s)}}catch(l){u={error:l}}finally{try{i&&!i.done&&(e=r.return)&&e.call(r)}finally{if(u)throw u.error}}else this.stream.send({type:Fl.FrameTypes.REQUEST_CHANNEL,data:this.payload.data,metadata:this.payload.metadata,requestN:this.initialRequestN,flags:(void 0!==this.payload.metadata?Fl.Flags.METADATA:Fl.Flags.NONE)|(t?Fl.Flags.COMPLETE:Fl.Flags.NONE),streamId:l});return this.hasExtension&&this.stream.send({type:Fl.FrameTypes.EXT,streamId:l,extendedContent:this.extendedContent,extendedType:this.extendedType,flags:this.flags}),!0},l.prototype.handleReject=function(l){this.inboundDone||(this.inboundDone=!0,this.outboundDone=!0,this.receiver.onError(l))},l.prototype.handle=function(l){var n,u=l.type;switch(u){case Fl.FrameTypes.PAYLOAD:var e=Fl.Flags.hasComplete(l.flags),t=Fl.Flags.hasNext(l.flags);if(e||!Fl.Flags.hasFollows(l.flags)){if(e&&(this.inboundDone=!0,this.outboundDone&&this.stream.disconnect(this),!t))return void this.receiver.onComplete();var r=this.hasFragments?Cl.reassemble(this,l.data,l.metadata):{data:l.data,metadata:l.metadata};return void this.receiver.onNext(r,e)}if(Cl.add(this,l.data,l.metadata))return;n="Unexpected frame size";break;case Fl.FrameTypes.CANCEL:if(this.outboundDone)return;return this.outboundDone=!0,this.inboundDone&&this.stream.disconnect(this),void this.receiver.cancel();case Fl.FrameTypes.REQUEST_N:if(this.outboundDone)return;if(this.hasFragments){n="Unexpected frame type [".concat(u,"] during reassembly");break}return void this.receiver.request(l.requestN);case Fl.FrameTypes.ERROR:var i=this.outboundDone;return this.inboundDone=!0,this.outboundDone=!0,this.stream.disconnect(this),Cl.cancel(this),i||this.receiver.cancel(),void this.receiver.onError(new Al.RSocketError(l.code,l.message));case Fl.FrameTypes.EXT:return void this.receiver.onExtension(l.extendedType,l.extendedContent,Fl.Flags.hasIgnore(l.flags));default:n="Unexpected frame type [".concat(u,"]")}this.close(new Al.RSocketError(Al.ErrorCodes.CANCELED,n)),this.stream.send({type:Fl.FrameTypes.CANCEL,streamId:this.streamId,flags:Fl.Flags.NONE}),this.stream.disconnect(this)},l.prototype.request=function(l){this.inboundDone||(this.streamId?this.stream.send({type:Fl.FrameTypes.REQUEST_N,flags:Fl.Flags.NONE,requestN:l,streamId:this.streamId}):this.initialRequestN+=l)},l.prototype.cancel=function(){var l,n=this.inboundDone,u=this.outboundDone;n&&u||(this.inboundDone=!0,this.outboundDone=!0,u||this.receiver.cancel(),this.streamId?(this.stream.send({type:n?Fl.FrameTypes.ERROR:Fl.FrameTypes.CANCEL,flags:Fl.Flags.NONE,streamId:this.streamId,code:Al.ErrorCodes.CANCELED,message:"Cancelled"}),this.stream.disconnect(this),Cl.cancel(this)):null===(l=this.leaseManager)||void 0===l||l.cancelRequest(this))},l.prototype.onNext=function(l,n){var u,e;if(!this.outboundDone)if(n&&(this.outboundDone=!0,this.inboundDone&&this.stream.disconnect(this)),(0,Ol.isFragmentable)(l,this.fragmentSize,Fl.FrameTypes.PAYLOAD))try{for(var t=_l((0,Ol.fragment)(this.streamId,l,this.fragmentSize,Fl.FrameTypes.PAYLOAD,n)),r=t.next();!r.done;r=t.next()){var i=r.value;this.stream.send(i)}}catch(l){u={error:l}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(u)throw u.error}}else this.stream.send({type:Fl.FrameTypes.PAYLOAD,streamId:this.streamId,flags:Fl.Flags.NEXT|(l.metadata?Fl.Flags.METADATA:Fl.Flags.NONE)|(n?Fl.Flags.COMPLETE:Fl.Flags.NONE),data:l.data,metadata:l.metadata})},l.prototype.onComplete=function(){this.streamId?this.outboundDone||(this.outboundDone=!0,this.stream.send({type:Fl.FrameTypes.PAYLOAD,streamId:this.streamId,flags:Fl.Flags.COMPLETE,data:null,metadata:null}),this.inboundDone&&this.stream.disconnect(this)):this.isComplete=!0},l.prototype.onError=function(l){if(!this.outboundDone){var n=this.inboundDone;this.outboundDone=!0,this.inboundDone=!0,this.stream.send({type:Fl.FrameTypes.ERROR,streamId:this.streamId,flags:Fl.Flags.NONE,code:l instanceof Al.RSocketError?l.code:Al.ErrorCodes.APPLICATION_ERROR,message:l.message}),this.stream.disconnect(this),n||this.receiver.onError(l)}},l.prototype.onExtension=function(l,n,u){if(!this.outboundDone)return this.streamId?void this.stream.send({streamId:this.streamId,type:Fl.FrameTypes.EXT,extendedType:l,extendedContent:n,flags:u?Fl.Flags.IGNORE:Fl.Flags.NONE}):(this.hasExtension=!0,this.extendedType=l,this.extendedContent=n,void(this.flags=u?Fl.Flags.IGNORE:Fl.Flags.NONE))},l.prototype.close=function(l){if(!this.inboundDone||!this.outboundDone){var n=this.inboundDone,u=this.outboundDone;this.inboundDone=!0,this.outboundDone=!0,Cl.cancel(this),u||this.receiver.cancel(),n||(l?this.receiver.onError(l):this.receiver.onComplete())}},l}();gl.RequestChannelRequesterStream=Il;var kl=function(){function l(l,n,u,e,t){if(this.streamId=l,this.stream=n,this.fragmentSize=u,this.handler=e,this.streamType=Fl.FrameTypes.REQUEST_CHANNEL,n.connect(this),Fl.Flags.hasFollows(t.flags))return Cl.add(this,t.data,t.metadata),this.initialRequestN=t.requestN,void(this.isComplete=Fl.Flags.hasComplete(t.flags));var r={data:t.data,metadata:t.metadata},i=Fl.Flags.hasComplete(t.flags);this.inboundDone=i;try{this.receiver=e(r,t.requestN,i,this),this.outboundDone&&this.defferedError&&this.receiver.onError(this.defferedError)}catch(l){this.outboundDone&&!this.inboundDone?this.cancel():this.inboundDone=!0,this.onError(l)}}return l.prototype.handle=function(l){var n,u=l.type;switch(u){case Fl.FrameTypes.PAYLOAD:if(Fl.Flags.hasFollows(l.flags)){if(Cl.add(this,l.data,l.metadata))return;n="Unexpected frame size";break}var e=this.hasFragments?Cl.reassemble(this,l.data,l.metadata):{data:l.data,metadata:l.metadata},t=Fl.Flags.hasComplete(l.flags);if(this.receiver){if(t&&(this.inboundDone=!0,this.outboundDone&&this.stream.disconnect(this),!Fl.Flags.hasNext(l.flags)))return void this.receiver.onComplete();this.receiver.onNext(e,t)}else{(r=this.isComplete||t)&&(this.inboundDone=!0,this.outboundDone&&this.stream.disconnect(this));try{this.receiver=this.handler(e,this.initialRequestN,r,this),this.outboundDone&&this.defferedError}catch(s){this.outboundDone&&!this.inboundDone?this.cancel():this.inboundDone=!0,this.onError(s)}}return;case Fl.FrameTypes.REQUEST_N:if(!this.receiver||this.hasFragments){n="Unexpected frame type [".concat(u,"] during reassembly");break}return void this.receiver.request(l.requestN);case Fl.FrameTypes.ERROR:case Fl.FrameTypes.CANCEL:var r=this.inboundDone,i=this.outboundDone;if(this.inboundDone=!0,this.outboundDone=!0,this.stream.disconnect(this),Cl.cancel(this),!this.receiver)return;if(i||this.receiver.cancel(),!r){var s=u===Fl.FrameTypes.CANCEL?new Al.RSocketError(Al.ErrorCodes.CANCELED,"Cancelled"):new Al.RSocketError(l.code,l.message);this.receiver.onError(s)}return;case Fl.FrameTypes.EXT:if(!this.receiver||this.hasFragments){n="Unexpected frame type [".concat(u,"] during reassembly");break}return void this.receiver.onExtension(l.extendedType,l.extendedContent,Fl.Flags.hasIgnore(l.flags));default:n="Unexpected frame type [".concat(u,"]")}this.stream.send({type:Fl.FrameTypes.ERROR,flags:Fl.Flags.NONE,code:Al.ErrorCodes.CANCELED,message:n,streamId:this.streamId}),this.stream.disconnect(this),this.close(new Al.RSocketError(Al.ErrorCodes.CANCELED,n))},l.prototype.onError=function(l){if(this.outboundDone)console.warn("Trying to error for the second time. ".concat(l?"Dropping error [".concat(l,"]."):""));else{var n=this.inboundDone;this.outboundDone=!0,this.inboundDone=!0,this.stream.send({type:Fl.FrameTypes.ERROR,flags:Fl.Flags.NONE,code:l instanceof Al.RSocketError?l.code:Al.ErrorCodes.APPLICATION_ERROR,message:l.message,streamId:this.streamId}),this.stream.disconnect(this),n||(this.receiver?this.receiver.onError(l):this.defferedError=l)}},l.prototype.onNext=function(l,n){var u,e;if(!this.outboundDone){if(n&&(this.outboundDone=!0),(0,Ol.isFragmentable)(l,this.fragmentSize,Fl.FrameTypes.PAYLOAD))try{for(var t=_l((0,Ol.fragment)(this.streamId,l,this.fragmentSize,Fl.FrameTypes.PAYLOAD,n)),r=t.next();!r.done;r=t.next()){var i=r.value;this.stream.send(i)}}catch(l){u={error:l}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(u)throw u.error}}else this.stream.send({type:Fl.FrameTypes.PAYLOAD,flags:Fl.Flags.NEXT|(n?Fl.Flags.COMPLETE:Fl.Flags.NONE)|(l.metadata?Fl.Flags.METADATA:Fl.Flags.NONE),data:l.data,metadata:l.metadata,streamId:this.streamId});n&&this.inboundDone&&this.stream.disconnect(this)}},l.prototype.onComplete=function(){this.outboundDone||(this.outboundDone=!0,this.stream.send({type:Fl.FrameTypes.PAYLOAD,flags:Fl.Flags.COMPLETE,streamId:this.streamId,data:null,metadata:null}),this.inboundDone&&this.stream.disconnect(this))},l.prototype.onExtension=function(l,n,u){this.outboundDone&&this.inboundDone||this.stream.send({type:Fl.FrameTypes.EXT,streamId:this.streamId,flags:u?Fl.Flags.IGNORE:Fl.Flags.NONE,extendedType:l,extendedContent:n})},l.prototype.request=function(l){this.inboundDone||this.stream.send({type:Fl.FrameTypes.REQUEST_N,flags:Fl.Flags.NONE,streamId:this.streamId,requestN:l})},l.prototype.cancel=function(){this.inboundDone||(this.inboundDone=!0,this.stream.send({type:Fl.FrameTypes.CANCEL,flags:Fl.Flags.NONE,streamId:this.streamId}),this.outboundDone&&this.stream.disconnect(this))},l.prototype.close=function(l){if(this.inboundDone&&this.outboundDone)console.warn("Trying to close for the second time. ".concat(l?"Dropping error [".concat(l,"]."):""));else{var n=this.inboundDone,u=this.outboundDone;this.inboundDone=!0,this.outboundDone=!0,Cl.cancel(this);var e=this.receiver;e&&(u||e.cancel(),n||(l?e.onError(l):e.onComplete()))}},l}();gl.RequestChannelResponderStream=kl;var Ll={},Nl=r&&r.__createBinding||(Object.create?function(l,n,u,e){void 0===e&&(e=u),Object.defineProperty(l,e,{enumerable:!0,get:function(){return n[u]}})}:function(l,n,u,e){void 0===e&&(e=u),l[e]=n[u]}),Ul=r&&r.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),xl=r&&r.__importStar||function(l){if(l&&l.__esModule)return l;var n={};if(null!=l)for(var u in l)"default"!==u&&Object.prototype.hasOwnProperty.call(l,u)&&Nl(n,l,u);return Ul(n,l),n},Pl=r&&r.__values||function(l){var n="function"==typeof Symbol&&Symbol.iterator,u=n&&l[n],e=0;if(u)return u.call(l);if(l&&"number"==typeof l.length)return{next:function(){return l&&e>=l.length&&(l=void 0),{value:l&&l[e++],done:!l}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(Ll,"__esModule",{value:!0}),Ll.RequestFnfResponderStream=Ll.RequestFnFRequesterStream=void 0;var Dl=cl,Ml=El,Bl=rl,ql=xl(bl),jl=function(){function l(l,n,u,e){this.payload=l,this.receiver=n,this.fragmentSize=u,this.leaseManager=e,this.streamType=Bl.FrameTypes.REQUEST_FNF}return l.prototype.handleReady=function(l,n){var u,e;if(this.done)return!1;if(this.streamId=l,(0,Ml.isFragmentable)(this.payload,this.fragmentSize,Bl.FrameTypes.REQUEST_FNF))try{for(var t=Pl((0,Ml.fragment)(l,this.payload,this.fragmentSize,Bl.FrameTypes.REQUEST_FNF)),r=t.next();!r.done;r=t.next()){var i=r.value;n.send(i)}}catch(l){u={error:l}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(u)throw u.error}}else n.send({type:Bl.FrameTypes.REQUEST_FNF,data:this.payload.data,metadata:this.payload.metadata,flags:this.payload.metadata?Bl.Flags.METADATA:0,streamId:l});return this.done=!0,this.receiver.onComplete(),!0},l.prototype.handleReject=function(l){this.done||(this.done=!0,this.receiver.onError(l))},l.prototype.cancel=function(){var l;this.done||(this.done=!0,null===(l=this.leaseManager)||void 0===l||l.cancelRequest(this))},l.prototype.handle=function(l){l.type!=Bl.FrameTypes.ERROR?this.close(new Dl.RSocketError(Dl.ErrorCodes.CANCELED,"Received invalid frame")):this.close(new Dl.RSocketError(l.code,l.message))},l.prototype.close=function(l){this.done?console.warn("Trying to close for the second time. ".concat(l?"Dropping error [".concat(l,"]."):"")):l?this.receiver.onError(l):this.receiver.onComplete()},l}();Ll.RequestFnFRequesterStream=jl;var Ql=function(){function l(l,n,u,e){if(this.streamId=l,this.stream=n,this.handler=u,this.streamType=Bl.FrameTypes.REQUEST_FNF,Bl.Flags.hasFollows(e.flags))return ql.add(this,e.data,e.metadata),void n.connect(this);var t={data:e.data,metadata:e.metadata};try{this.cancellable=u(t,this)}catch(l){}}return l.prototype.handle=function(l){var n;if(l.type==Bl.FrameTypes.PAYLOAD){if(!Bl.Flags.hasFollows(l.flags)){this.stream.disconnect(this);var u=ql.reassemble(this,l.data,l.metadata);try{this.cancellable=this.handler(u,this)}catch(l){}return}if(ql.add(this,l.data,l.metadata))return;n="Unexpected fragment size"}else n="Unexpected frame type [".concat(l.type,"]");this.done=!0,l.type!=Bl.FrameTypes.CANCEL&&l.type!=Bl.FrameTypes.ERROR&&this.stream.send({type:Bl.FrameTypes.ERROR,streamId:this.streamId,flags:Bl.Flags.NONE,code:Dl.ErrorCodes.CANCELED,message:n}),this.stream.disconnect(this),ql.cancel(this)},l.prototype.close=function(l){var n;this.done?console.warn("Trying to close for the second time. ".concat(l?"Dropping error [".concat(l,"]."):"")):(this.done=!0,ql.cancel(this),null===(n=this.cancellable)||void 0===n||n.cancel())},l.prototype.onError=function(l){},l.prototype.onComplete=function(){},l}();Ll.RequestFnfResponderStream=Ql;var Wl={},$l=r&&r.__createBinding||(Object.create?function(l,n,u,e){void 0===e&&(e=u),Object.defineProperty(l,e,{enumerable:!0,get:function(){return n[u]}})}:function(l,n,u,e){void 0===e&&(e=u),l[e]=n[u]}),zl=r&&r.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),Hl=r&&r.__importStar||function(l){if(l&&l.__esModule)return l;var n={};if(null!=l)for(var u in l)"default"!==u&&Object.prototype.hasOwnProperty.call(l,u)&&$l(n,l,u);return zl(n,l),n},Vl=r&&r.__values||function(l){var n="function"==typeof Symbol&&Symbol.iterator,u=n&&l[n],e=0;if(u)return u.call(l);if(l&&"number"==typeof l.length)return{next:function(){return l&&e>=l.length&&(l=void 0),{value:l&&l[e++],done:!l}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(Wl,"__esModule",{value:!0}),Wl.RequestResponseResponderStream=Wl.RequestResponseRequesterStream=void 0;var Jl=cl,Gl=El,Xl=rl,Yl=Hl(bl),Kl=function(){function l(l,n,u,e){this.payload=l,this.receiver=n,this.fragmentSize=u,this.leaseManager=e,this.streamType=Xl.FrameTypes.REQUEST_RESPONSE}return l.prototype.handleReady=function(l,n){var u,e;if(this.done)return!1;if(this.streamId=l,this.stream=n,n.connect(this),(0,Gl.isFragmentable)(this.payload,this.fragmentSize,Xl.FrameTypes.REQUEST_RESPONSE))try{for(var t=Vl((0,Gl.fragment)(l,this.payload,this.fragmentSize,Xl.FrameTypes.REQUEST_RESPONSE)),r=t.next();!r.done;r=t.next()){var i=r.value;this.stream.send(i)}}catch(l){u={error:l}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(u)throw u.error}}else this.stream.send({type:Xl.FrameTypes.REQUEST_RESPONSE,data:this.payload.data,metadata:this.payload.metadata,flags:this.payload.metadata?Xl.Flags.METADATA:0,streamId:l});return this.hasExtension&&this.stream.send({type:Xl.FrameTypes.EXT,streamId:l,extendedContent:this.extendedContent,extendedType:this.extendedType,flags:this.flags}),!0},l.prototype.handleReject=function(l){this.done||(this.done=!0,this.receiver.onError(l))},l.prototype.handle=function(l){var n,u=l.type;switch(u){case Xl.FrameTypes.PAYLOAD:var e=Xl.Flags.hasComplete(l.flags),t=Xl.Flags.hasNext(l.flags);if(e||!Xl.Flags.hasFollows(l.flags)){if(this.done=!0,this.stream.disconnect(this),!t)return void this.receiver.onComplete();var r=this.hasFragments?Yl.reassemble(this,l.data,l.metadata):{data:l.data,metadata:l.metadata};return void this.receiver.onNext(r,!0)}if(!Yl.add(this,l.data,l.metadata)){n="Unexpected fragment size";break}return;case Xl.FrameTypes.ERROR:return this.done=!0,this.stream.disconnect(this),Yl.cancel(this),void this.receiver.onError(new Jl.RSocketError(l.code,l.message));case Xl.FrameTypes.EXT:if(this.hasFragments){n="Unexpected frame type [".concat(u,"] during reassembly");break}return void this.receiver.onExtension(l.extendedType,l.extendedContent,Xl.Flags.hasIgnore(l.flags));default:n="Unexpected frame type [".concat(u,"]")}this.close(new Jl.RSocketError(Jl.ErrorCodes.CANCELED,n)),this.stream.send({type:Xl.FrameTypes.CANCEL,streamId:this.streamId,flags:Xl.Flags.NONE}),this.stream.disconnect(this)},l.prototype.cancel=function(){var l;this.done||(this.done=!0,this.streamId?(this.stream.send({type:Xl.FrameTypes.CANCEL,flags:Xl.Flags.NONE,streamId:this.streamId}),this.stream.disconnect(this),Yl.cancel(this)):null===(l=this.leaseManager)||void 0===l||l.cancelRequest(this))},l.prototype.onExtension=function(l,n,u){if(!this.done)return this.streamId?void this.stream.send({streamId:this.streamId,type:Xl.FrameTypes.EXT,extendedType:l,extendedContent:n,flags:u?Xl.Flags.IGNORE:Xl.Flags.NONE}):(this.hasExtension=!0,this.extendedType=l,this.extendedContent=n,void(this.flags=u?Xl.Flags.IGNORE:Xl.Flags.NONE))},l.prototype.close=function(l){this.done||(this.done=!0,Yl.cancel(this),l?this.receiver.onError(l):this.receiver.onComplete())},l}();Wl.RequestResponseRequesterStream=Kl;var Zl=function(){function l(l,n,u,e,t){if(this.streamId=l,this.stream=n,this.fragmentSize=u,this.handler=e,this.streamType=Xl.FrameTypes.REQUEST_RESPONSE,n.connect(this),Xl.Flags.hasFollows(t.flags))Yl.add(this,t.data,t.metadata);else{var r={data:t.data,metadata:t.metadata};try{this.receiver=e(r,this)}catch(l){this.onError(l)}}}return l.prototype.handle=function(l){var n,u;if(!this.receiver||this.hasFragments)if(l.type===Xl.FrameTypes.PAYLOAD){if(!Xl.Flags.hasFollows(l.flags)){var e=Yl.reassemble(this,l.data,l.metadata);try{this.receiver=this.handler(e,this)}catch(l){this.onError(l)}return}if(Yl.add(this,l.data,l.metadata))return;u="Unexpected fragment size"}else u="Unexpected frame type [".concat(l.type,"] during reassembly");else{if(l.type===Xl.FrameTypes.EXT)return void this.receiver.onExtension(l.extendedType,l.extendedContent,Xl.Flags.hasIgnore(l.flags));u="Unexpected frame type [".concat(l.type,"]")}this.done=!0,null===(n=this.receiver)||void 0===n||n.cancel(),l.type!==Xl.FrameTypes.CANCEL&&l.type!==Xl.FrameTypes.ERROR&&this.stream.send({type:Xl.FrameTypes.ERROR,flags:Xl.Flags.NONE,code:Jl.ErrorCodes.CANCELED,message:u,streamId:this.streamId}),this.stream.disconnect(this),Yl.cancel(this)},l.prototype.onError=function(l){this.done?console.warn("Trying to error for the second time. ".concat(l?"Dropping error [".concat(l,"]."):"")):(this.done=!0,this.stream.send({type:Xl.FrameTypes.ERROR,flags:Xl.Flags.NONE,code:l instanceof Jl.RSocketError?l.code:Jl.ErrorCodes.APPLICATION_ERROR,message:l.message,streamId:this.streamId}),this.stream.disconnect(this))},l.prototype.onNext=function(l,n){var u,e;if(!this.done){if(this.done=!0,(0,Gl.isFragmentable)(l,this.fragmentSize,Xl.FrameTypes.PAYLOAD))try{for(var t=Vl((0,Gl.fragment)(this.streamId,l,this.fragmentSize,Xl.FrameTypes.PAYLOAD,!0)),r=t.next();!r.done;r=t.next()){var i=r.value;this.stream.send(i)}}catch(l){u={error:l}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(u)throw u.error}}else this.stream.send({type:Xl.FrameTypes.PAYLOAD,flags:Xl.Flags.NEXT|Xl.Flags.COMPLETE|(l.metadata?Xl.Flags.METADATA:0),data:l.data,metadata:l.metadata,streamId:this.streamId});this.stream.disconnect(this)}},l.prototype.onComplete=function(){this.done||(this.done=!0,this.stream.send({type:Xl.FrameTypes.PAYLOAD,flags:Xl.Flags.COMPLETE,streamId:this.streamId,data:null,metadata:null}),this.stream.disconnect(this))},l.prototype.onExtension=function(l,n,u){this.done||this.stream.send({type:Xl.FrameTypes.EXT,streamId:this.streamId,flags:u?Xl.Flags.IGNORE:Xl.Flags.NONE,extendedType:l,extendedContent:n})},l.prototype.close=function(l){var n;this.done?console.warn("Trying to close for the second time. ".concat(l?"Dropping error [".concat(l,"]."):"")):(Yl.cancel(this),null===(n=this.receiver)||void 0===n||n.cancel())},l}();Wl.RequestResponseResponderStream=Zl;var ln={},nn=r&&r.__createBinding||(Object.create?function(l,n,u,e){void 0===e&&(e=u),Object.defineProperty(l,e,{enumerable:!0,get:function(){return n[u]}})}:function(l,n,u,e){void 0===e&&(e=u),l[e]=n[u]}),un=r&&r.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),en=r&&r.__importStar||function(l){if(l&&l.__esModule)return l;var n={};if(null!=l)for(var u in l)"default"!==u&&Object.prototype.hasOwnProperty.call(l,u)&&nn(n,l,u);return un(n,l),n},tn=r&&r.__values||function(l){var n="function"==typeof Symbol&&Symbol.iterator,u=n&&l[n],e=0;if(u)return u.call(l);if(l&&"number"==typeof l.length)return{next:function(){return l&&e>=l.length&&(l=void 0),{value:l&&l[e++],done:!l}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(ln,"__esModule",{value:!0}),ln.RequestStreamResponderStream=ln.RequestStreamRequesterStream=void 0;var rn=cl,sn=El,on=rl,an=en(bl),cn=function(){function l(l,n,u,e,t){this.payload=l,this.receiver=n,this.fragmentSize=u,this.initialRequestN=e,this.leaseManager=t,this.streamType=on.FrameTypes.REQUEST_STREAM}return l.prototype.handleReady=function(l,n){var u,e;if(this.done)return!1;if(this.streamId=l,this.stream=n,n.connect(this),(0,sn.isFragmentable)(this.payload,this.fragmentSize,on.FrameTypes.REQUEST_STREAM))try{for(var t=tn((0,sn.fragmentWithRequestN)(l,this.payload,this.fragmentSize,on.FrameTypes.REQUEST_STREAM,this.initialRequestN)),r=t.next();!r.done;r=t.next()){var i=r.value;this.stream.send(i)}}catch(l){u={error:l}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(u)throw u.error}}else this.stream.send({type:on.FrameTypes.REQUEST_STREAM,data:this.payload.data,metadata:this.payload.metadata,requestN:this.initialRequestN,flags:void 0!==this.payload.metadata?on.Flags.METADATA:0,streamId:l});return this.hasExtension&&this.stream.send({type:on.FrameTypes.EXT,streamId:l,extendedContent:this.extendedContent,extendedType:this.extendedType,flags:this.flags}),!0},l.prototype.handleReject=function(l){this.done||(this.done=!0,this.receiver.onError(l))},l.prototype.handle=function(l){var n,u=l.type;switch(u){case on.FrameTypes.PAYLOAD:var e=on.Flags.hasComplete(l.flags),t=on.Flags.hasNext(l.flags);if(e||!on.Flags.hasFollows(l.flags)){if(e&&(this.done=!0,this.stream.disconnect(this),!t))return void this.receiver.onComplete();var r=this.hasFragments?an.reassemble(this,l.data,l.metadata):{data:l.data,metadata:l.metadata};return void this.receiver.onNext(r,e)}if(!an.add(this,l.data,l.metadata)){n="Unexpected fragment size";break}return;case on.FrameTypes.ERROR:return this.done=!0,this.stream.disconnect(this),an.cancel(this),void this.receiver.onError(new rn.RSocketError(l.code,l.message));case on.FrameTypes.EXT:if(this.hasFragments){n="Unexpected frame type [".concat(u,"] during reassembly");break}return void this.receiver.onExtension(l.extendedType,l.extendedContent,on.Flags.hasIgnore(l.flags));default:n="Unexpected frame type [".concat(u,"]")}this.close(new rn.RSocketError(rn.ErrorCodes.CANCELED,n)),this.stream.send({type:on.FrameTypes.CANCEL,streamId:this.streamId,flags:on.Flags.NONE}),this.stream.disconnect(this)},l.prototype.request=function(l){this.done||(this.streamId?this.stream.send({type:on.FrameTypes.REQUEST_N,flags:on.Flags.NONE,requestN:l,streamId:this.streamId}):this.initialRequestN+=l)},l.prototype.cancel=function(){var l;this.done||(this.done=!0,this.streamId?(this.stream.send({type:on.FrameTypes.CANCEL,flags:on.Flags.NONE,streamId:this.streamId}),this.stream.disconnect(this),an.cancel(this)):null===(l=this.leaseManager)||void 0===l||l.cancelRequest(this))},l.prototype.onExtension=function(l,n,u){if(!this.done)return this.streamId?void this.stream.send({streamId:this.streamId,type:on.FrameTypes.EXT,extendedType:l,extendedContent:n,flags:u?on.Flags.IGNORE:on.Flags.NONE}):(this.hasExtension=!0,this.extendedType=l,this.extendedContent=n,void(this.flags=u?on.Flags.IGNORE:on.Flags.NONE))},l.prototype.close=function(l){this.done||(this.done=!0,an.cancel(this),l?this.receiver.onError(l):this.receiver.onComplete())},l}();ln.RequestStreamRequesterStream=cn;var hn=function(){function l(l,n,u,e,t){if(this.streamId=l,this.stream=n,this.fragmentSize=u,this.handler=e,this.streamType=on.FrameTypes.REQUEST_STREAM,n.connect(this),on.Flags.hasFollows(t.flags))return this.initialRequestN=t.requestN,void an.add(this,t.data,t.metadata);var r={data:t.data,metadata:t.metadata};try{this.receiver=e(r,t.requestN,this)}catch(l){this.onError(l)}}return l.prototype.handle=function(l){var n,u;if(!this.receiver||this.hasFragments)if(l.type===on.FrameTypes.PAYLOAD){if(!on.Flags.hasFollows(l.flags)){var e=an.reassemble(this,l.data,l.metadata);try{this.receiver=this.handler(e,this.initialRequestN,this)}catch(l){this.onError(l)}return}if(an.add(this,l.data,l.metadata))return;u="Unexpected frame size"}else u="Unexpected frame type [".concat(l.type,"] during reassembly");else{if(l.type===on.FrameTypes.REQUEST_N)return void this.receiver.request(l.requestN);if(l.type===on.FrameTypes.EXT)return void this.receiver.onExtension(l.extendedType,l.extendedContent,on.Flags.hasIgnore(l.flags));u="Unexpected frame type [".concat(l.type,"]")}this.done=!0,an.cancel(this),null===(n=this.receiver)||void 0===n||n.cancel(),l.type!==on.FrameTypes.CANCEL&&l.type!==on.FrameTypes.ERROR&&this.stream.send({type:on.FrameTypes.ERROR,flags:on.Flags.NONE,code:rn.ErrorCodes.CANCELED,message:u,streamId:this.streamId}),this.stream.disconnect(this)},l.prototype.onError=function(l){this.done?console.warn("Trying to error for the second time. ".concat(l?"Dropping error [".concat(l,"]."):"")):(this.done=!0,this.stream.send({type:on.FrameTypes.ERROR,flags:on.Flags.NONE,code:l instanceof rn.RSocketError?l.code:rn.ErrorCodes.APPLICATION_ERROR,message:l.message,streamId:this.streamId}),this.stream.disconnect(this))},l.prototype.onNext=function(l,n){var u,e;if(!this.done){if(n&&(this.done=!0),(0,sn.isFragmentable)(l,this.fragmentSize,on.FrameTypes.PAYLOAD))try{for(var t=tn((0,sn.fragment)(this.streamId,l,this.fragmentSize,on.FrameTypes.PAYLOAD,n)),r=t.next();!r.done;r=t.next()){var i=r.value;this.stream.send(i)}}catch(l){u={error:l}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(u)throw u.error}}else this.stream.send({type:on.FrameTypes.PAYLOAD,flags:on.Flags.NEXT|(n?on.Flags.COMPLETE:on.Flags.NONE)|(l.metadata?on.Flags.METADATA:on.Flags.NONE),data:l.data,metadata:l.metadata,streamId:this.streamId});n&&this.stream.disconnect(this)}},l.prototype.onComplete=function(){this.done||(this.done=!0,this.stream.send({type:on.FrameTypes.PAYLOAD,flags:on.Flags.COMPLETE,streamId:this.streamId,data:null,metadata:null}),this.stream.disconnect(this))},l.prototype.onExtension=function(l,n,u){this.done||this.stream.send({type:on.FrameTypes.EXT,streamId:this.streamId,flags:u?on.Flags.IGNORE:on.Flags.NONE,extendedType:l,extendedContent:n})},l.prototype.close=function(l){var n;this.done?console.warn("Trying to close for the second time. ".concat(l?"Dropping error [".concat(l,"]."):"")):(an.cancel(this),null===(n=this.receiver)||void 0===n||n.cancel())},l}();ln.RequestStreamResponderStream=hn,Object.defineProperty(ml,"__esModule",{value:!0}),ml.KeepAliveSender=ml.KeepAliveHandler=ml.DefaultConnectionFrameHandler=ml.DefaultStreamRequestHandler=ml.LeaseHandler=ml.RSocketRequester=void 0;var dn=cl,fn=rl,pn=gl,yn=Ll,mn=Wl,gn=ln,En=function(){function l(l,n,u){this.connection=l,this.fragmentSize=n,this.leaseManager=u}return l.prototype.fireAndForget=function(l,n){var u=new yn.RequestFnFRequesterStream(l,n,this.fragmentSize,this.leaseManager);return this.leaseManager?this.leaseManager.requestLease(u):this.connection.multiplexerDemultiplexer.createRequestStream(u),u},l.prototype.requestResponse=function(l,n){var u=new mn.RequestResponseRequesterStream(l,n,this.fragmentSize,this.leaseManager);return this.leaseManager?this.leaseManager.requestLease(u):this.connection.multiplexerDemultiplexer.createRequestStream(u),u},l.prototype.requestStream=function(l,n,u){var e=new gn.RequestStreamRequesterStream(l,u,this.fragmentSize,n,this.leaseManager);return this.leaseManager?this.leaseManager.requestLease(e):this.connection.multiplexerDemultiplexer.createRequestStream(e),e},l.prototype.requestChannel=function(l,n,u,e){var t=new pn.RequestChannelRequesterStream(l,u,e,this.fragmentSize,n,this.leaseManager);return this.leaseManager?this.leaseManager.requestLease(t):this.connection.multiplexerDemultiplexer.createRequestStream(t),t},l.prototype.metadataPush=function(l,n){throw new Error("Method not implemented.")},l.prototype.close=function(l){this.connection.close(l)},l.prototype.onClose=function(l){this.connection.onClose(l)},l}();ml.RSocketRequester=En;var wn=function(){function l(l,n){this.maxPendingRequests=l,this.multiplexer=n,this.pendingRequests=[],this.expirationTime=0,this.availableLease=0}return l.prototype.handle=function(l){for(this.expirationTime=l.ttl+Date.now(),this.availableLease=l.requestCount;this.availableLease>0&&this.pendingRequests.length>0;){var n=this.pendingRequests.shift();this.availableLease--,this.multiplexer.createRequestStream(n)}},l.prototype.requestLease=function(l){var n=this.availableLease;if(n>0&&Date.now()<this.expirationTime)return this.availableLease=n-1,void this.multiplexer.createRequestStream(l);this.pendingRequests.length>=this.maxPendingRequests?l.handleReject(new dn.RSocketError(dn.ErrorCodes.REJECTED,"No available lease given")):this.pendingRequests.push(l)},l.prototype.cancelRequest=function(l){var n=this.pendingRequests.indexOf(l);n>-1&&this.pendingRequests.splice(n,1)},l}();ml.LeaseHandler=wn;var vn=function(){function l(l,n){this.rsocket=l,this.fragmentSize=n}return l.prototype.handle=function(l,n){switch(l.type){case fn.FrameTypes.REQUEST_FNF:return void(this.rsocket.fireAndForget&&new yn.RequestFnfResponderStream(l.streamId,n,this.rsocket.fireAndForget.bind(this.rsocket),l));case fn.FrameTypes.REQUEST_RESPONSE:return this.rsocket.requestResponse?void new mn.RequestResponseResponderStream(l.streamId,n,this.fragmentSize,this.rsocket.requestResponse.bind(this.rsocket),l):void this.rejectRequest(l.streamId,n);case fn.FrameTypes.REQUEST_STREAM:return this.rsocket.requestStream?void new gn.RequestStreamResponderStream(l.streamId,n,this.fragmentSize,this.rsocket.requestStream.bind(this.rsocket),l):void this.rejectRequest(l.streamId,n);case fn.FrameTypes.REQUEST_CHANNEL:return this.rsocket.requestChannel?void new pn.RequestChannelResponderStream(l.streamId,n,this.fragmentSize,this.rsocket.requestChannel.bind(this.rsocket),l):void this.rejectRequest(l.streamId,n)}},l.prototype.rejectRequest=function(l,n){n.send({type:fn.FrameTypes.ERROR,streamId:l,flags:fn.Flags.NONE,code:dn.ErrorCodes.REJECTED,message:"No available handler found"})},l.prototype.close=function(){},l}();ml.DefaultStreamRequestHandler=vn;var bn,Sn=function(){function l(l,n,u,e,t){this.connection=l,this.keepAliveHandler=n,this.keepAliveSender=u,this.leaseHandler=e,this.rsocket=t}return l.prototype.handle=function(l){switch(l.type){case fn.FrameTypes.KEEPALIVE:return void this.keepAliveHandler.handle(l);case fn.FrameTypes.LEASE:return this.leaseHandler?void this.leaseHandler.handle(l):void 0;case fn.FrameTypes.ERROR:return void this.connection.close(new dn.RSocketError(l.code,l.message));case fn.FrameTypes.METADATA_PUSH:return void this.rsocket.metadataPush;default:this.connection.multiplexerDemultiplexer.connectionOutbound.send({type:fn.FrameTypes.ERROR,streamId:0,flags:fn.Flags.NONE,message:"Received unknown frame type",code:dn.ErrorCodes.CONNECTION_ERROR})}},l.prototype.pause=function(){var l;this.keepAliveHandler.pause(),null===(l=this.keepAliveSender)||void 0===l||l.pause()},l.prototype.resume=function(){var l;this.keepAliveHandler.start(),null===(l=this.keepAliveSender)||void 0===l||l.start()},l.prototype.close=function(l){var n;this.keepAliveHandler.close(),null===(n=this.rsocket.close)||void 0===n||n.call(this.rsocket,l)},l}();ml.DefaultConnectionFrameHandler=Sn,function(l){l[l.Paused=0]="Paused",l[l.Running=1]="Running",l[l.Closed=2]="Closed"}(bn||(bn={}));var Tn,Rn=function(){function l(l,n){this.connection=l,this.keepAliveTimeoutDuration=n,this.state=bn.Paused,this.outbound=l.multiplexerDemultiplexer.connectionOutbound}return l.prototype.handle=function(l){this.keepAliveLastReceivedMillis=Date.now(),fn.Flags.hasRespond(l.flags)&&this.outbound.send({type:fn.FrameTypes.KEEPALIVE,streamId:0,data:l.data,flags:l.flags^fn.Flags.RESPOND,lastReceivedPosition:0})},l.prototype.start=function(){this.state===bn.Paused&&(this.keepAliveLastReceivedMillis=Date.now(),this.state=bn.Running,this.activeTimeout=setTimeout(this.timeoutCheck.bind(this),this.keepAliveTimeoutDuration))},l.prototype.pause=function(){this.state===bn.Running&&(this.state=bn.Paused,clearTimeout(this.activeTimeout))},l.prototype.close=function(){this.state=bn.Closed,clearTimeout(this.activeTimeout)},l.prototype.timeoutCheck=function(){var l=Date.now()-this.keepAliveLastReceivedMillis;l>=this.keepAliveTimeoutDuration?this.connection.close(new Error("No keep-alive acks for ".concat(this.keepAliveTimeoutDuration," millis"))):this.activeTimeout=setTimeout(this.timeoutCheck.bind(this),Math.max(100,this.keepAliveTimeoutDuration-l))},l}();ml.KeepAliveHandler=Rn,function(l){l[l.Paused=0]="Paused",l[l.Running=1]="Running",l[l.Closed=2]="Closed"}(Tn||(Tn={}));var _n=function(){function l(l,n){this.outbound=l,this.keepAlivePeriodDuration=n,this.state=Tn.Paused}return l.prototype.sendKeepAlive=function(){this.outbound.send({type:fn.FrameTypes.KEEPALIVE,streamId:0,data:void 0,flags:fn.Flags.RESPOND,lastReceivedPosition:0})},l.prototype.start=function(){this.state===Tn.Paused&&(this.state=Tn.Running,this.activeInterval=setInterval(this.sendKeepAlive.bind(this),this.keepAlivePeriodDuration))},l.prototype.pause=function(){this.state===Tn.Running&&(this.state=Tn.Paused,clearInterval(this.activeInterval))},l.prototype.close=function(){this.state=Tn.Closed,clearInterval(this.activeInterval)},l}();ml.KeepAliveSender=_n;var An,On,Fn={};function Cn(){if(An)return Fn;An=1;var l=r&&r.__values||function(l){var n="function"==typeof Symbol&&Symbol.iterator,u=n&&l[n],e=0;if(u)return u.call(l);if(l&&"number"==typeof l.length)return{next:function(){return l&&e>=l.length&&(l=void 0),{value:l&&l[e++],done:!l}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(Fn,"__esModule",{value:!0}),Fn.FrameStore=void 0;var n=Pn(),u=tl,e=function(){function e(){this.storedFrames=[],this._lastReceivedFramePosition=0,this._firstAvailableFramePosition=0,this._lastSentFramePosition=0}return Object.defineProperty(e.prototype,"lastReceivedFramePosition",{get:function(){return this._lastReceivedFramePosition},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"firstAvailableFramePosition",{get:function(){return this._firstAvailableFramePosition},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"lastSentFramePosition",{get:function(){return this._lastSentFramePosition},enumerable:!1,configurable:!0}),e.prototype.store=function(l){this._lastSentFramePosition+=(0,u.sizeOfFrame)(l),this.storedFrames.push(l)},e.prototype.record=function(l){this._lastReceivedFramePosition+=(0,u.sizeOfFrame)(l)},e.prototype.dropTo=function(l){for(var e=l-this._firstAvailableFramePosition;e>0&&this.storedFrames.length>0;){var t=this.storedFrames.shift();e-=(0,u.sizeOfFrame)(t)}if(0!==e)throw new n.RSocketError(n.ErrorCodes.CONNECTION_ERROR,"State inconsistency. Expected bytes to drop ".concat(l-this._firstAvailableFramePosition," but actual ").concat(e));this._firstAvailableFramePosition=l},e.prototype.drain=function(n){var u,e;try{for(var t=l(this.storedFrames),r=t.next();!r.done;r=t.next()){n(r.value)}}catch(l){u={error:l}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(u)throw u.error}}},e}();return Fn.FrameStore=e,Fn}function In(){if(On)return fl;On=1;var l=r&&r.__awaiter||function(l,n,u,e){return new(u||(u=Promise))((function(t,r){function i(l){try{o(e.next(l))}catch(l){r(l)}}function s(l){try{o(e.throw(l))}catch(l){r(l)}}function o(l){var n;l.done?t(l.value):(n=l.value,n instanceof u?n:new u((function(l){l(n)}))).then(i,s)}o((e=e.apply(l,n||[])).next())}))},n=r&&r.__generator||function(l,n){var u,e,t,r,i={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function s(r){return function(s){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;i;)try{if(u=1,e&&(t=2&r[0]?e.return:r[0]?e.throw||((t=e.return)&&t.call(e),0):e.next)&&!(t=t.call(e,r[1])).done)return t;switch(e=0,t&&(r=[2&r[0],t.value]),r[0]){case 0:case 1:t=r;break;case 4:return i.label++,{value:r[1],done:!1};case 5:i.label++,e=r[1],r=[0];continue;case 7:r=i.ops.pop(),i.trys.pop();continue;default:if(!(t=i.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){i=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){i.label=r[1];break}if(6===r[0]&&i.label<t[1]){i.label=t[1],t=r;break}if(t&&i.label<t[2]){i.label=t[2],i.ops.push(r);break}t[2]&&i.ops.pop(),i.trys.pop();continue}r=n.call(l,i)}catch(l){r=[6,l],e=0}finally{u=t=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,s])}}};Object.defineProperty(fl,"__esModule",{value:!0}),fl.RSocketConnector=void 0;var u=yl(),e=rl,t=ml,i=Cn(),s=function(){function r(l){this.config=l}return r.prototype.connect=function(){var r,s,o,a,c,h,d,f,p,y,m,g,E,w,v,b,S,T,R,_;return l(this,void 0,void 0,(function(){var A,O,F,C,I,k,L,N,U,x=this;return n(this,(function(P){switch(P.label){case 0:return A=this.config,O={type:e.FrameTypes.SETUP,dataMimeType:null!==(s=null===(r=A.setup)||void 0===r?void 0:r.dataMimeType)&&void 0!==s?s:"application/octet-stream",metadataMimeType:null!==(a=null===(o=A.setup)||void 0===o?void 0:o.metadataMimeType)&&void 0!==a?a:"application/octet-stream",keepAlive:null!==(h=null===(c=A.setup)||void 0===c?void 0:c.keepAlive)&&void 0!==h?h:6e4,lifetime:null!==(f=null===(d=A.setup)||void 0===d?void 0:d.lifetime)&&void 0!==f?f:3e5,metadata:null===(y=null===(p=A.setup)||void 0===p?void 0:p.payload)||void 0===y?void 0:y.metadata,data:null===(g=null===(m=A.setup)||void 0===m?void 0:m.payload)||void 0===g?void 0:g.data,resumeToken:null!==(w=null===(E=A.resume)||void 0===E?void 0:E.tokenGenerator())&&void 0!==w?w:null,streamId:0,majorVersion:1,minorVersion:0,flags:((null===(b=null===(v=A.setup)||void 0===v?void 0:v.payload)||void 0===b?void 0:b.metadata)?e.Flags.METADATA:e.Flags.NONE)|(A.lease?e.Flags.LEASE:e.Flags.NONE)|(A.resume?e.Flags.RESUME_ENABLE:e.Flags.NONE)},[4,A.transport.connect((function(t){return A.resume?new u.ResumableClientServerInputMultiplexerDemultiplexer(u.StreamIdGenerator.create(-1),t,t,new i.FrameStore,O.resumeToken.toString(),(function(t,r){return l(x,void 0,void 0,(function(){var l,i,s;return n(this,(function(n){switch(n.label){case 0:return l=function(l){return l.send({type:e.FrameTypes.RESUME,streamId:0,flags:e.Flags.NONE,clientPosition:r.firstAvailableFramePosition,serverPosition:r.lastReceivedFramePosition,majorVersion:O.minorVersion,minorVersion:O.majorVersion,resumeToken:O.resumeToken}),new u.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer(l,l,t)},i=-1,[4,(s=function(){return i++,A.resume.reconnectFunction(i).then((function(){return A.transport.connect(l).catch(s)}))})()];case 1:return n.sent(),[2]}}))}))})):new u.ClientServerInputMultiplexerDemultiplexer(u.StreamIdGenerator.create(-1),t,t)}))];case 1:return F=P.sent(),C=new t.KeepAliveSender(F.multiplexerDemultiplexer.connectionOutbound,O.keepAlive),I=new t.KeepAliveHandler(F,O.lifetime),k=A.lease?new t.LeaseHandler(null!==(S=A.lease.maxPendingRequests)&&void 0!==S?S:256,F.multiplexerDemultiplexer):void 0,L=null!==(T=A.responder)&&void 0!==T?T:{},N=new t.DefaultConnectionFrameHandler(F,I,C,k,L),U=new t.DefaultStreamRequestHandler(L,0),F.onClose((function(l){C.close(),I.close(),N.close(l)})),F.multiplexerDemultiplexer.connectionInbound(N),F.multiplexerDemultiplexer.handleRequestStream(U),F.multiplexerDemultiplexer.connectionOutbound.send(O),I.start(),C.start(),[2,new t.RSocketRequester(F,null!==(_=null===(R=A.fragmentation)||void 0===R?void 0:R.maxOutboundFragmentSize)&&void 0!==_?_:0,k)]}}))}))},r}();return fl.RSocketConnector=s,fl}var kn,Ln={};function Nn(){if(kn)return Ln;kn=1;var l=r&&r.__awaiter||function(l,n,u,e){return new(u||(u=Promise))((function(t,r){function i(l){try{o(e.next(l))}catch(l){r(l)}}function s(l){try{o(e.throw(l))}catch(l){r(l)}}function o(l){var n;l.done?t(l.value):(n=l.value,n instanceof u?n:new u((function(l){l(n)}))).then(i,s)}o((e=e.apply(l,n||[])).next())}))},n=r&&r.__generator||function(l,n){var u,e,t,r,i={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function s(r){return function(s){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;i;)try{if(u=1,e&&(t=2&r[0]?e.return:r[0]?e.throw||((t=e.return)&&t.call(e),0):e.next)&&!(t=t.call(e,r[1])).done)return t;switch(e=0,t&&(r=[2&r[0],t.value]),r[0]){case 0:case 1:t=r;break;case 4:return i.label++,{value:r[1],done:!1};case 5:i.label++,e=r[1],r=[0];continue;case 7:r=i.ops.pop(),i.trys.pop();continue;default:if(!(t=i.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){i=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){i.label=r[1];break}if(6===r[0]&&i.label<t[1]){i.label=t[1],t=r;break}if(t&&i.label<t[2]){i.label=t[2],i.ops.push(r);break}t[2]&&i.ops.pop(),i.trys.pop();continue}r=n.call(l,i)}catch(l){r=[6,l],e=0}finally{u=t=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,s])}}};Object.defineProperty(Ln,"__esModule",{value:!0}),Ln.RSocketServer=void 0;var u=yl(),e=cl,t=rl,i=ml,s=Cn(),o=function(){function r(l){var n,u;this.acceptor=l.acceptor,this.transport=l.transport,this.lease=l.lease,this.serverSideKeepAlive=l.serverSideKeepAlive,this.sessionStore=l.resume?{}:void 0,this.sessionTimeout=null!==(u=null===(n=l.resume)||void 0===n?void 0:n.sessionTimeout)&&void 0!==u?u:void 0}return r.prototype.bind=function(){return l(this,void 0,void 0,(function(){var r=this;return n(this,(function(o){switch(o.label){case 0:return[4,this.transport.bind((function(u,s){return l(r,void 0,void 0,(function(){var l,r,o,a,c,h,d,f,p,y,m,g,E;return n(this,(function(n){switch(n.label){case 0:switch(u.type){case t.FrameTypes.SETUP:return[3,1];case t.FrameTypes.RESUME:return[3,5]}return[3,6];case 1:return n.trys.push([1,3,,4]),this.lease&&!t.Flags.hasLease(u.flags)?(l=new e.RSocketError(e.ErrorCodes.REJECTED_SETUP,"Lease has to be enabled"),s.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,flags:t.Flags.NONE,code:l.code,message:l.message}),s.close(l),[2]):t.Flags.hasLease(u.flags)&&!this.lease?(l=new e.RSocketError(e.ErrorCodes.REJECTED_SETUP,"Lease has to be disabled"),s.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,flags:t.Flags.NONE,code:l.code,message:l.message}),s.close(l),[2]):(r=t.Flags.hasLease(u.flags)?new i.LeaseHandler(null!==(y=this.lease.maxPendingRequests)&&void 0!==y?y:256,s.multiplexerDemultiplexer):void 0,o=new i.RSocketRequester(s,null!==(g=null===(m=this.fragmentation)||void 0===m?void 0:m.maxOutboundFragmentSize)&&void 0!==g?g:0,r),[4,this.acceptor.accept({data:u.data,dataMimeType:u.dataMimeType,metadata:u.metadata,metadataMimeType:u.metadataMimeType,flags:u.flags,keepAliveMaxLifetime:u.lifetime,keepAliveInterval:u.keepAlive,resumeToken:u.resumeToken},o)]);case 2:return a=n.sent(),c=new i.KeepAliveHandler(s,u.lifetime),h=this.serverSideKeepAlive?new i.KeepAliveSender(s.multiplexerDemultiplexer.connectionOutbound,u.keepAlive):void 0,d=new i.DefaultConnectionFrameHandler(s,c,h,r,a),f=new i.DefaultStreamRequestHandler(a,0),s.onClose((function(l){null==h||h.close(),c.close(),d.close(l)})),s.multiplexerDemultiplexer.connectionInbound(d),s.multiplexerDemultiplexer.handleRequestStream(f),c.start(),null==h||h.start(),[3,4];case 3:return p=n.sent(),s.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,code:e.ErrorCodes.REJECTED_SETUP,message:null!==(E=p.message)&&void 0!==E?E:"",flags:t.Flags.NONE}),s.close(p instanceof e.RSocketError?p:new e.RSocketError(e.ErrorCodes.REJECTED_SETUP,p.message)),[3,4];case 4:case 5:return[2];case 6:s.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,code:e.ErrorCodes.UNSUPPORTED_SETUP,message:"Unsupported setup",flags:t.Flags.NONE}),s.close(new e.RSocketError(e.ErrorCodes.UNSUPPORTED_SETUP)),n.label=7;case 7:return[2]}}))}))}),(function(l,n){if(l.type===t.FrameTypes.RESUME){if(r.sessionStore){var i=r.sessionStore[l.resumeToken.toString()];return i?(i.resume(l,n,n),i):(n.send({type:t.FrameTypes.ERROR,streamId:0,code:e.ErrorCodes.REJECTED_RESUME,message:"No session found for the given resume token",flags:t.Flags.NONE}),void n.close())}return n.send({type:t.FrameTypes.ERROR,streamId:0,code:e.ErrorCodes.REJECTED_RESUME,message:"Resume is not enabled",flags:t.Flags.NONE}),void n.close()}if(l.type===t.FrameTypes.SETUP&&t.Flags.hasResume(l.flags)){if(!r.sessionStore){var o=new e.RSocketError(e.ErrorCodes.REJECTED_SETUP,"No resume support");return n.send({type:t.FrameTypes.ERROR,streamId:0,flags:t.Flags.NONE,code:o.code,message:o.message}),void n.close(o)}var a=new u.ResumableClientServerInputMultiplexerDemultiplexer(u.StreamIdGenerator.create(0),n,n,new s.FrameStore,l.resumeToken.toString(),r.sessionStore,r.sessionTimeout);return r.sessionStore[l.resumeToken.toString()]=a,a}return new u.ClientServerInputMultiplexerDemultiplexer(u.StreamIdGenerator.create(0),n,n)}))];case 1:return[2,o.sent()]}}))}))},r}();return Ln.RSocketServer=o,Ln}var Un,xn={};function Pn(){return Un||(Un=1,function(l){var n=r&&r.__createBinding||(Object.create?function(l,n,u,e){void 0===e&&(e=u),Object.defineProperty(l,e,{enumerable:!0,get:function(){return n[u]}})}:function(l,n,u,e){void 0===e&&(e=u),l[e]=n[u]}),u=r&&r.__exportStar||function(l,u){for(var e in l)"default"===e||Object.prototype.hasOwnProperty.call(u,e)||n(u,l,e)};Object.defineProperty(l,"__esModule",{value:!0}),u(tl,l),u(il,l),u(sl,l),u(cl,l),u(rl,l),u(hl,l),u(In(),l),u(Nn(),l),u(xn,l)}(ul)),ul}Object.defineProperty(xn,"__esModule",{value:!0});var Dn=Pn(),Mn="1.33.1";const Bn={highWater:10,lowWater:0};class qn extends S{options;dataQueue;isClosed;processingPromise;notifyDataAdded;logger;mapLine;constructor(l){if(super(),this.options=l,this.processingPromise=null,this.isClosed=!1,this.dataQueue=[],this.mapLine=l?.mapLine??(l=>l),this.logger=l?.logger??y.get("DataStream"),l?.closeOnError){const l=this.registerListener({error:n=>{l?.(),this.close()}})}}get highWatermark(){return this.options?.pressure?.highWaterMark??Bn.highWater}get lowWatermark(){return this.options?.pressure?.lowWaterMark??Bn.lowWater}get closed(){return this.isClosed}async close(){this.isClosed=!0,await this.processingPromise,this.iterateListeners((l=>l.closed?.())),this.dataQueue=[],this.listeners.clear()}enqueueData(l){if(this.isClosed)throw new Error("Cannot enqueue data into closed stream.");this.dataQueue.push(l),this.notifyDataAdded?.(),this.processQueue()}async read(){return this.closed?null:new Promise(((l,n)=>{const u=this.registerListener({data:async n=>{l(n),u?.()},closed:()=>{l(null),u?.()},error:l=>{n(l),u?.()}});this.processQueue()}))}forEach(l){return this.dataQueue.length<=this.lowWatermark&&this.iterateAsyncErrored((async l=>l.lowWater?.())),this.registerListener({data:l})}processQueue(){if(this.processingPromise)return;const l=this.processingPromise=this._processQueue();return l.finally((()=>this.processingPromise=null)),l}hasDataReader(){return Array.from(this.listeners.values()).some((l=>!!l.data))}async _processQueue(){if(this.dataQueue.length>=this.highWatermark&&await this.iterateAsyncErrored((async l=>l.highWater?.())),!this.isClosed&&this.hasDataReader()){if(this.dataQueue.length){const l=this.dataQueue.shift(),n=this.mapLine(l);await this.iterateAsyncErrored((async l=>l.data?.(n)))}if(this.dataQueue.length<=this.lowWatermark){const l=new Promise((l=>{this.notifyDataAdded=l}));await Promise.race([this.iterateAsyncErrored((async l=>l.lowWater?.())),l]),this.notifyDataAdded=null}this.dataQueue.length>0&&setTimeout((()=>this.processQueue()))}}async iterateAsyncErrored(l){const n=Array.from(this.listeners.values());for(let u of n)try{await l(u)}catch(l){this.logger.error(l),this.iterateListeners((n=>n.error?.(l)))}}}var jn,Qn={},Wn=r&&r.__extends||(jn=function(l,n){return jn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(l,n){l.__proto__=n}||function(l,n){for(var u in n)Object.prototype.hasOwnProperty.call(n,u)&&(l[u]=n[u])},jn(l,n)},function(l,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function u(){this.constructor=l}jn(l,n),l.prototype=null===n?Object.create(n):(u.prototype=n.prototype,new u)});Object.defineProperty(Qn,"__esModule",{value:!0});var $n=Qn.WebsocketDuplexConnection=void 0,zn=Pn(),Hn=function(l){function n(n,u,e){var t=l.call(this)||this;return t.websocket=n,t.deserializer=u,t.handleClosed=function(l){t.close(new Error(l.reason||"WebsocketDuplexConnection: Socket closed unexpectedly."))},t.handleError=function(l){t.close(l.error)},t.handleMessage=function(l){try{var n=el.Buffer.from(l.data),u=t.deserializer.deserializeFrame(n);t.multiplexerDemultiplexer.handle(u)}catch(l){t.close(l)}},n.addEventListener("close",t.handleClosed),n.addEventListener("error",t.handleError),n.addEventListener("message",t.handleMessage),t.multiplexerDemultiplexer=e(t),t}return Wn(n,l),Object.defineProperty(n.prototype,"availability",{get:function(){return this.done?0:1},enumerable:!1,configurable:!0}),n.prototype.close=function(n){this.done||(this.websocket.removeEventListener("close",this.handleClosed),this.websocket.removeEventListener("error",this.handleError),this.websocket.removeEventListener("message",this.handleMessage),this.websocket.close(),delete this.websocket),l.prototype.close.call(this,n)},n.prototype.send=function(l){if(!this.done){var n=(0,zn.serializeFrame)(l);this.websocket.send(n)}},n}(zn.Deferred);$n=Qn.WebsocketDuplexConnection=Hn;class Vn{url;factory;constructor(l){this.url=l.url,this.factory=l.wsCreator??(l=>new WebSocket(l))}connect(l){return new Promise(((n,u)=>{const e=this.factory(this.url);let t;e.binaryType="arraybuffer";const r=()=>{t(),n(new $n(e,new Dn.Deserializer,l))},i=l=>{t(),null!=l.error?u(l.error):null!=l.message?u(new Error(`Failed to create websocket connection: ${l.message}`)):u(new Error(`Failed to create websocket connection to ${this.url}`))},s=()=>{t(),u(new Error("WebSocket connection closed while opening"))};t=()=>{e.removeEventListener("open",r),e.removeEventListener("error",i),e.removeEventListener("close",s)},e.addEventListener("open",r),e.addEventListener("error",i),e.addEventListener("close",s)}))}}const Jn=/\/+$/,Gn=Mn,Xn=y.get("PowerSyncRemote");var Yn;!function(l){l.Buffered="buffered",l.Sequential="sequential"}(Yn||(Yn={}));class Kn{getFetch(){throw new Error("Unspecified fetch implementation")}}const Zn={socketUrlTransformer:l=>l.replace(/^https?:\/\//,(function(l){return"https://"===l?"wss://":"ws://"})),fetchImplementation:new Kn,fetchOptions:{}};class lu{connector;logger;credentials=null;options;constructor(l,n=Xn,u){this.connector=l,this.logger=n,this.options={...Zn,...u??{}}}get fetch(){const{fetchImplementation:l}=this.options;return l instanceof Kn?l.getFetch():l}async getCredentials(){return this.credentials?this.credentials:this.prefetchCredentials()}async prefetchCredentials(){return this.credentials=await this.fetchCredentials(),this.credentials}async fetchCredentials(){const l=await this.connector.fetchCredentials();if(l?.endpoint.match(Jn))throw new Error(`A trailing forward slash "/" was found in the fetchCredentials endpoint: "${l.endpoint}". Remove the trailing forward slash "/" to fix this error.`);return l}invalidateCredentials(){this.credentials=null,this.connector.invalidateCredentials?.()}getUserAgent(){return`powersync-js/${Gn}`}async buildRequest(l){const n=await this.getCredentials();if(null!=n&&(null==n.endpoint||""==n.endpoint))throw new Error("PowerSync endpoint not configured");if(null==n?.token||""==n?.token){const l=new Error("Not signed in");throw l.status=401,l}const u=this.getUserAgent();return{url:n.endpoint+l,headers:{"content-type":"application/json",Authorization:`Token ${n.token}`,"x-user-agent":u}}}async post(l,n,u={}){const e=await this.buildRequest(l),t=await this.fetch(e.url,{method:"POST",headers:{...u,...e.headers},body:JSON.stringify(n)});if(401===t.status&&this.invalidateCredentials(),!t.ok)throw new Error(`Received ${t.status} - ${t.statusText} when posting to ${l}: ${await t.text()}}`);return t.json()}async get(l,n){const u=await this.buildRequest(l),e=await this.fetch(u.url,{method:"GET",headers:{...n,...u.headers}});if(401===e.status&&this.invalidateCredentials(),!e.ok)throw new Error(`Received ${e.status} - ${e.statusText} when getting from ${l}: ${await e.text()}}`);return e.json()}createSocket(l){return new WebSocket(l)}async socketStream(l){const n=await this.getBSON();return await this.socketStreamRaw(l,(l=>n.deserialize(l)),n)}async socketStreamRaw(l,n,u){const{path:e,fetchStrategy:t=Yn.Buffered}=l,r=null==u?"application/json":"application/bson";function i(l){let n;return n=null!=u?u.serialize(l):JSON.stringify(l),H.Buffer.from(n)}const s=t==Yn.Buffered?10:1,o=await this.buildRequest(e),a=this.getUserAgent();let c;const h=()=>{clearTimeout(c),c=setTimeout((()=>{this.logger.error("No data received on WebSocket in 30000ms, closing connection."),y.close()}),3e4)};h();const d=this.options.socketUrlTransformer(o.url),f=new Dn.RSocketConnector({transport:new Vn({url:d,wsCreator:l=>{const n=this.createSocket(l);return n.addEventListener("message",(l=>{h()})),n}}),setup:{keepAlive:2e4,lifetime:9e4,dataMimeType:r,metadataMimeType:r,payload:{data:null,metadata:i({token:o.headers.Authorization,user_agent:a})}}});let p;try{p=await f.connect()}catch(l){throw this.logger.error("Failed to connect WebSocket",l),clearTimeout(c),l}h();const y=new qn({logger:this.logger,pressure:{lowWaterMark:5},mapLine:n});let m=!1;p.onClose((()=>m=!0));let g=s;const E=y.registerListener({closed:()=>{clearTimeout(c),m||(m=!0,p.close()),E()}}),w=await new Promise(((n,u)=>{let t=!1;const r=p.requestStream({data:i(l.data),metadata:i({path:e})},s,{onError:l=>{l.message.includes("PSYNC_")?l.message.includes("PSYNC_S21")&&this.invalidateCredentials():"Closed. "!==l.message&&this.invalidateCredentials(),"Closed. "!==l.message&&this.logger.error(l),y.close(),t||u(l)},onNext:l=>{t||(t=!0,n(r));const{data:u}=l;g--,u&&y.enqueueData(u)},onComplete:()=>{y.close()},onExtension:()=>{}})})),v=y.registerListener({lowWater:async()=>{s-g>0&&(w.request(s-g),g=s)},closed:()=>{v()}});return l.abortSignal?.aborted?y.close():l.abortSignal?.addEventListener("abort",(()=>{y.close()})),y}async postStream(l){return await this.postStreamRaw(l,(l=>JSON.parse(l)))}async postStreamRaw(l,n){const{data:u,path:e,headers:t,abortSignal:r}=l,i=await this.buildRequest(e),s=new AbortController;let o=!1;r?.addEventListener("abort",(()=>{o||s.abort(r.reason??new D("Cancelling network request before it resolves. Abort signal has been received."))}));const a=await this.fetch(i.url,{method:"POST",headers:{...t,...i.headers},body:JSON.stringify(u),signal:s.signal,cache:"no-store",...this.options.fetchOptions??{},...l.fetchOptions}).catch((l=>{if("AbortError"==l.name)throw new D(`Pending fetch request to ${i.url} has been aborted.`);throw l}));if(!a)throw new Error("Fetch request was aborted");if(o=!0,!a.ok||!a.body){const l=await a.text();this.logger.error(`Could not POST streaming to ${e} - ${a.status} - ${a.statusText}: ${l}`);const n=new Error(`HTTP ${a.statusText}: ${l}`);throw n.status=a.status,n}const c=a.body.getReader(),h=async()=>{try{await c.cancel()}catch(l){}c.releaseLock()};r?.addEventListener("abort",(()=>{h()}));const d=new z.TextDecoder;let f="";const p=new qn({logger:this.logger,mapLine:n}),y=p.registerListener({lowWater:async()=>{try{let u=!1;for(;!u;){const{done:e,value:t}=await c.read();if(e){const l=f.trim();return 0!=l.length&&p.enqueueData(l),p.close(),void await h()}const r=d.decode(t,{stream:!0});f+=r;const i=f.split("\n");for(var l=0;l<i.length-1;l++){var n=i[l].trim();n.length>0&&(p.enqueueData(n),u=!0)}f=i[i.length-1]}}catch(l){throw p.close(),l}},closed:()=>{h(),y?.()}});return p}}function nu(l){return null!=l.data}function uu(l){return null!=l.token_expires_in}function eu(l){return null!=l.checkpoint}function tu(l){return null!=l.checkpoint_complete}function ru(l){return null!=l.partial_checkpoint_complete}function iu(l){return null!=l.checkpoint_diff}function su(l){return Array.isArray(l.buckets)&&"string"==typeof l.checkpoint_token}function ou(l){return"object"==typeof l.request_checkpoint}var au,cu,hu;!function(l){l.CRUD="crud",l.SYNC="sync"}(au||(au={})),function(l){l.HTTP="http",l.WEB_SOCKET="web-socket"}(cu||(cu={})),function(l){l.JAVASCRIPT="js",l.RUST="rust"}(hu||(hu={}));const du=hu.JAVASCRIPT,fu=1e3,pu=5e3,yu={retryDelayMs:pu,logger:y.get("PowerSyncStream"),crudUploadThrottleMs:fu},mu={connectionMethod:cu.WEB_SOCKET,clientImplementation:du,fetchStrategy:Yn.Buffered,params:{}};class gu extends S{_lastSyncedAt;options;abortController;crudUpdateListener;streamingSyncPromise;pendingCrudUpload;notifyCompletedUploads;syncStatus;triggerCrudUpload;constructor(l){super(),this.options={...yu,...l},this.syncStatus=new v({connected:!1,connecting:!1,lastSyncedAt:void 0,dataFlow:{uploading:!1,downloading:!1}}),this.abortController=null,this.triggerCrudUpload=function(l,n){let u=null,e=0;const t=()=>{l(),e=Date.now(),u=null};return function(){const l=Date.now(),r=n-(l-e);r<=0?t():u||(u=setTimeout(t,r))}}((()=>{this.syncStatus.connected&&null==this.pendingCrudUpload&&(this.pendingCrudUpload=new Promise((l=>{this._uploadAllCrud().finally((()=>{this.notifyCompletedUploads?.(),this.pendingCrudUpload=void 0,l()}))})))}),this.options.crudUploadThrottleMs)}async waitForReady(){}waitForStatus(l){return this.waitUntilStatusMatches((n=>{const u=(l,n)=>Object.entries(l).every((([l,e])=>{const t=n[l];return"object"==typeof e&&"object"==typeof t?u(e,t):e==t}));return u(l,n)}))}waitUntilStatusMatches(l){return new Promise((n=>{if(l(this.syncStatus))return void n();const u=this.registerListener({statusChanged:e=>{l(e)&&(n(),u?.())}})}))}get lastSyncedAt(){const l=this.syncStatus.lastSyncedAt;return l&&new Date(l)}get isConnected(){return this.syncStatus.connected}get logger(){return this.options.logger}async dispose(){this.crudUpdateListener?.(),this.crudUpdateListener=void 0}async hasCompletedSync(){return this.options.adapter.hasCompletedSync()}async getWriteCheckpoint(){let l=`/write-checkpoint2.json?client_id=${await this.options.adapter.getClientId()}`;return(await this.options.remote.get(l)).data.write_checkpoint}async _uploadAllCrud(){return this.obtainLock({type:au.CRUD,callback:async()=>{let l;for(;;)try{const n=await this.options.adapter.nextCrudItem();if(!n){await this.options.adapter.updateLocalTarget((()=>this.getWriteCheckpoint()));break}if(this.updateSyncStatus({dataFlow:{uploading:!0}}),n.clientId==l?.clientId)throw this.logger.warn("Potentially previously uploaded CRUD entries are still present in the upload queue.\nMake sure to handle uploads and complete CRUD transactions or batches by calling and awaiting their [.complete()] method.\nThe next upload iteration will be delayed."),new Error("Delaying due to previously encountered CRUD item.");l=n,await this.options.uploadCrud(),this.updateSyncStatus({dataFlow:{uploadError:void 0}})}catch(n){if(l=void 0,this.updateSyncStatus({dataFlow:{uploading:!1,uploadError:n}}),await this.delayRetry(),!this.isConnected)break;this.logger.debug(`Caught exception when uploading. Upload will retry after a delay. Exception: ${n.message}`)}finally{this.updateSyncStatus({dataFlow:{uploading:!1}})}}})}async connect(l){this.abortController&&await this.disconnect();const n=new AbortController;return this.abortController=n,this.streamingSyncPromise=this.streamingSync(this.abortController.signal,l),new Promise((l=>{const n=this.registerListener({statusChanged:u=>{if(null!=u.dataFlowStatus.downloadError)this.logger.warn("Initial connect attempt did not successfully connect to server");else if(u.connecting)return;n(),l()}})}))}async disconnect(){if(this.abortController){this.abortController.signal.aborted||this.abortController.abort(new D("Disconnect has been requested"));try{await this.streamingSyncPromise}catch(l){this.logger.warn(l)}this.streamingSyncPromise=void 0,this.abortController=null,this.updateSyncStatus({connected:!1,connecting:!1})}}async streamingSync(l,n){l||(this.abortController=new AbortController,l=this.abortController.signal),this.crudUpdateListener=this.options.adapter.registerListener({crudUpdate:()=>this.triggerCrudUpload()});let u=new AbortController;for(l.addEventListener("abort",(()=>{u.abort(l?.reason??new D("Received command to disconnect from upstream")),this.crudUpdateListener?.(),this.crudUpdateListener=void 0,this.updateSyncStatus({connected:!1,connecting:!1,dataFlow:{downloading:!1,downloadProgress:null}})}));;){this.updateSyncStatus({connecting:!0});let e=!0;try{if(l?.aborted)break;await this.streamingSyncIteration(u.signal,n)}catch(l){l instanceof D?(this.logger.warn(l),e=!1):this.logger.error(l),this.updateSyncStatus({dataFlow:{downloadError:l}})}finally{l.aborted||(u.abort(new D("Closing sync stream network requests before retry.")),u=new AbortController),this.updateSyncStatus({connected:!1,connecting:!0}),e&&await this.delayRetry(u.signal)}}this.updateSyncStatus({connected:!1,connecting:!1})}async collectLocalBucketState(){const l=await this.options.adapter.getBucketStates(),n=l.map((l=>({name:l.bucket,after:l.op_id}))),u=new Map;for(const n of l)u.set(n.bucket,null);return[n,u]}async requireKeyFormat(l){const n=await this.options.adapter.hasMigratedSubkeys();return l&&!n?(await this.options.adapter.migrateToFixedSubkeys(),!0):n}async streamingSyncIteration(l,n){await this.obtainLock({type:au.SYNC,signal:l,callback:async()=>{const u={...mu,...n??{}};u.clientImplementation==hu.JAVASCRIPT?await this.legacyStreamingSyncIteration(l,u):(await this.requireKeyFormat(!0),await this.rustSyncIteration(l,u))}})}async legacyStreamingSyncIteration(l,n){this.logger.debug("Streaming sync iteration started"),this.options.adapter.startSession();let[u,e]=await this.collectLocalBucketState(),t=null,r=null,i=null;const s=await this.options.adapter.getClientId(),o=await this.requireKeyFormat(!1);this.logger.debug("Requesting stream from server");const a={path:"/sync/stream",abortSignal:l,data:{buckets:u,include_checksum:!0,raw_data:!0,parameters:n.params,client_id:s}};let c;for(c=n?.connectionMethod==cu.HTTP?await this.options.remote.postStream(a):await this.options.remote.socketStream({...a,fetchStrategy:n.fetchStrategy}),this.logger.debug("Stream established. Processing events");!c.closed;){const n=await c.read();if(!n)return;if(this.syncStatus.connected||(Promise.resolve().then((()=>this.triggerCrudUpload())),this.updateSyncStatus({connected:!0})),eu(n)){t=n.checkpoint;const l=new Set(e.keys()),u=new Map;for(const e of n.checkpoint.buckets)u.set(e.bucket,{name:e.bucket,priority:e.priority??3}),l.delete(e.bucket);l.size>0&&this.logger.debug("Removing buckets",[...l]),e=u,await this.options.adapter.removeBuckets([...l]),await this.options.adapter.setTargetCheckpoint(t),await this.updateSyncStatusForStartingCheckpoint(t)}else if(tu(n)){const n=await this.applyCheckpoint(t,l);if(n.endIteration)return;n.applied&&(i=t),r=t}else if(ru(n)){const l=n.partial_checkpoint_complete.priority;this.logger.debug("Partial checkpoint complete",l);const u=await this.options.adapter.syncLocalDatabase(t,l);if(!u.checkpointValid)return void await new Promise((l=>setTimeout(l,50)));if(u.ready){this.logger.debug("partial checkpoint validation succeeded");const n=this.syncStatus.priorityStatusEntries.filter((n=>n.priority<=l));n.push({priority:l,lastSyncedAt:new Date,hasSynced:!0}),this.updateSyncStatus({connected:!0,priorityStatusEntries:n})}else;}else if(iu(n)){if(null==t)throw new Error("Checkpoint diff without previous checkpoint");const l=n.checkpoint_diff,u=new Map;for(const l of t.buckets)u.set(l.bucket,l);for(const n of l.updated_buckets)u.set(n.bucket,n);for(const n of l.removed_buckets)u.delete(n);t={last_op_id:l.last_op_id,buckets:[...u.values()],write_checkpoint:l.write_checkpoint},await this.updateSyncStatusForStartingCheckpoint(t),e=new Map,u.forEach(((l,n)=>e.set(n,{name:l.bucket,priority:l.priority??3})));const r=l.removed_buckets;r.length>0&&this.logger.debug("Remove buckets",r),await this.options.adapter.removeBuckets(r),await this.options.adapter.setTargetCheckpoint(t)}else if(nu(n)){const{data:l}=n,u=this.syncStatus.dataFlowStatus.downloadProgress;let e=null;if(u){e={...u};const n=e[l.bucket];n&&(e[l.bucket]={...n,since_last:n.since_last+l.data.length})}this.updateSyncStatus({dataFlow:{downloading:!0,downloadProgress:e}}),await this.options.adapter.saveSyncData({buckets:[q.fromRow(l)]},o)}else if(uu(n)){const l=n.token_expires_in;if(0==l)return this.logger.debug("Token expiring; reconnect"),void await this.delayRetry();if(l<30)return this.logger.debug("Token will expire soon; reconnect"),void this.options.remote.invalidateCredentials();this.triggerCrudUpload()}else if(this.logger.debug("Sync complete"),t===i)this.updateSyncStatus({connected:!0,lastSyncedAt:new Date,priorityStatusEntries:[],dataFlow:{downloadError:void 0}});else if(r===t){const n=await this.applyCheckpoint(t,l);if(n.endIteration)return;n.applied&&(i=t)}}this.logger.debug("Stream input empty")}async rustSyncIteration(l,n){const u=this,e=this.options.adapter,t=this.options.remote;let r=null,i=!1;const s=new AbortController;l.addEventListener("abort",(()=>s.abort()));let o=null;async function a(l,n){const u=await e.control(l,n??null);await async function(l){for(const n of l)await c(n)}(JSON.parse(u))}async function c(l){if("LogLine"in l)switch(l.LogLine.severity){case"DEBUG":u.logger.debug(l.LogLine.line);break;case"INFO":u.logger.info(l.LogLine.line);break;case"WARNING":u.logger.warn(l.LogLine.line)}else if("UpdateSyncStatus"in l){function e(l){return{priority:l.priority,hasSynced:l.has_synced??void 0,lastSyncedAt:null!=l?.last_synced_at?new Date(1e3*l.last_synced_at):void 0}}const c=l.UpdateSyncStatus.status,h=c.priority_status.find((l=>l.priority==E)),d=null!=h?e(h):null;u.updateSyncStatus({connected:c.connected,connecting:c.connecting,dataFlow:{downloading:null!=c.downloading,downloadProgress:c.downloading?.buckets},lastSyncedAt:d?.lastSyncedAt,hasSynced:d?.hasSynced,priorityStatusEntries:c.priority_status.map(e)})}else if("EstablishSyncStream"in l){if(null!=r)throw"Unexpected request to establish sync stream, already connected";r=async function(l){const e={path:"/sync/stream",abortSignal:s.signal,data:l.request};o=n.connectionMethod==cu.HTTP?await t.postStreamRaw(e,(l=>"string"==typeof l?{command:k.PROCESS_TEXT_LINE,payload:l}:l)):await t.socketStreamRaw({...e,fetchStrategy:n.fetchStrategy},(l=>l instanceof Uint8Array?{command:k.PROCESS_BSON_LINE,payload:l}:l)),u.updateSyncStatus({connected:!0});try{for(;!o.closed;){const l=await o.read();if(null==l)return;await a(l.command,l.payload),i||(u.triggerCrudUpload(),i=!0)}}finally{const l=o;o=null,await l.close()}}(l.EstablishSyncStream)}else"FetchCredentials"in l?l.FetchCredentials.did_expire?t.invalidateCredentials():(t.invalidateCredentials(),t.fetchCredentials().then((l=>{o?.enqueueData({command:k.NOTIFY_TOKEN_REFRESHED})}),(l=>{u.logger.warn("Could not prefetch credentials",l)}))):"CloseSyncStream"in l?s.abort():"FlushFileSystem"in l||"DidCompleteSync"in l&&u.updateSyncStatus({dataFlow:{downloadError:void 0}})}try{await a(k.START,JSON.stringify({parameters:n.params})),this.notifyCompletedUploads=()=>{o?.enqueueData({command:k.NOTIFY_CRUD_UPLOAD_COMPLETED})},await r}finally{this.notifyCompletedUploads=void 0,await async function(){await a(k.STOP)}()}}async updateSyncStatusForStartingCheckpoint(l){const n=await this.options.adapter.getBucketOperationProgress(),u={};let e=!1;for(const t of l.buckets){const l=n[t.bucket],r=l?.atLast??0,i=l?.sinceLast??0;u[t.bucket]={priority:t.priority??3,at_last:r,since_last:i,target_count:t.count??0},null!=t.count&&t.count<r+i&&(e=!0)}if(e)for(const l in u){const n=u[l];n.at_last=0,n.since_last=0}this.updateSyncStatus({dataFlow:{downloading:!0,downloadProgress:u}})}async applyCheckpoint(l,n){let u=await this.options.adapter.syncLocalDatabase(l);const e=this.pendingCrudUpload;if(!u.checkpointValid)return this.logger.debug("Checksum mismatch in checkpoint, will reconnect"),await new Promise((l=>setTimeout(l,50))),{applied:!1,endIteration:!0};if(!u.ready&&null!=e){if(this.logger.debug("Could not apply checkpoint due to local data. Waiting for in-progress upload before retrying."),await Promise.race([e,(t=n,new Promise((l=>{t.aborted?l():t.onabort=()=>l()})))]),n.aborted)return{applied:!1,endIteration:!0};u=await this.options.adapter.syncLocalDatabase(l)}var t;return u.checkpointValid&&u.ready?(this.logger.debug("validated checkpoint",l),this.updateSyncStatus({connected:!0,lastSyncedAt:new Date,dataFlow:{downloading:!1,downloadProgress:null,downloadError:void 0}}),{applied:!0,endIteration:!1}):(this.logger.debug("Could not apply checkpoint. Waiting for next sync complete line."),{applied:!1,endIteration:!1})}updateSyncStatus(l){const n=new v({connected:l.connected??this.syncStatus.connected,connecting:!l.connected&&(l.connecting??this.syncStatus.connecting),lastSyncedAt:l.lastSyncedAt??this.syncStatus.lastSyncedAt,dataFlow:{...this.syncStatus.dataFlowStatus,...l.dataFlow},priorityStatusEntries:l.priorityStatusEntries??this.syncStatus.priorityStatusEntries});this.syncStatus.isEqual(n)||(this.syncStatus=n,this.iterateListeners((l=>l.statusChanged?.(n)))),this.iterateListeners((n=>n.statusUpdated?.(l)))}async delayRetry(l){return new Promise((n=>{if(l?.aborted)return void n();const{retryDelayMs:u}=this.options;let e;const t=()=>{n(),e&&(clearTimeout(e),e=void 0),l?.removeEventListener("abort",t)};l?.addEventListener("abort",t,{once:!0}),e=setTimeout(t,u)}))}}const Eu=/(^ps_data__|^ps_data_local__)/,wu={clearLocal:!0},vu={disconnect:!0},bu=30,Su={retryDelayMs:5e3,logger:y.get("PowerSyncDatabase"),crudUploadThrottleMs:fu},Tu=100,Ru=12e4,_u=l=>"object"==typeof l&&A(l.database);class Au extends S{options;static transactionMutex=new t;closed;ready;currentStatus;sdkVersion;bucketStorageAdapter;_isReadyPromise;connectionManager;get syncStreamImplementation(){return this.connectionManager.syncStreamImplementation}_schema;_database;runExclusiveMutex;constructor(l){super(),this.options=l;const{database:n,schema:u}=l;if("function"!=typeof u?.toJSON)throw new Error("The `schema` option should be provided and should be an instance of `Schema`.");if(F(n))this._database=n;else if(O(n))this._database=n.openDB();else{if(!_u(l))throw new Error("The provided `database` option is invalid.");this._database=this.openDBAdapter(l)}this.bucketStorageAdapter=this.generateBucketStorageAdapter(),this.closed=!1,this.currentStatus=new v({}),this.options={...Su,...l},this._schema=u,this.ready=!1,this.sdkVersion="",this.runExclusiveMutex=new t,this.connectionManager=new _({createSyncImplementation:async(l,n)=>(await this.waitForReady(),this.runExclusive((async()=>{const u=this.generateSyncStreamImplementation(l,this.resolvedConnectionOptions(n)),e=u.registerListener({statusChanged:l=>{this.currentStatus=new v({...l.toJSON(),hasSynced:this.currentStatus?.hasSynced||!!l.lastSyncedAt}),this.iterateListeners((l=>l.statusChanged?.(this.currentStatus)))}});return await u.waitForReady(),{sync:u,onDispose:e}}))),logger:this.logger}),this._isReadyPromise=this.initialize()}get schema(){return this._schema}get database(){return this._database}get connected(){return this.currentStatus?.connected||!1}get connecting(){return this.currentStatus?.connecting||!1}async waitForReady(){this.ready||await this._isReadyPromise}async waitForFirstSync(l){const n=l instanceof AbortSignal?l:l?.signal,u=l&&"priority"in l?l.priority:void 0,e=void 0===u?l=>l.hasSynced:l=>l.statusForPriority(u).hasSynced;if(!e(this.currentStatus))return new Promise((l=>{const u=this.registerListener({statusChanged:n=>{e(n)&&(u(),l())}});n?.addEventListener("abort",(()=>{u(),l()}))}))}async initialize(){await this._initialize(),await this.bucketStorageAdapter.init(),await this._loadVersion(),await this.updateSchema(this.options.schema),await this.updateHasSynced(),await this.database.execute("PRAGMA RECURSIVE_TRIGGERS=TRUE"),this.ready=!0,this.iterateListeners((l=>l.initialized?.()))}async _loadVersion(){try{const{version:l}=await this.database.get("SELECT powersync_rs_version() as version");this.sdkVersion=l}catch(l){throw new Error(`The powersync extension is not loaded correctly. Details: ${l.message}`)}let l;try{l=this.sdkVersion.split(/[.\/]/).slice(0,3).map((l=>parseInt(l)))}catch(l){throw new Error(`Unsupported powersync extension version. Need >=0.3.11 <1.0.0, got: ${this.sdkVersion}. Details: ${l.message}`)}if(0!=l[0]||l[1]<3||3==l[1]&&l[2]<11)throw new Error(`Unsupported powersync extension version. Need >=0.3.11 <1.0.0, got: ${this.sdkVersion}`)}async updateHasSynced(){const l=await this.database.getAll("SELECT priority, last_synced_at FROM ps_sync_state ORDER BY priority DESC");let n;const u=[];for(const{priority:e,last_synced_at:t}of l){const l=new Date(t+"Z");e==E?n=l:u.push({priority:e,hasSynced:!0,lastSyncedAt:l})}const e=null!=n,t=new v({...this.currentStatus.toJSON(),hasSynced:e,priorityStatusEntries:u,lastSyncedAt:n});t.isEqual(this.currentStatus)||(this.currentStatus=t,this.iterateListeners((l=>l.statusChanged?.(this.currentStatus))))}async updateSchema(l){if(this.syncStreamImplementation)throw new Error("Cannot update schema while connected");try{l.validate()}catch(l){this.options.logger?.warn("Schema validation failed. Unexpected behaviour could occur",l)}this._schema=l,await this.database.execute("SELECT powersync_replace_schema(?)",[JSON.stringify(this.schema.toJSON())]),await this.database.refreshSchema(),this.iterateListeners((async n=>n.schemaChanged?.(l)))}get logger(){return this.options.logger}async init(){return this.waitForReady()}resolvedConnectionOptions(l){return{...l,retryDelayMs:l?.retryDelayMs??this.options.retryDelayMs??this.options.retryDelay??pu,crudUploadThrottleMs:l?.crudUploadThrottleMs??this.options.crudUploadThrottleMs??fu}}runExclusive(l){return this.runExclusiveMutex.runExclusive(l)}async connect(l,n){return this.connectionManager.connect(l,n)}async disconnect(){return this.connectionManager.disconnect()}async disconnectAndClear(l=wu){await this.disconnect(),await this.waitForReady();const{clearLocal:n}=l;await this.database.writeTransaction((async l=>{await l.execute("SELECT powersync_clear(?)",[n?1:0])})),this.currentStatus=new v({}),this.iterateListeners((l=>l.statusChanged?.(this.currentStatus)))}async close(l=vu){if(await this.waitForReady(),this.closed)return;const{disconnect:n}=l;n&&await this.disconnect(),await this.connectionManager.close(),await this.database.close(),this.closed=!0}async getUploadQueueStats(l){return this.readTransaction((async n=>{if(l){const l=(await n.execute(`SELECT SUM(cast(data as blob) + 20) as size, count(*) as count FROM ${I.CRUD}`)).rows.item(0);return new b(l?.count??0,l?.size??0)}{const l=(await n.execute(`SELECT count(*) as count FROM ${I.CRUD}`)).rows.item(0);return new b(l?.count??0)}}))}async getCrudBatch(l=100){const n=(await this.getAll(`SELECT id, tx_id, data FROM ${I.CRUD} ORDER BY id ASC LIMIT ?`,[l+1])).map((l=>x.fromRow(l)))??[];let u=!1;if(n.length>l&&(n.pop(),u=!0),0==n.length)return null;const e=n[n.length-1];return new U(n,u,(async l=>this.handleCrudCheckpoint(e.clientId,l)))}async getNextCrudTransaction(){return await this.readTransaction((async l=>{const n=await l.getOptional(`SELECT id, tx_id, data FROM ${I.CRUD} ORDER BY id ASC LIMIT 1`);if(!n)return null;const u=n.tx_id;let e;if(u){e=(await l.getAll(`SELECT id, tx_id, data FROM ${I.CRUD} WHERE tx_id = ? ORDER BY id ASC`,[u])).map((l=>x.fromRow(l)))}else e=[x.fromRow(n)];const t=e[e.length-1];return new P(e,(async l=>this.handleCrudCheckpoint(t.clientId,l)),u)}))}async getClientId(){return this.bucketStorageAdapter.getClientId()}async handleCrudCheckpoint(l,n){return this.writeTransaction((async u=>{if(await u.execute(`DELETE FROM ${I.CRUD} WHERE id <= ?`,[l]),n){const l=await u.execute(`SELECT 1 FROM ${I.CRUD} LIMIT 1`);l.rows?.length||await u.execute(`UPDATE ${I.BUCKETS} SET target_op = CAST(? as INTEGER) WHERE name='$local'`,[n])}else await u.execute(`UPDATE ${I.BUCKETS} SET target_op = CAST(? as INTEGER) WHERE name='$local'`,[this.bucketStorageAdapter.getMaxOpId()])}))}async execute(l,n){return await this.waitForReady(),this.database.execute(l,n)}async executeRaw(l,n){return await this.waitForReady(),this.database.executeRaw(l,n)}async executeBatch(l,n){return await this.waitForReady(),this.database.executeBatch(l,n)}async getAll(l,n){return await this.waitForReady(),this.database.getAll(l,n)}async getOptional(l,n){return await this.waitForReady(),this.database.getOptional(l,n)}async get(l,n){return await this.waitForReady(),this.database.get(l,n)}async readLock(l){return await this.waitForReady(),R(Au.transactionMutex,(()=>l(this.database)))}async writeLock(l){return await this.waitForReady(),R(Au.transactionMutex,(async()=>await l(this.database)))}async readTransaction(l,n=12e4){return await this.waitForReady(),this.database.readTransaction((async n=>{const u=await l({...n});return await n.rollback(),u}),{timeoutMs:n})}async writeTransaction(l,n=12e4){return await this.waitForReady(),this.database.writeTransaction((async n=>{const u=await l(n);return await n.commit(),u}),{timeoutMs:n})}watch(l,n,u,e){if(u&&"object"==typeof u&&"onResult"in u){const t=u,r=e;return this.watchWithCallback(l,n,t,r)}const t=u;return this.watchWithAsyncGenerator(l,n,t)}watchWithCallback(l,n,u,e){const{onResult:t,onError:r=l=>this.options.logger?.error(l)}=u??{};if(!t)throw new Error("onResult is required");C((async u=>{try{const i=await this.resolveTables(l,n,e),s=await this.executeReadOnly(l,n);t(s),this.onChangeWithCallback({onChange:async()=>{try{const u=await this.executeReadOnly(l,n);t(u)}catch(l){r?.(l)}},onError:r},{...e??{},tables:i,signal:u})}catch(l){r?.(l)}}),this,e)}watchWithAsyncGenerator(l,n,u){return new d((e=>{const t={onResult:l=>{e.push(l)},onError:l=>{e.fail(l)}};this.watchWithCallback(l,n,t,u),u?.signal?.addEventListener("abort",(()=>{e.stop()}))}))}async resolveTables(l,n,u){const e=u?.tables?[...u.tables]:[];if(!u?.tables){const u=(await this.getAll(`EXPLAIN ${l}`,n)).filter((l=>"OpenRead"==l.opcode&&0==l.p3&&"number"==typeof l.p2)).map((l=>l.p2)),t=await this.getAll("SELECT DISTINCT tbl_name FROM sqlite_master WHERE rootpage IN (SELECT json_each.value FROM json_each(?))",[JSON.stringify(u)]);for(const l of t)e.push(l.tbl_name.replace(Eu,""))}return e}onChange(l,n){if(l&&"object"==typeof l&&"onChange"in l){const u=l,e=n;return this.onChangeWithCallback(u,e)}const u=l;return this.onChangeWithAsyncGenerator(u)}onChangeWithCallback(l,n){const{onChange:u,onError:e=l=>this.options.logger?.error(l)}=l??{};if(!u)throw new Error("onChange is required");const t=n??{},r=new Set((t?.tables??[]).flatMap((l=>[l,`ps_data__${l}`,`ps_data_local__${l}`]))),i=new Set,s=t.throttleMs??30,o=new T((async l=>{await u(l)})),a=function(l,n){let u=null;const e=()=>{l(),u=null};return function(){null==u&&(u=setTimeout(e,n))}}((()=>this.handleTableChanges(i,r,(l=>{t?.signal?.aborted||o.schedule({changedTables:l})}))),s),c=this.database.registerListener({tablesUpdated:async l=>{try{this.processTableUpdates(l,i),a()}catch(l){e?.(l)}}});return t.signal?.addEventListener("abort",(()=>{o.dispose(),c()})),()=>c()}onChangeWithAsyncGenerator(l){const n=l??{};return new d((u=>{const e=this.onChangeWithCallback({onChange:l=>{u.push(l)},onError:l=>{u.fail(l)}},l);return n.signal?.addEventListener("abort",(()=>{u.stop()})),()=>e()}))}handleTableChanges(l,n,u){if(l.size>0){const e=Array.from(l.values()).filter((l=>n.has(l)));e.length&&u(e)}l.clear()}processTableUpdates(l,n){const u=m(l)?l.tables:[l.table];for(const l of u)n.add(l)}async executeReadOnly(l,n){return await this.waitForReady(),this.database.readLock((u=>u.execute(l,n)))}}class Ou{options;constructor(l){this.options=l,l.logger=l.logger??y.get(`PowerSync ${this.options.dbFilename}`)}get schema(){return this.options.schema}generateOptions(){return{database:this.openDB(),...this.options}}getInstance(){const l=this.generateOptions();return this.generateInstance(l)}}function Fu(l,n,u,e){const{onResult:t,onError:r=l=>{}}=u??{};if(!t)throw new Error("onResult is required");C((async u=>{try{const i=n.compile(),s=await l.resolveTables(i.sql,i.parameters,e),o=await n.execute();t(o),l.onChangeWithCallback({onChange:async()=>{try{const l=await n.execute();t(l)}catch(l){r(l)}},onError:r},{...e??{},tables:s,signal:u})}catch(l){r(l)}}),l,e)}const Cu="9223372036854775807";class Iu extends S{db;mutex;logger;tableNames;_hasCompletedSync;updateListener;_clientId;constructor(l,n,u=y.get("SqliteBucketStorage")){super(),this.db=l,this.mutex=n,this.logger=u,this._hasCompletedSync=!1,this.tableNames=new Set,this.updateListener=l.registerListener({tablesUpdated:l=>{g(l).includes(I.CRUD)&&this.iterateListeners((l=>l.crudUpdate?.()))}})}async init(){this._hasCompletedSync=!1;const l=await this.db.getAll("SELECT name FROM sqlite_master WHERE type='table' AND name GLOB 'ps_data_*'");for(const n of l??[])this.tableNames.add(n.name)}async dispose(){this.updateListener?.()}async _getClientId(){return(await this.db.get("SELECT powersync_client_id() as client_id")).client_id}getClientId(){return null==this._clientId&&(this._clientId=this._getClientId()),this._clientId}getMaxOpId(){return Cu}startSession(){}async getBucketStates(){return await this.db.getAll("SELECT name as bucket, cast(last_op as TEXT) as op_id FROM ps_buckets WHERE pending_delete = 0 AND name != '$local'")}async getBucketOperationProgress(){const l=await this.db.getAll("SELECT name, count_at_last, count_since_last FROM ps_buckets");return Object.fromEntries(l.map((l=>[l.name,{atLast:l.count_at_last,sinceLast:l.count_since_last}])))}async saveSyncData(l,n=!1){await this.writeTransaction((async u=>{for(const e of l.buckets){const l=await u.execute("INSERT INTO powersync_operations(op, data) VALUES(?, ?)",["save",JSON.stringify({buckets:[e.toJSON(n)]})]);this.logger.debug("saveSyncData",JSON.stringify(l))}}))}async removeBuckets(l){for(const n of l)await this.deleteBucket(n)}async deleteBucket(l){await this.writeTransaction((async n=>{await n.execute("INSERT INTO powersync_operations(op, data) VALUES(?, ?)",["delete_bucket",l])})),this.logger.debug("done deleting bucket")}async hasCompletedSync(){if(this._hasCompletedSync)return!0;const l=null!=(await this.db.get("SELECT powersync_last_synced_at() as synced_at")).synced_at;return l&&(this._hasCompletedSync=!0),l}async syncLocalDatabase(l,n){const u=await this.validateChecksums(l,n);if(!u.checkpointValid){this.logger.error("Checksums failed for",u.checkpointFailures);for(const l of u.checkpointFailures??[])await this.deleteBucket(l);return{ready:!1,checkpointValid:!1,checkpointFailures:u.checkpointFailures}}let e=l.buckets;void 0!==n&&(e=e.filter((l=>ku(n,l))));const t=e.map((l=>l.bucket));await this.writeTransaction((async u=>{await u.execute("UPDATE ps_buckets SET last_op = ? WHERE name IN (SELECT json_each.value FROM json_each(?))",[l.last_op_id,JSON.stringify(t)]),null==n&&l.write_checkpoint&&await u.execute("UPDATE ps_buckets SET last_op = ? WHERE name = '$local'",[l.write_checkpoint])}));return await this.updateObjectsFromBuckets(l,n)?{ready:!0,checkpointValid:!0}:(this.logger.debug("Not at a consistent checkpoint - cannot update local db"),{ready:!1,checkpointValid:!0})}async updateObjectsFromBuckets(l,n){let u="";if(void 0!==n){const e=[];for(const u of l.buckets)ku(n,u)&&e.push(u.bucket);u=JSON.stringify({priority:n,buckets:e})}return this.writeTransaction((async e=>{const{insertId:t}=await e.execute("INSERT INTO powersync_operations(op, data) VALUES(?, ?)",["sync_local",u]);if(1==t){if(null==n){const n=Object.fromEntries(l.buckets.map((l=>[l.bucket,l.count]))),u=JSON.stringify(n);await e.execute("UPDATE ps_buckets SET count_since_last = 0, count_at_last = ?->name WHERE name != '$local' AND ?->name IS NOT NULL",[u,u])}return!0}return!1}))}async validateChecksums(l,n){if(void 0!==n){const u=l.buckets.filter((l=>ku(n,l)));l={...l,buckets:u}}const u=await this.db.execute("SELECT powersync_validate_checkpoint(?) as result",[JSON.stringify({...l})]),e=u.rows?.item(0);if(this.logger.debug("validateChecksums priority, checkpoint, result item",n,l,e),!e)return{checkpointValid:!1,ready:!1,checkpointFailures:[]};const t=JSON.parse(e.result);return t.valid?{ready:!0,checkpointValid:!0}:{checkpointValid:!1,ready:!1,checkpointFailures:t.failed_buckets}}async updateLocalTarget(l){if(!(await this.db.getAll("SELECT target_op FROM ps_buckets WHERE name = '$local' AND target_op = CAST(? as INTEGER)",[Cu])).length)return!1;const n=await this.db.getAll("SELECT seq FROM sqlite_sequence WHERE name = 'ps_crud'");if(!n.length)return!1;const u=n[0].seq,e=await l();return this.logger.debug(`[updateLocalTarget] Updating target to checkpoint ${e}`),this.writeTransaction((async l=>{const n=await l.execute("SELECT 1 FROM ps_crud LIMIT 1");if(n.rows?.length)return this.logger.debug("updateLocalTarget","ps crud is not empty"),!1;const t=await l.execute("SELECT seq FROM sqlite_sequence WHERE name = 'ps_crud'");if(!t.rows?.length)throw new Error("SQlite Sequence should not be empty");const r=t.rows?.item(0).seq;if(this.logger.debug("seqAfter",JSON.stringify(t.rows?.item(0))),r!=u)return this.logger.debug("seqAfter != seqBefore",r,u),!1;const i=await l.execute("UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'",[e]);return this.logger.debug(["[updateLocalTarget] Response from updating target_op ",JSON.stringify(i)]),!0}))}async nextCrudItem(){const l=await this.db.getOptional("SELECT * FROM ps_crud ORDER BY id ASC LIMIT 1");if(l)return x.fromRow(l)}async hasCrud(){return!!await this.db.getOptional("SELECT 1 FROM ps_crud LIMIT 1")}async getCrudBatch(l=100){if(!await this.hasCrud())return null;const n=await this.db.getAll("SELECT * FROM ps_crud ORDER BY id ASC LIMIT ?",[l]),u=[];for(const l of n)u.push(x.fromRow(l));if(0===u.length)return null;const e=u[u.length-1];return{crud:u,haveMore:!0,complete:async l=>this.writeTransaction((async n=>{if(await n.execute("DELETE FROM ps_crud WHERE id <= ?",[e.clientId]),l){const u=await n.execute("SELECT 1 FROM ps_crud LIMIT 1");u.rows?.length&&await n.execute("UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'",[l])}else await n.execute("UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'",[this.getMaxOpId()])}))}}async writeTransaction(l,n){return this.db.writeTransaction(l,n)}async setTargetCheckpoint(l){}async control(l,n){return await this.writeTransaction((async u=>{const[[e]]=await u.executeRaw("SELECT powersync_control(?, ?)",[l,n]);return e}))}async hasMigratedSubkeys(){const{r:l}=await this.db.get("SELECT EXISTS(SELECT * FROM ps_kv WHERE key = ?) as r",[Iu._subkeyMigrationKey]);return 0!=l}async migrateToFixedSubkeys(){await this.writeTransaction((async l=>{await l.execute("UPDATE ps_oplog SET key = powersync_remove_duplicate_key_encoding(key);"),await l.execute("INSERT OR REPLACE INTO ps_kv (key, value) VALUES (?, ?);",[Iu._subkeyMigrationKey,"1"])}))}static _subkeyMigrationKey="powersync_js_migrated_subkeys"}function ku(l,n){return null!=n.priority&&n.priority<=l}class Lu{buckets;static fromJSON(l){return new Lu(l.buckets.map((l=>q.fromRow(l))))}constructor(l){this.buckets=l}}var Nu;!function(l){l.TEXT="TEXT",l.INTEGER="INTEGER",l.REAL="REAL"}(Nu||(Nu={}));const Uu={type:Nu.TEXT},xu={type:Nu.INTEGER},Pu={type:Nu.REAL},Du=1999,Mu={text:Uu,integer:xu,real:Pu};class Bu{options;constructor(l){this.options=l}get name(){return this.options.name}get type(){return this.options.type}toJSON(){return{name:this.name,type:this.type}}}const qu={ascending:!0};class ju{options;static createAscending(l){return new ju({name:l,ascending:!0})}constructor(l){this.options={...qu,...l}}get name(){return this.options.name}get ascending(){return this.options.ascending}toJSON(l){return{name:this.name,ascending:this.ascending,type:l.columns.find((l=>l.name===this.name))?.type??Nu.TEXT}}}const Qu={columns:[]};class Wu{options;static createAscending(l,n){return new Wu({...l,columns:n.map((l=>ju.createAscending(l)))})}constructor(l){this.options=l,this.options={...Qu,...l}}get name(){return this.options.name}get columns(){return this.options.columns??[]}toJSON(l){return{name:this.name,columns:this.columns.map((n=>n.toJSON(l)))}}}class $u{types;props;tables;constructor(l){if(Array.isArray(l)){for(const n of l)if(""===n.name)throw new Error("It appears you are trying to create a new Schema with an array instead of an object. Passing in an object instead of an array into 'new Schema()' may resolve your issue.");this.tables=l}else this.props=l,this.tables=this.convertToClassicTables(this.props)}validate(){for(const l of this.tables)l.validate()}toJSON(){return{tables:this.tables.map((l=>l.toJSON()))}}convertToClassicTables(l){return Object.entries(l).map((([l,n])=>n.copyWithName(l)))}}const zu={indexes:[],insertOnly:!1,localOnly:!1,trackPrevious:!1,trackMetadata:!1,ignoreEmptyUpdates:!1},Hu=/["'%,.#\s[\]]/;class Vu{options;_mappedColumns;static createLocalOnly(l){return new Vu({...l,localOnly:!0,insertOnly:!1})}static createInsertOnly(l){return new Vu({...l,localOnly:!1,insertOnly:!0})}static createTable(l,n){return new Vu({name:l,columns:n.columns,indexes:n.indexes,localOnly:n.options.localOnly,insertOnly:n.options.insertOnly,viewName:n.options.viewName})}constructor(l,n){this.isTableV1(l)?this.initTableV1(l):this.initTableV2(l,n)}copyWithName(l){return new Vu({...this.options,name:l})}isTableV1(l){return"columns"in l&&Array.isArray(l.columns)}initTableV1(l){this.options={...l,indexes:l.indexes||[]},this.applyDefaultOptions()}initTableV2(l,n){const u=Object.entries(l).map((([l,n])=>new Bu({name:l,type:n.type}))),e=Object.entries(n?.indexes??{}).map((([l,n])=>new Wu({name:l,columns:n.map((l=>new ju({name:l.replace(/^-/,""),ascending:!l.startsWith("-")})))})));this.options={name:"",columns:u,indexes:e,viewName:n?.viewName,insertOnly:n?.insertOnly,localOnly:n?.localOnly,trackPrevious:n?.trackPrevious,trackMetadata:n?.trackMetadata,ignoreEmptyUpdates:n?.ignoreEmptyUpdates},this.applyDefaultOptions(),this._mappedColumns=l}applyDefaultOptions(){this.options.insertOnly??=zu.insertOnly,this.options.localOnly??=zu.localOnly,this.options.trackPrevious??=zu.trackPrevious,this.options.trackMetadata??=zu.trackMetadata,this.options.ignoreEmptyUpdates??=zu.ignoreEmptyUpdates}get name(){return this.options.name}get viewNameOverride(){return this.options.viewName}get viewName(){return this.viewNameOverride??this.name}get columns(){return this.options.columns}get columnMap(){return this._mappedColumns??this.columns.reduce(((l,n)=>(l[n.name]={type:n.type??Nu.TEXT},l)),{})}get indexes(){return this.options.indexes??[]}get localOnly(){return this.options.localOnly}get insertOnly(){return this.options.insertOnly}get trackPrevious(){return this.options.trackPrevious}get trackMetadata(){return this.options.trackMetadata}get ignoreEmptyUpdates(){return this.options.ignoreEmptyUpdates}get internalName(){return this.options.localOnly?`ps_data_local__${this.name}`:`ps_data__${this.name}`}get validName(){return!Hu.test(this.name)&&(null==this.viewNameOverride||!Hu.test(this.viewNameOverride))}validate(){if(Hu.test(this.name))throw new Error(`Invalid characters in table name: ${this.name}`);if(this.viewNameOverride&&Hu.test(this.viewNameOverride))throw new Error(`Invalid characters in view name: ${this.viewNameOverride}`);if(this.columns.length>Du)throw new Error("Table has too many columns. The maximum number of columns is 1999.");if(this.trackMetadata&&this.localOnly)throw new Error("Can't include metadata for local-only tables.");if(0!=this.trackPrevious&&this.localOnly)throw new Error("Can't include old values for local-only tables.");const l=new Set;l.add("id");for(const n of this.columns){const{name:u}=n;if("id"===n.name)throw new Error("An id column is automatically added, custom id columns are not supported");if(l.has(u))throw new Error(`Duplicate column ${u}`);if(Hu.test(u))throw new Error(`Invalid characters in column name: ${n.name}`);l.add(u)}const n=new Set;for(const u of this.indexes){if(n.has(u.name))throw new Error(`Duplicate index ${u.name}`);if(Hu.test(u.name))throw new Error(`Invalid characters in index name: ${u.name}`);for(const n of u.columns)if(!l.has(n.name))throw new Error(`Column ${n.name} not found for index ${u.name}`);n.add(u.name)}}toJSON(){const l=this.trackPrevious;return{name:this.name,view_name:this.viewName,local_only:this.localOnly,insert_only:this.insertOnly,include_old:l&&(l.columns??!0),include_old_only_when_changed:"object"==typeof l&&1==l.onlyWhenChanged,include_metadata:this.trackMetadata,ignore_empty_update:this.ignoreEmptyUpdates,columns:this.columns.map((l=>l.toJSON())),indexes:this.indexes.map((l=>l.toJSON(this)))}}}class Ju extends Vu{}const Gu=y,Xu={TRACE:Gu.TRACE,DEBUG:Gu.DEBUG,INFO:Gu.INFO,TIME:Gu.TIME,WARN:Gu.WARN,ERROR:Gu.ERROR,OFF:Gu.OFF};function Yu(){return y}function Ku(l,n={}){const u=y.get(l);return n.logLevel&&u.setLevel(n.logLevel),u}const Zu=(l,n)=>{let u;if("string"==typeof l)u=l;else{if(n.length>0)throw new Error("You cannot pass parameters to a compiled query.");const e=l.compile();u=e.sql,n=e.parameters}return{sqlStatement:u,parameters:n}};
2455
+ !function(l){var n=V,u=nl,e="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;l.Buffer=i,l.SlowBuffer=function(l){+l!=l&&(l=0);return i.alloc(+l)},l.INSPECT_MAX_BYTES=50;var t=2147483647;function r(l){if(l>t)throw new RangeError('The value "'+l+'" is invalid for option "size"');var n=new Uint8Array(l);return Object.setPrototypeOf(n,i.prototype),n}function i(l,n,u){if("number"==typeof l){if("string"==typeof n)throw new TypeError('The "string" argument must be of type string. Received type number');return a(l)}return s(l,n,u)}function s(l,n,u){if("string"==typeof l)return function(l,n){"string"==typeof n&&""!==n||(n="utf8");if(!i.isEncoding(n))throw new TypeError("Unknown encoding: "+n);var u=0|f(l,n),e=r(u),t=e.write(l,n);t!==u&&(e=e.slice(0,t));return e}(l,n);if(ArrayBuffer.isView(l))return function(l){if(B(l,Uint8Array)){var n=new Uint8Array(l);return h(n.buffer,n.byteOffset,n.byteLength)}return c(l)}(l);if(null==l)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof l);if(B(l,ArrayBuffer)||l&&B(l.buffer,ArrayBuffer))return h(l,n,u);if("undefined"!=typeof SharedArrayBuffer&&(B(l,SharedArrayBuffer)||l&&B(l.buffer,SharedArrayBuffer)))return h(l,n,u);if("number"==typeof l)throw new TypeError('The "value" argument must not be of type number. Received type number');var e=l.valueOf&&l.valueOf();if(null!=e&&e!==l)return i.from(e,n,u);var t=function(l){if(i.isBuffer(l)){var n=0|d(l.length),u=r(n);return 0===u.length||l.copy(u,0,0,n),u}if(void 0!==l.length)return"number"!=typeof l.length||q(l.length)?r(0):c(l);if("Buffer"===l.type&&Array.isArray(l.data))return c(l.data)}(l);if(t)return t;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof l[Symbol.toPrimitive])return i.from(l[Symbol.toPrimitive]("string"),n,u);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof l)}function o(l){if("number"!=typeof l)throw new TypeError('"size" argument must be of type number');if(l<0)throw new RangeError('The value "'+l+'" is invalid for option "size"')}function a(l){return o(l),r(l<0?0:0|d(l))}function c(l){for(var n=l.length<0?0:0|d(l.length),u=r(n),e=0;e<n;e+=1)u[e]=255&l[e];return u}function h(l,n,u){if(n<0||l.byteLength<n)throw new RangeError('"offset" is outside of buffer bounds');if(l.byteLength<n+(u||0))throw new RangeError('"length" is outside of buffer bounds');var e;return e=void 0===n&&void 0===u?new Uint8Array(l):void 0===u?new Uint8Array(l,n):new Uint8Array(l,n,u),Object.setPrototypeOf(e,i.prototype),e}function d(l){if(l>=t)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+t.toString(16)+" bytes");return 0|l}function f(l,n){if(i.isBuffer(l))return l.length;if(ArrayBuffer.isView(l)||B(l,ArrayBuffer))return l.byteLength;if("string"!=typeof l)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof l);var u=l.length,e=arguments.length>2&&!0===arguments[2];if(!e&&0===u)return 0;for(var t=!1;;)switch(n){case"ascii":case"latin1":case"binary":return u;case"utf8":case"utf-8":return P(l).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*u;case"hex":return u>>>1;case"base64":return D(l).length;default:if(t)return e?-1:P(l).length;n=(""+n).toLowerCase(),t=!0}}function p(l,n,u){var e=!1;if((void 0===n||n<0)&&(n=0),n>this.length)return"";if((void 0===u||u>this.length)&&(u=this.length),u<=0)return"";if((u>>>=0)<=(n>>>=0))return"";for(l||(l="utf8");;)switch(l){case"hex":return F(this,n,u);case"utf8":case"utf-8":return R(this,n,u);case"ascii":return A(this,n,u);case"latin1":case"binary":return O(this,n,u);case"base64":return T(this,n,u);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,n,u);default:if(e)throw new TypeError("Unknown encoding: "+l);l=(l+"").toLowerCase(),e=!0}}function y(l,n,u){var e=l[n];l[n]=l[u],l[u]=e}function m(l,n,u,e,t){if(0===l.length)return-1;if("string"==typeof u?(e=u,u=0):u>2147483647?u=2147483647:u<-2147483648&&(u=-2147483648),q(u=+u)&&(u=t?0:l.length-1),u<0&&(u=l.length+u),u>=l.length){if(t)return-1;u=l.length-1}else if(u<0){if(!t)return-1;u=0}if("string"==typeof n&&(n=i.from(n,e)),i.isBuffer(n))return 0===n.length?-1:g(l,n,u,e,t);if("number"==typeof n)return n&=255,"function"==typeof Uint8Array.prototype.indexOf?t?Uint8Array.prototype.indexOf.call(l,n,u):Uint8Array.prototype.lastIndexOf.call(l,n,u):g(l,[n],u,e,t);throw new TypeError("val must be string, number or Buffer")}function g(l,n,u,e,t){var r,i=1,s=l.length,o=n.length;if(void 0!==e&&("ucs2"===(e=String(e).toLowerCase())||"ucs-2"===e||"utf16le"===e||"utf-16le"===e)){if(l.length<2||n.length<2)return-1;i=2,s/=2,o/=2,u/=2}function a(l,n){return 1===i?l[n]:l.readUInt16BE(n*i)}if(t){var c=-1;for(r=u;r<s;r++)if(a(l,r)===a(n,-1===c?0:r-c)){if(-1===c&&(c=r),r-c+1===o)return c*i}else-1!==c&&(r-=r-c),c=-1}else for(u+o>s&&(u=s-o),r=u;r>=0;r--){for(var h=!0,d=0;d<o;d++)if(a(l,r+d)!==a(n,d)){h=!1;break}if(h)return r}return-1}function E(l,n,u,e){u=Number(u)||0;var t=l.length-u;e?(e=Number(e))>t&&(e=t):e=t;var r=n.length;e>r/2&&(e=r/2);for(var i=0;i<e;++i){var s=parseInt(n.substr(2*i,2),16);if(q(s))return i;l[u+i]=s}return i}function w(l,n,u,e){return M(P(n,l.length-u),l,u,e)}function v(l,n,u,e){return M(function(l){for(var n=[],u=0;u<l.length;++u)n.push(255&l.charCodeAt(u));return n}(n),l,u,e)}function b(l,n,u,e){return M(D(n),l,u,e)}function S(l,n,u,e){return M(function(l,n){for(var u,e,t,r=[],i=0;i<l.length&&!((n-=2)<0);++i)e=(u=l.charCodeAt(i))>>8,t=u%256,r.push(t),r.push(e);return r}(n,l.length-u),l,u,e)}function T(l,u,e){return 0===u&&e===l.length?n.fromByteArray(l):n.fromByteArray(l.slice(u,e))}function R(l,n,u){u=Math.min(l.length,u);for(var e=[],t=n;t<u;){var r,i,s,o,a=l[t],c=null,h=a>239?4:a>223?3:a>191?2:1;if(t+h<=u)switch(h){case 1:a<128&&(c=a);break;case 2:128==(192&(r=l[t+1]))&&(o=(31&a)<<6|63&r)>127&&(c=o);break;case 3:r=l[t+1],i=l[t+2],128==(192&r)&&128==(192&i)&&(o=(15&a)<<12|(63&r)<<6|63&i)>2047&&(o<55296||o>57343)&&(c=o);break;case 4:r=l[t+1],i=l[t+2],s=l[t+3],128==(192&r)&&128==(192&i)&&128==(192&s)&&(o=(15&a)<<18|(63&r)<<12|(63&i)<<6|63&s)>65535&&o<1114112&&(c=o)}null===c?(c=65533,h=1):c>65535&&(c-=65536,e.push(c>>>10&1023|55296),c=56320|1023&c),e.push(c),t+=h}return function(l){var n=l.length;if(n<=_)return String.fromCharCode.apply(String,l);var u="",e=0;for(;e<n;)u+=String.fromCharCode.apply(String,l.slice(e,e+=_));return u}(e)}l.kMaxLength=t,i.TYPED_ARRAY_SUPPORT=function(){try{var l=new Uint8Array(1),n={foo:function(){return 42}};return Object.setPrototypeOf(n,Uint8Array.prototype),Object.setPrototypeOf(l,n),42===l.foo()}catch(l){return!1}}(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||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."),Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}}),i.poolSize=8192,i.from=function(l,n,u){return s(l,n,u)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array),i.alloc=function(l,n,u){return function(l,n,u){return o(l),l<=0?r(l):void 0!==n?"string"==typeof u?r(l).fill(n,u):r(l).fill(n):r(l)}(l,n,u)},i.allocUnsafe=function(l){return a(l)},i.allocUnsafeSlow=function(l){return a(l)},i.isBuffer=function(l){return null!=l&&!0===l._isBuffer&&l!==i.prototype},i.compare=function(l,n){if(B(l,Uint8Array)&&(l=i.from(l,l.offset,l.byteLength)),B(n,Uint8Array)&&(n=i.from(n,n.offset,n.byteLength)),!i.isBuffer(l)||!i.isBuffer(n))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(l===n)return 0;for(var u=l.length,e=n.length,t=0,r=Math.min(u,e);t<r;++t)if(l[t]!==n[t]){u=l[t],e=n[t];break}return u<e?-1:e<u?1:0},i.isEncoding=function(l){switch(String(l).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!0;default:return!1}},i.concat=function(l,n){if(!Array.isArray(l))throw new TypeError('"list" argument must be an Array of Buffers');if(0===l.length)return i.alloc(0);var u;if(void 0===n)for(n=0,u=0;u<l.length;++u)n+=l[u].length;var e=i.allocUnsafe(n),t=0;for(u=0;u<l.length;++u){var r=l[u];if(B(r,Uint8Array))t+r.length>e.length?i.from(r).copy(e,t):Uint8Array.prototype.set.call(e,r,t);else{if(!i.isBuffer(r))throw new TypeError('"list" argument must be an Array of Buffers');r.copy(e,t)}t+=r.length}return e},i.byteLength=f,i.prototype._isBuffer=!0,i.prototype.swap16=function(){var l=this.length;if(l%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var n=0;n<l;n+=2)y(this,n,n+1);return this},i.prototype.swap32=function(){var l=this.length;if(l%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var n=0;n<l;n+=4)y(this,n,n+3),y(this,n+1,n+2);return this},i.prototype.swap64=function(){var l=this.length;if(l%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var n=0;n<l;n+=8)y(this,n,n+7),y(this,n+1,n+6),y(this,n+2,n+5),y(this,n+3,n+4);return this},i.prototype.toString=function(){var l=this.length;return 0===l?"":0===arguments.length?R(this,0,l):p.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(l){if(!i.isBuffer(l))throw new TypeError("Argument must be a Buffer");return this===l||0===i.compare(this,l)},i.prototype.inspect=function(){var n="",u=l.INSPECT_MAX_BYTES;return n=this.toString("hex",0,u).replace(/(.{2})/g,"$1 ").trim(),this.length>u&&(n+=" ... "),"<Buffer "+n+">"},e&&(i.prototype[e]=i.prototype.inspect),i.prototype.compare=function(l,n,u,e,t){if(B(l,Uint8Array)&&(l=i.from(l,l.offset,l.byteLength)),!i.isBuffer(l))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof l);if(void 0===n&&(n=0),void 0===u&&(u=l?l.length:0),void 0===e&&(e=0),void 0===t&&(t=this.length),n<0||u>l.length||e<0||t>this.length)throw new RangeError("out of range index");if(e>=t&&n>=u)return 0;if(e>=t)return-1;if(n>=u)return 1;if(this===l)return 0;for(var r=(t>>>=0)-(e>>>=0),s=(u>>>=0)-(n>>>=0),o=Math.min(r,s),a=this.slice(e,t),c=l.slice(n,u),h=0;h<o;++h)if(a[h]!==c[h]){r=a[h],s=c[h];break}return r<s?-1:s<r?1:0},i.prototype.includes=function(l,n,u){return-1!==this.indexOf(l,n,u)},i.prototype.indexOf=function(l,n,u){return m(this,l,n,u,!0)},i.prototype.lastIndexOf=function(l,n,u){return m(this,l,n,u,!1)},i.prototype.write=function(l,n,u,e){if(void 0===n)e="utf8",u=this.length,n=0;else if(void 0===u&&"string"==typeof n)e=n,u=this.length,n=0;else{if(!isFinite(n))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");n>>>=0,isFinite(u)?(u>>>=0,void 0===e&&(e="utf8")):(e=u,u=void 0)}var t=this.length-n;if((void 0===u||u>t)&&(u=t),l.length>0&&(u<0||n<0)||n>this.length)throw new RangeError("Attempt to write outside buffer bounds");e||(e="utf8");for(var r=!1;;)switch(e){case"hex":return E(this,l,n,u);case"utf8":case"utf-8":return w(this,l,n,u);case"ascii":case"latin1":case"binary":return v(this,l,n,u);case"base64":return b(this,l,n,u);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,l,n,u);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(""+e).toLowerCase(),r=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var _=4096;function A(l,n,u){var e="";u=Math.min(l.length,u);for(var t=n;t<u;++t)e+=String.fromCharCode(127&l[t]);return e}function O(l,n,u){var e="";u=Math.min(l.length,u);for(var t=n;t<u;++t)e+=String.fromCharCode(l[t]);return e}function F(l,n,u){var e=l.length;(!n||n<0)&&(n=0),(!u||u<0||u>e)&&(u=e);for(var t="",r=n;r<u;++r)t+=j[l[r]];return t}function C(l,n,u){for(var e=l.slice(n,u),t="",r=0;r<e.length-1;r+=2)t+=String.fromCharCode(e[r]+256*e[r+1]);return t}function I(l,n,u){if(l%1!=0||l<0)throw new RangeError("offset is not uint");if(l+n>u)throw new RangeError("Trying to access beyond buffer length")}function k(l,n,u,e,t,r){if(!i.isBuffer(l))throw new TypeError('"buffer" argument must be a Buffer instance');if(n>t||n<r)throw new RangeError('"value" argument is out of bounds');if(u+e>l.length)throw new RangeError("Index out of range")}function L(l,n,u,e,t,r){if(u+e>l.length)throw new RangeError("Index out of range");if(u<0)throw new RangeError("Index out of range")}function N(l,n,e,t,r){return n=+n,e>>>=0,r||L(l,0,e,4),u.write(l,n,e,t,23,4),e+4}function U(l,n,e,t,r){return n=+n,e>>>=0,r||L(l,0,e,8),u.write(l,n,e,t,52,8),e+8}i.prototype.slice=function(l,n){var u=this.length;(l=~~l)<0?(l+=u)<0&&(l=0):l>u&&(l=u),(n=void 0===n?u:~~n)<0?(n+=u)<0&&(n=0):n>u&&(n=u),n<l&&(n=l);var e=this.subarray(l,n);return Object.setPrototypeOf(e,i.prototype),e},i.prototype.readUintLE=i.prototype.readUIntLE=function(l,n,u){l>>>=0,n>>>=0,u||I(l,n,this.length);for(var e=this[l],t=1,r=0;++r<n&&(t*=256);)e+=this[l+r]*t;return e},i.prototype.readUintBE=i.prototype.readUIntBE=function(l,n,u){l>>>=0,n>>>=0,u||I(l,n,this.length);for(var e=this[l+--n],t=1;n>0&&(t*=256);)e+=this[l+--n]*t;return e},i.prototype.readUint8=i.prototype.readUInt8=function(l,n){return l>>>=0,n||I(l,1,this.length),this[l]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(l,n){return l>>>=0,n||I(l,2,this.length),this[l]|this[l+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(l,n){return l>>>=0,n||I(l,2,this.length),this[l]<<8|this[l+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(l,n){return l>>>=0,n||I(l,4,this.length),(this[l]|this[l+1]<<8|this[l+2]<<16)+16777216*this[l+3]},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(l,n){return l>>>=0,n||I(l,4,this.length),16777216*this[l]+(this[l+1]<<16|this[l+2]<<8|this[l+3])},i.prototype.readIntLE=function(l,n,u){l>>>=0,n>>>=0,u||I(l,n,this.length);for(var e=this[l],t=1,r=0;++r<n&&(t*=256);)e+=this[l+r]*t;return e>=(t*=128)&&(e-=Math.pow(2,8*n)),e},i.prototype.readIntBE=function(l,n,u){l>>>=0,n>>>=0,u||I(l,n,this.length);for(var e=n,t=1,r=this[l+--e];e>0&&(t*=256);)r+=this[l+--e]*t;return r>=(t*=128)&&(r-=Math.pow(2,8*n)),r},i.prototype.readInt8=function(l,n){return l>>>=0,n||I(l,1,this.length),128&this[l]?-1*(255-this[l]+1):this[l]},i.prototype.readInt16LE=function(l,n){l>>>=0,n||I(l,2,this.length);var u=this[l]|this[l+1]<<8;return 32768&u?4294901760|u:u},i.prototype.readInt16BE=function(l,n){l>>>=0,n||I(l,2,this.length);var u=this[l+1]|this[l]<<8;return 32768&u?4294901760|u:u},i.prototype.readInt32LE=function(l,n){return l>>>=0,n||I(l,4,this.length),this[l]|this[l+1]<<8|this[l+2]<<16|this[l+3]<<24},i.prototype.readInt32BE=function(l,n){return l>>>=0,n||I(l,4,this.length),this[l]<<24|this[l+1]<<16|this[l+2]<<8|this[l+3]},i.prototype.readFloatLE=function(l,n){return l>>>=0,n||I(l,4,this.length),u.read(this,l,!0,23,4)},i.prototype.readFloatBE=function(l,n){return l>>>=0,n||I(l,4,this.length),u.read(this,l,!1,23,4)},i.prototype.readDoubleLE=function(l,n){return l>>>=0,n||I(l,8,this.length),u.read(this,l,!0,52,8)},i.prototype.readDoubleBE=function(l,n){return l>>>=0,n||I(l,8,this.length),u.read(this,l,!1,52,8)},i.prototype.writeUintLE=i.prototype.writeUIntLE=function(l,n,u,e){(l=+l,n>>>=0,u>>>=0,e)||k(this,l,n,u,Math.pow(2,8*u)-1,0);var t=1,r=0;for(this[n]=255&l;++r<u&&(t*=256);)this[n+r]=l/t&255;return n+u},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(l,n,u,e){(l=+l,n>>>=0,u>>>=0,e)||k(this,l,n,u,Math.pow(2,8*u)-1,0);var t=u-1,r=1;for(this[n+t]=255&l;--t>=0&&(r*=256);)this[n+t]=l/r&255;return n+u},i.prototype.writeUint8=i.prototype.writeUInt8=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,1,255,0),this[n]=255&l,n+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,2,65535,0),this[n]=255&l,this[n+1]=l>>>8,n+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,2,65535,0),this[n]=l>>>8,this[n+1]=255&l,n+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,4,4294967295,0),this[n+3]=l>>>24,this[n+2]=l>>>16,this[n+1]=l>>>8,this[n]=255&l,n+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,4,4294967295,0),this[n]=l>>>24,this[n+1]=l>>>16,this[n+2]=l>>>8,this[n+3]=255&l,n+4},i.prototype.writeIntLE=function(l,n,u,e){if(l=+l,n>>>=0,!e){var t=Math.pow(2,8*u-1);k(this,l,n,u,t-1,-t)}var r=0,i=1,s=0;for(this[n]=255&l;++r<u&&(i*=256);)l<0&&0===s&&0!==this[n+r-1]&&(s=1),this[n+r]=(l/i|0)-s&255;return n+u},i.prototype.writeIntBE=function(l,n,u,e){if(l=+l,n>>>=0,!e){var t=Math.pow(2,8*u-1);k(this,l,n,u,t-1,-t)}var r=u-1,i=1,s=0;for(this[n+r]=255&l;--r>=0&&(i*=256);)l<0&&0===s&&0!==this[n+r+1]&&(s=1),this[n+r]=(l/i|0)-s&255;return n+u},i.prototype.writeInt8=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,1,127,-128),l<0&&(l=255+l+1),this[n]=255&l,n+1},i.prototype.writeInt16LE=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,2,32767,-32768),this[n]=255&l,this[n+1]=l>>>8,n+2},i.prototype.writeInt16BE=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,2,32767,-32768),this[n]=l>>>8,this[n+1]=255&l,n+2},i.prototype.writeInt32LE=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,4,2147483647,-2147483648),this[n]=255&l,this[n+1]=l>>>8,this[n+2]=l>>>16,this[n+3]=l>>>24,n+4},i.prototype.writeInt32BE=function(l,n,u){return l=+l,n>>>=0,u||k(this,l,n,4,2147483647,-2147483648),l<0&&(l=4294967295+l+1),this[n]=l>>>24,this[n+1]=l>>>16,this[n+2]=l>>>8,this[n+3]=255&l,n+4},i.prototype.writeFloatLE=function(l,n,u){return N(this,l,n,!0,u)},i.prototype.writeFloatBE=function(l,n,u){return N(this,l,n,!1,u)},i.prototype.writeDoubleLE=function(l,n,u){return U(this,l,n,!0,u)},i.prototype.writeDoubleBE=function(l,n,u){return U(this,l,n,!1,u)},i.prototype.copy=function(l,n,u,e){if(!i.isBuffer(l))throw new TypeError("argument should be a Buffer");if(u||(u=0),e||0===e||(e=this.length),n>=l.length&&(n=l.length),n||(n=0),e>0&&e<u&&(e=u),e===u)return 0;if(0===l.length||0===this.length)return 0;if(n<0)throw new RangeError("targetStart out of bounds");if(u<0||u>=this.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("sourceEnd out of bounds");e>this.length&&(e=this.length),l.length-n<e-u&&(e=l.length-n+u);var t=e-u;return this===l&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(n,u,e):Uint8Array.prototype.set.call(l,this.subarray(u,e),n),t},i.prototype.fill=function(l,n,u,e){if("string"==typeof l){if("string"==typeof n?(e=n,n=0,u=this.length):"string"==typeof u&&(e=u,u=this.length),void 0!==e&&"string"!=typeof e)throw new TypeError("encoding must be a string");if("string"==typeof e&&!i.isEncoding(e))throw new TypeError("Unknown encoding: "+e);if(1===l.length){var t=l.charCodeAt(0);("utf8"===e&&t<128||"latin1"===e)&&(l=t)}}else"number"==typeof l?l&=255:"boolean"==typeof l&&(l=Number(l));if(n<0||this.length<n||this.length<u)throw new RangeError("Out of range index");if(u<=n)return this;var r;if(n>>>=0,u=void 0===u?this.length:u>>>0,l||(l=0),"number"==typeof l)for(r=n;r<u;++r)this[r]=l;else{var s=i.isBuffer(l)?l:i.from(l,e),o=s.length;if(0===o)throw new TypeError('The value "'+l+'" is invalid for argument "value"');for(r=0;r<u-n;++r)this[r+n]=s[r%o]}return this};var x=/[^+/0-9A-Za-z-_]/g;function P(l,n){var u;n=n||1/0;for(var e=l.length,t=null,r=[],i=0;i<e;++i){if((u=l.charCodeAt(i))>55295&&u<57344){if(!t){if(u>56319){(n-=3)>-1&&r.push(239,191,189);continue}if(i+1===e){(n-=3)>-1&&r.push(239,191,189);continue}t=u;continue}if(u<56320){(n-=3)>-1&&r.push(239,191,189),t=u;continue}u=65536+(t-55296<<10|u-56320)}else t&&(n-=3)>-1&&r.push(239,191,189);if(t=null,u<128){if((n-=1)<0)break;r.push(u)}else if(u<2048){if((n-=2)<0)break;r.push(u>>6|192,63&u|128)}else if(u<65536){if((n-=3)<0)break;r.push(u>>12|224,u>>6&63|128,63&u|128)}else{if(!(u<1114112))throw new Error("Invalid code point");if((n-=4)<0)break;r.push(u>>18|240,u>>12&63|128,u>>6&63|128,63&u|128)}}return r}function D(l){return n.toByteArray(function(l){if((l=(l=l.split("=")[0]).trim().replace(x,"")).length<2)return"";for(;l.length%4!=0;)l+="=";return l}(l))}function M(l,n,u,e){for(var t=0;t<e&&!(t+u>=n.length||t>=l.length);++t)n[t+u]=l[t];return t}function B(l,n){return l instanceof n||null!=l&&null!=l.constructor&&null!=l.constructor.name&&l.constructor.name===n.name}function q(l){return l!=l}var j=function(){for(var l="0123456789abcdef",n=new Array(256),u=0;u<16;++u)for(var e=16*u,t=0;t<16;++t)n[e+t]=l[u]+l[t];return n}()}(el);var tl={},rl={};!function(l){var n,u,e,t;Object.defineProperty(l,"__esModule",{value:!0}),l.Frame=l.Lengths=l.Flags=l.FrameTypes=void 0,function(l){l[l.RESERVED=0]="RESERVED",l[l.SETUP=1]="SETUP",l[l.LEASE=2]="LEASE",l[l.KEEPALIVE=3]="KEEPALIVE",l[l.REQUEST_RESPONSE=4]="REQUEST_RESPONSE",l[l.REQUEST_FNF=5]="REQUEST_FNF",l[l.REQUEST_STREAM=6]="REQUEST_STREAM",l[l.REQUEST_CHANNEL=7]="REQUEST_CHANNEL",l[l.REQUEST_N=8]="REQUEST_N",l[l.CANCEL=9]="CANCEL",l[l.PAYLOAD=10]="PAYLOAD",l[l.ERROR=11]="ERROR",l[l.METADATA_PUSH=12]="METADATA_PUSH",l[l.RESUME=13]="RESUME",l[l.RESUME_OK=14]="RESUME_OK",l[l.EXT=63]="EXT"}(n=l.FrameTypes||(l.FrameTypes={})),(u=l.Flags||(l.Flags={}))[u.NONE=0]="NONE",u[u.COMPLETE=64]="COMPLETE",u[u.FOLLOWS=128]="FOLLOWS",u[u.IGNORE=512]="IGNORE",u[u.LEASE=64]="LEASE",u[u.METADATA=256]="METADATA",u[u.NEXT=32]="NEXT",u[u.RESPOND=128]="RESPOND",u[u.RESUME_ENABLE=128]="RESUME_ENABLE",function(l){l.hasMetadata=function(n){return(n&l.METADATA)===l.METADATA},l.hasComplete=function(n){return(n&l.COMPLETE)===l.COMPLETE},l.hasNext=function(n){return(n&l.NEXT)===l.NEXT},l.hasFollows=function(n){return(n&l.FOLLOWS)===l.FOLLOWS},l.hasIgnore=function(n){return(n&l.IGNORE)===l.IGNORE},l.hasRespond=function(n){return(n&l.RESPOND)===l.RESPOND},l.hasLease=function(n){return(n&l.LEASE)===l.LEASE},l.hasResume=function(n){return(n&l.RESUME_ENABLE)===l.RESUME_ENABLE}}(l.Flags||(l.Flags={})),(e=l.Lengths||(l.Lengths={}))[e.FRAME=3]="FRAME",e[e.HEADER=6]="HEADER",e[e.METADATA=3]="METADATA",e[e.REQUEST=3]="REQUEST",(t=l.Frame||(l.Frame={})).isConnection=function(l){return 0===l.streamId},t.isRequest=function(l){return n.REQUEST_RESPONSE<=l.type&&l.type<=n.REQUEST_CHANNEL}}(rl),function(l){var n=r&&r.__generator||function(l,n){var u,e,t,r,i={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function s(r){return function(s){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;i;)try{if(u=1,e&&(t=2&r[0]?e.return:r[0]?e.throw||((t=e.return)&&t.call(e),0):e.next)&&!(t=t.call(e,r[1])).done)return t;switch(e=0,t&&(r=[2&r[0],t.value]),r[0]){case 0:case 1:t=r;break;case 4:return i.label++,{value:r[1],done:!1};case 5:i.label++,e=r[1],r=[0];continue;case 7:r=i.ops.pop(),i.trys.pop();continue;default:if(!(t=i.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){i=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){i.label=r[1];break}if(6===r[0]&&i.label<t[1]){i.label=t[1],t=r;break}if(t&&i.label<t[2]){i.label=t[2],i.ops.push(r);break}t[2]&&i.ops.pop(),i.trys.pop();continue}r=n.call(l,i)}catch(l){r=[6,l],e=0}finally{u=t=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,s])}}};Object.defineProperty(l,"__esModule",{value:!0}),l.Deserializer=l.sizeOfFrame=l.serializeFrame=l.deserializeFrame=l.serializeFrameWithLength=l.deserializeFrames=l.deserializeFrameWithLength=l.writeUInt64BE=l.readUInt64BE=l.writeUInt24BE=l.readUInt24BE=l.MAX_VERSION=l.MAX_TTL=l.MAX_STREAM_ID=l.MAX_RESUME_LENGTH=l.MAX_REQUEST_N=l.MAX_REQUEST_COUNT=l.MAX_MIME_LENGTH=l.MAX_METADATA_LENGTH=l.MAX_LIFETIME=l.MAX_KEEPALIVE=l.MAX_CODE=l.FRAME_TYPE_OFFFSET=l.FLAGS_MASK=void 0;var u=rl;l.FLAGS_MASK=1023,l.FRAME_TYPE_OFFFSET=10,l.MAX_CODE=2147483647,l.MAX_KEEPALIVE=2147483647,l.MAX_LIFETIME=2147483647,l.MAX_METADATA_LENGTH=16777215,l.MAX_MIME_LENGTH=255,l.MAX_REQUEST_COUNT=2147483647,l.MAX_REQUEST_N=2147483647,l.MAX_RESUME_LENGTH=65535,l.MAX_STREAM_ID=2147483647,l.MAX_TTL=2147483647,l.MAX_VERSION=65535;var e=4294967296;function t(l,n){return l.readUInt8(n)<<16|l.readUInt8(n+1)<<8|l.readUInt8(n+2)}function i(l,n,u){return u=l.writeUInt8(n>>>16,u),u=l.writeUInt8(n>>>8&255,u),l.writeUInt8(255&n,u)}function s(l,n){var u=l.readUInt32BE(n),t=l.readUInt32BE(n+4);return u*e+t}function o(l,n,u){var t=n/e|0,r=n%e;return u=l.writeUInt32BE(t,u),l.writeUInt32BE(r,u)}l.readUInt24BE=t,l.writeUInt24BE=i,l.readUInt64BE=s,l.writeUInt64BE=o;function a(l){var n=t(l,0);return h(l.slice(3,3+n))}function c(l){var u,e,r,i,s;return n(this,(function(n){switch(n.label){case 0:u=0,n.label=1;case 1:return u+3<l.length?(e=t(l,u),(i=(r=u+3)+e)>l.length?[3,3]:(s=l.slice(r,i),[4,[h(s),u=i]])):[3,3];case 2:return n.sent(),[3,1];case 3:return[2]}}))}function h(n){var e=0,t=n.readInt32BE(e);e+=4;var r=n.readUInt16BE(e);e+=2;var i=r>>>l.FRAME_TYPE_OFFFSET,o=r&l.FLAGS_MASK;switch(i){case u.FrameTypes.SETUP:return function(l,n,e){l.length;var t=6,r=l.readUInt16BE(t);t+=2;var i=l.readUInt16BE(t);t+=2;var s=l.readInt32BE(t);t+=4;var o=l.readInt32BE(t);t+=4;var a=null;if(e&u.Flags.RESUME_ENABLE){var c=l.readInt16BE(t);t+=2,a=l.slice(t,t+c),t+=c}var h=l.readUInt8(t);t+=1;var d=l.toString("ascii",t,t+h);t+=h;var f=l.readUInt8(t);t+=1;var p=l.toString("ascii",t,t+f);t+=f;var y={data:null,dataMimeType:p,flags:e,keepAlive:s,lifetime:o,majorVersion:r,metadata:null,metadataMimeType:d,minorVersion:i,resumeToken:a,streamId:0,type:u.FrameTypes.SETUP};return _(l,y,t),y}(n,0,o);case u.FrameTypes.PAYLOAD:return function(l,n,e){l.length;var t={data:null,flags:e,metadata:null,streamId:n,type:u.FrameTypes.PAYLOAD};return _(l,t,6),t}(n,t,o);case u.FrameTypes.ERROR:return function(l,n,e){l.length;var t=6,r=l.readInt32BE(t);t+=4;var i=l.length-t,s="";i>0&&(s=l.toString("utf8",t,t+i),t+=i);return{code:r,flags:e,message:s,streamId:n,type:u.FrameTypes.ERROR}}(n,t,o);case u.FrameTypes.KEEPALIVE:return function(l,n,e){l.length;var t=6,r=s(l,t);t+=8;var i=null;t<l.length&&(i=l.slice(t,l.length));return{data:i,flags:e,lastReceivedPosition:r,streamId:0,type:u.FrameTypes.KEEPALIVE}}(n,0,o);case u.FrameTypes.REQUEST_FNF:return function(l,n,e){l.length;var t={data:null,flags:e,metadata:null,streamId:n,type:u.FrameTypes.REQUEST_FNF};return _(l,t,6),t}(n,t,o);case u.FrameTypes.REQUEST_RESPONSE:return function(l,n,e){var t={data:null,flags:e,metadata:null,streamId:n,type:u.FrameTypes.REQUEST_RESPONSE};return _(l,t,6),t}(n,t,o);case u.FrameTypes.REQUEST_STREAM:return function(l,n,e){l.length;var t=6,r=l.readInt32BE(t);t+=4;var i={data:null,flags:e,metadata:null,requestN:r,streamId:n,type:u.FrameTypes.REQUEST_STREAM};return _(l,i,t),i}(n,t,o);case u.FrameTypes.REQUEST_CHANNEL:return function(l,n,e){l.length;var t=6,r=l.readInt32BE(t);t+=4;var i={data:null,flags:e,metadata:null,requestN:r,streamId:n,type:u.FrameTypes.REQUEST_CHANNEL};return _(l,i,t),i}(n,t,o);case u.FrameTypes.METADATA_PUSH:return function(l,n,e){return{flags:e,metadata:6===length?null:l.slice(6,length),streamId:0,type:u.FrameTypes.METADATA_PUSH}}(n,0,o);case u.FrameTypes.REQUEST_N:return function(l,n,e){l.length;var t=l.readInt32BE(6);return{flags:e,requestN:t,streamId:n,type:u.FrameTypes.REQUEST_N}}(n,t,o);case u.FrameTypes.RESUME:return function(l,n,e){l.length;var t=6,r=l.readUInt16BE(t);t+=2;var i=l.readUInt16BE(t);t+=2;var o=l.readInt16BE(t);t+=2;var a=l.slice(t,t+o);t+=o;var c=s(l,t);t+=8;var h=s(l,t);return t+=8,{clientPosition:h,flags:e,majorVersion:r,minorVersion:i,resumeToken:a,serverPosition:c,streamId:0,type:u.FrameTypes.RESUME}}(n,0,o);case u.FrameTypes.RESUME_OK:return function(l,n,e){l.length;var t=s(l,6);return{clientPosition:t,flags:e,streamId:0,type:u.FrameTypes.RESUME_OK}}(n,0,o);case u.FrameTypes.CANCEL:return function(l,n,e){return l.length,{flags:e,streamId:n,type:u.FrameTypes.CANCEL}}(n,t,o);case u.FrameTypes.LEASE:return function(l,n,e){var t=6,r=l.readUInt32BE(t);t+=4;var i=l.readUInt32BE(t);t+=4;var s=null;t<l.length&&(s=l.slice(t,l.length));return{flags:e,metadata:s,requestCount:i,streamId:0,ttl:r,type:u.FrameTypes.LEASE}}(n,0,o)}}function d(l){switch(l.type){case u.FrameTypes.SETUP:return function(l){var n=null!=l.resumeToken?l.resumeToken.byteLength:0,e=null!=l.metadataMimeType?el.Buffer.byteLength(l.metadataMimeType,"ascii"):0,t=null!=l.dataMimeType?el.Buffer.byteLength(l.dataMimeType,"ascii"):0,r=T(l),i=el.Buffer.allocUnsafe(6+f+(n?p+n:0)+e+t+r),s=S(l,i);s=i.writeUInt16BE(l.majorVersion,s),s=i.writeUInt16BE(l.minorVersion,s),s=i.writeUInt32BE(l.keepAlive,s),s=i.writeUInt32BE(l.lifetime,s),l.flags&u.Flags.RESUME_ENABLE&&(s=i.writeUInt16BE(n,s),null!=l.resumeToken&&(s+=l.resumeToken.copy(i,s)));s=i.writeUInt8(e,s),null!=l.metadataMimeType&&(s+=i.write(l.metadataMimeType,s,s+e,"ascii"));s=i.writeUInt8(t,s),null!=l.dataMimeType&&(s+=i.write(l.dataMimeType,s,s+t,"ascii"));return R(l,i,s),i}(l);case u.FrameTypes.PAYLOAD:return function(l){var n=T(l),u=el.Buffer.allocUnsafe(6+n),e=S(l,u);return R(l,u,e),u}(l);case u.FrameTypes.ERROR:return function(l){var n=null!=l.message?el.Buffer.byteLength(l.message,"utf8"):0,u=el.Buffer.allocUnsafe(6+y+n),e=S(l,u);e=u.writeUInt32BE(l.code,e),null!=l.message&&u.write(l.message,e,e+n,"utf8");return u}(l);case u.FrameTypes.KEEPALIVE:return function(l){var n=null!=l.data?l.data.byteLength:0,u=el.Buffer.allocUnsafe(6+m+n),e=S(l,u);e=o(u,l.lastReceivedPosition,e),null!=l.data&&l.data.copy(u,e);return u}(l);case u.FrameTypes.REQUEST_FNF:case u.FrameTypes.REQUEST_RESPONSE:return function(l){var n=T(l),u=el.Buffer.allocUnsafe(6+n),e=S(l,u);return R(l,u,e),u}(l);case u.FrameTypes.REQUEST_STREAM:case u.FrameTypes.REQUEST_CHANNEL:return function(l){var n=T(l),u=el.Buffer.allocUnsafe(6+E+n),e=S(l,u);return e=u.writeUInt32BE(l.requestN,e),R(l,u,e),u}(l);case u.FrameTypes.METADATA_PUSH:return function(l){var n=l.metadata;if(null!=n){var u=S(l,e=el.Buffer.allocUnsafe(6+n.byteLength));return n.copy(e,u),e}var e;return S(l,e=el.Buffer.allocUnsafe(6)),e}(l);case u.FrameTypes.REQUEST_N:return function(l){var n=el.Buffer.allocUnsafe(6+w),u=S(l,n);return n.writeUInt32BE(l.requestN,u),n}(l);case u.FrameTypes.RESUME:return function(l){var n=l.resumeToken.byteLength,u=el.Buffer.allocUnsafe(6+v+n),e=S(l,u);return e=u.writeUInt16BE(l.majorVersion,e),e=u.writeUInt16BE(l.minorVersion,e),e=u.writeUInt16BE(n,e),e+=l.resumeToken.copy(u,e),e=o(u,l.serverPosition,e),o(u,l.clientPosition,e),u}(l);case u.FrameTypes.RESUME_OK:return function(l){var n=el.Buffer.allocUnsafe(6+b),u=S(l,n);return o(n,l.clientPosition,u),n}(l);case u.FrameTypes.CANCEL:return function(l){var n=el.Buffer.allocUnsafe(6);return S(l,n),n}(l);case u.FrameTypes.LEASE:return function(l){var n=null!=l.metadata?l.metadata.byteLength:0,u=el.Buffer.allocUnsafe(6+g+n),e=S(l,u);e=u.writeUInt32BE(l.ttl,e),e=u.writeUInt32BE(l.requestCount,e),null!=l.metadata&&l.metadata.copy(u,e);return u}(l)}}l.deserializeFrameWithLength=a,l.deserializeFrames=c,l.serializeFrameWithLength=function(l){var n=d(l),u=el.Buffer.allocUnsafe(n.length+3);return i(u,n.length,0),n.copy(u,3),u},l.deserializeFrame=h,l.serializeFrame=d,l.sizeOfFrame=function(l){switch(l.type){case u.FrameTypes.SETUP:return function(l){var n=null!=l.resumeToken?l.resumeToken.byteLength:0,u=null!=l.metadataMimeType?el.Buffer.byteLength(l.metadataMimeType,"ascii"):0,e=null!=l.dataMimeType?el.Buffer.byteLength(l.dataMimeType,"ascii"):0,t=T(l);return 6+f+(n?p+n:0)+u+e+t}(l);case u.FrameTypes.PAYLOAD:return function(l){var n=T(l);return 6+n}(l);case u.FrameTypes.ERROR:return function(l){var n=null!=l.message?el.Buffer.byteLength(l.message,"utf8"):0;return 6+y+n}(l);case u.FrameTypes.KEEPALIVE:return function(l){var n=null!=l.data?l.data.byteLength:0;return 6+m+n}(l);case u.FrameTypes.REQUEST_FNF:case u.FrameTypes.REQUEST_RESPONSE:return function(l){var n=T(l);return 6+n}(l);case u.FrameTypes.REQUEST_STREAM:case u.FrameTypes.REQUEST_CHANNEL:return function(l){var n=T(l);return 6+E+n}(l);case u.FrameTypes.METADATA_PUSH:return function(l){return 6+(null!=l.metadata?l.metadata.byteLength:0)}(l);case u.FrameTypes.REQUEST_N:return 6+w;case u.FrameTypes.RESUME:return function(l){var n=l.resumeToken.byteLength;return 6+v+n}(l);case u.FrameTypes.RESUME_OK:return 6+b;case u.FrameTypes.CANCEL:return 6;case u.FrameTypes.LEASE:return function(l){var n=null!=l.metadata?l.metadata.byteLength:0;return 6+g+n}(l)}};var f=14,p=2;var y=4;var m=8;var g=8;var E=4;var w=4;var v=22;var b=8;function S(n,u){var e=u.writeInt32BE(n.streamId,0);return u.writeUInt16BE(n.type<<l.FRAME_TYPE_OFFFSET|n.flags&l.FLAGS_MASK,e)}function T(l){var n=0;return null!=l.data&&(n+=l.data.byteLength),u.Flags.hasMetadata(l.flags)&&(n+=3,null!=l.metadata&&(n+=l.metadata.byteLength)),n}function R(l,n,e){u.Flags.hasMetadata(l.flags)&&(null!=l.metadata?(e=i(n,l.metadata.byteLength,e),e+=l.metadata.copy(n,e)):e=i(n,0,e));null!=l.data&&l.data.copy(n,e)}function _(l,n,e){if(u.Flags.hasMetadata(n.flags)){var r=t(l,e);e+=3,r>0&&(n.metadata=l.slice(e,e+r),e+=r)}e<l.length&&(n.data=l.slice(e,l.length))}var A=function(){function l(){}return l.prototype.deserializeFrame=function(l){return h(l)},l.prototype.deserializeFrameWithLength=function(l){return a(l)},l.prototype.deserializeFrames=function(l){return c(l)},l}();l.Deserializer=A}(tl);var il={};Object.defineProperty(il,"__esModule",{value:!0});var sl={},ol=r&&r.__values||function(l){var n="function"==typeof Symbol&&Symbol.iterator,u=n&&l[n],e=0;if(u)return u.call(l);if(l&&"number"==typeof l.length)return{next:function(){return l&&e>=l.length&&(l=void 0),{value:l&&l[e++],done:!l}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(sl,"__esModule",{value:!0}),sl.Deferred=void 0;var al=function(){function l(){this._done=!1,this.onCloseCallbacks=[]}return Object.defineProperty(l.prototype,"done",{get:function(){return this._done},enumerable:!1,configurable:!0}),l.prototype.close=function(l){var n,u,e,t;if(this.done)console.warn("Trying to close for the second time. ".concat(l?"Dropping error [".concat(l,"]."):""));else if(this._done=!0,this._error=l,l)try{for(var r=ol(this.onCloseCallbacks),i=r.next();!i.done;i=r.next()){(0,i.value)(l)}}catch(l){n={error:l}}finally{try{i&&!i.done&&(u=r.return)&&u.call(r)}finally{if(n)throw n.error}}else try{for(var s=ol(this.onCloseCallbacks),o=s.next();!o.done;o=s.next()){(0,o.value)()}}catch(l){e={error:l}}finally{try{o&&!o.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}},l.prototype.onClose=function(l){this._done?l(this._error):this.onCloseCallbacks.push(l)},l}();sl.Deferred=al;var cl={};!function(l){var n,u=r&&r.__extends||(n=function(l,u){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(l,n){l.__proto__=n}||function(l,n){for(var u in n)Object.prototype.hasOwnProperty.call(n,u)&&(l[u]=n[u])},n(l,u)},function(l,u){if("function"!=typeof u&&null!==u)throw new TypeError("Class extends value "+String(u)+" is not a constructor or null");function e(){this.constructor=l}n(l,u),l.prototype=null===u?Object.create(u):(e.prototype=u.prototype,new e)});Object.defineProperty(l,"__esModule",{value:!0}),l.ErrorCodes=l.RSocketError=void 0;var e,t=function(l){function n(n,u){var e=l.call(this,u)||this;return e.code=n,e}return u(n,l),n}(Error);l.RSocketError=t,(e=l.ErrorCodes||(l.ErrorCodes={}))[e.RESERVED=0]="RESERVED",e[e.INVALID_SETUP=1]="INVALID_SETUP",e[e.UNSUPPORTED_SETUP=2]="UNSUPPORTED_SETUP",e[e.REJECTED_SETUP=3]="REJECTED_SETUP",e[e.REJECTED_RESUME=4]="REJECTED_RESUME",e[e.CONNECTION_CLOSE=258]="CONNECTION_CLOSE",e[e.CONNECTION_ERROR=257]="CONNECTION_ERROR",e[e.APPLICATION_ERROR=513]="APPLICATION_ERROR",e[e.REJECTED=514]="REJECTED",e[e.CANCELED=515]="CANCELED",e[e.INVALID=516]="INVALID",e[e.RESERVED_EXTENSION=4294967295]="RESERVED_EXTENSION"}(cl);var hl={};Object.defineProperty(hl,"__esModule",{value:!0});var dl,fl={},pl={};function yl(){return dl||(dl=1,function(l){var n,u=r&&r.__extends||(n=function(l,u){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(l,n){l.__proto__=n}||function(l,n){for(var u in n)Object.prototype.hasOwnProperty.call(n,u)&&(l[u]=n[u])},n(l,u)},function(l,u){if("function"!=typeof u&&null!==u)throw new TypeError("Class extends value "+String(u)+" is not a constructor or null");function e(){this.constructor=l}n(l,u),l.prototype=null===u?Object.create(u):(e.prototype=u.prototype,new e)}),e=r&&r.__awaiter||function(l,n,u,e){return new(u||(u=Promise))((function(t,r){function i(l){try{o(e.next(l))}catch(l){r(l)}}function s(l){try{o(e.throw(l))}catch(l){r(l)}}function o(l){var n;l.done?t(l.value):(n=l.value,n instanceof u?n:new u((function(l){l(n)}))).then(i,s)}o((e=e.apply(l,n||[])).next())}))},t=r&&r.__generator||function(l,n){var u,e,t,r,i={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function s(r){return function(s){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;i;)try{if(u=1,e&&(t=2&r[0]?e.return:r[0]?e.throw||((t=e.return)&&t.call(e),0):e.next)&&!(t=t.call(e,r[1])).done)return t;switch(e=0,t&&(r=[2&r[0],t.value]),r[0]){case 0:case 1:t=r;break;case 4:return i.label++,{value:r[1],done:!1};case 5:i.label++,e=r[1],r=[0];continue;case 7:r=i.ops.pop(),i.trys.pop();continue;default:if(!(t=i.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){i=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){i.label=r[1];break}if(6===r[0]&&i.label<t[1]){i.label=t[1],t=r;break}if(t&&i.label<t[2]){i.label=t[2],i.ops.push(r);break}t[2]&&i.ops.pop(),i.trys.pop();continue}r=n.call(l,i)}catch(l){r=[6,l],e=0}finally{u=t=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,s])}}};Object.defineProperty(l,"__esModule",{value:!0}),l.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer=l.ResumableClientServerInputMultiplexerDemultiplexer=l.ClientServerInputMultiplexerDemultiplexer=l.StreamIdGenerator=void 0;var i=Pn(),s=sl,o=cl,a=rl;!function(l){l.create=function(l){return new n(l)};var n=function(){function l(l){this.currentId=l}return l.prototype.next=function(l){var n=this.currentId+2;l(n)&&(this.currentId=n)},l}()}(l.StreamIdGenerator||(l.StreamIdGenerator={}));var c=function(l){function n(n,u,e){var t=l.call(this)||this;return t.streamIdSupplier=n,t.outbound=u,t.closeable=e,t.registry={},e.onClose(t.close.bind(t)),t}return u(n,l),n.prototype.handle=function(l){if(a.Frame.isConnection(l)){if(l.type===i.FrameTypes.RESERVED)return;this.connectionFramesHandler.handle(l)}else if(a.Frame.isRequest(l)){if(this.registry[l.streamId])return;this.requestFramesHandler.handle(l,this)}else{var n=this.registry[l.streamId];if(!n)return;n.handle(l)}},n.prototype.connectionInbound=function(l){if(this.connectionFramesHandler)throw new Error("Connection frame handler has already been installed");this.connectionFramesHandler=l},n.prototype.handleRequestStream=function(l){if(this.requestFramesHandler)throw new Error("Stream handler has already been installed");this.requestFramesHandler=l},n.prototype.send=function(l){this.outbound.send(l)},Object.defineProperty(n.prototype,"connectionOutbound",{get:function(){return this},enumerable:!1,configurable:!0}),n.prototype.createRequestStream=function(l){var n=this;if(this.done)l.handleReject(new Error("Already closed"));else{var u=this.registry;this.streamIdSupplier.next((function(u){return l.handleReady(u,n)}),Object.keys(u))}},n.prototype.connect=function(l){this.registry[l.streamId]=l},n.prototype.disconnect=function(l){delete this.registry[l.streamId]},n.prototype.close=function(n){if(this.done)l.prototype.close.call(this,n);else{for(var u in this.registry){this.registry[u].close(new Error("Closed. ".concat(n?"Original cause [".concat(n,"]."):"")))}l.prototype.close.call(this,n)}},n}(s.Deferred);l.ClientServerInputMultiplexerDemultiplexer=c;var h=function(l){function n(n,u,e,t,r,i,o){var a=l.call(this,n,u,new s.Deferred)||this;return a.frameStore=t,a.token=r,a.sessionTimeout=o,i instanceof Function?a.reconnector=i:a.sessionStore=i,e.onClose(a.handleConnectionClose.bind(a)),a}return u(n,l),n.prototype.send=function(n){if(a.Frame.isConnection(n)){if(n.type===i.FrameTypes.KEEPALIVE)n.lastReceivedPosition=this.frameStore.lastReceivedFramePosition;else if(n.type===i.FrameTypes.ERROR)return this.outbound.send(n),this.sessionStore&&delete this.sessionStore[this.token],void l.prototype.close.call(this,new o.RSocketError(n.code,n.message))}else this.frameStore.store(n);this.outbound.send(n)},n.prototype.handle=function(n){if(a.Frame.isConnection(n)){if(n.type===i.FrameTypes.KEEPALIVE)try{this.frameStore.dropTo(n.lastReceivedPosition)}catch(l){this.outbound.send({type:i.FrameTypes.ERROR,streamId:0,flags:i.Flags.NONE,code:l.code,message:l.message}),this.close(l)}else if(n.type===i.FrameTypes.ERROR)return l.prototype.handle.call(this,n),this.sessionStore&&delete this.sessionStore[this.token],void l.prototype.close.call(this,new o.RSocketError(n.code,n.message))}else this.frameStore.record(n);l.prototype.handle.call(this,n)},n.prototype.resume=function(l,n,u){switch(this.outbound=n,l.type){case i.FrameTypes.RESUME:if(clearTimeout(this.timeoutId),this.frameStore.lastReceivedFramePosition<l.clientPosition){var e=new o.RSocketError(i.ErrorCodes.REJECTED_RESUME,"Impossible to resume since first available client frame position is greater than last received server frame position");return this.outbound.send({type:i.FrameTypes.ERROR,streamId:0,flags:i.Flags.NONE,code:e.code,message:e.message}),void this.close(e)}try{this.frameStore.dropTo(l.serverPosition)}catch(l){return this.outbound.send({type:i.FrameTypes.ERROR,streamId:0,flags:i.Flags.NONE,code:l.code,message:l.message}),void this.close(l)}this.outbound.send({type:i.FrameTypes.RESUME_OK,streamId:0,flags:i.Flags.NONE,clientPosition:this.frameStore.lastReceivedFramePosition});break;case i.FrameTypes.RESUME_OK:try{this.frameStore.dropTo(l.clientPosition)}catch(l){this.outbound.send({type:i.FrameTypes.ERROR,streamId:0,flags:i.Flags.NONE,code:l.code,message:l.message}),this.close(l)}}this.frameStore.drain(this.outbound.send.bind(this.outbound)),u.onClose(this.handleConnectionClose.bind(this)),this.connectionFramesHandler.resume()},n.prototype.handleConnectionClose=function(l){return e(this,void 0,void 0,(function(){var l;return t(this,(function(n){switch(n.label){case 0:if(this.connectionFramesHandler.pause(),!this.reconnector)return[3,5];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.reconnector(this,this.frameStore)];case 2:return n.sent(),[3,4];case 3:return l=n.sent(),this.close(l),[3,4];case 4:return[3,6];case 5:this.timeoutId=setTimeout(this.close.bind(this),this.sessionTimeout),n.label=6;case 6:return[2]}}))}))},n}(c);l.ResumableClientServerInputMultiplexerDemultiplexer=h;var d=function(){function l(l,n,u){this.outbound=l,this.closeable=n,this.delegate=u,this.resumed=!1}return l.prototype.close=function(){this.delegate.close()},l.prototype.onClose=function(l){this.delegate.onClose(l)},Object.defineProperty(l.prototype,"connectionOutbound",{get:function(){return this.delegate.connectionOutbound},enumerable:!1,configurable:!0}),l.prototype.createRequestStream=function(l){this.delegate.createRequestStream(l)},l.prototype.connectionInbound=function(l){this.delegate.connectionInbound(l)},l.prototype.handleRequestStream=function(l){this.delegate.handleRequestStream(l)},l.prototype.handle=function(l){var n=this;if(!this.resumed)return l.type===i.FrameTypes.RESUME_OK?(this.resumed=!0,void this.delegate.resume(l,this.outbound,this.closeable)):(this.outbound.send({type:i.FrameTypes.ERROR,streamId:0,code:i.ErrorCodes.CONNECTION_ERROR,message:"Incomplete RESUME handshake. Unexpected frame ".concat(l.type," received"),flags:i.Flags.NONE}),this.closeable.close(),void this.closeable.onClose((function(){return n.delegate.close(new o.RSocketError(i.ErrorCodes.CONNECTION_ERROR,"Incomplete RESUME handshake. Unexpected frame ".concat(l.type," received")))})));this.delegate.handle(l)},l}();l.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer=d}(pl)),pl}var ml={},gl={},El={},wl=r&&r.__generator||function(l,n){var u,e,t,r,i={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function s(r){return function(s){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;i;)try{if(u=1,e&&(t=2&r[0]?e.return:r[0]?e.throw||((t=e.return)&&t.call(e),0):e.next)&&!(t=t.call(e,r[1])).done)return t;switch(e=0,t&&(r=[2&r[0],t.value]),r[0]){case 0:case 1:t=r;break;case 4:return i.label++,{value:r[1],done:!1};case 5:i.label++,e=r[1],r=[0];continue;case 7:r=i.ops.pop(),i.trys.pop();continue;default:if(!(t=i.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){i=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){i.label=r[1];break}if(6===r[0]&&i.label<t[1]){i.label=t[1],t=r;break}if(t&&i.label<t[2]){i.label=t[2],i.ops.push(r);break}t[2]&&i.ops.pop(),i.trys.pop();continue}r=n.call(l,i)}catch(l){r=[6,l],e=0}finally{u=t=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,s])}}};Object.defineProperty(El,"__esModule",{value:!0}),El.fragmentWithRequestN=El.fragment=El.isFragmentable=void 0;var vl=rl;El.isFragmentable=function(l,n,u){return 0!==n&&l.data.byteLength+(l.metadata?l.metadata.byteLength+vl.Lengths.METADATA:0)+(u==vl.FrameTypes.REQUEST_STREAM||u==vl.FrameTypes.REQUEST_CHANNEL?vl.Lengths.REQUEST:0)>n},El.fragment=function(l,n,u,e,t){var r,i,s,o,a,c,h,d,f,p,y,m;return void 0===t&&(t=!1),wl(this,(function(g){switch(g.label){case 0:return r=null!==(m=null===(y=n.data)||void 0===y?void 0:y.byteLength)&&void 0!==m?m:0,i=e!==vl.FrameTypes.PAYLOAD,s=u,n.metadata?0!==(a=n.metadata.byteLength)?[3,1]:(s-=vl.Lengths.METADATA,o=el.Buffer.allocUnsafe(0),[3,6]):[3,6];case 1:return c=0,i?(s-=vl.Lengths.METADATA,h=Math.min(a,c+s),o=n.metadata.slice(c,h),s-=o.byteLength,c=h,0!==s?[3,3]:(i=!1,[4,{type:e,flags:vl.Flags.FOLLOWS|vl.Flags.METADATA,data:void 0,metadata:o,streamId:l}])):[3,3];case 2:g.sent(),o=void 0,s=u,g.label=3;case 3:return c<a?(s-=vl.Lengths.METADATA,h=Math.min(a,c+s),o=n.metadata.slice(c,h),s-=o.byteLength,c=h,0!==s&&0!==r?[3,5]:[4,{type:vl.FrameTypes.PAYLOAD,flags:vl.Flags.NEXT|vl.Flags.METADATA|(c===a&&t&&0===r?vl.Flags.COMPLETE:vl.Flags.FOLLOWS),data:void 0,metadata:o,streamId:l}]):[3,6];case 4:g.sent(),o=void 0,s=u,g.label=5;case 5:return[3,3];case 6:return d=0,i?(p=Math.min(r,d+s),f=n.data.slice(d,p),s-=f.byteLength,d=p,[4,{type:e,flags:vl.Flags.FOLLOWS|(o?vl.Flags.METADATA:vl.Flags.NONE),data:f,metadata:o,streamId:l}]):[3,8];case 7:g.sent(),o=void 0,f=void 0,s=u,g.label=8;case 8:return d<r?(p=Math.min(r,d+s),f=n.data.slice(d,p),s-=f.byteLength,d=p,[4,{type:vl.FrameTypes.PAYLOAD,flags:d===r?(t?vl.Flags.COMPLETE:vl.Flags.NONE)|vl.Flags.NEXT|(o?vl.Flags.METADATA:0):vl.Flags.FOLLOWS|vl.Flags.NEXT|(o?vl.Flags.METADATA:0),data:f,metadata:o,streamId:l}]):[3,10];case 9:return g.sent(),o=void 0,f=void 0,s=u,[3,8];case 10:return[2]}}))},El.fragmentWithRequestN=function(l,n,u,e,t,r){var i,s,o,a,c,h,d,f,p,y,m,g;return void 0===r&&(r=!1),wl(this,(function(E){switch(E.label){case 0:return i=null!==(g=null===(m=n.data)||void 0===m?void 0:m.byteLength)&&void 0!==g?g:0,s=!0,o=u,n.metadata?0!==(c=n.metadata.byteLength)?[3,1]:(o-=vl.Lengths.METADATA,a=el.Buffer.allocUnsafe(0),[3,6]):[3,6];case 1:return h=0,s?(o-=vl.Lengths.METADATA+vl.Lengths.REQUEST,d=Math.min(c,h+o),a=n.metadata.slice(h,d),o-=a.byteLength,h=d,0!==o?[3,3]:(s=!1,[4,{type:e,flags:vl.Flags.FOLLOWS|vl.Flags.METADATA,data:void 0,requestN:t,metadata:a,streamId:l}])):[3,3];case 2:E.sent(),a=void 0,o=u,E.label=3;case 3:return h<c?(o-=vl.Lengths.METADATA,d=Math.min(c,h+o),a=n.metadata.slice(h,d),o-=a.byteLength,h=d,0!==o&&0!==i?[3,5]:[4,{type:vl.FrameTypes.PAYLOAD,flags:vl.Flags.NEXT|vl.Flags.METADATA|(h===c&&r&&0===i?vl.Flags.COMPLETE:vl.Flags.FOLLOWS),data:void 0,metadata:a,streamId:l}]):[3,6];case 4:E.sent(),a=void 0,o=u,E.label=5;case 5:return[3,3];case 6:return f=0,s?(o-=vl.Lengths.REQUEST,y=Math.min(i,f+o),p=n.data.slice(f,y),o-=p.byteLength,f=y,[4,{type:e,flags:vl.Flags.FOLLOWS|(a?vl.Flags.METADATA:vl.Flags.NONE),data:p,requestN:t,metadata:a,streamId:l}]):[3,8];case 7:E.sent(),a=void 0,p=void 0,o=u,E.label=8;case 8:return f<i?(y=Math.min(i,f+o),p=n.data.slice(f,y),o-=p.byteLength,f=y,[4,{type:vl.FrameTypes.PAYLOAD,flags:f===i?(r?vl.Flags.COMPLETE:vl.Flags.NONE)|vl.Flags.NEXT|(a?vl.Flags.METADATA:0):vl.Flags.FOLLOWS|vl.Flags.NEXT|(a?vl.Flags.METADATA:0),data:p,metadata:a,streamId:l}]):[3,10];case 9:return E.sent(),a=void 0,p=void 0,o=u,[3,8];case 10:return[2]}}))};var bl={};Object.defineProperty(bl,"__esModule",{value:!0}),bl.cancel=bl.reassemble=bl.add=void 0,bl.add=function(l,n,u){return l.hasFragments?(l.data=l.data?el.Buffer.concat([l.data,n]):n,l.metadata&&u&&(l.metadata=el.Buffer.concat([l.metadata,u])),!0):(l.hasFragments=!0,l.data=n,u&&(l.metadata=u),!0)},bl.reassemble=function(l,n,u){l.hasFragments=!1;var e=l.data?el.Buffer.concat([l.data,n]):n;if(l.data=void 0,l.metadata){var t=u?el.Buffer.concat([l.metadata,u]):l.metadata;return l.metadata=void 0,{data:e,metadata:t}}return{data:e}},bl.cancel=function(l){l.hasFragments=!1,l.data=void 0,l.metadata=void 0};var Sl=r&&r.__createBinding||(Object.create?function(l,n,u,e){void 0===e&&(e=u),Object.defineProperty(l,e,{enumerable:!0,get:function(){return n[u]}})}:function(l,n,u,e){void 0===e&&(e=u),l[e]=n[u]}),Tl=r&&r.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),Rl=r&&r.__importStar||function(l){if(l&&l.__esModule)return l;var n={};if(null!=l)for(var u in l)"default"!==u&&Object.prototype.hasOwnProperty.call(l,u)&&Sl(n,l,u);return Tl(n,l),n},_l=r&&r.__values||function(l){var n="function"==typeof Symbol&&Symbol.iterator,u=n&&l[n],e=0;if(u)return u.call(l);if(l&&"number"==typeof l.length)return{next:function(){return l&&e>=l.length&&(l=void 0),{value:l&&l[e++],done:!l}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(gl,"__esModule",{value:!0}),gl.RequestChannelResponderStream=gl.RequestChannelRequesterStream=void 0;var Al=cl,Ol=El,Fl=rl,Cl=Rl(bl),Il=function(){function l(l,n,u,e,t,r){this.payload=l,this.isComplete=n,this.receiver=u,this.fragmentSize=e,this.initialRequestN=t,this.leaseManager=r,this.streamType=Fl.FrameTypes.REQUEST_CHANNEL}return l.prototype.handleReady=function(l,n){var u,e;if(this.outboundDone)return!1;this.streamId=l,this.stream=n,n.connect(this);var t=this.isComplete;if(t&&(this.outboundDone=t),(0,Ol.isFragmentable)(this.payload,this.fragmentSize,Fl.FrameTypes.REQUEST_CHANNEL))try{for(var r=_l((0,Ol.fragmentWithRequestN)(l,this.payload,this.fragmentSize,Fl.FrameTypes.REQUEST_CHANNEL,this.initialRequestN,t)),i=r.next();!i.done;i=r.next()){var s=i.value;this.stream.send(s)}}catch(l){u={error:l}}finally{try{i&&!i.done&&(e=r.return)&&e.call(r)}finally{if(u)throw u.error}}else this.stream.send({type:Fl.FrameTypes.REQUEST_CHANNEL,data:this.payload.data,metadata:this.payload.metadata,requestN:this.initialRequestN,flags:(void 0!==this.payload.metadata?Fl.Flags.METADATA:Fl.Flags.NONE)|(t?Fl.Flags.COMPLETE:Fl.Flags.NONE),streamId:l});return this.hasExtension&&this.stream.send({type:Fl.FrameTypes.EXT,streamId:l,extendedContent:this.extendedContent,extendedType:this.extendedType,flags:this.flags}),!0},l.prototype.handleReject=function(l){this.inboundDone||(this.inboundDone=!0,this.outboundDone=!0,this.receiver.onError(l))},l.prototype.handle=function(l){var n,u=l.type;switch(u){case Fl.FrameTypes.PAYLOAD:var e=Fl.Flags.hasComplete(l.flags),t=Fl.Flags.hasNext(l.flags);if(e||!Fl.Flags.hasFollows(l.flags)){if(e&&(this.inboundDone=!0,this.outboundDone&&this.stream.disconnect(this),!t))return void this.receiver.onComplete();var r=this.hasFragments?Cl.reassemble(this,l.data,l.metadata):{data:l.data,metadata:l.metadata};return void this.receiver.onNext(r,e)}if(Cl.add(this,l.data,l.metadata))return;n="Unexpected frame size";break;case Fl.FrameTypes.CANCEL:if(this.outboundDone)return;return this.outboundDone=!0,this.inboundDone&&this.stream.disconnect(this),void this.receiver.cancel();case Fl.FrameTypes.REQUEST_N:if(this.outboundDone)return;if(this.hasFragments){n="Unexpected frame type [".concat(u,"] during reassembly");break}return void this.receiver.request(l.requestN);case Fl.FrameTypes.ERROR:var i=this.outboundDone;return this.inboundDone=!0,this.outboundDone=!0,this.stream.disconnect(this),Cl.cancel(this),i||this.receiver.cancel(),void this.receiver.onError(new Al.RSocketError(l.code,l.message));case Fl.FrameTypes.EXT:return void this.receiver.onExtension(l.extendedType,l.extendedContent,Fl.Flags.hasIgnore(l.flags));default:n="Unexpected frame type [".concat(u,"]")}this.close(new Al.RSocketError(Al.ErrorCodes.CANCELED,n)),this.stream.send({type:Fl.FrameTypes.CANCEL,streamId:this.streamId,flags:Fl.Flags.NONE}),this.stream.disconnect(this)},l.prototype.request=function(l){this.inboundDone||(this.streamId?this.stream.send({type:Fl.FrameTypes.REQUEST_N,flags:Fl.Flags.NONE,requestN:l,streamId:this.streamId}):this.initialRequestN+=l)},l.prototype.cancel=function(){var l,n=this.inboundDone,u=this.outboundDone;n&&u||(this.inboundDone=!0,this.outboundDone=!0,u||this.receiver.cancel(),this.streamId?(this.stream.send({type:n?Fl.FrameTypes.ERROR:Fl.FrameTypes.CANCEL,flags:Fl.Flags.NONE,streamId:this.streamId,code:Al.ErrorCodes.CANCELED,message:"Cancelled"}),this.stream.disconnect(this),Cl.cancel(this)):null===(l=this.leaseManager)||void 0===l||l.cancelRequest(this))},l.prototype.onNext=function(l,n){var u,e;if(!this.outboundDone)if(n&&(this.outboundDone=!0,this.inboundDone&&this.stream.disconnect(this)),(0,Ol.isFragmentable)(l,this.fragmentSize,Fl.FrameTypes.PAYLOAD))try{for(var t=_l((0,Ol.fragment)(this.streamId,l,this.fragmentSize,Fl.FrameTypes.PAYLOAD,n)),r=t.next();!r.done;r=t.next()){var i=r.value;this.stream.send(i)}}catch(l){u={error:l}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(u)throw u.error}}else this.stream.send({type:Fl.FrameTypes.PAYLOAD,streamId:this.streamId,flags:Fl.Flags.NEXT|(l.metadata?Fl.Flags.METADATA:Fl.Flags.NONE)|(n?Fl.Flags.COMPLETE:Fl.Flags.NONE),data:l.data,metadata:l.metadata})},l.prototype.onComplete=function(){this.streamId?this.outboundDone||(this.outboundDone=!0,this.stream.send({type:Fl.FrameTypes.PAYLOAD,streamId:this.streamId,flags:Fl.Flags.COMPLETE,data:null,metadata:null}),this.inboundDone&&this.stream.disconnect(this)):this.isComplete=!0},l.prototype.onError=function(l){if(!this.outboundDone){var n=this.inboundDone;this.outboundDone=!0,this.inboundDone=!0,this.stream.send({type:Fl.FrameTypes.ERROR,streamId:this.streamId,flags:Fl.Flags.NONE,code:l instanceof Al.RSocketError?l.code:Al.ErrorCodes.APPLICATION_ERROR,message:l.message}),this.stream.disconnect(this),n||this.receiver.onError(l)}},l.prototype.onExtension=function(l,n,u){if(!this.outboundDone)return this.streamId?void this.stream.send({streamId:this.streamId,type:Fl.FrameTypes.EXT,extendedType:l,extendedContent:n,flags:u?Fl.Flags.IGNORE:Fl.Flags.NONE}):(this.hasExtension=!0,this.extendedType=l,this.extendedContent=n,void(this.flags=u?Fl.Flags.IGNORE:Fl.Flags.NONE))},l.prototype.close=function(l){if(!this.inboundDone||!this.outboundDone){var n=this.inboundDone,u=this.outboundDone;this.inboundDone=!0,this.outboundDone=!0,Cl.cancel(this),u||this.receiver.cancel(),n||(l?this.receiver.onError(l):this.receiver.onComplete())}},l}();gl.RequestChannelRequesterStream=Il;var kl=function(){function l(l,n,u,e,t){if(this.streamId=l,this.stream=n,this.fragmentSize=u,this.handler=e,this.streamType=Fl.FrameTypes.REQUEST_CHANNEL,n.connect(this),Fl.Flags.hasFollows(t.flags))return Cl.add(this,t.data,t.metadata),this.initialRequestN=t.requestN,void(this.isComplete=Fl.Flags.hasComplete(t.flags));var r={data:t.data,metadata:t.metadata},i=Fl.Flags.hasComplete(t.flags);this.inboundDone=i;try{this.receiver=e(r,t.requestN,i,this),this.outboundDone&&this.defferedError&&this.receiver.onError(this.defferedError)}catch(l){this.outboundDone&&!this.inboundDone?this.cancel():this.inboundDone=!0,this.onError(l)}}return l.prototype.handle=function(l){var n,u=l.type;switch(u){case Fl.FrameTypes.PAYLOAD:if(Fl.Flags.hasFollows(l.flags)){if(Cl.add(this,l.data,l.metadata))return;n="Unexpected frame size";break}var e=this.hasFragments?Cl.reassemble(this,l.data,l.metadata):{data:l.data,metadata:l.metadata},t=Fl.Flags.hasComplete(l.flags);if(this.receiver){if(t&&(this.inboundDone=!0,this.outboundDone&&this.stream.disconnect(this),!Fl.Flags.hasNext(l.flags)))return void this.receiver.onComplete();this.receiver.onNext(e,t)}else{(r=this.isComplete||t)&&(this.inboundDone=!0,this.outboundDone&&this.stream.disconnect(this));try{this.receiver=this.handler(e,this.initialRequestN,r,this),this.outboundDone&&this.defferedError}catch(s){this.outboundDone&&!this.inboundDone?this.cancel():this.inboundDone=!0,this.onError(s)}}return;case Fl.FrameTypes.REQUEST_N:if(!this.receiver||this.hasFragments){n="Unexpected frame type [".concat(u,"] during reassembly");break}return void this.receiver.request(l.requestN);case Fl.FrameTypes.ERROR:case Fl.FrameTypes.CANCEL:var r=this.inboundDone,i=this.outboundDone;if(this.inboundDone=!0,this.outboundDone=!0,this.stream.disconnect(this),Cl.cancel(this),!this.receiver)return;if(i||this.receiver.cancel(),!r){var s=u===Fl.FrameTypes.CANCEL?new Al.RSocketError(Al.ErrorCodes.CANCELED,"Cancelled"):new Al.RSocketError(l.code,l.message);this.receiver.onError(s)}return;case Fl.FrameTypes.EXT:if(!this.receiver||this.hasFragments){n="Unexpected frame type [".concat(u,"] during reassembly");break}return void this.receiver.onExtension(l.extendedType,l.extendedContent,Fl.Flags.hasIgnore(l.flags));default:n="Unexpected frame type [".concat(u,"]")}this.stream.send({type:Fl.FrameTypes.ERROR,flags:Fl.Flags.NONE,code:Al.ErrorCodes.CANCELED,message:n,streamId:this.streamId}),this.stream.disconnect(this),this.close(new Al.RSocketError(Al.ErrorCodes.CANCELED,n))},l.prototype.onError=function(l){if(this.outboundDone)console.warn("Trying to error for the second time. ".concat(l?"Dropping error [".concat(l,"]."):""));else{var n=this.inboundDone;this.outboundDone=!0,this.inboundDone=!0,this.stream.send({type:Fl.FrameTypes.ERROR,flags:Fl.Flags.NONE,code:l instanceof Al.RSocketError?l.code:Al.ErrorCodes.APPLICATION_ERROR,message:l.message,streamId:this.streamId}),this.stream.disconnect(this),n||(this.receiver?this.receiver.onError(l):this.defferedError=l)}},l.prototype.onNext=function(l,n){var u,e;if(!this.outboundDone){if(n&&(this.outboundDone=!0),(0,Ol.isFragmentable)(l,this.fragmentSize,Fl.FrameTypes.PAYLOAD))try{for(var t=_l((0,Ol.fragment)(this.streamId,l,this.fragmentSize,Fl.FrameTypes.PAYLOAD,n)),r=t.next();!r.done;r=t.next()){var i=r.value;this.stream.send(i)}}catch(l){u={error:l}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(u)throw u.error}}else this.stream.send({type:Fl.FrameTypes.PAYLOAD,flags:Fl.Flags.NEXT|(n?Fl.Flags.COMPLETE:Fl.Flags.NONE)|(l.metadata?Fl.Flags.METADATA:Fl.Flags.NONE),data:l.data,metadata:l.metadata,streamId:this.streamId});n&&this.inboundDone&&this.stream.disconnect(this)}},l.prototype.onComplete=function(){this.outboundDone||(this.outboundDone=!0,this.stream.send({type:Fl.FrameTypes.PAYLOAD,flags:Fl.Flags.COMPLETE,streamId:this.streamId,data:null,metadata:null}),this.inboundDone&&this.stream.disconnect(this))},l.prototype.onExtension=function(l,n,u){this.outboundDone&&this.inboundDone||this.stream.send({type:Fl.FrameTypes.EXT,streamId:this.streamId,flags:u?Fl.Flags.IGNORE:Fl.Flags.NONE,extendedType:l,extendedContent:n})},l.prototype.request=function(l){this.inboundDone||this.stream.send({type:Fl.FrameTypes.REQUEST_N,flags:Fl.Flags.NONE,streamId:this.streamId,requestN:l})},l.prototype.cancel=function(){this.inboundDone||(this.inboundDone=!0,this.stream.send({type:Fl.FrameTypes.CANCEL,flags:Fl.Flags.NONE,streamId:this.streamId}),this.outboundDone&&this.stream.disconnect(this))},l.prototype.close=function(l){if(this.inboundDone&&this.outboundDone)console.warn("Trying to close for the second time. ".concat(l?"Dropping error [".concat(l,"]."):""));else{var n=this.inboundDone,u=this.outboundDone;this.inboundDone=!0,this.outboundDone=!0,Cl.cancel(this);var e=this.receiver;e&&(u||e.cancel(),n||(l?e.onError(l):e.onComplete()))}},l}();gl.RequestChannelResponderStream=kl;var Ll={},Nl=r&&r.__createBinding||(Object.create?function(l,n,u,e){void 0===e&&(e=u),Object.defineProperty(l,e,{enumerable:!0,get:function(){return n[u]}})}:function(l,n,u,e){void 0===e&&(e=u),l[e]=n[u]}),Ul=r&&r.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),xl=r&&r.__importStar||function(l){if(l&&l.__esModule)return l;var n={};if(null!=l)for(var u in l)"default"!==u&&Object.prototype.hasOwnProperty.call(l,u)&&Nl(n,l,u);return Ul(n,l),n},Pl=r&&r.__values||function(l){var n="function"==typeof Symbol&&Symbol.iterator,u=n&&l[n],e=0;if(u)return u.call(l);if(l&&"number"==typeof l.length)return{next:function(){return l&&e>=l.length&&(l=void 0),{value:l&&l[e++],done:!l}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(Ll,"__esModule",{value:!0}),Ll.RequestFnfResponderStream=Ll.RequestFnFRequesterStream=void 0;var Dl=cl,Ml=El,Bl=rl,ql=xl(bl),jl=function(){function l(l,n,u,e){this.payload=l,this.receiver=n,this.fragmentSize=u,this.leaseManager=e,this.streamType=Bl.FrameTypes.REQUEST_FNF}return l.prototype.handleReady=function(l,n){var u,e;if(this.done)return!1;if(this.streamId=l,(0,Ml.isFragmentable)(this.payload,this.fragmentSize,Bl.FrameTypes.REQUEST_FNF))try{for(var t=Pl((0,Ml.fragment)(l,this.payload,this.fragmentSize,Bl.FrameTypes.REQUEST_FNF)),r=t.next();!r.done;r=t.next()){var i=r.value;n.send(i)}}catch(l){u={error:l}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(u)throw u.error}}else n.send({type:Bl.FrameTypes.REQUEST_FNF,data:this.payload.data,metadata:this.payload.metadata,flags:this.payload.metadata?Bl.Flags.METADATA:0,streamId:l});return this.done=!0,this.receiver.onComplete(),!0},l.prototype.handleReject=function(l){this.done||(this.done=!0,this.receiver.onError(l))},l.prototype.cancel=function(){var l;this.done||(this.done=!0,null===(l=this.leaseManager)||void 0===l||l.cancelRequest(this))},l.prototype.handle=function(l){l.type!=Bl.FrameTypes.ERROR?this.close(new Dl.RSocketError(Dl.ErrorCodes.CANCELED,"Received invalid frame")):this.close(new Dl.RSocketError(l.code,l.message))},l.prototype.close=function(l){this.done?console.warn("Trying to close for the second time. ".concat(l?"Dropping error [".concat(l,"]."):"")):l?this.receiver.onError(l):this.receiver.onComplete()},l}();Ll.RequestFnFRequesterStream=jl;var Ql=function(){function l(l,n,u,e){if(this.streamId=l,this.stream=n,this.handler=u,this.streamType=Bl.FrameTypes.REQUEST_FNF,Bl.Flags.hasFollows(e.flags))return ql.add(this,e.data,e.metadata),void n.connect(this);var t={data:e.data,metadata:e.metadata};try{this.cancellable=u(t,this)}catch(l){}}return l.prototype.handle=function(l){var n;if(l.type==Bl.FrameTypes.PAYLOAD){if(!Bl.Flags.hasFollows(l.flags)){this.stream.disconnect(this);var u=ql.reassemble(this,l.data,l.metadata);try{this.cancellable=this.handler(u,this)}catch(l){}return}if(ql.add(this,l.data,l.metadata))return;n="Unexpected fragment size"}else n="Unexpected frame type [".concat(l.type,"]");this.done=!0,l.type!=Bl.FrameTypes.CANCEL&&l.type!=Bl.FrameTypes.ERROR&&this.stream.send({type:Bl.FrameTypes.ERROR,streamId:this.streamId,flags:Bl.Flags.NONE,code:Dl.ErrorCodes.CANCELED,message:n}),this.stream.disconnect(this),ql.cancel(this)},l.prototype.close=function(l){var n;this.done?console.warn("Trying to close for the second time. ".concat(l?"Dropping error [".concat(l,"]."):"")):(this.done=!0,ql.cancel(this),null===(n=this.cancellable)||void 0===n||n.cancel())},l.prototype.onError=function(l){},l.prototype.onComplete=function(){},l}();Ll.RequestFnfResponderStream=Ql;var Wl={},$l=r&&r.__createBinding||(Object.create?function(l,n,u,e){void 0===e&&(e=u),Object.defineProperty(l,e,{enumerable:!0,get:function(){return n[u]}})}:function(l,n,u,e){void 0===e&&(e=u),l[e]=n[u]}),zl=r&&r.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),Hl=r&&r.__importStar||function(l){if(l&&l.__esModule)return l;var n={};if(null!=l)for(var u in l)"default"!==u&&Object.prototype.hasOwnProperty.call(l,u)&&$l(n,l,u);return zl(n,l),n},Vl=r&&r.__values||function(l){var n="function"==typeof Symbol&&Symbol.iterator,u=n&&l[n],e=0;if(u)return u.call(l);if(l&&"number"==typeof l.length)return{next:function(){return l&&e>=l.length&&(l=void 0),{value:l&&l[e++],done:!l}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(Wl,"__esModule",{value:!0}),Wl.RequestResponseResponderStream=Wl.RequestResponseRequesterStream=void 0;var Jl=cl,Gl=El,Xl=rl,Yl=Hl(bl),Kl=function(){function l(l,n,u,e){this.payload=l,this.receiver=n,this.fragmentSize=u,this.leaseManager=e,this.streamType=Xl.FrameTypes.REQUEST_RESPONSE}return l.prototype.handleReady=function(l,n){var u,e;if(this.done)return!1;if(this.streamId=l,this.stream=n,n.connect(this),(0,Gl.isFragmentable)(this.payload,this.fragmentSize,Xl.FrameTypes.REQUEST_RESPONSE))try{for(var t=Vl((0,Gl.fragment)(l,this.payload,this.fragmentSize,Xl.FrameTypes.REQUEST_RESPONSE)),r=t.next();!r.done;r=t.next()){var i=r.value;this.stream.send(i)}}catch(l){u={error:l}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(u)throw u.error}}else this.stream.send({type:Xl.FrameTypes.REQUEST_RESPONSE,data:this.payload.data,metadata:this.payload.metadata,flags:this.payload.metadata?Xl.Flags.METADATA:0,streamId:l});return this.hasExtension&&this.stream.send({type:Xl.FrameTypes.EXT,streamId:l,extendedContent:this.extendedContent,extendedType:this.extendedType,flags:this.flags}),!0},l.prototype.handleReject=function(l){this.done||(this.done=!0,this.receiver.onError(l))},l.prototype.handle=function(l){var n,u=l.type;switch(u){case Xl.FrameTypes.PAYLOAD:var e=Xl.Flags.hasComplete(l.flags),t=Xl.Flags.hasNext(l.flags);if(e||!Xl.Flags.hasFollows(l.flags)){if(this.done=!0,this.stream.disconnect(this),!t)return void this.receiver.onComplete();var r=this.hasFragments?Yl.reassemble(this,l.data,l.metadata):{data:l.data,metadata:l.metadata};return void this.receiver.onNext(r,!0)}if(!Yl.add(this,l.data,l.metadata)){n="Unexpected fragment size";break}return;case Xl.FrameTypes.ERROR:return this.done=!0,this.stream.disconnect(this),Yl.cancel(this),void this.receiver.onError(new Jl.RSocketError(l.code,l.message));case Xl.FrameTypes.EXT:if(this.hasFragments){n="Unexpected frame type [".concat(u,"] during reassembly");break}return void this.receiver.onExtension(l.extendedType,l.extendedContent,Xl.Flags.hasIgnore(l.flags));default:n="Unexpected frame type [".concat(u,"]")}this.close(new Jl.RSocketError(Jl.ErrorCodes.CANCELED,n)),this.stream.send({type:Xl.FrameTypes.CANCEL,streamId:this.streamId,flags:Xl.Flags.NONE}),this.stream.disconnect(this)},l.prototype.cancel=function(){var l;this.done||(this.done=!0,this.streamId?(this.stream.send({type:Xl.FrameTypes.CANCEL,flags:Xl.Flags.NONE,streamId:this.streamId}),this.stream.disconnect(this),Yl.cancel(this)):null===(l=this.leaseManager)||void 0===l||l.cancelRequest(this))},l.prototype.onExtension=function(l,n,u){if(!this.done)return this.streamId?void this.stream.send({streamId:this.streamId,type:Xl.FrameTypes.EXT,extendedType:l,extendedContent:n,flags:u?Xl.Flags.IGNORE:Xl.Flags.NONE}):(this.hasExtension=!0,this.extendedType=l,this.extendedContent=n,void(this.flags=u?Xl.Flags.IGNORE:Xl.Flags.NONE))},l.prototype.close=function(l){this.done||(this.done=!0,Yl.cancel(this),l?this.receiver.onError(l):this.receiver.onComplete())},l}();Wl.RequestResponseRequesterStream=Kl;var Zl=function(){function l(l,n,u,e,t){if(this.streamId=l,this.stream=n,this.fragmentSize=u,this.handler=e,this.streamType=Xl.FrameTypes.REQUEST_RESPONSE,n.connect(this),Xl.Flags.hasFollows(t.flags))Yl.add(this,t.data,t.metadata);else{var r={data:t.data,metadata:t.metadata};try{this.receiver=e(r,this)}catch(l){this.onError(l)}}}return l.prototype.handle=function(l){var n,u;if(!this.receiver||this.hasFragments)if(l.type===Xl.FrameTypes.PAYLOAD){if(!Xl.Flags.hasFollows(l.flags)){var e=Yl.reassemble(this,l.data,l.metadata);try{this.receiver=this.handler(e,this)}catch(l){this.onError(l)}return}if(Yl.add(this,l.data,l.metadata))return;u="Unexpected fragment size"}else u="Unexpected frame type [".concat(l.type,"] during reassembly");else{if(l.type===Xl.FrameTypes.EXT)return void this.receiver.onExtension(l.extendedType,l.extendedContent,Xl.Flags.hasIgnore(l.flags));u="Unexpected frame type [".concat(l.type,"]")}this.done=!0,null===(n=this.receiver)||void 0===n||n.cancel(),l.type!==Xl.FrameTypes.CANCEL&&l.type!==Xl.FrameTypes.ERROR&&this.stream.send({type:Xl.FrameTypes.ERROR,flags:Xl.Flags.NONE,code:Jl.ErrorCodes.CANCELED,message:u,streamId:this.streamId}),this.stream.disconnect(this),Yl.cancel(this)},l.prototype.onError=function(l){this.done?console.warn("Trying to error for the second time. ".concat(l?"Dropping error [".concat(l,"]."):"")):(this.done=!0,this.stream.send({type:Xl.FrameTypes.ERROR,flags:Xl.Flags.NONE,code:l instanceof Jl.RSocketError?l.code:Jl.ErrorCodes.APPLICATION_ERROR,message:l.message,streamId:this.streamId}),this.stream.disconnect(this))},l.prototype.onNext=function(l,n){var u,e;if(!this.done){if(this.done=!0,(0,Gl.isFragmentable)(l,this.fragmentSize,Xl.FrameTypes.PAYLOAD))try{for(var t=Vl((0,Gl.fragment)(this.streamId,l,this.fragmentSize,Xl.FrameTypes.PAYLOAD,!0)),r=t.next();!r.done;r=t.next()){var i=r.value;this.stream.send(i)}}catch(l){u={error:l}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(u)throw u.error}}else this.stream.send({type:Xl.FrameTypes.PAYLOAD,flags:Xl.Flags.NEXT|Xl.Flags.COMPLETE|(l.metadata?Xl.Flags.METADATA:0),data:l.data,metadata:l.metadata,streamId:this.streamId});this.stream.disconnect(this)}},l.prototype.onComplete=function(){this.done||(this.done=!0,this.stream.send({type:Xl.FrameTypes.PAYLOAD,flags:Xl.Flags.COMPLETE,streamId:this.streamId,data:null,metadata:null}),this.stream.disconnect(this))},l.prototype.onExtension=function(l,n,u){this.done||this.stream.send({type:Xl.FrameTypes.EXT,streamId:this.streamId,flags:u?Xl.Flags.IGNORE:Xl.Flags.NONE,extendedType:l,extendedContent:n})},l.prototype.close=function(l){var n;this.done?console.warn("Trying to close for the second time. ".concat(l?"Dropping error [".concat(l,"]."):"")):(Yl.cancel(this),null===(n=this.receiver)||void 0===n||n.cancel())},l}();Wl.RequestResponseResponderStream=Zl;var ln={},nn=r&&r.__createBinding||(Object.create?function(l,n,u,e){void 0===e&&(e=u),Object.defineProperty(l,e,{enumerable:!0,get:function(){return n[u]}})}:function(l,n,u,e){void 0===e&&(e=u),l[e]=n[u]}),un=r&&r.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),en=r&&r.__importStar||function(l){if(l&&l.__esModule)return l;var n={};if(null!=l)for(var u in l)"default"!==u&&Object.prototype.hasOwnProperty.call(l,u)&&nn(n,l,u);return un(n,l),n},tn=r&&r.__values||function(l){var n="function"==typeof Symbol&&Symbol.iterator,u=n&&l[n],e=0;if(u)return u.call(l);if(l&&"number"==typeof l.length)return{next:function(){return l&&e>=l.length&&(l=void 0),{value:l&&l[e++],done:!l}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(ln,"__esModule",{value:!0}),ln.RequestStreamResponderStream=ln.RequestStreamRequesterStream=void 0;var rn=cl,sn=El,on=rl,an=en(bl),cn=function(){function l(l,n,u,e,t){this.payload=l,this.receiver=n,this.fragmentSize=u,this.initialRequestN=e,this.leaseManager=t,this.streamType=on.FrameTypes.REQUEST_STREAM}return l.prototype.handleReady=function(l,n){var u,e;if(this.done)return!1;if(this.streamId=l,this.stream=n,n.connect(this),(0,sn.isFragmentable)(this.payload,this.fragmentSize,on.FrameTypes.REQUEST_STREAM))try{for(var t=tn((0,sn.fragmentWithRequestN)(l,this.payload,this.fragmentSize,on.FrameTypes.REQUEST_STREAM,this.initialRequestN)),r=t.next();!r.done;r=t.next()){var i=r.value;this.stream.send(i)}}catch(l){u={error:l}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(u)throw u.error}}else this.stream.send({type:on.FrameTypes.REQUEST_STREAM,data:this.payload.data,metadata:this.payload.metadata,requestN:this.initialRequestN,flags:void 0!==this.payload.metadata?on.Flags.METADATA:0,streamId:l});return this.hasExtension&&this.stream.send({type:on.FrameTypes.EXT,streamId:l,extendedContent:this.extendedContent,extendedType:this.extendedType,flags:this.flags}),!0},l.prototype.handleReject=function(l){this.done||(this.done=!0,this.receiver.onError(l))},l.prototype.handle=function(l){var n,u=l.type;switch(u){case on.FrameTypes.PAYLOAD:var e=on.Flags.hasComplete(l.flags),t=on.Flags.hasNext(l.flags);if(e||!on.Flags.hasFollows(l.flags)){if(e&&(this.done=!0,this.stream.disconnect(this),!t))return void this.receiver.onComplete();var r=this.hasFragments?an.reassemble(this,l.data,l.metadata):{data:l.data,metadata:l.metadata};return void this.receiver.onNext(r,e)}if(!an.add(this,l.data,l.metadata)){n="Unexpected fragment size";break}return;case on.FrameTypes.ERROR:return this.done=!0,this.stream.disconnect(this),an.cancel(this),void this.receiver.onError(new rn.RSocketError(l.code,l.message));case on.FrameTypes.EXT:if(this.hasFragments){n="Unexpected frame type [".concat(u,"] during reassembly");break}return void this.receiver.onExtension(l.extendedType,l.extendedContent,on.Flags.hasIgnore(l.flags));default:n="Unexpected frame type [".concat(u,"]")}this.close(new rn.RSocketError(rn.ErrorCodes.CANCELED,n)),this.stream.send({type:on.FrameTypes.CANCEL,streamId:this.streamId,flags:on.Flags.NONE}),this.stream.disconnect(this)},l.prototype.request=function(l){this.done||(this.streamId?this.stream.send({type:on.FrameTypes.REQUEST_N,flags:on.Flags.NONE,requestN:l,streamId:this.streamId}):this.initialRequestN+=l)},l.prototype.cancel=function(){var l;this.done||(this.done=!0,this.streamId?(this.stream.send({type:on.FrameTypes.CANCEL,flags:on.Flags.NONE,streamId:this.streamId}),this.stream.disconnect(this),an.cancel(this)):null===(l=this.leaseManager)||void 0===l||l.cancelRequest(this))},l.prototype.onExtension=function(l,n,u){if(!this.done)return this.streamId?void this.stream.send({streamId:this.streamId,type:on.FrameTypes.EXT,extendedType:l,extendedContent:n,flags:u?on.Flags.IGNORE:on.Flags.NONE}):(this.hasExtension=!0,this.extendedType=l,this.extendedContent=n,void(this.flags=u?on.Flags.IGNORE:on.Flags.NONE))},l.prototype.close=function(l){this.done||(this.done=!0,an.cancel(this),l?this.receiver.onError(l):this.receiver.onComplete())},l}();ln.RequestStreamRequesterStream=cn;var hn=function(){function l(l,n,u,e,t){if(this.streamId=l,this.stream=n,this.fragmentSize=u,this.handler=e,this.streamType=on.FrameTypes.REQUEST_STREAM,n.connect(this),on.Flags.hasFollows(t.flags))return this.initialRequestN=t.requestN,void an.add(this,t.data,t.metadata);var r={data:t.data,metadata:t.metadata};try{this.receiver=e(r,t.requestN,this)}catch(l){this.onError(l)}}return l.prototype.handle=function(l){var n,u;if(!this.receiver||this.hasFragments)if(l.type===on.FrameTypes.PAYLOAD){if(!on.Flags.hasFollows(l.flags)){var e=an.reassemble(this,l.data,l.metadata);try{this.receiver=this.handler(e,this.initialRequestN,this)}catch(l){this.onError(l)}return}if(an.add(this,l.data,l.metadata))return;u="Unexpected frame size"}else u="Unexpected frame type [".concat(l.type,"] during reassembly");else{if(l.type===on.FrameTypes.REQUEST_N)return void this.receiver.request(l.requestN);if(l.type===on.FrameTypes.EXT)return void this.receiver.onExtension(l.extendedType,l.extendedContent,on.Flags.hasIgnore(l.flags));u="Unexpected frame type [".concat(l.type,"]")}this.done=!0,an.cancel(this),null===(n=this.receiver)||void 0===n||n.cancel(),l.type!==on.FrameTypes.CANCEL&&l.type!==on.FrameTypes.ERROR&&this.stream.send({type:on.FrameTypes.ERROR,flags:on.Flags.NONE,code:rn.ErrorCodes.CANCELED,message:u,streamId:this.streamId}),this.stream.disconnect(this)},l.prototype.onError=function(l){this.done?console.warn("Trying to error for the second time. ".concat(l?"Dropping error [".concat(l,"]."):"")):(this.done=!0,this.stream.send({type:on.FrameTypes.ERROR,flags:on.Flags.NONE,code:l instanceof rn.RSocketError?l.code:rn.ErrorCodes.APPLICATION_ERROR,message:l.message,streamId:this.streamId}),this.stream.disconnect(this))},l.prototype.onNext=function(l,n){var u,e;if(!this.done){if(n&&(this.done=!0),(0,sn.isFragmentable)(l,this.fragmentSize,on.FrameTypes.PAYLOAD))try{for(var t=tn((0,sn.fragment)(this.streamId,l,this.fragmentSize,on.FrameTypes.PAYLOAD,n)),r=t.next();!r.done;r=t.next()){var i=r.value;this.stream.send(i)}}catch(l){u={error:l}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(u)throw u.error}}else this.stream.send({type:on.FrameTypes.PAYLOAD,flags:on.Flags.NEXT|(n?on.Flags.COMPLETE:on.Flags.NONE)|(l.metadata?on.Flags.METADATA:on.Flags.NONE),data:l.data,metadata:l.metadata,streamId:this.streamId});n&&this.stream.disconnect(this)}},l.prototype.onComplete=function(){this.done||(this.done=!0,this.stream.send({type:on.FrameTypes.PAYLOAD,flags:on.Flags.COMPLETE,streamId:this.streamId,data:null,metadata:null}),this.stream.disconnect(this))},l.prototype.onExtension=function(l,n,u){this.done||this.stream.send({type:on.FrameTypes.EXT,streamId:this.streamId,flags:u?on.Flags.IGNORE:on.Flags.NONE,extendedType:l,extendedContent:n})},l.prototype.close=function(l){var n;this.done?console.warn("Trying to close for the second time. ".concat(l?"Dropping error [".concat(l,"]."):"")):(an.cancel(this),null===(n=this.receiver)||void 0===n||n.cancel())},l}();ln.RequestStreamResponderStream=hn,Object.defineProperty(ml,"__esModule",{value:!0}),ml.KeepAliveSender=ml.KeepAliveHandler=ml.DefaultConnectionFrameHandler=ml.DefaultStreamRequestHandler=ml.LeaseHandler=ml.RSocketRequester=void 0;var dn=cl,fn=rl,pn=gl,yn=Ll,mn=Wl,gn=ln,En=function(){function l(l,n,u){this.connection=l,this.fragmentSize=n,this.leaseManager=u}return l.prototype.fireAndForget=function(l,n){var u=new yn.RequestFnFRequesterStream(l,n,this.fragmentSize,this.leaseManager);return this.leaseManager?this.leaseManager.requestLease(u):this.connection.multiplexerDemultiplexer.createRequestStream(u),u},l.prototype.requestResponse=function(l,n){var u=new mn.RequestResponseRequesterStream(l,n,this.fragmentSize,this.leaseManager);return this.leaseManager?this.leaseManager.requestLease(u):this.connection.multiplexerDemultiplexer.createRequestStream(u),u},l.prototype.requestStream=function(l,n,u){var e=new gn.RequestStreamRequesterStream(l,u,this.fragmentSize,n,this.leaseManager);return this.leaseManager?this.leaseManager.requestLease(e):this.connection.multiplexerDemultiplexer.createRequestStream(e),e},l.prototype.requestChannel=function(l,n,u,e){var t=new pn.RequestChannelRequesterStream(l,u,e,this.fragmentSize,n,this.leaseManager);return this.leaseManager?this.leaseManager.requestLease(t):this.connection.multiplexerDemultiplexer.createRequestStream(t),t},l.prototype.metadataPush=function(l,n){throw new Error("Method not implemented.")},l.prototype.close=function(l){this.connection.close(l)},l.prototype.onClose=function(l){this.connection.onClose(l)},l}();ml.RSocketRequester=En;var wn=function(){function l(l,n){this.maxPendingRequests=l,this.multiplexer=n,this.pendingRequests=[],this.expirationTime=0,this.availableLease=0}return l.prototype.handle=function(l){for(this.expirationTime=l.ttl+Date.now(),this.availableLease=l.requestCount;this.availableLease>0&&this.pendingRequests.length>0;){var n=this.pendingRequests.shift();this.availableLease--,this.multiplexer.createRequestStream(n)}},l.prototype.requestLease=function(l){var n=this.availableLease;if(n>0&&Date.now()<this.expirationTime)return this.availableLease=n-1,void this.multiplexer.createRequestStream(l);this.pendingRequests.length>=this.maxPendingRequests?l.handleReject(new dn.RSocketError(dn.ErrorCodes.REJECTED,"No available lease given")):this.pendingRequests.push(l)},l.prototype.cancelRequest=function(l){var n=this.pendingRequests.indexOf(l);n>-1&&this.pendingRequests.splice(n,1)},l}();ml.LeaseHandler=wn;var vn=function(){function l(l,n){this.rsocket=l,this.fragmentSize=n}return l.prototype.handle=function(l,n){switch(l.type){case fn.FrameTypes.REQUEST_FNF:return void(this.rsocket.fireAndForget&&new yn.RequestFnfResponderStream(l.streamId,n,this.rsocket.fireAndForget.bind(this.rsocket),l));case fn.FrameTypes.REQUEST_RESPONSE:return this.rsocket.requestResponse?void new mn.RequestResponseResponderStream(l.streamId,n,this.fragmentSize,this.rsocket.requestResponse.bind(this.rsocket),l):void this.rejectRequest(l.streamId,n);case fn.FrameTypes.REQUEST_STREAM:return this.rsocket.requestStream?void new gn.RequestStreamResponderStream(l.streamId,n,this.fragmentSize,this.rsocket.requestStream.bind(this.rsocket),l):void this.rejectRequest(l.streamId,n);case fn.FrameTypes.REQUEST_CHANNEL:return this.rsocket.requestChannel?void new pn.RequestChannelResponderStream(l.streamId,n,this.fragmentSize,this.rsocket.requestChannel.bind(this.rsocket),l):void this.rejectRequest(l.streamId,n)}},l.prototype.rejectRequest=function(l,n){n.send({type:fn.FrameTypes.ERROR,streamId:l,flags:fn.Flags.NONE,code:dn.ErrorCodes.REJECTED,message:"No available handler found"})},l.prototype.close=function(){},l}();ml.DefaultStreamRequestHandler=vn;var bn,Sn=function(){function l(l,n,u,e,t){this.connection=l,this.keepAliveHandler=n,this.keepAliveSender=u,this.leaseHandler=e,this.rsocket=t}return l.prototype.handle=function(l){switch(l.type){case fn.FrameTypes.KEEPALIVE:return void this.keepAliveHandler.handle(l);case fn.FrameTypes.LEASE:return this.leaseHandler?void this.leaseHandler.handle(l):void 0;case fn.FrameTypes.ERROR:return void this.connection.close(new dn.RSocketError(l.code,l.message));case fn.FrameTypes.METADATA_PUSH:return void this.rsocket.metadataPush;default:this.connection.multiplexerDemultiplexer.connectionOutbound.send({type:fn.FrameTypes.ERROR,streamId:0,flags:fn.Flags.NONE,message:"Received unknown frame type",code:dn.ErrorCodes.CONNECTION_ERROR})}},l.prototype.pause=function(){var l;this.keepAliveHandler.pause(),null===(l=this.keepAliveSender)||void 0===l||l.pause()},l.prototype.resume=function(){var l;this.keepAliveHandler.start(),null===(l=this.keepAliveSender)||void 0===l||l.start()},l.prototype.close=function(l){var n;this.keepAliveHandler.close(),null===(n=this.rsocket.close)||void 0===n||n.call(this.rsocket,l)},l}();ml.DefaultConnectionFrameHandler=Sn,function(l){l[l.Paused=0]="Paused",l[l.Running=1]="Running",l[l.Closed=2]="Closed"}(bn||(bn={}));var Tn,Rn=function(){function l(l,n){this.connection=l,this.keepAliveTimeoutDuration=n,this.state=bn.Paused,this.outbound=l.multiplexerDemultiplexer.connectionOutbound}return l.prototype.handle=function(l){this.keepAliveLastReceivedMillis=Date.now(),fn.Flags.hasRespond(l.flags)&&this.outbound.send({type:fn.FrameTypes.KEEPALIVE,streamId:0,data:l.data,flags:l.flags^fn.Flags.RESPOND,lastReceivedPosition:0})},l.prototype.start=function(){this.state===bn.Paused&&(this.keepAliveLastReceivedMillis=Date.now(),this.state=bn.Running,this.activeTimeout=setTimeout(this.timeoutCheck.bind(this),this.keepAliveTimeoutDuration))},l.prototype.pause=function(){this.state===bn.Running&&(this.state=bn.Paused,clearTimeout(this.activeTimeout))},l.prototype.close=function(){this.state=bn.Closed,clearTimeout(this.activeTimeout)},l.prototype.timeoutCheck=function(){var l=Date.now()-this.keepAliveLastReceivedMillis;l>=this.keepAliveTimeoutDuration?this.connection.close(new Error("No keep-alive acks for ".concat(this.keepAliveTimeoutDuration," millis"))):this.activeTimeout=setTimeout(this.timeoutCheck.bind(this),Math.max(100,this.keepAliveTimeoutDuration-l))},l}();ml.KeepAliveHandler=Rn,function(l){l[l.Paused=0]="Paused",l[l.Running=1]="Running",l[l.Closed=2]="Closed"}(Tn||(Tn={}));var _n=function(){function l(l,n){this.outbound=l,this.keepAlivePeriodDuration=n,this.state=Tn.Paused}return l.prototype.sendKeepAlive=function(){this.outbound.send({type:fn.FrameTypes.KEEPALIVE,streamId:0,data:void 0,flags:fn.Flags.RESPOND,lastReceivedPosition:0})},l.prototype.start=function(){this.state===Tn.Paused&&(this.state=Tn.Running,this.activeInterval=setInterval(this.sendKeepAlive.bind(this),this.keepAlivePeriodDuration))},l.prototype.pause=function(){this.state===Tn.Running&&(this.state=Tn.Paused,clearInterval(this.activeInterval))},l.prototype.close=function(){this.state=Tn.Closed,clearInterval(this.activeInterval)},l}();ml.KeepAliveSender=_n;var An,On,Fn={};function Cn(){if(An)return Fn;An=1;var l=r&&r.__values||function(l){var n="function"==typeof Symbol&&Symbol.iterator,u=n&&l[n],e=0;if(u)return u.call(l);if(l&&"number"==typeof l.length)return{next:function(){return l&&e>=l.length&&(l=void 0),{value:l&&l[e++],done:!l}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(Fn,"__esModule",{value:!0}),Fn.FrameStore=void 0;var n=Pn(),u=tl,e=function(){function e(){this.storedFrames=[],this._lastReceivedFramePosition=0,this._firstAvailableFramePosition=0,this._lastSentFramePosition=0}return Object.defineProperty(e.prototype,"lastReceivedFramePosition",{get:function(){return this._lastReceivedFramePosition},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"firstAvailableFramePosition",{get:function(){return this._firstAvailableFramePosition},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"lastSentFramePosition",{get:function(){return this._lastSentFramePosition},enumerable:!1,configurable:!0}),e.prototype.store=function(l){this._lastSentFramePosition+=(0,u.sizeOfFrame)(l),this.storedFrames.push(l)},e.prototype.record=function(l){this._lastReceivedFramePosition+=(0,u.sizeOfFrame)(l)},e.prototype.dropTo=function(l){for(var e=l-this._firstAvailableFramePosition;e>0&&this.storedFrames.length>0;){var t=this.storedFrames.shift();e-=(0,u.sizeOfFrame)(t)}if(0!==e)throw new n.RSocketError(n.ErrorCodes.CONNECTION_ERROR,"State inconsistency. Expected bytes to drop ".concat(l-this._firstAvailableFramePosition," but actual ").concat(e));this._firstAvailableFramePosition=l},e.prototype.drain=function(n){var u,e;try{for(var t=l(this.storedFrames),r=t.next();!r.done;r=t.next()){n(r.value)}}catch(l){u={error:l}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(u)throw u.error}}},e}();return Fn.FrameStore=e,Fn}function In(){if(On)return fl;On=1;var l=r&&r.__awaiter||function(l,n,u,e){return new(u||(u=Promise))((function(t,r){function i(l){try{o(e.next(l))}catch(l){r(l)}}function s(l){try{o(e.throw(l))}catch(l){r(l)}}function o(l){var n;l.done?t(l.value):(n=l.value,n instanceof u?n:new u((function(l){l(n)}))).then(i,s)}o((e=e.apply(l,n||[])).next())}))},n=r&&r.__generator||function(l,n){var u,e,t,r,i={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function s(r){return function(s){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;i;)try{if(u=1,e&&(t=2&r[0]?e.return:r[0]?e.throw||((t=e.return)&&t.call(e),0):e.next)&&!(t=t.call(e,r[1])).done)return t;switch(e=0,t&&(r=[2&r[0],t.value]),r[0]){case 0:case 1:t=r;break;case 4:return i.label++,{value:r[1],done:!1};case 5:i.label++,e=r[1],r=[0];continue;case 7:r=i.ops.pop(),i.trys.pop();continue;default:if(!(t=i.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){i=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){i.label=r[1];break}if(6===r[0]&&i.label<t[1]){i.label=t[1],t=r;break}if(t&&i.label<t[2]){i.label=t[2],i.ops.push(r);break}t[2]&&i.ops.pop(),i.trys.pop();continue}r=n.call(l,i)}catch(l){r=[6,l],e=0}finally{u=t=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,s])}}};Object.defineProperty(fl,"__esModule",{value:!0}),fl.RSocketConnector=void 0;var u=yl(),e=rl,t=ml,i=Cn(),s=function(){function r(l){this.config=l}return r.prototype.connect=function(){var r,s,o,a,c,h,d,f,p,y,m,g,E,w,v,b,S,T,R,_;return l(this,void 0,void 0,(function(){var A,O,F,C,I,k,L,N,U,x=this;return n(this,(function(P){switch(P.label){case 0:return A=this.config,O={type:e.FrameTypes.SETUP,dataMimeType:null!==(s=null===(r=A.setup)||void 0===r?void 0:r.dataMimeType)&&void 0!==s?s:"application/octet-stream",metadataMimeType:null!==(a=null===(o=A.setup)||void 0===o?void 0:o.metadataMimeType)&&void 0!==a?a:"application/octet-stream",keepAlive:null!==(h=null===(c=A.setup)||void 0===c?void 0:c.keepAlive)&&void 0!==h?h:6e4,lifetime:null!==(f=null===(d=A.setup)||void 0===d?void 0:d.lifetime)&&void 0!==f?f:3e5,metadata:null===(y=null===(p=A.setup)||void 0===p?void 0:p.payload)||void 0===y?void 0:y.metadata,data:null===(g=null===(m=A.setup)||void 0===m?void 0:m.payload)||void 0===g?void 0:g.data,resumeToken:null!==(w=null===(E=A.resume)||void 0===E?void 0:E.tokenGenerator())&&void 0!==w?w:null,streamId:0,majorVersion:1,minorVersion:0,flags:((null===(b=null===(v=A.setup)||void 0===v?void 0:v.payload)||void 0===b?void 0:b.metadata)?e.Flags.METADATA:e.Flags.NONE)|(A.lease?e.Flags.LEASE:e.Flags.NONE)|(A.resume?e.Flags.RESUME_ENABLE:e.Flags.NONE)},[4,A.transport.connect((function(t){return A.resume?new u.ResumableClientServerInputMultiplexerDemultiplexer(u.StreamIdGenerator.create(-1),t,t,new i.FrameStore,O.resumeToken.toString(),(function(t,r){return l(x,void 0,void 0,(function(){var l,i,s;return n(this,(function(n){switch(n.label){case 0:return l=function(l){return l.send({type:e.FrameTypes.RESUME,streamId:0,flags:e.Flags.NONE,clientPosition:r.firstAvailableFramePosition,serverPosition:r.lastReceivedFramePosition,majorVersion:O.minorVersion,minorVersion:O.majorVersion,resumeToken:O.resumeToken}),new u.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer(l,l,t)},i=-1,[4,(s=function(){return i++,A.resume.reconnectFunction(i).then((function(){return A.transport.connect(l).catch(s)}))})()];case 1:return n.sent(),[2]}}))}))})):new u.ClientServerInputMultiplexerDemultiplexer(u.StreamIdGenerator.create(-1),t,t)}))];case 1:return F=P.sent(),C=new t.KeepAliveSender(F.multiplexerDemultiplexer.connectionOutbound,O.keepAlive),I=new t.KeepAliveHandler(F,O.lifetime),k=A.lease?new t.LeaseHandler(null!==(S=A.lease.maxPendingRequests)&&void 0!==S?S:256,F.multiplexerDemultiplexer):void 0,L=null!==(T=A.responder)&&void 0!==T?T:{},N=new t.DefaultConnectionFrameHandler(F,I,C,k,L),U=new t.DefaultStreamRequestHandler(L,0),F.onClose((function(l){C.close(),I.close(),N.close(l)})),F.multiplexerDemultiplexer.connectionInbound(N),F.multiplexerDemultiplexer.handleRequestStream(U),F.multiplexerDemultiplexer.connectionOutbound.send(O),I.start(),C.start(),[2,new t.RSocketRequester(F,null!==(_=null===(R=A.fragmentation)||void 0===R?void 0:R.maxOutboundFragmentSize)&&void 0!==_?_:0,k)]}}))}))},r}();return fl.RSocketConnector=s,fl}var kn,Ln={};function Nn(){if(kn)return Ln;kn=1;var l=r&&r.__awaiter||function(l,n,u,e){return new(u||(u=Promise))((function(t,r){function i(l){try{o(e.next(l))}catch(l){r(l)}}function s(l){try{o(e.throw(l))}catch(l){r(l)}}function o(l){var n;l.done?t(l.value):(n=l.value,n instanceof u?n:new u((function(l){l(n)}))).then(i,s)}o((e=e.apply(l,n||[])).next())}))},n=r&&r.__generator||function(l,n){var u,e,t,r,i={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function s(r){return function(s){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;i;)try{if(u=1,e&&(t=2&r[0]?e.return:r[0]?e.throw||((t=e.return)&&t.call(e),0):e.next)&&!(t=t.call(e,r[1])).done)return t;switch(e=0,t&&(r=[2&r[0],t.value]),r[0]){case 0:case 1:t=r;break;case 4:return i.label++,{value:r[1],done:!1};case 5:i.label++,e=r[1],r=[0];continue;case 7:r=i.ops.pop(),i.trys.pop();continue;default:if(!(t=i.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){i=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){i.label=r[1];break}if(6===r[0]&&i.label<t[1]){i.label=t[1],t=r;break}if(t&&i.label<t[2]){i.label=t[2],i.ops.push(r);break}t[2]&&i.ops.pop(),i.trys.pop();continue}r=n.call(l,i)}catch(l){r=[6,l],e=0}finally{u=t=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,s])}}};Object.defineProperty(Ln,"__esModule",{value:!0}),Ln.RSocketServer=void 0;var u=yl(),e=cl,t=rl,i=ml,s=Cn(),o=function(){function r(l){var n,u;this.acceptor=l.acceptor,this.transport=l.transport,this.lease=l.lease,this.serverSideKeepAlive=l.serverSideKeepAlive,this.sessionStore=l.resume?{}:void 0,this.sessionTimeout=null!==(u=null===(n=l.resume)||void 0===n?void 0:n.sessionTimeout)&&void 0!==u?u:void 0}return r.prototype.bind=function(){return l(this,void 0,void 0,(function(){var r=this;return n(this,(function(o){switch(o.label){case 0:return[4,this.transport.bind((function(u,s){return l(r,void 0,void 0,(function(){var l,r,o,a,c,h,d,f,p,y,m,g,E;return n(this,(function(n){switch(n.label){case 0:switch(u.type){case t.FrameTypes.SETUP:return[3,1];case t.FrameTypes.RESUME:return[3,5]}return[3,6];case 1:return n.trys.push([1,3,,4]),this.lease&&!t.Flags.hasLease(u.flags)?(l=new e.RSocketError(e.ErrorCodes.REJECTED_SETUP,"Lease has to be enabled"),s.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,flags:t.Flags.NONE,code:l.code,message:l.message}),s.close(l),[2]):t.Flags.hasLease(u.flags)&&!this.lease?(l=new e.RSocketError(e.ErrorCodes.REJECTED_SETUP,"Lease has to be disabled"),s.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,flags:t.Flags.NONE,code:l.code,message:l.message}),s.close(l),[2]):(r=t.Flags.hasLease(u.flags)?new i.LeaseHandler(null!==(y=this.lease.maxPendingRequests)&&void 0!==y?y:256,s.multiplexerDemultiplexer):void 0,o=new i.RSocketRequester(s,null!==(g=null===(m=this.fragmentation)||void 0===m?void 0:m.maxOutboundFragmentSize)&&void 0!==g?g:0,r),[4,this.acceptor.accept({data:u.data,dataMimeType:u.dataMimeType,metadata:u.metadata,metadataMimeType:u.metadataMimeType,flags:u.flags,keepAliveMaxLifetime:u.lifetime,keepAliveInterval:u.keepAlive,resumeToken:u.resumeToken},o)]);case 2:return a=n.sent(),c=new i.KeepAliveHandler(s,u.lifetime),h=this.serverSideKeepAlive?new i.KeepAliveSender(s.multiplexerDemultiplexer.connectionOutbound,u.keepAlive):void 0,d=new i.DefaultConnectionFrameHandler(s,c,h,r,a),f=new i.DefaultStreamRequestHandler(a,0),s.onClose((function(l){null==h||h.close(),c.close(),d.close(l)})),s.multiplexerDemultiplexer.connectionInbound(d),s.multiplexerDemultiplexer.handleRequestStream(f),c.start(),null==h||h.start(),[3,4];case 3:return p=n.sent(),s.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,code:e.ErrorCodes.REJECTED_SETUP,message:null!==(E=p.message)&&void 0!==E?E:"",flags:t.Flags.NONE}),s.close(p instanceof e.RSocketError?p:new e.RSocketError(e.ErrorCodes.REJECTED_SETUP,p.message)),[3,4];case 4:case 5:return[2];case 6:s.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,code:e.ErrorCodes.UNSUPPORTED_SETUP,message:"Unsupported setup",flags:t.Flags.NONE}),s.close(new e.RSocketError(e.ErrorCodes.UNSUPPORTED_SETUP)),n.label=7;case 7:return[2]}}))}))}),(function(l,n){if(l.type===t.FrameTypes.RESUME){if(r.sessionStore){var i=r.sessionStore[l.resumeToken.toString()];return i?(i.resume(l,n,n),i):(n.send({type:t.FrameTypes.ERROR,streamId:0,code:e.ErrorCodes.REJECTED_RESUME,message:"No session found for the given resume token",flags:t.Flags.NONE}),void n.close())}return n.send({type:t.FrameTypes.ERROR,streamId:0,code:e.ErrorCodes.REJECTED_RESUME,message:"Resume is not enabled",flags:t.Flags.NONE}),void n.close()}if(l.type===t.FrameTypes.SETUP&&t.Flags.hasResume(l.flags)){if(!r.sessionStore){var o=new e.RSocketError(e.ErrorCodes.REJECTED_SETUP,"No resume support");return n.send({type:t.FrameTypes.ERROR,streamId:0,flags:t.Flags.NONE,code:o.code,message:o.message}),void n.close(o)}var a=new u.ResumableClientServerInputMultiplexerDemultiplexer(u.StreamIdGenerator.create(0),n,n,new s.FrameStore,l.resumeToken.toString(),r.sessionStore,r.sessionTimeout);return r.sessionStore[l.resumeToken.toString()]=a,a}return new u.ClientServerInputMultiplexerDemultiplexer(u.StreamIdGenerator.create(0),n,n)}))];case 1:return[2,o.sent()]}}))}))},r}();return Ln.RSocketServer=o,Ln}var Un,xn={};function Pn(){return Un||(Un=1,function(l){var n=r&&r.__createBinding||(Object.create?function(l,n,u,e){void 0===e&&(e=u),Object.defineProperty(l,e,{enumerable:!0,get:function(){return n[u]}})}:function(l,n,u,e){void 0===e&&(e=u),l[e]=n[u]}),u=r&&r.__exportStar||function(l,u){for(var e in l)"default"===e||Object.prototype.hasOwnProperty.call(u,e)||n(u,l,e)};Object.defineProperty(l,"__esModule",{value:!0}),u(tl,l),u(il,l),u(sl,l),u(cl,l),u(rl,l),u(hl,l),u(In(),l),u(Nn(),l),u(xn,l)}(ul)),ul}Object.defineProperty(xn,"__esModule",{value:!0});var Dn=Pn(),Mn="1.33.2";const Bn={highWater:10,lowWater:0};class qn extends S{options;dataQueue;isClosed;processingPromise;notifyDataAdded;logger;mapLine;constructor(l){if(super(),this.options=l,this.processingPromise=null,this.isClosed=!1,this.dataQueue=[],this.mapLine=l?.mapLine??(l=>l),this.logger=l?.logger??y.get("DataStream"),l?.closeOnError){const l=this.registerListener({error:n=>{l?.(),this.close()}})}}get highWatermark(){return this.options?.pressure?.highWaterMark??Bn.highWater}get lowWatermark(){return this.options?.pressure?.lowWaterMark??Bn.lowWater}get closed(){return this.isClosed}async close(){this.isClosed=!0,await this.processingPromise,this.iterateListeners((l=>l.closed?.())),this.dataQueue=[],this.listeners.clear()}enqueueData(l){if(this.isClosed)throw new Error("Cannot enqueue data into closed stream.");this.dataQueue.push(l),this.notifyDataAdded?.(),this.processQueue()}async read(){return this.closed?null:new Promise(((l,n)=>{const u=this.registerListener({data:async n=>{l(n),u?.()},closed:()=>{l(null),u?.()},error:l=>{n(l),u?.()}});this.processQueue()}))}forEach(l){return this.dataQueue.length<=this.lowWatermark&&this.iterateAsyncErrored((async l=>l.lowWater?.())),this.registerListener({data:l})}processQueue(){if(this.processingPromise)return;const l=this.processingPromise=this._processQueue();return l.finally((()=>this.processingPromise=null)),l}hasDataReader(){return Array.from(this.listeners.values()).some((l=>!!l.data))}async _processQueue(){if(this.dataQueue.length>=this.highWatermark&&await this.iterateAsyncErrored((async l=>l.highWater?.())),!this.isClosed&&this.hasDataReader()){if(this.dataQueue.length){const l=this.dataQueue.shift(),n=this.mapLine(l);await this.iterateAsyncErrored((async l=>l.data?.(n)))}if(this.dataQueue.length<=this.lowWatermark){const l=new Promise((l=>{this.notifyDataAdded=l}));await Promise.race([this.iterateAsyncErrored((async l=>l.lowWater?.())),l]),this.notifyDataAdded=null}this.dataQueue.length>0&&setTimeout((()=>this.processQueue()))}}async iterateAsyncErrored(l){const n=Array.from(this.listeners.values());for(let u of n)try{await l(u)}catch(l){this.logger.error(l),this.iterateListeners((n=>n.error?.(l)))}}}var jn,Qn={},Wn=r&&r.__extends||(jn=function(l,n){return jn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(l,n){l.__proto__=n}||function(l,n){for(var u in n)Object.prototype.hasOwnProperty.call(n,u)&&(l[u]=n[u])},jn(l,n)},function(l,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function u(){this.constructor=l}jn(l,n),l.prototype=null===n?Object.create(n):(u.prototype=n.prototype,new u)});Object.defineProperty(Qn,"__esModule",{value:!0});var $n=Qn.WebsocketDuplexConnection=void 0,zn=Pn(),Hn=function(l){function n(n,u,e){var t=l.call(this)||this;return t.websocket=n,t.deserializer=u,t.handleClosed=function(l){t.close(new Error(l.reason||"WebsocketDuplexConnection: Socket closed unexpectedly."))},t.handleError=function(l){t.close(l.error)},t.handleMessage=function(l){try{var n=el.Buffer.from(l.data),u=t.deserializer.deserializeFrame(n);t.multiplexerDemultiplexer.handle(u)}catch(l){t.close(l)}},n.addEventListener("close",t.handleClosed),n.addEventListener("error",t.handleError),n.addEventListener("message",t.handleMessage),t.multiplexerDemultiplexer=e(t),t}return Wn(n,l),Object.defineProperty(n.prototype,"availability",{get:function(){return this.done?0:1},enumerable:!1,configurable:!0}),n.prototype.close=function(n){this.done||(this.websocket.removeEventListener("close",this.handleClosed),this.websocket.removeEventListener("error",this.handleError),this.websocket.removeEventListener("message",this.handleMessage),this.websocket.close(),delete this.websocket),l.prototype.close.call(this,n)},n.prototype.send=function(l){if(!this.done){var n=(0,zn.serializeFrame)(l);this.websocket.send(n)}},n}(zn.Deferred);$n=Qn.WebsocketDuplexConnection=Hn;class Vn{url;factory;constructor(l){this.url=l.url,this.factory=l.wsCreator??(l=>new WebSocket(l))}connect(l){return new Promise(((n,u)=>{const e=this.factory(this.url);let t;e.binaryType="arraybuffer";const r=()=>{t(),n(new $n(e,new Dn.Deserializer,l))},i=l=>{t(),null!=l.error?u(l.error):null!=l.message?u(new Error(`Failed to create websocket connection: ${l.message}`)):u(new Error(`Failed to create websocket connection to ${this.url}`))},s=()=>{t(),u(new Error("WebSocket connection closed while opening"))};t=()=>{e.removeEventListener("open",r),e.removeEventListener("error",i),e.removeEventListener("close",s)},e.addEventListener("open",r),e.addEventListener("error",i),e.addEventListener("close",s)}))}}const Jn=/\/+$/,Gn=Mn,Xn=y.get("PowerSyncRemote");var Yn;!function(l){l.Buffered="buffered",l.Sequential="sequential"}(Yn||(Yn={}));class Kn{getFetch(){throw new Error("Unspecified fetch implementation")}}const Zn={socketUrlTransformer:l=>l.replace(/^https?:\/\//,(function(l){return"https://"===l?"wss://":"ws://"})),fetchImplementation:new Kn,fetchOptions:{}};class lu{connector;logger;credentials=null;options;constructor(l,n=Xn,u){this.connector=l,this.logger=n,this.options={...Zn,...u??{}}}get fetch(){const{fetchImplementation:l}=this.options;return l instanceof Kn?l.getFetch():l}async getCredentials(){return this.credentials?this.credentials:this.prefetchCredentials()}async prefetchCredentials(){return this.credentials=await this.fetchCredentials(),this.credentials}async fetchCredentials(){const l=await this.connector.fetchCredentials();if(l?.endpoint.match(Jn))throw new Error(`A trailing forward slash "/" was found in the fetchCredentials endpoint: "${l.endpoint}". Remove the trailing forward slash "/" to fix this error.`);return l}invalidateCredentials(){this.credentials=null,this.connector.invalidateCredentials?.()}getUserAgent(){return`powersync-js/${Gn}`}async buildRequest(l){const n=await this.getCredentials();if(null!=n&&(null==n.endpoint||""==n.endpoint))throw new Error("PowerSync endpoint not configured");if(null==n?.token||""==n?.token){const l=new Error("Not signed in");throw l.status=401,l}const u=this.getUserAgent();return{url:n.endpoint+l,headers:{"content-type":"application/json",Authorization:`Token ${n.token}`,"x-user-agent":u}}}async post(l,n,u={}){const e=await this.buildRequest(l),t=await this.fetch(e.url,{method:"POST",headers:{...u,...e.headers},body:JSON.stringify(n)});if(401===t.status&&this.invalidateCredentials(),!t.ok)throw new Error(`Received ${t.status} - ${t.statusText} when posting to ${l}: ${await t.text()}}`);return t.json()}async get(l,n){const u=await this.buildRequest(l),e=await this.fetch(u.url,{method:"GET",headers:{...n,...u.headers}});if(401===e.status&&this.invalidateCredentials(),!e.ok)throw new Error(`Received ${e.status} - ${e.statusText} when getting from ${l}: ${await e.text()}}`);return e.json()}createSocket(l){return new WebSocket(l)}async socketStream(l){const n=await this.getBSON();return await this.socketStreamRaw(l,(l=>n.deserialize(l)),n)}async socketStreamRaw(l,n,u){const{path:e,fetchStrategy:t=Yn.Buffered}=l,r=null==u?"application/json":"application/bson";function i(l){let n;return n=null!=u?u.serialize(l):JSON.stringify(l),H.Buffer.from(n)}const s=t==Yn.Buffered?10:1,o=await this.buildRequest(e),a=this.getUserAgent();let c;const h=()=>{clearTimeout(c),c=setTimeout((()=>{this.logger.error("No data received on WebSocket in 30000ms, closing connection."),y.close()}),3e4)};h();const d=this.options.socketUrlTransformer(o.url),f=new Dn.RSocketConnector({transport:new Vn({url:d,wsCreator:l=>{const n=this.createSocket(l);return n.addEventListener("message",(l=>{h()})),n}}),setup:{keepAlive:2e4,lifetime:9e4,dataMimeType:r,metadataMimeType:r,payload:{data:null,metadata:i({token:o.headers.Authorization,user_agent:a})}}});let p;try{p=await f.connect()}catch(l){throw this.logger.error("Failed to connect WebSocket",l),clearTimeout(c),l}h();const y=new qn({logger:this.logger,pressure:{lowWaterMark:5},mapLine:n});let m=!1;p.onClose((()=>m=!0));let g=s;const E=y.registerListener({closed:()=>{clearTimeout(c),m||(m=!0,p.close()),E()}}),w=await new Promise(((n,u)=>{let t=!1;const r=p.requestStream({data:i(l.data),metadata:i({path:e})},s,{onError:l=>{l.message.includes("PSYNC_")?l.message.includes("PSYNC_S21")&&this.invalidateCredentials():"Closed. "!==l.message&&this.invalidateCredentials(),"Closed. "!==l.message&&this.logger.error(l),y.close(),t||u(l)},onNext:l=>{t||(t=!0,n(r));const{data:u}=l;g--,u&&y.enqueueData(u)},onComplete:()=>{y.close()},onExtension:()=>{}})})),v=y.registerListener({lowWater:async()=>{s-g>0&&(w.request(s-g),g=s)},closed:()=>{v()}});return l.abortSignal?.aborted?y.close():l.abortSignal?.addEventListener("abort",(()=>{y.close()})),y}async postStream(l){return await this.postStreamRaw(l,(l=>JSON.parse(l)))}async postStreamRaw(l,n){const{data:u,path:e,headers:t,abortSignal:r}=l,i=await this.buildRequest(e),s=new AbortController;let o=!1;r?.addEventListener("abort",(()=>{o||s.abort(r.reason??new D("Cancelling network request before it resolves. Abort signal has been received."))}));const a=await this.fetch(i.url,{method:"POST",headers:{...t,...i.headers},body:JSON.stringify(u),signal:s.signal,cache:"no-store",...this.options.fetchOptions??{},...l.fetchOptions}).catch((l=>{if("AbortError"==l.name)throw new D(`Pending fetch request to ${i.url} has been aborted.`);throw l}));if(!a)throw new Error("Fetch request was aborted");if(o=!0,!a.ok||!a.body){const l=await a.text();this.logger.error(`Could not POST streaming to ${e} - ${a.status} - ${a.statusText}: ${l}`);const n=new Error(`HTTP ${a.statusText}: ${l}`);throw n.status=a.status,n}const c=a.body.getReader(),h=async()=>{try{await c.cancel()}catch(l){}c.releaseLock()};r?.addEventListener("abort",(()=>{h()}));const d=new z.TextDecoder;let f="";const p=new qn({logger:this.logger,mapLine:n}),y=p.registerListener({lowWater:async()=>{try{let u=!1;for(;!u;){const{done:e,value:t}=await c.read();if(e){const l=f.trim();return 0!=l.length&&p.enqueueData(l),p.close(),void await h()}const r=d.decode(t,{stream:!0});f+=r;const i=f.split("\n");for(var l=0;l<i.length-1;l++){var n=i[l].trim();n.length>0&&(p.enqueueData(n),u=!0)}f=i[i.length-1]}}catch(l){throw p.close(),l}},closed:()=>{h(),y?.()}});return p}}function nu(l){return null!=l.data}function uu(l){return null!=l.token_expires_in}function eu(l){return null!=l.checkpoint}function tu(l){return null!=l.checkpoint_complete}function ru(l){return null!=l.partial_checkpoint_complete}function iu(l){return null!=l.checkpoint_diff}function su(l){return Array.isArray(l.buckets)&&"string"==typeof l.checkpoint_token}function ou(l){return"object"==typeof l.request_checkpoint}var au,cu,hu;!function(l){l.CRUD="crud",l.SYNC="sync"}(au||(au={})),function(l){l.HTTP="http",l.WEB_SOCKET="web-socket"}(cu||(cu={})),function(l){l.JAVASCRIPT="js",l.RUST="rust"}(hu||(hu={}));const du=hu.JAVASCRIPT,fu=1e3,pu=5e3,yu={retryDelayMs:pu,logger:y.get("PowerSyncStream"),crudUploadThrottleMs:fu},mu={connectionMethod:cu.WEB_SOCKET,clientImplementation:du,fetchStrategy:Yn.Buffered,params:{}};class gu extends S{_lastSyncedAt;options;abortController;crudUpdateListener;streamingSyncPromise;pendingCrudUpload;notifyCompletedUploads;syncStatus;triggerCrudUpload;constructor(l){super(),this.options={...yu,...l},this.syncStatus=new v({connected:!1,connecting:!1,lastSyncedAt:void 0,dataFlow:{uploading:!1,downloading:!1}}),this.abortController=null,this.triggerCrudUpload=function(l,n){let u=null,e=0;const t=()=>{l(),e=Date.now(),u=null};return function(){const l=Date.now(),r=n-(l-e);r<=0?t():u||(u=setTimeout(t,r))}}((()=>{this.syncStatus.connected&&null==this.pendingCrudUpload&&(this.pendingCrudUpload=new Promise((l=>{this._uploadAllCrud().finally((()=>{this.notifyCompletedUploads?.(),this.pendingCrudUpload=void 0,l()}))})))}),this.options.crudUploadThrottleMs)}async waitForReady(){}waitForStatus(l){return this.waitUntilStatusMatches((n=>{const u=(l,n)=>Object.entries(l).every((([l,e])=>{const t=n[l];return"object"==typeof e&&"object"==typeof t?u(e,t):e==t}));return u(l,n)}))}waitUntilStatusMatches(l){return new Promise((n=>{if(l(this.syncStatus))return void n();const u=this.registerListener({statusChanged:e=>{l(e)&&(n(),u?.())}})}))}get lastSyncedAt(){const l=this.syncStatus.lastSyncedAt;return l&&new Date(l)}get isConnected(){return this.syncStatus.connected}get logger(){return this.options.logger}async dispose(){this.crudUpdateListener?.(),this.crudUpdateListener=void 0}async hasCompletedSync(){return this.options.adapter.hasCompletedSync()}async getWriteCheckpoint(){let l=`/write-checkpoint2.json?client_id=${await this.options.adapter.getClientId()}`;return(await this.options.remote.get(l)).data.write_checkpoint}async _uploadAllCrud(){return this.obtainLock({type:au.CRUD,callback:async()=>{let l;for(;;)try{const n=await this.options.adapter.nextCrudItem();if(!n){await this.options.adapter.updateLocalTarget((()=>this.getWriteCheckpoint()));break}if(this.updateSyncStatus({dataFlow:{uploading:!0}}),n.clientId==l?.clientId)throw this.logger.warn("Potentially previously uploaded CRUD entries are still present in the upload queue.\nMake sure to handle uploads and complete CRUD transactions or batches by calling and awaiting their [.complete()] method.\nThe next upload iteration will be delayed."),new Error("Delaying due to previously encountered CRUD item.");l=n,await this.options.uploadCrud(),this.updateSyncStatus({dataFlow:{uploadError:void 0}})}catch(n){if(l=void 0,this.updateSyncStatus({dataFlow:{uploading:!1,uploadError:n}}),await this.delayRetry(),!this.isConnected)break;this.logger.debug(`Caught exception when uploading. Upload will retry after a delay. Exception: ${n.message}`)}finally{this.updateSyncStatus({dataFlow:{uploading:!1}})}}})}async connect(l){this.abortController&&await this.disconnect();const n=new AbortController;return this.abortController=n,this.streamingSyncPromise=this.streamingSync(this.abortController.signal,l),new Promise((l=>{const n=this.registerListener({statusChanged:u=>{if(null!=u.dataFlowStatus.downloadError)this.logger.warn("Initial connect attempt did not successfully connect to server");else if(u.connecting)return;n(),l()}})}))}async disconnect(){if(this.abortController){this.abortController.signal.aborted||this.abortController.abort(new D("Disconnect has been requested"));try{await this.streamingSyncPromise}catch(l){this.logger.warn(l)}this.streamingSyncPromise=void 0,this.abortController=null,this.updateSyncStatus({connected:!1,connecting:!1})}}async streamingSync(l,n){l||(this.abortController=new AbortController,l=this.abortController.signal),this.crudUpdateListener=this.options.adapter.registerListener({crudUpdate:()=>this.triggerCrudUpload()});let u=new AbortController;for(l.addEventListener("abort",(()=>{u.abort(l?.reason??new D("Received command to disconnect from upstream")),this.crudUpdateListener?.(),this.crudUpdateListener=void 0,this.updateSyncStatus({connected:!1,connecting:!1,dataFlow:{downloading:!1,downloadProgress:null}})}));;){this.updateSyncStatus({connecting:!0});let e=!0;try{if(l?.aborted)break;await this.streamingSyncIteration(u.signal,n)}catch(l){l instanceof D?(this.logger.warn(l),e=!1):this.logger.error(l),this.updateSyncStatus({dataFlow:{downloadError:l}})}finally{l.aborted||(u.abort(new D("Closing sync stream network requests before retry.")),u=new AbortController),this.updateSyncStatus({connected:!1,connecting:!0}),e&&await this.delayRetry(u.signal)}}this.updateSyncStatus({connected:!1,connecting:!1})}async collectLocalBucketState(){const l=await this.options.adapter.getBucketStates(),n=l.map((l=>({name:l.bucket,after:l.op_id}))),u=new Map;for(const n of l)u.set(n.bucket,null);return[n,u]}async requireKeyFormat(l){const n=await this.options.adapter.hasMigratedSubkeys();return l&&!n?(await this.options.adapter.migrateToFixedSubkeys(),!0):n}async streamingSyncIteration(l,n){await this.obtainLock({type:au.SYNC,signal:l,callback:async()=>{const u={...mu,...n??{}};u.clientImplementation==hu.JAVASCRIPT?await this.legacyStreamingSyncIteration(l,u):(await this.requireKeyFormat(!0),await this.rustSyncIteration(l,u))}})}async legacyStreamingSyncIteration(l,n){this.logger.debug("Streaming sync iteration started"),this.options.adapter.startSession();let[u,e]=await this.collectLocalBucketState(),t=null,r=null,i=null;const s=await this.options.adapter.getClientId(),o=await this.requireKeyFormat(!1);this.logger.debug("Requesting stream from server");const a={path:"/sync/stream",abortSignal:l,data:{buckets:u,include_checksum:!0,raw_data:!0,parameters:n.params,client_id:s}};let c;for(c=n?.connectionMethod==cu.HTTP?await this.options.remote.postStream(a):await this.options.remote.socketStream({...a,fetchStrategy:n.fetchStrategy}),this.logger.debug("Stream established. Processing events");!c.closed;){const n=await c.read();if(!n)return;if(this.syncStatus.connected||(Promise.resolve().then((()=>this.triggerCrudUpload())),this.updateSyncStatus({connected:!0})),eu(n)){t=n.checkpoint;const l=new Set(e.keys()),u=new Map;for(const e of n.checkpoint.buckets)u.set(e.bucket,{name:e.bucket,priority:e.priority??3}),l.delete(e.bucket);l.size>0&&this.logger.debug("Removing buckets",[...l]),e=u,await this.options.adapter.removeBuckets([...l]),await this.options.adapter.setTargetCheckpoint(t),await this.updateSyncStatusForStartingCheckpoint(t)}else if(tu(n)){const n=await this.applyCheckpoint(t,l);if(n.endIteration)return;n.applied&&(i=t),r=t}else if(ru(n)){const l=n.partial_checkpoint_complete.priority;this.logger.debug("Partial checkpoint complete",l);const u=await this.options.adapter.syncLocalDatabase(t,l);if(!u.checkpointValid)return void await new Promise((l=>setTimeout(l,50)));if(u.ready){this.logger.debug("partial checkpoint validation succeeded");const n=this.syncStatus.priorityStatusEntries.filter((n=>n.priority<=l));n.push({priority:l,lastSyncedAt:new Date,hasSynced:!0}),this.updateSyncStatus({connected:!0,priorityStatusEntries:n})}else;}else if(iu(n)){if(null==t)throw new Error("Checkpoint diff without previous checkpoint");const l=n.checkpoint_diff,u=new Map;for(const l of t.buckets)u.set(l.bucket,l);for(const n of l.updated_buckets)u.set(n.bucket,n);for(const n of l.removed_buckets)u.delete(n);t={last_op_id:l.last_op_id,buckets:[...u.values()],write_checkpoint:l.write_checkpoint},await this.updateSyncStatusForStartingCheckpoint(t),e=new Map,u.forEach(((l,n)=>e.set(n,{name:l.bucket,priority:l.priority??3})));const r=l.removed_buckets;r.length>0&&this.logger.debug("Remove buckets",r),await this.options.adapter.removeBuckets(r),await this.options.adapter.setTargetCheckpoint(t)}else if(nu(n)){const{data:l}=n,u=this.syncStatus.dataFlowStatus.downloadProgress;let e=null;if(u){e={...u};const n=e[l.bucket];n&&(e[l.bucket]={...n,since_last:n.since_last+l.data.length})}this.updateSyncStatus({dataFlow:{downloading:!0,downloadProgress:e}}),await this.options.adapter.saveSyncData({buckets:[q.fromRow(l)]},o)}else if(uu(n)){const l=n.token_expires_in;if(0==l)return this.logger.debug("Token expiring; reconnect"),void await this.delayRetry();if(l<30)return this.logger.debug("Token will expire soon; reconnect"),void this.options.remote.invalidateCredentials();this.triggerCrudUpload()}else if(this.logger.debug("Sync complete"),t===i)this.updateSyncStatus({connected:!0,lastSyncedAt:new Date,priorityStatusEntries:[],dataFlow:{downloadError:void 0}});else if(r===t){const n=await this.applyCheckpoint(t,l);if(n.endIteration)return;n.applied&&(i=t)}}this.logger.debug("Stream input empty")}async rustSyncIteration(l,n){const u=this,e=this.options.adapter,t=this.options.remote;let r=null,i=!1;const s=new AbortController;l.addEventListener("abort",(()=>s.abort()));let o=null;async function a(l,n){const u=await e.control(l,n??null);await async function(l){for(const n of l)await c(n)}(JSON.parse(u))}async function c(l){if("LogLine"in l)switch(l.LogLine.severity){case"DEBUG":u.logger.debug(l.LogLine.line);break;case"INFO":u.logger.info(l.LogLine.line);break;case"WARNING":u.logger.warn(l.LogLine.line)}else if("UpdateSyncStatus"in l){function e(l){return{priority:l.priority,hasSynced:l.has_synced??void 0,lastSyncedAt:null!=l?.last_synced_at?new Date(1e3*l.last_synced_at):void 0}}const c=l.UpdateSyncStatus.status,h=c.priority_status.find((l=>l.priority==E)),d=null!=h?e(h):null;u.updateSyncStatus({connected:c.connected,connecting:c.connecting,dataFlow:{downloading:null!=c.downloading,downloadProgress:c.downloading?.buckets},lastSyncedAt:d?.lastSyncedAt,hasSynced:d?.hasSynced,priorityStatusEntries:c.priority_status.map(e)})}else if("EstablishSyncStream"in l){if(null!=r)throw"Unexpected request to establish sync stream, already connected";r=async function(l){const e={path:"/sync/stream",abortSignal:s.signal,data:l.request};o=n.connectionMethod==cu.HTTP?await t.postStreamRaw(e,(l=>"string"==typeof l?{command:k.PROCESS_TEXT_LINE,payload:l}:l)):await t.socketStreamRaw({...e,fetchStrategy:n.fetchStrategy},(l=>l instanceof Uint8Array?{command:k.PROCESS_BSON_LINE,payload:l}:l)),u.updateSyncStatus({connected:!0});try{for(;!o.closed;){const l=await o.read();if(null==l)return;await a(l.command,l.payload),i||(u.triggerCrudUpload(),i=!0)}}finally{const l=o;o=null,await l.close()}}(l.EstablishSyncStream)}else"FetchCredentials"in l?l.FetchCredentials.did_expire?t.invalidateCredentials():(t.invalidateCredentials(),t.fetchCredentials().then((l=>{o?.enqueueData({command:k.NOTIFY_TOKEN_REFRESHED})}),(l=>{u.logger.warn("Could not prefetch credentials",l)}))):"CloseSyncStream"in l?s.abort():"FlushFileSystem"in l||"DidCompleteSync"in l&&u.updateSyncStatus({dataFlow:{downloadError:void 0}})}try{await a(k.START,JSON.stringify({parameters:n.params})),this.notifyCompletedUploads=()=>{o?.enqueueData({command:k.NOTIFY_CRUD_UPLOAD_COMPLETED})},await r}finally{this.notifyCompletedUploads=void 0,await async function(){await a(k.STOP)}()}}async updateSyncStatusForStartingCheckpoint(l){const n=await this.options.adapter.getBucketOperationProgress(),u={};let e=!1;for(const t of l.buckets){const l=n[t.bucket],r=l?.atLast??0,i=l?.sinceLast??0;u[t.bucket]={priority:t.priority??3,at_last:r,since_last:i,target_count:t.count??0},null!=t.count&&t.count<r+i&&(e=!0)}if(e)for(const l in u){const n=u[l];n.at_last=0,n.since_last=0}this.updateSyncStatus({dataFlow:{downloading:!0,downloadProgress:u}})}async applyCheckpoint(l,n){let u=await this.options.adapter.syncLocalDatabase(l);const e=this.pendingCrudUpload;if(!u.checkpointValid)return this.logger.debug("Checksum mismatch in checkpoint, will reconnect"),await new Promise((l=>setTimeout(l,50))),{applied:!1,endIteration:!0};if(!u.ready&&null!=e){if(this.logger.debug("Could not apply checkpoint due to local data. Waiting for in-progress upload before retrying."),await Promise.race([e,(t=n,new Promise((l=>{t.aborted?l():t.onabort=()=>l()})))]),n.aborted)return{applied:!1,endIteration:!0};u=await this.options.adapter.syncLocalDatabase(l)}var t;return u.checkpointValid&&u.ready?(this.logger.debug("validated checkpoint",l),this.updateSyncStatus({connected:!0,lastSyncedAt:new Date,dataFlow:{downloading:!1,downloadProgress:null,downloadError:void 0}}),{applied:!0,endIteration:!1}):(this.logger.debug("Could not apply checkpoint. Waiting for next sync complete line."),{applied:!1,endIteration:!1})}updateSyncStatus(l){const n=new v({connected:l.connected??this.syncStatus.connected,connecting:!l.connected&&(l.connecting??this.syncStatus.connecting),lastSyncedAt:l.lastSyncedAt??this.syncStatus.lastSyncedAt,dataFlow:{...this.syncStatus.dataFlowStatus,...l.dataFlow},priorityStatusEntries:l.priorityStatusEntries??this.syncStatus.priorityStatusEntries});this.syncStatus.isEqual(n)||(this.syncStatus=n,this.iterateListeners((l=>l.statusChanged?.(n)))),this.iterateListeners((n=>n.statusUpdated?.(l)))}async delayRetry(l){return new Promise((n=>{if(l?.aborted)return void n();const{retryDelayMs:u}=this.options;let e;const t=()=>{n(),e&&(clearTimeout(e),e=void 0),l?.removeEventListener("abort",t)};l?.addEventListener("abort",t,{once:!0}),e=setTimeout(t,u)}))}}const Eu=/(^ps_data__|^ps_data_local__)/,wu={clearLocal:!0},vu={disconnect:!0},bu=30,Su={retryDelayMs:5e3,logger:y.get("PowerSyncDatabase"),crudUploadThrottleMs:fu},Tu=100,Ru=12e4,_u=l=>"object"==typeof l&&A(l.database);class Au extends S{options;static transactionMutex=new t;closed;ready;currentStatus;sdkVersion;bucketStorageAdapter;_isReadyPromise;connectionManager;get syncStreamImplementation(){return this.connectionManager.syncStreamImplementation}_schema;_database;runExclusiveMutex;constructor(l){super(),this.options=l;const{database:n,schema:u}=l;if("function"!=typeof u?.toJSON)throw new Error("The `schema` option should be provided and should be an instance of `Schema`.");if(F(n))this._database=n;else if(O(n))this._database=n.openDB();else{if(!_u(l))throw new Error("The provided `database` option is invalid.");this._database=this.openDBAdapter(l)}this.bucketStorageAdapter=this.generateBucketStorageAdapter(),this.closed=!1,this.currentStatus=new v({}),this.options={...Su,...l},this._schema=u,this.ready=!1,this.sdkVersion="",this.runExclusiveMutex=new t,this.connectionManager=new _({createSyncImplementation:async(l,n)=>(await this.waitForReady(),this.runExclusive((async()=>{const u=this.generateSyncStreamImplementation(l,this.resolvedConnectionOptions(n)),e=u.registerListener({statusChanged:l=>{this.currentStatus=new v({...l.toJSON(),hasSynced:this.currentStatus?.hasSynced||!!l.lastSyncedAt}),this.iterateListeners((l=>l.statusChanged?.(this.currentStatus)))}});return await u.waitForReady(),{sync:u,onDispose:e}}))),logger:this.logger}),this._isReadyPromise=this.initialize()}get schema(){return this._schema}get database(){return this._database}get connected(){return this.currentStatus?.connected||!1}get connecting(){return this.currentStatus?.connecting||!1}async waitForReady(){this.ready||await this._isReadyPromise}async waitForFirstSync(l){const n=l instanceof AbortSignal?l:l?.signal,u=l&&"priority"in l?l.priority:void 0,e=void 0===u?l=>l.hasSynced:l=>l.statusForPriority(u).hasSynced;if(!e(this.currentStatus))return new Promise((l=>{const u=this.registerListener({statusChanged:n=>{e(n)&&(u(),l())}});n?.addEventListener("abort",(()=>{u(),l()}))}))}async initialize(){await this._initialize(),await this.bucketStorageAdapter.init(),await this._loadVersion(),await this.updateSchema(this.options.schema),await this.updateHasSynced(),await this.database.execute("PRAGMA RECURSIVE_TRIGGERS=TRUE"),this.ready=!0,this.iterateListeners((l=>l.initialized?.()))}async _loadVersion(){try{const{version:l}=await this.database.get("SELECT powersync_rs_version() as version");this.sdkVersion=l}catch(l){throw new Error(`The powersync extension is not loaded correctly. Details: ${l.message}`)}let l;try{l=this.sdkVersion.split(/[.\/]/).slice(0,3).map((l=>parseInt(l)))}catch(l){throw new Error(`Unsupported powersync extension version. Need >=0.3.11 <1.0.0, got: ${this.sdkVersion}. Details: ${l.message}`)}if(0!=l[0]||l[1]<3||3==l[1]&&l[2]<11)throw new Error(`Unsupported powersync extension version. Need >=0.3.11 <1.0.0, got: ${this.sdkVersion}`)}async updateHasSynced(){const l=await this.database.getAll("SELECT priority, last_synced_at FROM ps_sync_state ORDER BY priority DESC");let n;const u=[];for(const{priority:e,last_synced_at:t}of l){const l=new Date(t+"Z");e==E?n=l:u.push({priority:e,hasSynced:!0,lastSyncedAt:l})}const e=null!=n,t=new v({...this.currentStatus.toJSON(),hasSynced:e,priorityStatusEntries:u,lastSyncedAt:n});t.isEqual(this.currentStatus)||(this.currentStatus=t,this.iterateListeners((l=>l.statusChanged?.(this.currentStatus))))}async updateSchema(l){if(this.syncStreamImplementation)throw new Error("Cannot update schema while connected");try{l.validate()}catch(l){this.options.logger?.warn("Schema validation failed. Unexpected behaviour could occur",l)}this._schema=l,await this.database.execute("SELECT powersync_replace_schema(?)",[JSON.stringify(this.schema.toJSON())]),await this.database.refreshSchema(),this.iterateListeners((async n=>n.schemaChanged?.(l)))}get logger(){return this.options.logger}async init(){return this.waitForReady()}resolvedConnectionOptions(l){return{...l,retryDelayMs:l?.retryDelayMs??this.options.retryDelayMs??this.options.retryDelay??pu,crudUploadThrottleMs:l?.crudUploadThrottleMs??this.options.crudUploadThrottleMs??fu}}runExclusive(l){return this.runExclusiveMutex.runExclusive(l)}async connect(l,n){return this.connectionManager.connect(l,n)}async disconnect(){return this.connectionManager.disconnect()}async disconnectAndClear(l=wu){await this.disconnect(),await this.waitForReady();const{clearLocal:n}=l;await this.database.writeTransaction((async l=>{await l.execute("SELECT powersync_clear(?)",[n?1:0])})),this.currentStatus=new v({}),this.iterateListeners((l=>l.statusChanged?.(this.currentStatus)))}async close(l=vu){if(await this.waitForReady(),this.closed)return;const{disconnect:n}=l;n&&await this.disconnect(),await this.connectionManager.close(),await this.database.close(),this.closed=!0}async getUploadQueueStats(l){return this.readTransaction((async n=>{if(l){const l=(await n.execute(`SELECT SUM(cast(data as blob) + 20) as size, count(*) as count FROM ${I.CRUD}`)).rows.item(0);return new b(l?.count??0,l?.size??0)}{const l=(await n.execute(`SELECT count(*) as count FROM ${I.CRUD}`)).rows.item(0);return new b(l?.count??0)}}))}async getCrudBatch(l=100){const n=(await this.getAll(`SELECT id, tx_id, data FROM ${I.CRUD} ORDER BY id ASC LIMIT ?`,[l+1])).map((l=>x.fromRow(l)))??[];let u=!1;if(n.length>l&&(n.pop(),u=!0),0==n.length)return null;const e=n[n.length-1];return new U(n,u,(async l=>this.handleCrudCheckpoint(e.clientId,l)))}async getNextCrudTransaction(){return await this.readTransaction((async l=>{const n=await l.getOptional(`SELECT id, tx_id, data FROM ${I.CRUD} ORDER BY id ASC LIMIT 1`);if(!n)return null;const u=n.tx_id;let e;if(u){e=(await l.getAll(`SELECT id, tx_id, data FROM ${I.CRUD} WHERE tx_id = ? ORDER BY id ASC`,[u])).map((l=>x.fromRow(l)))}else e=[x.fromRow(n)];const t=e[e.length-1];return new P(e,(async l=>this.handleCrudCheckpoint(t.clientId,l)),u)}))}async getClientId(){return this.bucketStorageAdapter.getClientId()}async handleCrudCheckpoint(l,n){return this.writeTransaction((async u=>{if(await u.execute(`DELETE FROM ${I.CRUD} WHERE id <= ?`,[l]),n){const l=await u.execute(`SELECT 1 FROM ${I.CRUD} LIMIT 1`);l.rows?.length||await u.execute(`UPDATE ${I.BUCKETS} SET target_op = CAST(? as INTEGER) WHERE name='$local'`,[n])}else await u.execute(`UPDATE ${I.BUCKETS} SET target_op = CAST(? as INTEGER) WHERE name='$local'`,[this.bucketStorageAdapter.getMaxOpId()])}))}async execute(l,n){return await this.waitForReady(),this.database.execute(l,n)}async executeRaw(l,n){return await this.waitForReady(),this.database.executeRaw(l,n)}async executeBatch(l,n){return await this.waitForReady(),this.database.executeBatch(l,n)}async getAll(l,n){return await this.waitForReady(),this.database.getAll(l,n)}async getOptional(l,n){return await this.waitForReady(),this.database.getOptional(l,n)}async get(l,n){return await this.waitForReady(),this.database.get(l,n)}async readLock(l){return await this.waitForReady(),R(Au.transactionMutex,(()=>l(this.database)))}async writeLock(l){return await this.waitForReady(),R(Au.transactionMutex,(async()=>await l(this.database)))}async readTransaction(l,n=12e4){return await this.waitForReady(),this.database.readTransaction((async n=>{const u=await l({...n});return await n.rollback(),u}),{timeoutMs:n})}async writeTransaction(l,n=12e4){return await this.waitForReady(),this.database.writeTransaction((async n=>{const u=await l(n);return await n.commit(),u}),{timeoutMs:n})}watch(l,n,u,e){if(u&&"object"==typeof u&&"onResult"in u){const t=u,r=e;return this.watchWithCallback(l,n,t,r)}const t=u;return this.watchWithAsyncGenerator(l,n,t)}watchWithCallback(l,n,u,e){const{onResult:t,onError:r=l=>this.options.logger?.error(l)}=u??{};if(!t)throw new Error("onResult is required");C((async u=>{try{const i=await this.resolveTables(l,n,e),s=await this.executeReadOnly(l,n);t(s),this.onChangeWithCallback({onChange:async()=>{try{const u=await this.executeReadOnly(l,n);t(u)}catch(l){r?.(l)}},onError:r},{...e??{},tables:i,signal:u})}catch(l){r?.(l)}}),this,e)}watchWithAsyncGenerator(l,n,u){return new d((e=>{const t={onResult:l=>{e.push(l)},onError:l=>{e.fail(l)}};this.watchWithCallback(l,n,t,u),u?.signal?.addEventListener("abort",(()=>{e.stop()}))}))}async resolveTables(l,n,u){const e=u?.tables?[...u.tables]:[];if(!u?.tables){const u=(await this.getAll(`EXPLAIN ${l}`,n)).filter((l=>"OpenRead"==l.opcode&&0==l.p3&&"number"==typeof l.p2)).map((l=>l.p2)),t=await this.getAll("SELECT DISTINCT tbl_name FROM sqlite_master WHERE rootpage IN (SELECT json_each.value FROM json_each(?))",[JSON.stringify(u)]);for(const l of t)e.push(l.tbl_name.replace(Eu,""))}return e}onChange(l,n){if(l&&"object"==typeof l&&"onChange"in l){const u=l,e=n;return this.onChangeWithCallback(u,e)}const u=l;return this.onChangeWithAsyncGenerator(u)}onChangeWithCallback(l,n){const{onChange:u,onError:e=l=>this.options.logger?.error(l)}=l??{};if(!u)throw new Error("onChange is required");const t=n??{},r=new Set((t?.tables??[]).flatMap((l=>[l,`ps_data__${l}`,`ps_data_local__${l}`]))),i=new Set,s=t.throttleMs??30,o=new T((async l=>{await u(l)})),a=function(l,n){let u=null;const e=()=>{l(),u=null};return function(){null==u&&(u=setTimeout(e,n))}}((()=>this.handleTableChanges(i,r,(l=>{t?.signal?.aborted||o.schedule({changedTables:l})}))),s),c=this.database.registerListener({tablesUpdated:async l=>{try{this.processTableUpdates(l,i),a()}catch(l){e?.(l)}}});return t.signal?.addEventListener("abort",(()=>{o.dispose(),c()})),()=>c()}onChangeWithAsyncGenerator(l){const n=l??{};return new d((u=>{const e=this.onChangeWithCallback({onChange:l=>{u.push(l)},onError:l=>{u.fail(l)}},l);return n.signal?.addEventListener("abort",(()=>{u.stop()})),()=>e()}))}handleTableChanges(l,n,u){if(l.size>0){const e=Array.from(l.values()).filter((l=>n.has(l)));e.length&&u(e)}l.clear()}processTableUpdates(l,n){const u=m(l)?l.tables:[l.table];for(const l of u)n.add(l)}async executeReadOnly(l,n){return await this.waitForReady(),this.database.readLock((u=>u.execute(l,n)))}}class Ou{options;constructor(l){this.options=l,l.logger=l.logger??y.get(`PowerSync ${this.options.dbFilename}`)}get schema(){return this.options.schema}generateOptions(){return{database:this.openDB(),...this.options}}getInstance(){const l=this.generateOptions();return this.generateInstance(l)}}function Fu(l,n,u,e){const{onResult:t,onError:r=l=>{}}=u??{};if(!t)throw new Error("onResult is required");C((async u=>{try{const i=n.compile(),s=await l.resolveTables(i.sql,i.parameters,e),o=await n.execute();t(o),l.onChangeWithCallback({onChange:async()=>{try{const l=await n.execute();t(l)}catch(l){r(l)}},onError:r},{...e??{},tables:s,signal:u})}catch(l){r(l)}}),l,e)}const Cu="9223372036854775807";class Iu extends S{db;mutex;logger;tableNames;_hasCompletedSync;updateListener;_clientId;constructor(l,n,u=y.get("SqliteBucketStorage")){super(),this.db=l,this.mutex=n,this.logger=u,this._hasCompletedSync=!1,this.tableNames=new Set,this.updateListener=l.registerListener({tablesUpdated:l=>{g(l).includes(I.CRUD)&&this.iterateListeners((l=>l.crudUpdate?.()))}})}async init(){this._hasCompletedSync=!1;const l=await this.db.getAll("SELECT name FROM sqlite_master WHERE type='table' AND name GLOB 'ps_data_*'");for(const n of l??[])this.tableNames.add(n.name)}async dispose(){this.updateListener?.()}async _getClientId(){return(await this.db.get("SELECT powersync_client_id() as client_id")).client_id}getClientId(){return null==this._clientId&&(this._clientId=this._getClientId()),this._clientId}getMaxOpId(){return Cu}startSession(){}async getBucketStates(){return await this.db.getAll("SELECT name as bucket, cast(last_op as TEXT) as op_id FROM ps_buckets WHERE pending_delete = 0 AND name != '$local'")}async getBucketOperationProgress(){const l=await this.db.getAll("SELECT name, count_at_last, count_since_last FROM ps_buckets");return Object.fromEntries(l.map((l=>[l.name,{atLast:l.count_at_last,sinceLast:l.count_since_last}])))}async saveSyncData(l,n=!1){await this.writeTransaction((async u=>{for(const e of l.buckets){const l=await u.execute("INSERT INTO powersync_operations(op, data) VALUES(?, ?)",["save",JSON.stringify({buckets:[e.toJSON(n)]})]);this.logger.debug("saveSyncData",JSON.stringify(l))}}))}async removeBuckets(l){for(const n of l)await this.deleteBucket(n)}async deleteBucket(l){await this.writeTransaction((async n=>{await n.execute("INSERT INTO powersync_operations(op, data) VALUES(?, ?)",["delete_bucket",l])})),this.logger.debug("done deleting bucket")}async hasCompletedSync(){if(this._hasCompletedSync)return!0;const l=null!=(await this.db.get("SELECT powersync_last_synced_at() as synced_at")).synced_at;return l&&(this._hasCompletedSync=!0),l}async syncLocalDatabase(l,n){const u=await this.validateChecksums(l,n);if(!u.checkpointValid){this.logger.error("Checksums failed for",u.checkpointFailures);for(const l of u.checkpointFailures??[])await this.deleteBucket(l);return{ready:!1,checkpointValid:!1,checkpointFailures:u.checkpointFailures}}let e=l.buckets;void 0!==n&&(e=e.filter((l=>ku(n,l))));const t=e.map((l=>l.bucket));await this.writeTransaction((async u=>{await u.execute("UPDATE ps_buckets SET last_op = ? WHERE name IN (SELECT json_each.value FROM json_each(?))",[l.last_op_id,JSON.stringify(t)]),null==n&&l.write_checkpoint&&await u.execute("UPDATE ps_buckets SET last_op = ? WHERE name = '$local'",[l.write_checkpoint])}));return await this.updateObjectsFromBuckets(l,n)?{ready:!0,checkpointValid:!0}:(this.logger.debug("Not at a consistent checkpoint - cannot update local db"),{ready:!1,checkpointValid:!0})}async updateObjectsFromBuckets(l,n){let u="";if(void 0!==n){const e=[];for(const u of l.buckets)ku(n,u)&&e.push(u.bucket);u=JSON.stringify({priority:n,buckets:e})}return this.writeTransaction((async e=>{const{insertId:t}=await e.execute("INSERT INTO powersync_operations(op, data) VALUES(?, ?)",["sync_local",u]);if(1==t){if(null==n){const n=Object.fromEntries(l.buckets.map((l=>[l.bucket,l.count]))),u=JSON.stringify(n);await e.execute("UPDATE ps_buckets SET count_since_last = 0, count_at_last = ?->name WHERE name != '$local' AND ?->name IS NOT NULL",[u,u])}return!0}return!1}))}async validateChecksums(l,n){if(void 0!==n){const u=l.buckets.filter((l=>ku(n,l)));l={...l,buckets:u}}const u=await this.db.execute("SELECT powersync_validate_checkpoint(?) as result",[JSON.stringify({...l})]),e=u.rows?.item(0);if(this.logger.debug("validateChecksums priority, checkpoint, result item",n,l,e),!e)return{checkpointValid:!1,ready:!1,checkpointFailures:[]};const t=JSON.parse(e.result);return t.valid?{ready:!0,checkpointValid:!0}:{checkpointValid:!1,ready:!1,checkpointFailures:t.failed_buckets}}async updateLocalTarget(l){if(!(await this.db.getAll("SELECT target_op FROM ps_buckets WHERE name = '$local' AND target_op = CAST(? as INTEGER)",[Cu])).length)return!1;const n=await this.db.getAll("SELECT seq FROM sqlite_sequence WHERE name = 'ps_crud'");if(!n.length)return!1;const u=n[0].seq,e=await l();return this.logger.debug(`[updateLocalTarget] Updating target to checkpoint ${e}`),this.writeTransaction((async l=>{const n=await l.execute("SELECT 1 FROM ps_crud LIMIT 1");if(n.rows?.length)return this.logger.debug("updateLocalTarget","ps crud is not empty"),!1;const t=await l.execute("SELECT seq FROM sqlite_sequence WHERE name = 'ps_crud'");if(!t.rows?.length)throw new Error("SQlite Sequence should not be empty");const r=t.rows?.item(0).seq;if(this.logger.debug("seqAfter",JSON.stringify(t.rows?.item(0))),r!=u)return this.logger.debug("seqAfter != seqBefore",r,u),!1;const i=await l.execute("UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'",[e]);return this.logger.debug(["[updateLocalTarget] Response from updating target_op ",JSON.stringify(i)]),!0}))}async nextCrudItem(){const l=await this.db.getOptional("SELECT * FROM ps_crud ORDER BY id ASC LIMIT 1");if(l)return x.fromRow(l)}async hasCrud(){return!!await this.db.getOptional("SELECT 1 FROM ps_crud LIMIT 1")}async getCrudBatch(l=100){if(!await this.hasCrud())return null;const n=await this.db.getAll("SELECT * FROM ps_crud ORDER BY id ASC LIMIT ?",[l]),u=[];for(const l of n)u.push(x.fromRow(l));if(0===u.length)return null;const e=u[u.length-1];return{crud:u,haveMore:!0,complete:async l=>this.writeTransaction((async n=>{if(await n.execute("DELETE FROM ps_crud WHERE id <= ?",[e.clientId]),l){const u=await n.execute("SELECT 1 FROM ps_crud LIMIT 1");u.rows?.length&&await n.execute("UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'",[l])}else await n.execute("UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'",[this.getMaxOpId()])}))}}async writeTransaction(l,n){return this.db.writeTransaction(l,n)}async setTargetCheckpoint(l){}async control(l,n){return await this.writeTransaction((async u=>{const[[e]]=await u.executeRaw("SELECT powersync_control(?, ?)",[l,n]);return e}))}async hasMigratedSubkeys(){const{r:l}=await this.db.get("SELECT EXISTS(SELECT * FROM ps_kv WHERE key = ?) as r",[Iu._subkeyMigrationKey]);return 0!=l}async migrateToFixedSubkeys(){await this.writeTransaction((async l=>{await l.execute("UPDATE ps_oplog SET key = powersync_remove_duplicate_key_encoding(key);"),await l.execute("INSERT OR REPLACE INTO ps_kv (key, value) VALUES (?, ?);",[Iu._subkeyMigrationKey,"1"])}))}static _subkeyMigrationKey="powersync_js_migrated_subkeys"}function ku(l,n){return null!=n.priority&&n.priority<=l}class Lu{buckets;static fromJSON(l){return new Lu(l.buckets.map((l=>q.fromRow(l))))}constructor(l){this.buckets=l}}var Nu;!function(l){l.TEXT="TEXT",l.INTEGER="INTEGER",l.REAL="REAL"}(Nu||(Nu={}));const Uu={type:Nu.TEXT},xu={type:Nu.INTEGER},Pu={type:Nu.REAL},Du=1999,Mu={text:Uu,integer:xu,real:Pu};class Bu{options;constructor(l){this.options=l}get name(){return this.options.name}get type(){return this.options.type}toJSON(){return{name:this.name,type:this.type}}}const qu={ascending:!0};class ju{options;static createAscending(l){return new ju({name:l,ascending:!0})}constructor(l){this.options={...qu,...l}}get name(){return this.options.name}get ascending(){return this.options.ascending}toJSON(l){return{name:this.name,ascending:this.ascending,type:l.columns.find((l=>l.name===this.name))?.type??Nu.TEXT}}}const Qu={columns:[]};class Wu{options;static createAscending(l,n){return new Wu({...l,columns:n.map((l=>ju.createAscending(l)))})}constructor(l){this.options=l,this.options={...Qu,...l}}get name(){return this.options.name}get columns(){return this.options.columns??[]}toJSON(l){return{name:this.name,columns:this.columns.map((n=>n.toJSON(l)))}}}class $u{types;props;tables;constructor(l){if(Array.isArray(l)){for(const n of l)if(""===n.name)throw new Error("It appears you are trying to create a new Schema with an array instead of an object. Passing in an object instead of an array into 'new Schema()' may resolve your issue.");this.tables=l}else this.props=l,this.tables=this.convertToClassicTables(this.props)}validate(){for(const l of this.tables)l.validate()}toJSON(){return{tables:this.tables.map((l=>l.toJSON()))}}convertToClassicTables(l){return Object.entries(l).map((([l,n])=>n.copyWithName(l)))}}const zu={indexes:[],insertOnly:!1,localOnly:!1,trackPrevious:!1,trackMetadata:!1,ignoreEmptyUpdates:!1},Hu=/["'%,.#\s[\]]/;class Vu{options;_mappedColumns;static createLocalOnly(l){return new Vu({...l,localOnly:!0,insertOnly:!1})}static createInsertOnly(l){return new Vu({...l,localOnly:!1,insertOnly:!0})}static createTable(l,n){return new Vu({name:l,columns:n.columns,indexes:n.indexes,localOnly:n.options.localOnly,insertOnly:n.options.insertOnly,viewName:n.options.viewName})}constructor(l,n){this.isTableV1(l)?this.initTableV1(l):this.initTableV2(l,n)}copyWithName(l){return new Vu({...this.options,name:l})}isTableV1(l){return"columns"in l&&Array.isArray(l.columns)}initTableV1(l){this.options={...l,indexes:l.indexes||[]},this.applyDefaultOptions()}initTableV2(l,n){const u=Object.entries(l).map((([l,n])=>new Bu({name:l,type:n.type}))),e=Object.entries(n?.indexes??{}).map((([l,n])=>new Wu({name:l,columns:n.map((l=>new ju({name:l.replace(/^-/,""),ascending:!l.startsWith("-")})))})));this.options={name:"",columns:u,indexes:e,viewName:n?.viewName,insertOnly:n?.insertOnly,localOnly:n?.localOnly,trackPrevious:n?.trackPrevious,trackMetadata:n?.trackMetadata,ignoreEmptyUpdates:n?.ignoreEmptyUpdates},this.applyDefaultOptions(),this._mappedColumns=l}applyDefaultOptions(){this.options.insertOnly??=zu.insertOnly,this.options.localOnly??=zu.localOnly,this.options.trackPrevious??=zu.trackPrevious,this.options.trackMetadata??=zu.trackMetadata,this.options.ignoreEmptyUpdates??=zu.ignoreEmptyUpdates}get name(){return this.options.name}get viewNameOverride(){return this.options.viewName}get viewName(){return this.viewNameOverride??this.name}get columns(){return this.options.columns}get columnMap(){return this._mappedColumns??this.columns.reduce(((l,n)=>(l[n.name]={type:n.type??Nu.TEXT},l)),{})}get indexes(){return this.options.indexes??[]}get localOnly(){return this.options.localOnly}get insertOnly(){return this.options.insertOnly}get trackPrevious(){return this.options.trackPrevious}get trackMetadata(){return this.options.trackMetadata}get ignoreEmptyUpdates(){return this.options.ignoreEmptyUpdates}get internalName(){return this.options.localOnly?`ps_data_local__${this.name}`:`ps_data__${this.name}`}get validName(){return!Hu.test(this.name)&&(null==this.viewNameOverride||!Hu.test(this.viewNameOverride))}validate(){if(Hu.test(this.name))throw new Error(`Invalid characters in table name: ${this.name}`);if(this.viewNameOverride&&Hu.test(this.viewNameOverride))throw new Error(`Invalid characters in view name: ${this.viewNameOverride}`);if(this.columns.length>Du)throw new Error("Table has too many columns. The maximum number of columns is 1999.");if(this.trackMetadata&&this.localOnly)throw new Error("Can't include metadata for local-only tables.");if(0!=this.trackPrevious&&this.localOnly)throw new Error("Can't include old values for local-only tables.");const l=new Set;l.add("id");for(const n of this.columns){const{name:u}=n;if("id"===n.name)throw new Error("An id column is automatically added, custom id columns are not supported");if(l.has(u))throw new Error(`Duplicate column ${u}`);if(Hu.test(u))throw new Error(`Invalid characters in column name: ${n.name}`);l.add(u)}const n=new Set;for(const u of this.indexes){if(n.has(u.name))throw new Error(`Duplicate index ${u.name}`);if(Hu.test(u.name))throw new Error(`Invalid characters in index name: ${u.name}`);for(const n of u.columns)if(!l.has(n.name))throw new Error(`Column ${n.name} not found for index ${u.name}`);n.add(u.name)}}toJSON(){const l=this.trackPrevious;return{name:this.name,view_name:this.viewName,local_only:this.localOnly,insert_only:this.insertOnly,include_old:l&&(l.columns??!0),include_old_only_when_changed:"object"==typeof l&&1==l.onlyWhenChanged,include_metadata:this.trackMetadata,ignore_empty_update:this.ignoreEmptyUpdates,columns:this.columns.map((l=>l.toJSON())),indexes:this.indexes.map((l=>l.toJSON(this)))}}}class Ju extends Vu{}const Gu=y,Xu={TRACE:Gu.TRACE,DEBUG:Gu.DEBUG,INFO:Gu.INFO,TIME:Gu.TIME,WARN:Gu.WARN,ERROR:Gu.ERROR,OFF:Gu.OFF};function Yu(){return y}function Ku(l,n={}){const u=y.get(l);return n.logLevel&&u.setLevel(n.logLevel),u}const Zu=(l,n)=>{let u;if("string"==typeof l)u=l;else{if(n.length>0)throw new Error("You cannot pass parameters to a compiled query.");const e=l.compile();u=e.sql,n=e.parameters}return{sqlStatement:u,parameters:n}};
2456
2456
 
2457
2457
 
2458
2458
  /***/ }),