@powersync/common 0.0.0-dev-20250529141956 → 0.0.0-dev-20250609122429

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.
package/dist/bundle.mjs CHANGED
@@ -3,7 +3,7 @@ const l=new Error("request for lock canceled");var n=function(l,n,u,e){return ne
3
3
  * js-logger - http://github.com/jonnyreeves/js-logger
4
4
  * Jonny Reeves, http://jonnyreeves.co.uk/
5
5
  * js-logger may be freely distributed under the MIT license.
6
- */!function(l){!function(n){var u,e={};e.VERSION="1.6.1";var t={},r=function(l,n){return function(){return n.apply(l,arguments)}},o=function(){var l,n,u=arguments,e=u[0];for(n=1;n<u.length;n++)for(l in u[n])!(l in e)&&u[n].hasOwnProperty(l)&&(e[l]=u[n][l]);return e},i=function(l,n){return{value:l,name:n}};e.TRACE=i(1,"TRACE"),e.DEBUG=i(2,"DEBUG"),e.INFO=i(3,"INFO"),e.TIME=i(4,"TIME"),e.WARN=i(5,"WARN"),e.ERROR=i(8,"ERROR"),e.OFF=i(99,"OFF");var a=function(l){this.context=l,this.setLevel(l.filterLevel),this.log=this.info};a.prototype={setLevel:function(l){l&&"value"in l&&(this.context.filterLevel=l)},getLevel:function(){return this.context.filterLevel},enabledFor:function(l){var n=this.context.filterLevel;return l.value>=n.value},trace:function(){this.invoke(e.TRACE,arguments)},debug:function(){this.invoke(e.DEBUG,arguments)},info:function(){this.invoke(e.INFO,arguments)},warn:function(){this.invoke(e.WARN,arguments)},error:function(){this.invoke(e.ERROR,arguments)},time:function(l){"string"==typeof l&&l.length>0&&this.invoke(e.TIME,[l,"start"])},timeEnd:function(l){"string"==typeof l&&l.length>0&&this.invoke(e.TIME,[l,"end"])},invoke:function(l,n){u&&this.enabledFor(l)&&u(n,o({level:l},this.context))}};var s,c=new a({filterLevel:e.OFF});(s=e).enabledFor=r(c,c.enabledFor),s.trace=r(c,c.trace),s.debug=r(c,c.debug),s.time=r(c,c.time),s.timeEnd=r(c,c.timeEnd),s.info=r(c,c.info),s.warn=r(c,c.warn),s.error=r(c,c.error),s.log=s.info,e.setHandler=function(l){u=l},e.setLevel=function(l){for(var n in c.setLevel(l),t)t.hasOwnProperty(n)&&t[n].setLevel(l)},e.getLevel=function(){return c.getLevel()},e.get=function(l){return t[l]||(t[l]=new a(o({name:l},c.context)))},e.createDefaultHandler=function(l){(l=l||{}).formatter=l.formatter||function(l,n){n.name&&l.unshift("["+n.name+"]")};var n={},u=function(l,n){Function.prototype.apply.call(l,console,n)};return"undefined"==typeof console?function(){}:function(t,r){t=Array.prototype.slice.call(t);var o,i=console.log;r.level===e.TIME?(o=(r.name?"["+r.name+"] ":"")+t[0],"start"===t[1]?console.time?console.time(o):n[o]=(new Date).getTime():console.timeEnd?console.timeEnd(o):u(i,[o+": "+((new Date).getTime()-n[o])+"ms"])):(r.level===e.WARN&&console.warn?i=console.warn:r.level===e.ERROR&&console.error?i=console.error:r.level===e.INFO&&console.info?i=console.info:r.level===e.DEBUG&&console.debug?i=console.debug:r.level===e.TRACE&&console.trace&&(i=console.trace),l.formatter(t,r),u(i,t))}},e.useDefaults=function(l){e.setLevel(l&&l.defaultLevel||e.DEBUG),e.setHandler(e.createDefaultHandler(l))},e.setDefaults=e.useDefaults,l.exports?l.exports=e:(e._prevLogger=n.Logger,e.noConflict=function(){return n.Logger=e._prevLogger,e},n.Logger=e)}(r)}(f);var p,y=o(f.exports);function m(l){return"tables"in l}function g(l){return m(l)?l.tables:[l.table]}!function(l){l[l.SQLITE_INSERT=18]="SQLITE_INSERT",l[l.SQLITE_DELETE=9]="SQLITE_DELETE",l[l.SQLITE_UPDATE=23]="SQLITE_UPDATE"}(p||(p={}));const b=2147483647;class v{internal;totalOperations;downloadedOperations;downloadedFraction;constructor(l){this.internal=l;const n=this.untilPriority(b);this.totalOperations=n.totalOperations,this.downloadedOperations=n.downloadedOperations,this.downloadedFraction=n.downloadedFraction}untilPriority(l){let n=0,u=0;for(const e of Object.values(this.internal))e.priority<=l&&(u+=e.sinceLast,n+=e.targetCount-e.atLast);return{totalOperations:n,downloadedOperations:u,downloadedFraction:0==n?0:u/n}}}class E{options;constructor(l){this.options=l}get connected(){return this.options.connected??!1}get connecting(){return this.options.connecting??!1}get lastSyncedAt(){return this.options.lastSyncedAt}get hasSynced(){return this.options.hasSynced}get dataFlowStatus(){return this.options.dataFlow??{downloading:!1,uploading:!1}}get priorityStatusEntries(){return(this.options.priorityStatusEntries??[]).slice().sort(E.comparePriorities)}get downloadProgress(){const l=this.options.dataFlow?.downloadProgress;return null==l?null:new v(l)}statusForPriority(l){for(const n of this.priorityStatusEntries)if(n.priority>=l)return n;return{priority:l,lastSyncedAt:this.lastSyncedAt,hasSynced:this.hasSynced}}isEqual(l){return JSON.stringify(this.options)==JSON.stringify(l.options)}getMessage(){const l=this.dataFlowStatus;return`SyncStatus<connected: ${this.connected} connecting: ${this.connecting} lastSyncedAt: ${this.lastSyncedAt} hasSynced: ${this.hasSynced}. Downloading: ${l.downloading}. Uploading: ${l.uploading}. UploadError: ${l.uploadError}, DownloadError?: ${l.downloadError}>`}toJSON(){return{connected:this.connected,connecting:this.connecting,dataFlow:this.dataFlowStatus,lastSyncedAt:this.lastSyncedAt,hasSynced:this.hasSynced,priorityStatusEntries:this.priorityStatusEntries}}static comparePriorities(l,n){return n.priority-l.priority}}class w{count;size;constructor(l,n=null){this.count=l,this.size=n}toString(){return null==this.size?`UploadQueueStats<count:${this.count}>`:`UploadQueueStats<count: $count size: ${this.size/1024}kB>`}}class _{listeners=new Set;constructor(){}registerListener(l){return this.listeners.add(l),()=>{this.listeners.delete(l)}}iterateListeners(l){for(const n of this.listeners)l(n)}async iterateAsyncListeners(l){for(let n of Array.from(this.listeners.values()))await l(n)}}class S{task;runningTask;pendingTaskParam;isThrottling;closed;constructor(l,n){this.task=l;const{throttleEnabled:u=!0}=n??{};this.isThrottling=u,this.closed=!1}schedule(l){this.closed||(this.isThrottling?this.runningTask?this.pendingTaskParam=l:this.execute(l):this.task(l))}dispose(){this.closed=!0,this.runningTask&&(this.runningTask=void 0)}async execute(l){if(this.runningTask=this.task(l),await this.runningTask,this.runningTask=void 0,this.pendingTaskParam){const l=this.pendingTaskParam;this.pendingTaskParam=void 0,this.execute(l)}}}async function T(l,n,u){return new Promise(((e,t)=>{const r=u?.timeoutMs;let o=!1;const i=r?setTimeout((()=>{o=!0,t(new Error("Timeout waiting for lock"))}),r):void 0;l.runExclusive((async()=>{if(i&&clearTimeout(i),!o)try{e(await n())}catch(l){t(l)}}))}))}class R extends _{options;connectingPromise;syncStreamInitPromise;disconnectingPromise;pendingConnectionOptions;syncStreamImplementation;syncDisposer;constructor(l){super(),this.options=l,this.connectingPromise=null,this.syncStreamInitPromise=null,this.disconnectingPromise=null,this.pendingConnectionOptions=null,this.syncStreamImplementation=null,this.syncDisposer=null}get logger(){return this.options.logger}async close(){await(this.syncStreamImplementation?.dispose()),await(this.syncDisposer?.())}async connect(l,n){const u=!!this.pendingConnectionOptions;this.pendingConnectionOptions={connector:l,options:n??{}},u&&!this.syncStreamImplementation||await this.disconnectInternal();const e=async()=>this.pendingConnectionOptions?(this.connectingPromise=this.connectInternal().finally(e),this.connectingPromise):void(this.connectingPromise=null);return this.connectingPromise??=this.connectInternal().finally(e),this.connectingPromise}async connectInternal(){let l=null;await this.disconnectInternal(),this.syncStreamInitPromise=new Promise((async(n,u)=>{try{if(!this.pendingConnectionOptions)return void this.logger.debug("No pending connection options found, not creating sync stream implementation");if(this.disconnectingPromise)return;const{connector:u,options:e}=this.pendingConnectionOptions;l=e,this.pendingConnectionOptions=null;const{sync:t,onDispose:r}=await this.options.createSyncImplementation(u,e);this.iterateListeners((l=>l.syncStreamCreated?.(t))),this.syncStreamImplementation=t,this.syncDisposer=r,await this.syncStreamImplementation.waitForReady(),n()}catch(l){u(l)}})),await this.syncStreamInitPromise,this.syncStreamInitPromise=null,l&&(await this.disconnectingPromise,this.logger.debug("Attempting to connect to PowerSync instance"),await(this.syncStreamImplementation?.connect(l)),this.syncStreamImplementation?.triggerCrudUpload())}async disconnect(){this.pendingConnectionOptions=null,await this.disconnectInternal()}async disconnectInternal(){if(this.disconnectingPromise)return this.disconnectingPromise;this.disconnectingPromise=this.performDisconnect(),await this.disconnectingPromise,this.disconnectingPromise=null}async performDisconnect(){await this.syncStreamInitPromise;const l=this.syncStreamImplementation;this.syncStreamImplementation=null;const n=this.syncDisposer;this.syncDisposer=null,await(l?.disconnect()),await(l?.dispose()),await(n?.())}}const O=l=>l&&"object"==typeof l&&"dbFilename"in l,A=l=>"function"==typeof l?.openDB,C=l=>"function"==typeof l?.writeTransaction;function F(l,n,u){const e=()=>{const t=new AbortController;let r=null;const o=()=>{t.abort("Abort triggered"),r?.(),r=null,u?.signal?.removeEventListener("abort",o)};u?.signal?.addEventListener("abort",o),r=n.registerListener({schemaChanged:async()=>{o(),setTimeout((()=>e()),0)}}),l(t.signal)};e()}var I,k,P;!function(l){l.DATA="ps_data",l.CRUD="ps_crud",l.BUCKETS="ps_buckets",l.OPLOG="ps_oplog",l.UNTYPED="ps_untyped"}(I||(I={}));class L{crud;haveMore;complete;constructor(l,n,u){this.crud=l,this.haveMore=n,this.complete=u}}!function(l){l.PUT="PUT",l.PATCH="PATCH",l.DELETE="DELETE"}(k||(k={}));class N{clientId;id;op;opData;previousValues;table;transactionId;metadata;static fromRow(l){const n=JSON.parse(l.data);return new N(parseInt(l.id),n.op,n.type,n.id,l.tx_id,n.data,n.old,n.metadata)}constructor(l,n,u,e,t,r,o,i){this.clientId=l,this.id=e,this.op=n,this.opData=r,this.table=u,this.transactionId=t,this.previousValues=o,this.metadata=i}toJSON(){return{op_id:this.clientId,op:this.op,type:this.table,id:this.id,tx_id:this.transactionId,data:this.opData}}equals(l){return JSON.stringify(this.toComparisonArray())==JSON.stringify(l.toComparisonArray())}hashCode(){return JSON.stringify(this.toComparisonArray())}toComparisonArray(){return[this.transactionId,this.clientId,this.op,this.table,this.id,this.opData]}}class x extends L{crud;complete;transactionId;constructor(l,n,u){super(l,!1,n),this.crud=l,this.complete=n,this.transactionId=u}}class U extends Error{reason;constructor(l){super(l),this.reason=l,Object.setPrototypeOf(this,U.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,U)}}!function(l){l[l.CLEAR=1]="CLEAR",l[l.MOVE=2]="MOVE",l[l.PUT=3]="PUT",l[l.REMOVE=4]="REMOVE"}(P||(P={}));class D{value;static fromJSON(l){return new D(P[l])}constructor(l){this.value=l}toJSON(){return Object.entries(P).find((([,l])=>l===this.value))[0]}}class M{op_id;op;checksum;subkey;object_type;object_id;data;static fromRow(l){return new M(l.op_id,D.fromJSON(l.op),l.checksum,"string"==typeof l.subkey?l.subkey:JSON.stringify(l.subkey),l.object_type,l.object_id,l.data)}constructor(l,n,u,e,t,r,o){this.op_id=l,this.op=n,this.checksum=u,this.subkey=e,this.object_type=t,this.object_id=r,this.data=o}toJSON(){return{op_id:this.op_id,op:this.op.toJSON(),object_type:this.object_type,object_id:this.object_id,checksum:this.checksum,data:this.data,subkey:JSON.stringify(this.subkey)}}}class B{bucket;data;has_more;after;next_after;static fromRow(l){return new B(l.bucket,l.data.map((l=>M.fromRow(l))),l.has_more??!1,l.after,l.next_after)}constructor(l,n,u,e,t){this.bucket=l,this.data=n,this.has_more=u,this.after=e,this.next_after=t}toJSON(){return{bucket:this.bucket,has_more:this.has_more,after:this.after,next_after:this.next_after,data:this.data.map((l=>l.toJSON()))}}}var q="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:function(l){return"Symbol("+l+")"};function j(){}var W="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0;function z(l){return"object"==typeof l&&null!==l||"function"==typeof l}var Q=j,$=Promise,H=Promise.prototype.then,V=Promise.resolve.bind($),J=Promise.reject.bind($);function Y(l){return new $(l)}function G(l){return V(l)}function X(l){return J(l)}function K(l,n,u){return H.call(l,n,u)}function Z(l,n,u){K(K(l,n,u),void 0,Q)}function ll(l,n){Z(l,n)}function nl(l,n){Z(l,void 0,n)}function ul(l,n,u){return K(l,n,u)}function el(l){K(l,void 0,Q)}var tl=function(){var l=W&&W.queueMicrotask;if("function"==typeof l)return l;var n=G(void 0);return function(l){return K(n,l)}}();function rl(l,n,u){if("function"!=typeof l)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(l,n,u)}function ol(l,n,u){try{return G(rl(l,n,u))}catch(l){return X(l)}}var il=function(){function l(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}return Object.defineProperty(l.prototype,"length",{get:function(){return this._size},enumerable:!1,configurable:!0}),l.prototype.push=function(l){var n=this._back,u=n;16383===n._elements.length&&(u={_elements:[],_next:void 0}),n._elements.push(l),u!==n&&(this._back=u,n._next=u),++this._size},l.prototype.shift=function(){var l=this._front,n=l,u=this._cursor,e=u+1,t=l._elements,r=t[u];return 16384===e&&(n=l._next,e=0),--this._size,this._cursor=e,l!==n&&(this._front=n),t[u]=void 0,r},l.prototype.forEach=function(l){for(var n=this._cursor,u=this._front,e=u._elements;!(n===e.length&&void 0===u._next||n===e.length&&(n=0,0===(e=(u=u._next)._elements).length));)l(e[n]),++n},l.prototype.peek=function(){var l=this._front,n=this._cursor;return l._elements[n]},l}();function al(l,n){l._ownerReadableStream=n,n._reader=l,"readable"===n._state?hl(l):"closed"===n._state?function(l){hl(l),yl(l)}(l):fl(l,n._storedError)}function sl(l,n){return ae(l._ownerReadableStream,n)}function cl(l){"readable"===l._ownerReadableStream._state?pl(l,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(l,n){fl(l,n)}(l,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),l._ownerReadableStream._reader=void 0,l._ownerReadableStream=void 0}function dl(l){return new TypeError("Cannot "+l+" a stream using a released reader")}function hl(l){l._closedPromise=Y((function(n,u){l._closedPromise_resolve=n,l._closedPromise_reject=u}))}function fl(l,n){hl(l),pl(l,n)}function pl(l,n){void 0!==l._closedPromise_reject&&(el(l._closedPromise),l._closedPromise_reject(n),l._closedPromise_resolve=void 0,l._closedPromise_reject=void 0)}function yl(l){void 0!==l._closedPromise_resolve&&(l._closedPromise_resolve(void 0),l._closedPromise_resolve=void 0,l._closedPromise_reject=void 0)}var ml=q("[[AbortSteps]]"),gl=q("[[ErrorSteps]]"),bl=q("[[CancelSteps]]"),vl=q("[[PullSteps]]"),El=Number.isFinite||function(l){return"number"==typeof l&&isFinite(l)},wl=Math.trunc||function(l){return l<0?Math.ceil(l):Math.floor(l)};function _l(l,n){if(void 0!==l&&("object"!=typeof(u=l)&&"function"!=typeof u))throw new TypeError(n+" is not an object.");var u}function Sl(l,n){if("function"!=typeof l)throw new TypeError(n+" is not a function.")}function Tl(l,n){if(!function(l){return"object"==typeof l&&null!==l||"function"==typeof l}(l))throw new TypeError(n+" is not an object.")}function Rl(l,n,u){if(void 0===l)throw new TypeError("Parameter "+n+" is required in '"+u+"'.")}function Ol(l,n,u){if(void 0===l)throw new TypeError(n+" is required in '"+u+"'.")}function Al(l){return Number(l)}function Cl(l){return 0===l?0:l}function Fl(l,n){var u=Number.MAX_SAFE_INTEGER,e=Number(l);if(e=Cl(e),!El(e))throw new TypeError(n+" is not a finite number");if((e=function(l){return Cl(wl(l))}(e))<0||e>u)throw new TypeError(n+" is outside the accepted range of 0 to "+u+", inclusive");return El(e)&&0!==e?e:0}function Il(l,n){if(!oe(l))throw new TypeError(n+" is not a ReadableStream.")}function kl(l){return new Ml(l)}function Pl(l,n){l._reader._readRequests.push(n)}function Ll(l,n,u){var e=l._reader._readRequests.shift();u?e._closeSteps():e._chunkSteps(n)}function Nl(l){return l._reader._readRequests.length}function xl(l){var n=l._reader;return void 0!==n&&!!Bl(n)}var Ul,Dl,Ml=function(){function l(l){if(Rl(l,1,"ReadableStreamDefaultReader"),Il(l,"First parameter"),ie(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");al(this,l),this._readRequests=new il}return Object.defineProperty(l.prototype,"closed",{get:function(){return Bl(this)?this._closedPromise:X(jl("closed"))},enumerable:!1,configurable:!0}),l.prototype.cancel=function(l){return void 0===l&&(l=void 0),Bl(this)?void 0===this._ownerReadableStream?X(dl("cancel")):sl(this,l):X(jl("cancel"))},l.prototype.read=function(){if(!Bl(this))return X(jl("read"));if(void 0===this._ownerReadableStream)return X(dl("read from"));var l,n,u=Y((function(u,e){l=u,n=e}));return ql(this,{_chunkSteps:function(n){return l({value:n,done:!1})},_closeSteps:function(){return l({value:void 0,done:!0})},_errorSteps:function(l){return n(l)}}),u},l.prototype.releaseLock=function(){if(!Bl(this))throw jl("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");cl(this)}},l}();function Bl(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_readRequests")&&l instanceof Ml)}function ql(l,n){var u=l._ownerReadableStream;u._disturbed=!0,"closed"===u._state?n._closeSteps():"errored"===u._state?n._errorSteps(u._storedError):u._readableStreamController[vl](n)}function jl(l){return new TypeError("ReadableStreamDefaultReader.prototype."+l+" can only be used on a ReadableStreamDefaultReader")}Object.defineProperties(Ml.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(Ml.prototype,q.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0}),"symbol"==typeof q.asyncIterator&&((Ul={})[q.asyncIterator]=function(){return this},Dl=Ul,Object.defineProperty(Dl,q.asyncIterator,{enumerable:!1}));var Wl=function(){function l(l,n){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=l,this._preventCancel=n}return l.prototype.next=function(){var l=this,n=function(){return l._nextSteps()};return this._ongoingPromise=this._ongoingPromise?ul(this._ongoingPromise,n,n):n(),this._ongoingPromise},l.prototype.return=function(l){var n=this,u=function(){return n._returnSteps(l)};return this._ongoingPromise?ul(this._ongoingPromise,u,u):u()},l.prototype._nextSteps=function(){var l=this;if(this._isFinished)return Promise.resolve({value:void 0,done:!0});var n,u,e=this._reader;if(void 0===e._ownerReadableStream)return X(dl("iterate"));var t=Y((function(l,e){n=l,u=e}));return ql(e,{_chunkSteps:function(u){l._ongoingPromise=void 0,tl((function(){return n({value:u,done:!1})}))},_closeSteps:function(){l._ongoingPromise=void 0,l._isFinished=!0,cl(e),n({value:void 0,done:!0})},_errorSteps:function(n){l._ongoingPromise=void 0,l._isFinished=!0,cl(e),u(n)}}),t},l.prototype._returnSteps=function(l){if(this._isFinished)return Promise.resolve({value:l,done:!0});this._isFinished=!0;var n=this._reader;if(void 0===n._ownerReadableStream)return X(dl("finish iterating"));if(!this._preventCancel){var u=sl(n,l);return cl(n),ul(u,(function(){return{value:l,done:!0}}))}return cl(n),G({value:l,done:!0})},l}(),zl={next:function(){return Ql(this)?this._asyncIteratorImpl.next():X($l("next"))},return:function(l){return Ql(this)?this._asyncIteratorImpl.return(l):X($l("return"))}};function Ql(l){if(!z(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_asyncIteratorImpl"))return!1;try{return l._asyncIteratorImpl instanceof Wl}catch(l){return!1}}function $l(l){return new TypeError("ReadableStreamAsyncIterator."+l+" can only be used on a ReadableSteamAsyncIterator")}void 0!==Dl&&Object.setPrototypeOf(zl,Dl);var Hl=Number.isNaN||function(l){return l!=l};function Vl(l){return l.slice()}function Jl(l,n,u,e,t){new Uint8Array(l).set(new Uint8Array(u,e,t),n)}function Yl(l,n,u){if(l.slice)return l.slice(n,u);var e=u-n,t=new ArrayBuffer(e);return Jl(t,0,l,n,e),t}function Gl(l){var n=Yl(l.buffer,l.byteOffset,l.byteOffset+l.byteLength);return new Uint8Array(n)}function Xl(l){var n=l._queue.shift();return l._queueTotalSize-=n.size,l._queueTotalSize<0&&(l._queueTotalSize=0),n.value}function Kl(l,n,u){if("number"!=typeof(e=u)||Hl(e)||e<0||u===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var e;l._queue.push({value:n,size:u}),l._queueTotalSize+=u}function Zl(l){l._queue=new il,l._queueTotalSize=0}var ln=function(){function l(){throw new TypeError("Illegal constructor")}return Object.defineProperty(l.prototype,"view",{get:function(){if(!en(this))throw On("view");return this._view},enumerable:!1,configurable:!0}),l.prototype.respond=function(l){if(!en(this))throw On("respond");if(Rl(l,1,"respond"),l=Fl(l,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,Sn(this._associatedReadableByteStreamController,l)},l.prototype.respondWithNewView=function(l){if(!en(this))throw On("respondWithNewView");if(Rl(l,1,"respondWithNewView"),!ArrayBuffer.isView(l))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");l.buffer,Tn(this._associatedReadableByteStreamController,l)},l}();Object.defineProperties(ln.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(ln.prototype,q.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});var nn=function(){function l(){throw new TypeError("Illegal constructor")}return Object.defineProperty(l.prototype,"byobRequest",{get:function(){if(!un(this))throw An("byobRequest");return wn(this)},enumerable:!1,configurable:!0}),Object.defineProperty(l.prototype,"desiredSize",{get:function(){if(!un(this))throw An("desiredSize");return _n(this)},enumerable:!1,configurable:!0}),l.prototype.close=function(){if(!un(this))throw An("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var l=this._controlledReadableByteStream._state;if("readable"!==l)throw new TypeError("The stream (in "+l+" state) is not in the readable state and cannot be closed");bn(this)},l.prototype.enqueue=function(l){if(!un(this))throw An("enqueue");if(Rl(l,1,"enqueue"),!ArrayBuffer.isView(l))throw new TypeError("chunk must be an array buffer view");if(0===l.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===l.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");var n=this._controlledReadableByteStream._state;if("readable"!==n)throw new TypeError("The stream (in "+n+" state) is not in the readable state and cannot be enqueued to");vn(this,l)},l.prototype.error=function(l){if(void 0===l&&(l=void 0),!un(this))throw An("error");En(this,l)},l.prototype[bl]=function(l){rn(this),Zl(this);var n=this._cancelAlgorithm(l);return gn(this),n},l.prototype[vl]=function(l){var n=this._controlledReadableByteStream;if(this._queueTotalSize>0){var u=this._queue.shift();this._queueTotalSize-=u.byteLength,hn(this);var e=new Uint8Array(u.buffer,u.byteOffset,u.byteLength);l._chunkSteps(e)}else{var t=this._autoAllocateChunkSize;if(void 0!==t){var r=void 0;try{r=new ArrayBuffer(t)}catch(n){return void l._errorSteps(n)}var o={buffer:r,bufferByteLength:t,byteOffset:0,byteLength:t,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}Pl(n,l),tn(this)}},l}();function un(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_controlledReadableByteStream")&&l instanceof nn)}function en(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_associatedReadableByteStreamController")&&l instanceof ln)}function tn(l){var n=function(l){var n=l._controlledReadableByteStream;if("readable"!==n._state)return!1;if(l._closeRequested)return!1;if(!l._started)return!1;if(xl(n)&&Nl(n)>0)return!0;if(kn(n)&&In(n)>0)return!0;var u=_n(l);if(u>0)return!0;return!1}(l);n&&(l._pulling?l._pullAgain=!0:(l._pulling=!0,Z(l._pullAlgorithm(),(function(){l._pulling=!1,l._pullAgain&&(l._pullAgain=!1,tn(l))}),(function(n){En(l,n)}))))}function rn(l){fn(l),l._pendingPullIntos=new il}function on(l,n){var u=!1;"closed"===l._state&&(u=!0);var e=an(n);"default"===n.readerType?Ll(l,e,u):function(l,n,u){var e=l._reader,t=e._readIntoRequests.shift();u?t._closeSteps(n):t._chunkSteps(n)}(l,e,u)}function an(l){var n=l.bytesFilled,u=l.elementSize;return new l.viewConstructor(l.buffer,l.byteOffset,n/u)}function sn(l,n,u,e){l._queue.push({buffer:n,byteOffset:u,byteLength:e}),l._queueTotalSize+=e}function cn(l,n){var u=n.elementSize,e=n.bytesFilled-n.bytesFilled%u,t=Math.min(l._queueTotalSize,n.byteLength-n.bytesFilled),r=n.bytesFilled+t,o=r-r%u,i=t,a=!1;o>e&&(i=o-n.bytesFilled,a=!0);for(var s=l._queue;i>0;){var c=s.peek(),d=Math.min(i,c.byteLength),h=n.byteOffset+n.bytesFilled;Jl(n.buffer,h,c.buffer,c.byteOffset,d),c.byteLength===d?s.shift():(c.byteOffset+=d,c.byteLength-=d),l._queueTotalSize-=d,dn(l,d,n),i-=d}return a}function dn(l,n,u){u.bytesFilled+=n}function hn(l){0===l._queueTotalSize&&l._closeRequested?(gn(l),se(l._controlledReadableByteStream)):tn(l)}function fn(l){null!==l._byobRequest&&(l._byobRequest._associatedReadableByteStreamController=void 0,l._byobRequest._view=null,l._byobRequest=null)}function pn(l){for(;l._pendingPullIntos.length>0;){if(0===l._queueTotalSize)return;var n=l._pendingPullIntos.peek();cn(l,n)&&(mn(l),on(l._controlledReadableByteStream,n))}}function yn(l,n){var u=l._pendingPullIntos.peek();fn(l),"closed"===l._controlledReadableByteStream._state?function(l){var n=l._controlledReadableByteStream;if(kn(n))for(;In(n)>0;)on(n,mn(l))}(l):function(l,n,u){if(dn(0,n,u),!(u.bytesFilled<u.elementSize)){mn(l);var e=u.bytesFilled%u.elementSize;if(e>0){var t=u.byteOffset+u.bytesFilled,r=Yl(u.buffer,t-e,t);sn(l,r,0,r.byteLength)}u.bytesFilled-=e,on(l._controlledReadableByteStream,u),pn(l)}}(l,n,u),tn(l)}function mn(l){return l._pendingPullIntos.shift()}function gn(l){l._pullAlgorithm=void 0,l._cancelAlgorithm=void 0}function bn(l){var n=l._controlledReadableByteStream;if(!l._closeRequested&&"readable"===n._state)if(l._queueTotalSize>0)l._closeRequested=!0;else{if(l._pendingPullIntos.length>0)if(l._pendingPullIntos.peek().bytesFilled>0){var u=new TypeError("Insufficient bytes to fill elements in the given buffer");throw En(l,u),u}gn(l),se(n)}}function vn(l,n){var u=l._controlledReadableByteStream;if(!l._closeRequested&&"readable"===u._state){var e=n.buffer,t=n.byteOffset,r=n.byteLength,o=e;if(l._pendingPullIntos.length>0){var i=l._pendingPullIntos.peek();i.buffer,0,i.buffer=i.buffer}if(fn(l),xl(u))if(0===Nl(u))sn(l,o,t,r);else l._pendingPullIntos.length>0&&mn(l),Ll(u,new Uint8Array(o,t,r),!1);else kn(u)?(sn(l,o,t,r),pn(l)):sn(l,o,t,r);tn(l)}}function En(l,n){var u=l._controlledReadableByteStream;"readable"===u._state&&(rn(l),Zl(l),gn(l),ce(u,n))}function wn(l){if(null===l._byobRequest&&l._pendingPullIntos.length>0){var n=l._pendingPullIntos.peek(),u=new Uint8Array(n.buffer,n.byteOffset+n.bytesFilled,n.byteLength-n.bytesFilled),e=Object.create(ln.prototype);!function(l,n,u){l._associatedReadableByteStreamController=n,l._view=u}(e,l,u),l._byobRequest=e}return l._byobRequest}function _n(l){var n=l._controlledReadableByteStream._state;return"errored"===n?null:"closed"===n?0:l._strategyHWM-l._queueTotalSize}function Sn(l,n){var u=l._pendingPullIntos.peek();if("closed"===l._controlledReadableByteStream._state){if(0!==n)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===n)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(u.bytesFilled+n>u.byteLength)throw new RangeError("bytesWritten out of range")}u.buffer=u.buffer,yn(l,n)}function Tn(l,n){var u=l._pendingPullIntos.peek();if("closed"===l._controlledReadableByteStream._state){if(0!==n.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===n.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(u.byteOffset+u.bytesFilled!==n.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(u.bufferByteLength!==n.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(u.bytesFilled+n.byteLength>u.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");var e=n.byteLength;u.buffer=n.buffer,yn(l,e)}function Rn(l,n,u,e,t,r,o){n._controlledReadableByteStream=l,n._pullAgain=!1,n._pulling=!1,n._byobRequest=null,n._queue=n._queueTotalSize=void 0,Zl(n),n._closeRequested=!1,n._started=!1,n._strategyHWM=r,n._pullAlgorithm=e,n._cancelAlgorithm=t,n._autoAllocateChunkSize=o,n._pendingPullIntos=new il,l._readableStreamController=n,Z(G(u()),(function(){n._started=!0,tn(n)}),(function(l){En(n,l)}))}function On(l){return new TypeError("ReadableStreamBYOBRequest.prototype."+l+" can only be used on a ReadableStreamBYOBRequest")}function An(l){return new TypeError("ReadableByteStreamController.prototype."+l+" can only be used on a ReadableByteStreamController")}function Cn(l){return new Pn(l)}function Fn(l,n){l._reader._readIntoRequests.push(n)}function In(l){return l._reader._readIntoRequests.length}function kn(l){var n=l._reader;return void 0!==n&&!!Ln(n)}Object.defineProperties(nn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(nn.prototype,q.toStringTag,{value:"ReadableByteStreamController",configurable:!0});var Pn=function(){function l(l){if(Rl(l,1,"ReadableStreamBYOBReader"),Il(l,"First parameter"),ie(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!un(l._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");al(this,l),this._readIntoRequests=new il}return Object.defineProperty(l.prototype,"closed",{get:function(){return Ln(this)?this._closedPromise:X(xn("closed"))},enumerable:!1,configurable:!0}),l.prototype.cancel=function(l){return void 0===l&&(l=void 0),Ln(this)?void 0===this._ownerReadableStream?X(dl("cancel")):sl(this,l):X(xn("cancel"))},l.prototype.read=function(l){if(!Ln(this))return X(xn("read"));if(!ArrayBuffer.isView(l))return X(new TypeError("view must be an array buffer view"));if(0===l.byteLength)return X(new TypeError("view must have non-zero byteLength"));if(0===l.buffer.byteLength)return X(new TypeError("view's buffer must have non-zero byteLength"));if(l.buffer,void 0===this._ownerReadableStream)return X(dl("read from"));var n,u,e=Y((function(l,e){n=l,u=e}));return Nn(this,l,{_chunkSteps:function(l){return n({value:l,done:!1})},_closeSteps:function(l){return n({value:l,done:!0})},_errorSteps:function(l){return u(l)}}),e},l.prototype.releaseLock=function(){if(!Ln(this))throw xn("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");cl(this)}},l}();function Ln(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_readIntoRequests")&&l instanceof Pn)}function Nn(l,n,u){var e=l._ownerReadableStream;e._disturbed=!0,"errored"===e._state?u._errorSteps(e._storedError):function(l,n,u){var e=l._controlledReadableByteStream,t=1;n.constructor!==DataView&&(t=n.constructor.BYTES_PER_ELEMENT);var r=n.constructor,o=n.buffer,i={buffer:o,bufferByteLength:o.byteLength,byteOffset:n.byteOffset,byteLength:n.byteLength,bytesFilled:0,elementSize:t,viewConstructor:r,readerType:"byob"};if(l._pendingPullIntos.length>0)return l._pendingPullIntos.push(i),void Fn(e,u);if("closed"!==e._state){if(l._queueTotalSize>0){if(cn(l,i)){var a=an(i);return hn(l),void u._chunkSteps(a)}if(l._closeRequested){var s=new TypeError("Insufficient bytes to fill elements in the given buffer");return En(l,s),void u._errorSteps(s)}}l._pendingPullIntos.push(i),Fn(e,u),tn(l)}else{var c=new r(i.buffer,i.byteOffset,0);u._closeSteps(c)}}(e._readableStreamController,n,u)}function xn(l){return new TypeError("ReadableStreamBYOBReader.prototype."+l+" can only be used on a ReadableStreamBYOBReader")}function Un(l,n){var u=l.highWaterMark;if(void 0===u)return n;if(Hl(u)||u<0)throw new RangeError("Invalid highWaterMark");return u}function Dn(l){var n=l.size;return n||function(){return 1}}function Mn(l,n){_l(l,n);var u=null==l?void 0:l.highWaterMark,e=null==l?void 0:l.size;return{highWaterMark:void 0===u?void 0:Al(u),size:void 0===e?void 0:Bn(e,n+" has member 'size' that")}}function Bn(l,n){return Sl(l,n),function(n){return Al(l(n))}}function qn(l,n,u){return Sl(l,u),function(u){return ol(l,n,[u])}}function jn(l,n,u){return Sl(l,u),function(){return ol(l,n,[])}}function Wn(l,n,u){return Sl(l,u),function(u){return rl(l,n,[u])}}function zn(l,n,u){return Sl(l,u),function(u,e){return ol(l,n,[u,e])}}function Qn(l,n){if(!Jn(l))throw new TypeError(n+" is not a WritableStream.")}Object.defineProperties(Pn.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(Pn.prototype,q.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});var $n="function"==typeof AbortController;var Hn=function(){function l(l,n){void 0===l&&(l={}),void 0===n&&(n={}),void 0===l?l=null:Tl(l,"First parameter");var u,e=Mn(n,"Second parameter"),t=function(l,n){_l(l,n);var u=null==l?void 0:l.abort,e=null==l?void 0:l.close,t=null==l?void 0:l.start,r=null==l?void 0:l.type,o=null==l?void 0:l.write;return{abort:void 0===u?void 0:qn(u,l,n+" has member 'abort' that"),close:void 0===e?void 0:jn(e,l,n+" has member 'close' that"),start:void 0===t?void 0:Wn(t,l,n+" has member 'start' that"),write:void 0===o?void 0:zn(o,l,n+" has member 'write' that"),type:r}}(l,"First parameter");if((u=this)._state="writable",u._storedError=void 0,u._writer=void 0,u._writableStreamController=void 0,u._writeRequests=new il,u._inFlightWriteRequest=void 0,u._closeRequest=void 0,u._inFlightCloseRequest=void 0,u._pendingAbortRequest=void 0,u._backpressure=!1,void 0!==t.type)throw new RangeError("Invalid type is specified");var r=Dn(e);!function(l,n,u,e){var t=Object.create(hu.prototype),r=function(){},o=function(){return G(void 0)},i=function(){return G(void 0)},a=function(){return G(void 0)};void 0!==n.start&&(r=function(){return n.start(t)});void 0!==n.write&&(o=function(l){return n.write(l,t)});void 0!==n.close&&(i=function(){return n.close()});void 0!==n.abort&&(a=function(l){return n.abort(l)});!function(l,n,u,e,t,r,o,i){n._controlledWritableStream=l,l._writableStreamController=n,n._queue=void 0,n._queueTotalSize=void 0,Zl(n),n._abortReason=void 0,n._abortController=function(){if($n)return new AbortController}(),n._started=!1,n._strategySizeAlgorithm=i,n._strategyHWM=o,n._writeAlgorithm=e,n._closeAlgorithm=t,n._abortAlgorithm=r;var a=bu(n);eu(l,a);var s=u();Z(G(s),(function(){n._started=!0,mu(n)}),(function(u){n._started=!0,Kn(l,u)}))}(l,t,r,o,i,a,u,e)}(this,t,Un(e,1),r)}return Object.defineProperty(l.prototype,"locked",{get:function(){if(!Jn(this))throw Eu("locked");return Yn(this)},enumerable:!1,configurable:!0}),l.prototype.abort=function(l){return void 0===l&&(l=void 0),Jn(this)?Yn(this)?X(new TypeError("Cannot abort a stream that already has a writer")):Gn(this,l):X(Eu("abort"))},l.prototype.close=function(){return Jn(this)?Yn(this)?X(new TypeError("Cannot close a stream that already has a writer")):nu(this)?X(new TypeError("Cannot close an already-closing stream")):Xn(this):X(Eu("close"))},l.prototype.getWriter=function(){if(!Jn(this))throw Eu("getWriter");return Vn(this)},l}();function Vn(l){return new tu(l)}function Jn(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_writableStreamController")&&l instanceof Hn)}function Yn(l){return void 0!==l._writer}function Gn(l,n){var u;if("closed"===l._state||"errored"===l._state)return G(void 0);l._writableStreamController._abortReason=n,null===(u=l._writableStreamController._abortController)||void 0===u||u.abort();var e=l._state;if("closed"===e||"errored"===e)return G(void 0);if(void 0!==l._pendingAbortRequest)return l._pendingAbortRequest._promise;var t=!1;"erroring"===e&&(t=!0,n=void 0);var r=Y((function(u,e){l._pendingAbortRequest={_promise:void 0,_resolve:u,_reject:e,_reason:n,_wasAlreadyErroring:t}}));return l._pendingAbortRequest._promise=r,t||Zn(l,n),r}function Xn(l){var n=l._state;if("closed"===n||"errored"===n)return X(new TypeError("The stream (in "+n+" state) is not in the writable state and cannot be closed"));var u,e=Y((function(n,u){var e={_resolve:n,_reject:u};l._closeRequest=e})),t=l._writer;return void 0!==t&&l._backpressure&&"writable"===n&&Pu(t),Kl(u=l._writableStreamController,du,0),mu(u),e}function Kn(l,n){"writable"!==l._state?lu(l):Zn(l,n)}function Zn(l,n){var u=l._writableStreamController;l._state="erroring",l._storedError=n;var e=l._writer;void 0!==e&&au(e,n),!function(l){if(void 0===l._inFlightWriteRequest&&void 0===l._inFlightCloseRequest)return!1;return!0}(l)&&u._started&&lu(l)}function lu(l){l._state="errored",l._writableStreamController[gl]();var n=l._storedError;if(l._writeRequests.forEach((function(l){l._reject(n)})),l._writeRequests=new il,void 0!==l._pendingAbortRequest){var u=l._pendingAbortRequest;if(l._pendingAbortRequest=void 0,u._wasAlreadyErroring)return u._reject(n),void uu(l);Z(l._writableStreamController[ml](u._reason),(function(){u._resolve(),uu(l)}),(function(n){u._reject(n),uu(l)}))}else uu(l)}function nu(l){return void 0!==l._closeRequest||void 0!==l._inFlightCloseRequest}function uu(l){void 0!==l._closeRequest&&(l._closeRequest._reject(l._storedError),l._closeRequest=void 0);var n=l._writer;void 0!==n&&Ou(n,l._storedError)}function eu(l,n){var u=l._writer;void 0!==u&&n!==l._backpressure&&(n?function(l){Cu(l)}(u):Pu(u)),l._backpressure=n}Object.defineProperties(Hn.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(Hn.prototype,q.toStringTag,{value:"WritableStream",configurable:!0});var tu=function(){function l(l){if(Rl(l,1,"WritableStreamDefaultWriter"),Qn(l,"First parameter"),Yn(l))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=l,l._writer=this;var n,u=l._state;if("writable"===u)!nu(l)&&l._backpressure?Cu(this):Iu(this),Tu(this);else if("erroring"===u)Fu(this,l._storedError),Tu(this);else if("closed"===u)Iu(this),Tu(n=this),Au(n);else{var e=l._storedError;Fu(this,e),Ru(this,e)}}return Object.defineProperty(l.prototype,"closed",{get:function(){return ru(this)?this._closedPromise:X(_u("closed"))},enumerable:!1,configurable:!0}),Object.defineProperty(l.prototype,"desiredSize",{get:function(){if(!ru(this))throw _u("desiredSize");if(void 0===this._ownerWritableStream)throw Su("desiredSize");return function(l){var n=l._ownerWritableStream,u=n._state;if("errored"===u||"erroring"===u)return null;if("closed"===u)return 0;return yu(n._writableStreamController)}(this)},enumerable:!1,configurable:!0}),Object.defineProperty(l.prototype,"ready",{get:function(){return ru(this)?this._readyPromise:X(_u("ready"))},enumerable:!1,configurable:!0}),l.prototype.abort=function(l){return void 0===l&&(l=void 0),ru(this)?void 0===this._ownerWritableStream?X(Su("abort")):function(l,n){return Gn(l._ownerWritableStream,n)}(this,l):X(_u("abort"))},l.prototype.close=function(){if(!ru(this))return X(_u("close"));var l=this._ownerWritableStream;return void 0===l?X(Su("close")):nu(l)?X(new TypeError("Cannot close an already-closing stream")):ou(this)},l.prototype.releaseLock=function(){if(!ru(this))throw _u("releaseLock");void 0!==this._ownerWritableStream&&su(this)},l.prototype.write=function(l){return void 0===l&&(l=void 0),ru(this)?void 0===this._ownerWritableStream?X(Su("write to")):cu(this,l):X(_u("write"))},l}();function ru(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_ownerWritableStream")&&l instanceof tu)}function ou(l){return Xn(l._ownerWritableStream)}function iu(l,n){"pending"===l._closedPromiseState?Ou(l,n):function(l,n){Ru(l,n)}(l,n)}function au(l,n){"pending"===l._readyPromiseState?ku(l,n):function(l,n){Fu(l,n)}(l,n)}function su(l){var n=l._ownerWritableStream,u=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");au(l,u),iu(l,u),n._writer=void 0,l._ownerWritableStream=void 0}function cu(l,n){var u=l._ownerWritableStream,e=u._writableStreamController,t=function(l,n){try{return l._strategySizeAlgorithm(n)}catch(n){return gu(l,n),1}}(e,n);if(u!==l._ownerWritableStream)return X(Su("write to"));var r=u._state;if("errored"===r)return X(u._storedError);if(nu(u)||"closed"===r)return X(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===r)return X(u._storedError);var o=function(l){return Y((function(n,u){var e={_resolve:n,_reject:u};l._writeRequests.push(e)}))}(u);return function(l,n,u){try{Kl(l,n,u)}catch(n){return void gu(l,n)}var e=l._controlledWritableStream;if(!nu(e)&&"writable"===e._state){eu(e,bu(l))}mu(l)}(e,n,t),o}Object.defineProperties(tu.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(tu.prototype,q.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});var du={},hu=function(){function l(){throw new TypeError("Illegal constructor")}return Object.defineProperty(l.prototype,"abortReason",{get:function(){if(!fu(this))throw wu("abortReason");return this._abortReason},enumerable:!1,configurable:!0}),Object.defineProperty(l.prototype,"signal",{get:function(){if(!fu(this))throw wu("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal},enumerable:!1,configurable:!0}),l.prototype.error=function(l){if(void 0===l&&(l=void 0),!fu(this))throw wu("error");"writable"===this._controlledWritableStream._state&&vu(this,l)},l.prototype[ml]=function(l){var n=this._abortAlgorithm(l);return pu(this),n},l.prototype[gl]=function(){Zl(this)},l}();function fu(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_controlledWritableStream")&&l instanceof hu)}function pu(l){l._writeAlgorithm=void 0,l._closeAlgorithm=void 0,l._abortAlgorithm=void 0,l._strategySizeAlgorithm=void 0}function yu(l){return l._strategyHWM-l._queueTotalSize}function mu(l){var n=l._controlledWritableStream;if(l._started&&void 0===n._inFlightWriteRequest)if("erroring"!==n._state){if(0!==l._queue.length){var u=l._queue.peek().value;u===du?function(l){var n=l._controlledWritableStream;(function(l){l._inFlightCloseRequest=l._closeRequest,l._closeRequest=void 0})(n),Xl(l);var u=l._closeAlgorithm();pu(l),Z(u,(function(){!function(l){l._inFlightCloseRequest._resolve(void 0),l._inFlightCloseRequest=void 0,"erroring"===l._state&&(l._storedError=void 0,void 0!==l._pendingAbortRequest&&(l._pendingAbortRequest._resolve(),l._pendingAbortRequest=void 0)),l._state="closed";var n=l._writer;void 0!==n&&Au(n)}(n)}),(function(l){!function(l,n){l._inFlightCloseRequest._reject(n),l._inFlightCloseRequest=void 0,void 0!==l._pendingAbortRequest&&(l._pendingAbortRequest._reject(n),l._pendingAbortRequest=void 0),Kn(l,n)}(n,l)}))}(l):function(l,n){var u=l._controlledWritableStream;!function(l){l._inFlightWriteRequest=l._writeRequests.shift()}(u);var e=l._writeAlgorithm(n);Z(e,(function(){!function(l){l._inFlightWriteRequest._resolve(void 0),l._inFlightWriteRequest=void 0}(u);var n=u._state;if(Xl(l),!nu(u)&&"writable"===n){var e=bu(l);eu(u,e)}mu(l)}),(function(n){"writable"===u._state&&pu(l),function(l,n){l._inFlightWriteRequest._reject(n),l._inFlightWriteRequest=void 0,Kn(l,n)}(u,n)}))}(l,u)}}else lu(n)}function gu(l,n){"writable"===l._controlledWritableStream._state&&vu(l,n)}function bu(l){return yu(l)<=0}function vu(l,n){var u=l._controlledWritableStream;pu(l),Zn(u,n)}function Eu(l){return new TypeError("WritableStream.prototype."+l+" can only be used on a WritableStream")}function wu(l){return new TypeError("WritableStreamDefaultController.prototype."+l+" can only be used on a WritableStreamDefaultController")}function _u(l){return new TypeError("WritableStreamDefaultWriter.prototype."+l+" can only be used on a WritableStreamDefaultWriter")}function Su(l){return new TypeError("Cannot "+l+" a stream using a released writer")}function Tu(l){l._closedPromise=Y((function(n,u){l._closedPromise_resolve=n,l._closedPromise_reject=u,l._closedPromiseState="pending"}))}function Ru(l,n){Tu(l),Ou(l,n)}function Ou(l,n){void 0!==l._closedPromise_reject&&(el(l._closedPromise),l._closedPromise_reject(n),l._closedPromise_resolve=void 0,l._closedPromise_reject=void 0,l._closedPromiseState="rejected")}function Au(l){void 0!==l._closedPromise_resolve&&(l._closedPromise_resolve(void 0),l._closedPromise_resolve=void 0,l._closedPromise_reject=void 0,l._closedPromiseState="resolved")}function Cu(l){l._readyPromise=Y((function(n,u){l._readyPromise_resolve=n,l._readyPromise_reject=u})),l._readyPromiseState="pending"}function Fu(l,n){Cu(l),ku(l,n)}function Iu(l){Cu(l),Pu(l)}function ku(l,n){void 0!==l._readyPromise_reject&&(el(l._readyPromise),l._readyPromise_reject(n),l._readyPromise_resolve=void 0,l._readyPromise_reject=void 0,l._readyPromiseState="rejected")}function Pu(l){void 0!==l._readyPromise_resolve&&(l._readyPromise_resolve(void 0),l._readyPromise_resolve=void 0,l._readyPromise_reject=void 0,l._readyPromiseState="fulfilled")}Object.defineProperties(hu.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(hu.prototype,q.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});var Lu="undefined"!=typeof DOMException?DOMException:void 0;var Nu,xu=function(l){if("function"!=typeof l&&"object"!=typeof l)return!1;try{return new l,!0}catch(l){return!1}}(Lu)?Lu:(Nu=function(l,n){this.message=l||"",this.name=n||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)},Nu.prototype=Object.create(Error.prototype),Object.defineProperty(Nu.prototype,"constructor",{value:Nu,writable:!0,configurable:!0}),Nu);function Uu(l,n,u,e,t,r){var o=kl(l),i=Vn(n);l._disturbed=!0;var a=!1,s=G(void 0);return Y((function(c,d){var h,f,p,y;if(void 0!==r){if(h=function(){var u=new xu("Aborted","AbortError"),r=[];e||r.push((function(){return"writable"===n._state?Gn(n,u):G(void 0)})),t||r.push((function(){return"readable"===l._state?ae(l,u):G(void 0)})),v((function(){return Promise.all(r.map((function(l){return l()})))}),!0,u)},r.aborted)return void h();r.addEventListener("abort",h)}if(b(l,o._closedPromise,(function(l){e?E(!0,l):v((function(){return Gn(n,l)}),!0,l)})),b(n,i._closedPromise,(function(n){t?E(!0,n):v((function(){return ae(l,n)}),!0,n)})),f=l,p=o._closedPromise,y=function(){u?E():v((function(){return function(l){var n=l._ownerWritableStream,u=n._state;return nu(n)||"closed"===u?G(void 0):"errored"===u?X(n._storedError):ou(l)}(i)}))},"closed"===f._state?y():ll(p,y),nu(n)||"closed"===n._state){var m=new TypeError("the destination writable stream closed before all data could be piped to it");t?E(!0,m):v((function(){return ae(l,m)}),!0,m)}function g(){var l=s;return K(s,(function(){return l!==s?g():void 0}))}function b(l,n,u){"errored"===l._state?u(l._storedError):nl(n,u)}function v(l,u,e){function t(){Z(l(),(function(){return w(u,e)}),(function(l){return w(!0,l)}))}a||(a=!0,"writable"!==n._state||nu(n)?t():ll(g(),t))}function E(l,u){a||(a=!0,"writable"!==n._state||nu(n)?w(l,u):ll(g(),(function(){return w(l,u)})))}function w(l,n){su(i),cl(o),void 0!==r&&r.removeEventListener("abort",h),l?d(n):c(void 0)}el(Y((function(l,n){!function u(e){e?l():K(a?G(!0):K(i._readyPromise,(function(){return Y((function(l,n){ql(o,{_chunkSteps:function(n){s=K(cu(i,n),void 0,j),l(!1)},_closeSteps:function(){return l(!0)},_errorSteps:n})}))})),u,n)}(!1)})))}))}var Du=function(){function l(){throw new TypeError("Illegal constructor")}return Object.defineProperty(l.prototype,"desiredSize",{get:function(){if(!Mu(this))throw Ju("desiredSize");return $u(this)},enumerable:!1,configurable:!0}),l.prototype.close=function(){if(!Mu(this))throw Ju("close");if(!Hu(this))throw new TypeError("The stream is not in a state that permits close");Wu(this)},l.prototype.enqueue=function(l){if(void 0===l&&(l=void 0),!Mu(this))throw Ju("enqueue");if(!Hu(this))throw new TypeError("The stream is not in a state that permits enqueue");return zu(this,l)},l.prototype.error=function(l){if(void 0===l&&(l=void 0),!Mu(this))throw Ju("error");Qu(this,l)},l.prototype[bl]=function(l){Zl(this);var n=this._cancelAlgorithm(l);return ju(this),n},l.prototype[vl]=function(l){var n=this._controlledReadableStream;if(this._queue.length>0){var u=Xl(this);this._closeRequested&&0===this._queue.length?(ju(this),se(n)):Bu(this),l._chunkSteps(u)}else Pl(n,l),Bu(this)},l}();function Mu(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_controlledReadableStream")&&l instanceof Du)}function Bu(l){qu(l)&&(l._pulling?l._pullAgain=!0:(l._pulling=!0,Z(l._pullAlgorithm(),(function(){l._pulling=!1,l._pullAgain&&(l._pullAgain=!1,Bu(l))}),(function(n){Qu(l,n)}))))}function qu(l){var n=l._controlledReadableStream;return!!Hu(l)&&(!!l._started&&(!!(ie(n)&&Nl(n)>0)||$u(l)>0))}function ju(l){l._pullAlgorithm=void 0,l._cancelAlgorithm=void 0,l._strategySizeAlgorithm=void 0}function Wu(l){if(Hu(l)){var n=l._controlledReadableStream;l._closeRequested=!0,0===l._queue.length&&(ju(l),se(n))}}function zu(l,n){if(Hu(l)){var u=l._controlledReadableStream;if(ie(u)&&Nl(u)>0)Ll(u,n,!1);else{var e=void 0;try{e=l._strategySizeAlgorithm(n)}catch(n){throw Qu(l,n),n}try{Kl(l,n,e)}catch(n){throw Qu(l,n),n}}Bu(l)}}function Qu(l,n){var u=l._controlledReadableStream;"readable"===u._state&&(Zl(l),ju(l),ce(u,n))}function $u(l){var n=l._controlledReadableStream._state;return"errored"===n?null:"closed"===n?0:l._strategyHWM-l._queueTotalSize}function Hu(l){var n=l._controlledReadableStream._state;return!l._closeRequested&&"readable"===n}function Vu(l,n,u,e,t,r,o){n._controlledReadableStream=l,n._queue=void 0,n._queueTotalSize=void 0,Zl(n),n._started=!1,n._closeRequested=!1,n._pullAgain=!1,n._pulling=!1,n._strategySizeAlgorithm=o,n._strategyHWM=r,n._pullAlgorithm=e,n._cancelAlgorithm=t,l._readableStreamController=n,Z(G(u()),(function(){n._started=!0,Bu(n)}),(function(l){Qu(n,l)}))}function Ju(l){return new TypeError("ReadableStreamDefaultController.prototype."+l+" can only be used on a ReadableStreamDefaultController")}function Yu(l,n){return un(l._readableStreamController)?function(l){var n,u,e,t,r,o=kl(l),i=!1,a=!1,s=!1,c=!1,d=!1,h=Y((function(l){r=l}));function f(l){nl(l._closedPromise,(function(n){l===o&&(En(e._readableStreamController,n),En(t._readableStreamController,n),c&&d||r(void 0))}))}function p(){Ln(o)&&(cl(o),f(o=kl(l))),ql(o,{_chunkSteps:function(n){tl((function(){a=!1,s=!1;var u=n,o=n;if(!c&&!d)try{o=Gl(n)}catch(n){return En(e._readableStreamController,n),En(t._readableStreamController,n),void r(ae(l,n))}c||vn(e._readableStreamController,u),d||vn(t._readableStreamController,o),i=!1,a?m():s&&g()}))},_closeSteps:function(){i=!1,c||bn(e._readableStreamController),d||bn(t._readableStreamController),e._readableStreamController._pendingPullIntos.length>0&&Sn(e._readableStreamController,0),t._readableStreamController._pendingPullIntos.length>0&&Sn(t._readableStreamController,0),c&&d||r(void 0)},_errorSteps:function(){i=!1}})}function y(n,u){Bl(o)&&(cl(o),f(o=Cn(l)));var h=u?t:e,p=u?e:t;Nn(o,n,{_chunkSteps:function(n){tl((function(){a=!1,s=!1;var e=u?d:c;if(u?c:d)e||Tn(h._readableStreamController,n);else{var t=void 0;try{t=Gl(n)}catch(n){return En(h._readableStreamController,n),En(p._readableStreamController,n),void r(ae(l,n))}e||Tn(h._readableStreamController,n),vn(p._readableStreamController,t)}i=!1,a?m():s&&g()}))},_closeSteps:function(l){i=!1;var n=u?d:c,e=u?c:d;n||bn(h._readableStreamController),e||bn(p._readableStreamController),void 0!==l&&(n||Tn(h._readableStreamController,l),!e&&p._readableStreamController._pendingPullIntos.length>0&&Sn(p._readableStreamController,0)),n&&e||r(void 0)},_errorSteps:function(){i=!1}})}function m(){if(i)return a=!0,G(void 0);i=!0;var l=wn(e._readableStreamController);return null===l?p():y(l._view,!1),G(void 0)}function g(){if(i)return s=!0,G(void 0);i=!0;var l=wn(t._readableStreamController);return null===l?p():y(l._view,!0),G(void 0)}function b(e){if(c=!0,n=e,d){var t=Vl([n,u]),o=ae(l,t);r(o)}return h}function v(e){if(d=!0,u=e,c){var t=Vl([n,u]),o=ae(l,t);r(o)}return h}function E(){}return e=te(E,m,b),t=te(E,g,v),f(o),[e,t]}(l):function(l){var n,u,e,t,r,o=kl(l),i=!1,a=!1,s=!1,c=!1,d=Y((function(l){r=l}));function h(){return i?(a=!0,G(void 0)):(i=!0,ql(o,{_chunkSteps:function(l){tl((function(){a=!1;var n=l,u=l;s||zu(e._readableStreamController,n),c||zu(t._readableStreamController,u),i=!1,a&&h()}))},_closeSteps:function(){i=!1,s||Wu(e._readableStreamController),c||Wu(t._readableStreamController),s&&c||r(void 0)},_errorSteps:function(){i=!1}}),G(void 0))}function f(e){if(s=!0,n=e,c){var t=Vl([n,u]),o=ae(l,t);r(o)}return d}function p(e){if(c=!0,u=e,s){var t=Vl([n,u]),o=ae(l,t);r(o)}return d}function y(){}return e=ee(y,h,f),t=ee(y,h,p),nl(o._closedPromise,(function(l){Qu(e._readableStreamController,l),Qu(t._readableStreamController,l),s&&c||r(void 0)})),[e,t]}(l)}function Gu(l,n,u){return Sl(l,u),function(u){return ol(l,n,[u])}}function Xu(l,n,u){return Sl(l,u),function(u){return ol(l,n,[u])}}function Ku(l,n,u){return Sl(l,u),function(u){return rl(l,n,[u])}}function Zu(l,n){if("bytes"!==(l=""+l))throw new TypeError(n+" '"+l+"' is not a valid enumeration value for ReadableStreamType");return l}function le(l,n){if("byob"!==(l=""+l))throw new TypeError(n+" '"+l+"' is not a valid enumeration value for ReadableStreamReaderMode");return l}function ne(l,n){_l(l,n);var u=null==l?void 0:l.preventAbort,e=null==l?void 0:l.preventCancel,t=null==l?void 0:l.preventClose,r=null==l?void 0:l.signal;return void 0!==r&&function(l,n){if(!function(l){if("object"!=typeof l||null===l)return!1;try{return"boolean"==typeof l.aborted}catch(l){return!1}}(l))throw new TypeError(n+" is not an AbortSignal.")}(r,n+" has member 'signal' that"),{preventAbort:Boolean(u),preventCancel:Boolean(e),preventClose:Boolean(t),signal:r}}Object.defineProperties(Du.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(Du.prototype,q.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});var ue=function(){function l(l,n){void 0===l&&(l={}),void 0===n&&(n={}),void 0===l?l=null:Tl(l,"First parameter");var u=Mn(n,"Second parameter"),e=function(l,n){_l(l,n);var u=l,e=null==u?void 0:u.autoAllocateChunkSize,t=null==u?void 0:u.cancel,r=null==u?void 0:u.pull,o=null==u?void 0:u.start,i=null==u?void 0:u.type;return{autoAllocateChunkSize:void 0===e?void 0:Fl(e,n+" has member 'autoAllocateChunkSize' that"),cancel:void 0===t?void 0:Gu(t,u,n+" has member 'cancel' that"),pull:void 0===r?void 0:Xu(r,u,n+" has member 'pull' that"),start:void 0===o?void 0:Ku(o,u,n+" has member 'start' that"),type:void 0===i?void 0:Zu(i,n+" has member 'type' that")}}(l,"First parameter");if(re(this),"bytes"===e.type){if(void 0!==u.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(l,n,u){var e=Object.create(nn.prototype),t=function(){},r=function(){return G(void 0)},o=function(){return G(void 0)};void 0!==n.start&&(t=function(){return n.start(e)}),void 0!==n.pull&&(r=function(){return n.pull(e)}),void 0!==n.cancel&&(o=function(l){return n.cancel(l)});var i=n.autoAllocateChunkSize;if(0===i)throw new TypeError("autoAllocateChunkSize must be greater than 0");Rn(l,e,t,r,o,u,i)}(this,e,Un(u,0))}else{var t=Dn(u);!function(l,n,u,e){var t=Object.create(Du.prototype),r=function(){},o=function(){return G(void 0)},i=function(){return G(void 0)};void 0!==n.start&&(r=function(){return n.start(t)}),void 0!==n.pull&&(o=function(){return n.pull(t)}),void 0!==n.cancel&&(i=function(l){return n.cancel(l)}),Vu(l,t,r,o,i,u,e)}(this,e,Un(u,1),t)}}return Object.defineProperty(l.prototype,"locked",{get:function(){if(!oe(this))throw de("locked");return ie(this)},enumerable:!1,configurable:!0}),l.prototype.cancel=function(l){return void 0===l&&(l=void 0),oe(this)?ie(this)?X(new TypeError("Cannot cancel a stream that already has a reader")):ae(this,l):X(de("cancel"))},l.prototype.getReader=function(l){if(void 0===l&&(l=void 0),!oe(this))throw de("getReader");return void 0===function(l,n){_l(l,n);var u=null==l?void 0:l.mode;return{mode:void 0===u?void 0:le(u,n+" has member 'mode' that")}}(l,"First parameter").mode?kl(this):Cn(this)},l.prototype.pipeThrough=function(l,n){if(void 0===n&&(n={}),!oe(this))throw de("pipeThrough");Rl(l,1,"pipeThrough");var u=function(l,n){_l(l,n);var u=null==l?void 0:l.readable;Ol(u,"readable","ReadableWritablePair"),Il(u,n+" has member 'readable' that");var e=null==l?void 0:l.writable;return Ol(e,"writable","ReadableWritablePair"),Qn(e,n+" has member 'writable' that"),{readable:u,writable:e}}(l,"First parameter"),e=ne(n,"Second parameter");if(ie(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Yn(u.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return el(Uu(this,u.writable,e.preventClose,e.preventAbort,e.preventCancel,e.signal)),u.readable},l.prototype.pipeTo=function(l,n){if(void 0===n&&(n={}),!oe(this))return X(de("pipeTo"));if(void 0===l)return X("Parameter 1 is required in 'pipeTo'.");if(!Jn(l))return X(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));var u;try{u=ne(n,"Second parameter")}catch(l){return X(l)}return ie(this)?X(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Yn(l)?X(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Uu(this,l,u.preventClose,u.preventAbort,u.preventCancel,u.signal)},l.prototype.tee=function(){if(!oe(this))throw de("tee");return Vl(Yu(this))},l.prototype.values=function(l){if(void 0===l&&(l=void 0),!oe(this))throw de("values");var n,u,e,t,r,o=function(l,n){_l(l,n);var u=null==l?void 0:l.preventCancel;return{preventCancel:Boolean(u)}}(l,"First parameter");return n=this,u=o.preventCancel,e=kl(n),t=new Wl(e,u),(r=Object.create(zl))._asyncIteratorImpl=t,r},l}();function ee(l,n,u,e,t){void 0===e&&(e=1),void 0===t&&(t=function(){return 1});var r=Object.create(ue.prototype);return re(r),Vu(r,Object.create(Du.prototype),l,n,u,e,t),r}function te(l,n,u){var e=Object.create(ue.prototype);return re(e),Rn(e,Object.create(nn.prototype),l,n,u,0,void 0),e}function re(l){l._state="readable",l._reader=void 0,l._storedError=void 0,l._disturbed=!1}function oe(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_readableStreamController")&&l instanceof ue)}function ie(l){return void 0!==l._reader}function ae(l,n){if(l._disturbed=!0,"closed"===l._state)return G(void 0);if("errored"===l._state)return X(l._storedError);se(l);var u=l._reader;return void 0!==u&&Ln(u)&&(u._readIntoRequests.forEach((function(l){l._closeSteps(void 0)})),u._readIntoRequests=new il),ul(l._readableStreamController[bl](n),j)}function se(l){l._state="closed";var n=l._reader;void 0!==n&&(yl(n),Bl(n)&&(n._readRequests.forEach((function(l){l._closeSteps()})),n._readRequests=new il))}function ce(l,n){l._state="errored",l._storedError=n;var u=l._reader;void 0!==u&&(pl(u,n),Bl(u)?(u._readRequests.forEach((function(l){l._errorSteps(n)})),u._readRequests=new il):(u._readIntoRequests.forEach((function(l){l._errorSteps(n)})),u._readIntoRequests=new il))}function de(l){return new TypeError("ReadableStream.prototype."+l+" can only be used on a ReadableStream")}Object.defineProperties(ue.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(ue.prototype,q.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof q.asyncIterator&&Object.defineProperty(ue.prototype,q.asyncIterator,{value:ue.prototype.values,writable:!0,configurable:!0});try{Object.defineProperty((function(l){return l.byteLength}),"name",{value:"size",configurable:!0})}catch(Ul){}try{Object.defineProperty((function(){return 1}),"name",{value:"size",configurable:!0})}catch(Ul){}function he(l,n){var u;(u=l._transformStreamController)._transformAlgorithm=void 0,u._flushAlgorithm=void 0,gu(l._writable._writableStreamController,n),l._backpressure&&fe(l,!1)}function fe(l,n){void 0!==l._backpressureChangePromise&&l._backpressureChangePromise_resolve(),l._backpressureChangePromise=Y((function(n){l._backpressureChangePromise_resolve=n})),l._backpressure=n}var pe=function(){function l(){throw new TypeError("Illegal constructor")}return Object.defineProperty(l.prototype,"desiredSize",{get:function(){if(!ye(this))throw me("desiredSize");return $u(this._controlledTransformStream._readable._readableStreamController)},enumerable:!1,configurable:!0}),l.prototype.enqueue=function(l){if(void 0===l&&(l=void 0),!ye(this))throw me("enqueue");!function(l,n){var u=l._controlledTransformStream,e=u._readable._readableStreamController;if(!Hu(e))throw new TypeError("Readable side is not in a state that permits enqueue");try{zu(e,n)}catch(l){throw he(u,l),u._readable._storedError}(function(l){return!qu(l)})(e)!==u._backpressure&&fe(u,!0)}(this,l)},l.prototype.error=function(l){if(void 0===l&&(l=void 0),!ye(this))throw me("error");var n;n=l,function(l,n){Qu(l._readable._readableStreamController,n),he(l,n)}(this._controlledTransformStream,n)},l.prototype.terminate=function(){if(!ye(this))throw me("terminate");!function(l){var n=l._controlledTransformStream;Wu(n._readable._readableStreamController);var u=new TypeError("TransformStream terminated");he(n,u)}(this)},l}();function ye(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_controlledTransformStream")&&l instanceof pe)}function me(l){return new TypeError("TransformStreamDefaultController.prototype."+l+" can only be used on a TransformStreamDefaultController")}Object.defineProperties(pe.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(pe.prototype,q.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});for(var ge={},be={byteLength:function(l){var n=Te(l),u=n[0],e=n[1];return 3*(u+e)/4-e},toByteArray:function(l){var n,u,e=Te(l),t=e[0],r=e[1],o=new we(function(l,n,u){return 3*(n+u)/4-u}(0,t,r)),i=0,a=r>0?t-4:t;for(u=0;u<a;u+=4)n=Ee[l.charCodeAt(u)]<<18|Ee[l.charCodeAt(u+1)]<<12|Ee[l.charCodeAt(u+2)]<<6|Ee[l.charCodeAt(u+3)],o[i++]=n>>16&255,o[i++]=n>>8&255,o[i++]=255&n;2===r&&(n=Ee[l.charCodeAt(u)]<<2|Ee[l.charCodeAt(u+1)]>>4,o[i++]=255&n);1===r&&(n=Ee[l.charCodeAt(u)]<<10|Ee[l.charCodeAt(u+1)]<<4|Ee[l.charCodeAt(u+2)]>>2,o[i++]=n>>8&255,o[i++]=255&n);return o},fromByteArray:function(l){for(var n,u=l.length,e=u%3,t=[],r=16383,o=0,i=u-e;o<i;o+=r)t.push(Re(l,o,o+r>i?i:o+r));1===e?(n=l[u-1],t.push(ve[n>>2]+ve[n<<4&63]+"==")):2===e&&(n=(l[u-2]<<8)+l[u-1],t.push(ve[n>>10]+ve[n>>4&63]+ve[n<<2&63]+"="));return t.join("")}},ve=[],Ee=[],we="undefined"!=typeof Uint8Array?Uint8Array:Array,_e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Se=0;Se<64;++Se)ve[Se]=_e[Se],Ee[_e.charCodeAt(Se)]=Se;function Te(l){var n=l.length;if(n%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var u=l.indexOf("=");return-1===u&&(u=n),[u,u===n?0:4-u%4]}function Re(l,n,u){for(var e,t,r=[],o=n;o<u;o+=3)e=(l[o]<<16&16711680)+(l[o+1]<<8&65280)+(255&l[o+2]),r.push(ve[(t=e)>>18&63]+ve[t>>12&63]+ve[t>>6&63]+ve[63&t]);return r.join("")}Ee["-".charCodeAt(0)]=62,Ee["_".charCodeAt(0)]=63;var Oe={
6
+ */!function(l){!function(n){var u,e={};e.VERSION="1.6.1";var t={},r=function(l,n){return function(){return n.apply(l,arguments)}},o=function(){var l,n,u=arguments,e=u[0];for(n=1;n<u.length;n++)for(l in u[n])!(l in e)&&u[n].hasOwnProperty(l)&&(e[l]=u[n][l]);return e},i=function(l,n){return{value:l,name:n}};e.TRACE=i(1,"TRACE"),e.DEBUG=i(2,"DEBUG"),e.INFO=i(3,"INFO"),e.TIME=i(4,"TIME"),e.WARN=i(5,"WARN"),e.ERROR=i(8,"ERROR"),e.OFF=i(99,"OFF");var a=function(l){this.context=l,this.setLevel(l.filterLevel),this.log=this.info};a.prototype={setLevel:function(l){l&&"value"in l&&(this.context.filterLevel=l)},getLevel:function(){return this.context.filterLevel},enabledFor:function(l){var n=this.context.filterLevel;return l.value>=n.value},trace:function(){this.invoke(e.TRACE,arguments)},debug:function(){this.invoke(e.DEBUG,arguments)},info:function(){this.invoke(e.INFO,arguments)},warn:function(){this.invoke(e.WARN,arguments)},error:function(){this.invoke(e.ERROR,arguments)},time:function(l){"string"==typeof l&&l.length>0&&this.invoke(e.TIME,[l,"start"])},timeEnd:function(l){"string"==typeof l&&l.length>0&&this.invoke(e.TIME,[l,"end"])},invoke:function(l,n){u&&this.enabledFor(l)&&u(n,o({level:l},this.context))}};var s,c=new a({filterLevel:e.OFF});(s=e).enabledFor=r(c,c.enabledFor),s.trace=r(c,c.trace),s.debug=r(c,c.debug),s.time=r(c,c.time),s.timeEnd=r(c,c.timeEnd),s.info=r(c,c.info),s.warn=r(c,c.warn),s.error=r(c,c.error),s.log=s.info,e.setHandler=function(l){u=l},e.setLevel=function(l){for(var n in c.setLevel(l),t)t.hasOwnProperty(n)&&t[n].setLevel(l)},e.getLevel=function(){return c.getLevel()},e.get=function(l){return t[l]||(t[l]=new a(o({name:l},c.context)))},e.createDefaultHandler=function(l){(l=l||{}).formatter=l.formatter||function(l,n){n.name&&l.unshift("["+n.name+"]")};var n={},u=function(l,n){Function.prototype.apply.call(l,console,n)};return"undefined"==typeof console?function(){}:function(t,r){t=Array.prototype.slice.call(t);var o,i=console.log;r.level===e.TIME?(o=(r.name?"["+r.name+"] ":"")+t[0],"start"===t[1]?console.time?console.time(o):n[o]=(new Date).getTime():console.timeEnd?console.timeEnd(o):u(i,[o+": "+((new Date).getTime()-n[o])+"ms"])):(r.level===e.WARN&&console.warn?i=console.warn:r.level===e.ERROR&&console.error?i=console.error:r.level===e.INFO&&console.info?i=console.info:r.level===e.DEBUG&&console.debug?i=console.debug:r.level===e.TRACE&&console.trace&&(i=console.trace),l.formatter(t,r),u(i,t))}},e.useDefaults=function(l){e.setLevel(l&&l.defaultLevel||e.DEBUG),e.setHandler(e.createDefaultHandler(l))},e.setDefaults=e.useDefaults,l.exports?l.exports=e:(e._prevLogger=n.Logger,e.noConflict=function(){return n.Logger=e._prevLogger,e},n.Logger=e)}(r)}(f);var p,y=o(f.exports);function m(l){return"tables"in l}function g(l){return m(l)?l.tables:[l.table]}!function(l){l[l.SQLITE_INSERT=18]="SQLITE_INSERT",l[l.SQLITE_DELETE=9]="SQLITE_DELETE",l[l.SQLITE_UPDATE=23]="SQLITE_UPDATE"}(p||(p={}));const b=2147483647;class v{internal;totalOperations;downloadedOperations;downloadedFraction;constructor(l){this.internal=l;const n=this.untilPriority(b);this.totalOperations=n.totalOperations,this.downloadedOperations=n.downloadedOperations,this.downloadedFraction=n.downloadedFraction}untilPriority(l){let n=0,u=0;for(const e of Object.values(this.internal))e.priority<=l&&(u+=e.sinceLast,n+=e.targetCount-e.atLast);return{totalOperations:n,downloadedOperations:u,downloadedFraction:0==n?0:u/n}}}class E{options;constructor(l){this.options=l}get connected(){return this.options.connected??!1}get connecting(){return this.options.connecting??!1}get lastSyncedAt(){return this.options.lastSyncedAt}get hasSynced(){return this.options.hasSynced}get dataFlowStatus(){return this.options.dataFlow??{downloading:!1,uploading:!1}}get priorityStatusEntries(){return(this.options.priorityStatusEntries??[]).slice().sort(E.comparePriorities)}get downloadProgress(){const l=this.options.dataFlow?.downloadProgress;return null==l?null:new v(l)}statusForPriority(l){for(const n of this.priorityStatusEntries)if(n.priority>=l)return n;return{priority:l,lastSyncedAt:this.lastSyncedAt,hasSynced:this.hasSynced}}isEqual(l){const n=(l,n)=>n instanceof Error?{name:n.name,message:n.message,stack:n.stack}:n;return JSON.stringify(this.options,n)==JSON.stringify(l.options,n)}getMessage(){const l=this.dataFlowStatus;return`SyncStatus<connected: ${this.connected} connecting: ${this.connecting} lastSyncedAt: ${this.lastSyncedAt} hasSynced: ${this.hasSynced}. Downloading: ${l.downloading}. Uploading: ${l.uploading}. UploadError: ${l.uploadError}, DownloadError?: ${l.downloadError}>`}toJSON(){return{connected:this.connected,connecting:this.connecting,dataFlow:this.dataFlowStatus,lastSyncedAt:this.lastSyncedAt,hasSynced:this.hasSynced,priorityStatusEntries:this.priorityStatusEntries}}static comparePriorities(l,n){return n.priority-l.priority}}class w{count;size;constructor(l,n=null){this.count=l,this.size=n}toString(){return null==this.size?`UploadQueueStats<count:${this.count}>`:`UploadQueueStats<count: $count size: ${this.size/1024}kB>`}}class _{listeners=new Set;constructor(){}registerListener(l){return this.listeners.add(l),()=>{this.listeners.delete(l)}}iterateListeners(l){for(const n of this.listeners)l(n)}async iterateAsyncListeners(l){for(let n of Array.from(this.listeners.values()))await l(n)}}class S{task;runningTask;pendingTaskParam;isThrottling;closed;constructor(l,n){this.task=l;const{throttleEnabled:u=!0}=n??{};this.isThrottling=u,this.closed=!1}schedule(l){this.closed||(this.isThrottling?this.runningTask?this.pendingTaskParam=l:this.execute(l):this.task(l))}dispose(){this.closed=!0,this.runningTask&&(this.runningTask=void 0)}async execute(l){if(this.runningTask=this.task(l),await this.runningTask,this.runningTask=void 0,this.pendingTaskParam){const l=this.pendingTaskParam;this.pendingTaskParam=void 0,this.execute(l)}}}async function T(l,n,u){return new Promise(((e,t)=>{const r=u?.timeoutMs;let o=!1;const i=r?setTimeout((()=>{o=!0,t(new Error("Timeout waiting for lock"))}),r):void 0;l.runExclusive((async()=>{if(i&&clearTimeout(i),!o)try{e(await n())}catch(l){t(l)}}))}))}class R extends _{options;connectingPromise;syncStreamInitPromise;disconnectingPromise;pendingConnectionOptions;syncStreamImplementation;syncDisposer;constructor(l){super(),this.options=l,this.connectingPromise=null,this.syncStreamInitPromise=null,this.disconnectingPromise=null,this.pendingConnectionOptions=null,this.syncStreamImplementation=null,this.syncDisposer=null}get logger(){return this.options.logger}async close(){await(this.syncStreamImplementation?.dispose()),await(this.syncDisposer?.())}async connect(l,n){const u=!!this.pendingConnectionOptions;this.pendingConnectionOptions={connector:l,options:n??{}},u&&!this.syncStreamImplementation||await this.disconnectInternal();const e=async()=>this.pendingConnectionOptions?(this.connectingPromise=this.connectInternal().catch((()=>{})).finally(e),this.connectingPromise):void(this.connectingPromise=null);return this.connectingPromise??=this.connectInternal().catch((()=>{})).finally(e),this.connectingPromise}async connectInternal(){let l=null;await this.disconnectInternal(),this.syncStreamInitPromise=new Promise((async(n,u)=>{try{if(!this.pendingConnectionOptions)return this.logger.debug("No pending connection options found, not creating sync stream implementation"),void n();if(this.disconnectingPromise)return void n();const{connector:u,options:e}=this.pendingConnectionOptions;l=e,this.pendingConnectionOptions=null;const{sync:t,onDispose:r}=await this.options.createSyncImplementation(u,e);this.iterateListeners((l=>l.syncStreamCreated?.(t))),this.syncStreamImplementation=t,this.syncDisposer=r,await this.syncStreamImplementation.waitForReady(),n()}catch(l){u(l)}})),await this.syncStreamInitPromise,this.syncStreamInitPromise=null,l&&(await this.disconnectingPromise,this.logger.debug("Attempting to connect to PowerSync instance"),await(this.syncStreamImplementation?.connect(l)),this.syncStreamImplementation?.triggerCrudUpload())}async disconnect(){this.pendingConnectionOptions=null,await this.disconnectInternal()}async disconnectInternal(){if(this.disconnectingPromise)return this.disconnectingPromise;this.disconnectingPromise=this.performDisconnect(),await this.disconnectingPromise,this.disconnectingPromise=null}async performDisconnect(){await this.syncStreamInitPromise;const l=this.syncStreamImplementation;this.syncStreamImplementation=null;const n=this.syncDisposer;this.syncDisposer=null,await(l?.disconnect()),await(l?.dispose()),await(n?.())}}const O=l=>l&&"object"==typeof l&&"dbFilename"in l,A=l=>"function"==typeof l?.openDB,C=l=>"function"==typeof l?.writeTransaction;function F(l,n,u){const e=()=>{const t=new AbortController;let r=null;const o=()=>{t.abort("Abort triggered"),r?.(),r=null,u?.signal?.removeEventListener("abort",o)};u?.signal?.addEventListener("abort",o),r=n.registerListener({schemaChanged:async()=>{o(),setTimeout((()=>e()),0)}}),l(t.signal)};e()}var I,k,P;!function(l){l.DATA="ps_data",l.CRUD="ps_crud",l.BUCKETS="ps_buckets",l.OPLOG="ps_oplog",l.UNTYPED="ps_untyped"}(I||(I={}));class L{crud;haveMore;complete;constructor(l,n,u){this.crud=l,this.haveMore=n,this.complete=u}}!function(l){l.PUT="PUT",l.PATCH="PATCH",l.DELETE="DELETE"}(k||(k={}));class N{clientId;id;op;opData;previousValues;table;transactionId;metadata;static fromRow(l){const n=JSON.parse(l.data);return new N(parseInt(l.id),n.op,n.type,n.id,l.tx_id,n.data,n.old,n.metadata)}constructor(l,n,u,e,t,r,o,i){this.clientId=l,this.id=e,this.op=n,this.opData=r,this.table=u,this.transactionId=t,this.previousValues=o,this.metadata=i}toJSON(){return{op_id:this.clientId,op:this.op,type:this.table,id:this.id,tx_id:this.transactionId,data:this.opData}}equals(l){return JSON.stringify(this.toComparisonArray())==JSON.stringify(l.toComparisonArray())}hashCode(){return JSON.stringify(this.toComparisonArray())}toComparisonArray(){return[this.transactionId,this.clientId,this.op,this.table,this.id,this.opData]}}class x extends L{crud;complete;transactionId;constructor(l,n,u){super(l,!1,n),this.crud=l,this.complete=n,this.transactionId=u}}class U extends Error{reason;constructor(l){super(l),this.reason=l,Object.setPrototypeOf(this,U.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,U)}}!function(l){l[l.CLEAR=1]="CLEAR",l[l.MOVE=2]="MOVE",l[l.PUT=3]="PUT",l[l.REMOVE=4]="REMOVE"}(P||(P={}));class D{value;static fromJSON(l){return new D(P[l])}constructor(l){this.value=l}toJSON(){return Object.entries(P).find((([,l])=>l===this.value))[0]}}class M{op_id;op;checksum;subkey;object_type;object_id;data;static fromRow(l){return new M(l.op_id,D.fromJSON(l.op),l.checksum,"string"==typeof l.subkey?l.subkey:JSON.stringify(l.subkey),l.object_type,l.object_id,l.data)}constructor(l,n,u,e,t,r,o){this.op_id=l,this.op=n,this.checksum=u,this.subkey=e,this.object_type=t,this.object_id=r,this.data=o}toJSON(){return{op_id:this.op_id,op:this.op.toJSON(),object_type:this.object_type,object_id:this.object_id,checksum:this.checksum,data:this.data,subkey:JSON.stringify(this.subkey)}}}class B{bucket;data;has_more;after;next_after;static fromRow(l){return new B(l.bucket,l.data.map((l=>M.fromRow(l))),l.has_more??!1,l.after,l.next_after)}constructor(l,n,u,e,t){this.bucket=l,this.data=n,this.has_more=u,this.after=e,this.next_after=t}toJSON(){return{bucket:this.bucket,has_more:this.has_more,after:this.after,next_after:this.next_after,data:this.data.map((l=>l.toJSON()))}}}var q="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:function(l){return"Symbol("+l+")"};function j(){}var W="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0;function z(l){return"object"==typeof l&&null!==l||"function"==typeof l}var Q=j,$=Promise,H=Promise.prototype.then,V=Promise.resolve.bind($),J=Promise.reject.bind($);function Y(l){return new $(l)}function G(l){return V(l)}function X(l){return J(l)}function K(l,n,u){return H.call(l,n,u)}function Z(l,n,u){K(K(l,n,u),void 0,Q)}function ll(l,n){Z(l,n)}function nl(l,n){Z(l,void 0,n)}function ul(l,n,u){return K(l,n,u)}function el(l){K(l,void 0,Q)}var tl=function(){var l=W&&W.queueMicrotask;if("function"==typeof l)return l;var n=G(void 0);return function(l){return K(n,l)}}();function rl(l,n,u){if("function"!=typeof l)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(l,n,u)}function ol(l,n,u){try{return G(rl(l,n,u))}catch(l){return X(l)}}var il=function(){function l(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}return Object.defineProperty(l.prototype,"length",{get:function(){return this._size},enumerable:!1,configurable:!0}),l.prototype.push=function(l){var n=this._back,u=n;16383===n._elements.length&&(u={_elements:[],_next:void 0}),n._elements.push(l),u!==n&&(this._back=u,n._next=u),++this._size},l.prototype.shift=function(){var l=this._front,n=l,u=this._cursor,e=u+1,t=l._elements,r=t[u];return 16384===e&&(n=l._next,e=0),--this._size,this._cursor=e,l!==n&&(this._front=n),t[u]=void 0,r},l.prototype.forEach=function(l){for(var n=this._cursor,u=this._front,e=u._elements;!(n===e.length&&void 0===u._next||n===e.length&&(n=0,0===(e=(u=u._next)._elements).length));)l(e[n]),++n},l.prototype.peek=function(){var l=this._front,n=this._cursor;return l._elements[n]},l}();function al(l,n){l._ownerReadableStream=n,n._reader=l,"readable"===n._state?hl(l):"closed"===n._state?function(l){hl(l),yl(l)}(l):fl(l,n._storedError)}function sl(l,n){return ae(l._ownerReadableStream,n)}function cl(l){"readable"===l._ownerReadableStream._state?pl(l,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(l,n){fl(l,n)}(l,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),l._ownerReadableStream._reader=void 0,l._ownerReadableStream=void 0}function dl(l){return new TypeError("Cannot "+l+" a stream using a released reader")}function hl(l){l._closedPromise=Y((function(n,u){l._closedPromise_resolve=n,l._closedPromise_reject=u}))}function fl(l,n){hl(l),pl(l,n)}function pl(l,n){void 0!==l._closedPromise_reject&&(el(l._closedPromise),l._closedPromise_reject(n),l._closedPromise_resolve=void 0,l._closedPromise_reject=void 0)}function yl(l){void 0!==l._closedPromise_resolve&&(l._closedPromise_resolve(void 0),l._closedPromise_resolve=void 0,l._closedPromise_reject=void 0)}var ml=q("[[AbortSteps]]"),gl=q("[[ErrorSteps]]"),bl=q("[[CancelSteps]]"),vl=q("[[PullSteps]]"),El=Number.isFinite||function(l){return"number"==typeof l&&isFinite(l)},wl=Math.trunc||function(l){return l<0?Math.ceil(l):Math.floor(l)};function _l(l,n){if(void 0!==l&&("object"!=typeof(u=l)&&"function"!=typeof u))throw new TypeError(n+" is not an object.");var u}function Sl(l,n){if("function"!=typeof l)throw new TypeError(n+" is not a function.")}function Tl(l,n){if(!function(l){return"object"==typeof l&&null!==l||"function"==typeof l}(l))throw new TypeError(n+" is not an object.")}function Rl(l,n,u){if(void 0===l)throw new TypeError("Parameter "+n+" is required in '"+u+"'.")}function Ol(l,n,u){if(void 0===l)throw new TypeError(n+" is required in '"+u+"'.")}function Al(l){return Number(l)}function Cl(l){return 0===l?0:l}function Fl(l,n){var u=Number.MAX_SAFE_INTEGER,e=Number(l);if(e=Cl(e),!El(e))throw new TypeError(n+" is not a finite number");if((e=function(l){return Cl(wl(l))}(e))<0||e>u)throw new TypeError(n+" is outside the accepted range of 0 to "+u+", inclusive");return El(e)&&0!==e?e:0}function Il(l,n){if(!oe(l))throw new TypeError(n+" is not a ReadableStream.")}function kl(l){return new Ml(l)}function Pl(l,n){l._reader._readRequests.push(n)}function Ll(l,n,u){var e=l._reader._readRequests.shift();u?e._closeSteps():e._chunkSteps(n)}function Nl(l){return l._reader._readRequests.length}function xl(l){var n=l._reader;return void 0!==n&&!!Bl(n)}var Ul,Dl,Ml=function(){function l(l){if(Rl(l,1,"ReadableStreamDefaultReader"),Il(l,"First parameter"),ie(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");al(this,l),this._readRequests=new il}return Object.defineProperty(l.prototype,"closed",{get:function(){return Bl(this)?this._closedPromise:X(jl("closed"))},enumerable:!1,configurable:!0}),l.prototype.cancel=function(l){return void 0===l&&(l=void 0),Bl(this)?void 0===this._ownerReadableStream?X(dl("cancel")):sl(this,l):X(jl("cancel"))},l.prototype.read=function(){if(!Bl(this))return X(jl("read"));if(void 0===this._ownerReadableStream)return X(dl("read from"));var l,n,u=Y((function(u,e){l=u,n=e}));return ql(this,{_chunkSteps:function(n){return l({value:n,done:!1})},_closeSteps:function(){return l({value:void 0,done:!0})},_errorSteps:function(l){return n(l)}}),u},l.prototype.releaseLock=function(){if(!Bl(this))throw jl("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");cl(this)}},l}();function Bl(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_readRequests")&&l instanceof Ml)}function ql(l,n){var u=l._ownerReadableStream;u._disturbed=!0,"closed"===u._state?n._closeSteps():"errored"===u._state?n._errorSteps(u._storedError):u._readableStreamController[vl](n)}function jl(l){return new TypeError("ReadableStreamDefaultReader.prototype."+l+" can only be used on a ReadableStreamDefaultReader")}Object.defineProperties(Ml.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(Ml.prototype,q.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0}),"symbol"==typeof q.asyncIterator&&((Ul={})[q.asyncIterator]=function(){return this},Dl=Ul,Object.defineProperty(Dl,q.asyncIterator,{enumerable:!1}));var Wl=function(){function l(l,n){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=l,this._preventCancel=n}return l.prototype.next=function(){var l=this,n=function(){return l._nextSteps()};return this._ongoingPromise=this._ongoingPromise?ul(this._ongoingPromise,n,n):n(),this._ongoingPromise},l.prototype.return=function(l){var n=this,u=function(){return n._returnSteps(l)};return this._ongoingPromise?ul(this._ongoingPromise,u,u):u()},l.prototype._nextSteps=function(){var l=this;if(this._isFinished)return Promise.resolve({value:void 0,done:!0});var n,u,e=this._reader;if(void 0===e._ownerReadableStream)return X(dl("iterate"));var t=Y((function(l,e){n=l,u=e}));return ql(e,{_chunkSteps:function(u){l._ongoingPromise=void 0,tl((function(){return n({value:u,done:!1})}))},_closeSteps:function(){l._ongoingPromise=void 0,l._isFinished=!0,cl(e),n({value:void 0,done:!0})},_errorSteps:function(n){l._ongoingPromise=void 0,l._isFinished=!0,cl(e),u(n)}}),t},l.prototype._returnSteps=function(l){if(this._isFinished)return Promise.resolve({value:l,done:!0});this._isFinished=!0;var n=this._reader;if(void 0===n._ownerReadableStream)return X(dl("finish iterating"));if(!this._preventCancel){var u=sl(n,l);return cl(n),ul(u,(function(){return{value:l,done:!0}}))}return cl(n),G({value:l,done:!0})},l}(),zl={next:function(){return Ql(this)?this._asyncIteratorImpl.next():X($l("next"))},return:function(l){return Ql(this)?this._asyncIteratorImpl.return(l):X($l("return"))}};function Ql(l){if(!z(l))return!1;if(!Object.prototype.hasOwnProperty.call(l,"_asyncIteratorImpl"))return!1;try{return l._asyncIteratorImpl instanceof Wl}catch(l){return!1}}function $l(l){return new TypeError("ReadableStreamAsyncIterator."+l+" can only be used on a ReadableSteamAsyncIterator")}void 0!==Dl&&Object.setPrototypeOf(zl,Dl);var Hl=Number.isNaN||function(l){return l!=l};function Vl(l){return l.slice()}function Jl(l,n,u,e,t){new Uint8Array(l).set(new Uint8Array(u,e,t),n)}function Yl(l,n,u){if(l.slice)return l.slice(n,u);var e=u-n,t=new ArrayBuffer(e);return Jl(t,0,l,n,e),t}function Gl(l){var n=Yl(l.buffer,l.byteOffset,l.byteOffset+l.byteLength);return new Uint8Array(n)}function Xl(l){var n=l._queue.shift();return l._queueTotalSize-=n.size,l._queueTotalSize<0&&(l._queueTotalSize=0),n.value}function Kl(l,n,u){if("number"!=typeof(e=u)||Hl(e)||e<0||u===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var e;l._queue.push({value:n,size:u}),l._queueTotalSize+=u}function Zl(l){l._queue=new il,l._queueTotalSize=0}var ln=function(){function l(){throw new TypeError("Illegal constructor")}return Object.defineProperty(l.prototype,"view",{get:function(){if(!en(this))throw On("view");return this._view},enumerable:!1,configurable:!0}),l.prototype.respond=function(l){if(!en(this))throw On("respond");if(Rl(l,1,"respond"),l=Fl(l,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,Sn(this._associatedReadableByteStreamController,l)},l.prototype.respondWithNewView=function(l){if(!en(this))throw On("respondWithNewView");if(Rl(l,1,"respondWithNewView"),!ArrayBuffer.isView(l))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");l.buffer,Tn(this._associatedReadableByteStreamController,l)},l}();Object.defineProperties(ln.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(ln.prototype,q.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});var nn=function(){function l(){throw new TypeError("Illegal constructor")}return Object.defineProperty(l.prototype,"byobRequest",{get:function(){if(!un(this))throw An("byobRequest");return wn(this)},enumerable:!1,configurable:!0}),Object.defineProperty(l.prototype,"desiredSize",{get:function(){if(!un(this))throw An("desiredSize");return _n(this)},enumerable:!1,configurable:!0}),l.prototype.close=function(){if(!un(this))throw An("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var l=this._controlledReadableByteStream._state;if("readable"!==l)throw new TypeError("The stream (in "+l+" state) is not in the readable state and cannot be closed");bn(this)},l.prototype.enqueue=function(l){if(!un(this))throw An("enqueue");if(Rl(l,1,"enqueue"),!ArrayBuffer.isView(l))throw new TypeError("chunk must be an array buffer view");if(0===l.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===l.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");var n=this._controlledReadableByteStream._state;if("readable"!==n)throw new TypeError("The stream (in "+n+" state) is not in the readable state and cannot be enqueued to");vn(this,l)},l.prototype.error=function(l){if(void 0===l&&(l=void 0),!un(this))throw An("error");En(this,l)},l.prototype[bl]=function(l){rn(this),Zl(this);var n=this._cancelAlgorithm(l);return gn(this),n},l.prototype[vl]=function(l){var n=this._controlledReadableByteStream;if(this._queueTotalSize>0){var u=this._queue.shift();this._queueTotalSize-=u.byteLength,hn(this);var e=new Uint8Array(u.buffer,u.byteOffset,u.byteLength);l._chunkSteps(e)}else{var t=this._autoAllocateChunkSize;if(void 0!==t){var r=void 0;try{r=new ArrayBuffer(t)}catch(n){return void l._errorSteps(n)}var o={buffer:r,bufferByteLength:t,byteOffset:0,byteLength:t,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}Pl(n,l),tn(this)}},l}();function un(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_controlledReadableByteStream")&&l instanceof nn)}function en(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_associatedReadableByteStreamController")&&l instanceof ln)}function tn(l){var n=function(l){var n=l._controlledReadableByteStream;if("readable"!==n._state)return!1;if(l._closeRequested)return!1;if(!l._started)return!1;if(xl(n)&&Nl(n)>0)return!0;if(kn(n)&&In(n)>0)return!0;var u=_n(l);if(u>0)return!0;return!1}(l);n&&(l._pulling?l._pullAgain=!0:(l._pulling=!0,Z(l._pullAlgorithm(),(function(){l._pulling=!1,l._pullAgain&&(l._pullAgain=!1,tn(l))}),(function(n){En(l,n)}))))}function rn(l){fn(l),l._pendingPullIntos=new il}function on(l,n){var u=!1;"closed"===l._state&&(u=!0);var e=an(n);"default"===n.readerType?Ll(l,e,u):function(l,n,u){var e=l._reader,t=e._readIntoRequests.shift();u?t._closeSteps(n):t._chunkSteps(n)}(l,e,u)}function an(l){var n=l.bytesFilled,u=l.elementSize;return new l.viewConstructor(l.buffer,l.byteOffset,n/u)}function sn(l,n,u,e){l._queue.push({buffer:n,byteOffset:u,byteLength:e}),l._queueTotalSize+=e}function cn(l,n){var u=n.elementSize,e=n.bytesFilled-n.bytesFilled%u,t=Math.min(l._queueTotalSize,n.byteLength-n.bytesFilled),r=n.bytesFilled+t,o=r-r%u,i=t,a=!1;o>e&&(i=o-n.bytesFilled,a=!0);for(var s=l._queue;i>0;){var c=s.peek(),d=Math.min(i,c.byteLength),h=n.byteOffset+n.bytesFilled;Jl(n.buffer,h,c.buffer,c.byteOffset,d),c.byteLength===d?s.shift():(c.byteOffset+=d,c.byteLength-=d),l._queueTotalSize-=d,dn(l,d,n),i-=d}return a}function dn(l,n,u){u.bytesFilled+=n}function hn(l){0===l._queueTotalSize&&l._closeRequested?(gn(l),se(l._controlledReadableByteStream)):tn(l)}function fn(l){null!==l._byobRequest&&(l._byobRequest._associatedReadableByteStreamController=void 0,l._byobRequest._view=null,l._byobRequest=null)}function pn(l){for(;l._pendingPullIntos.length>0;){if(0===l._queueTotalSize)return;var n=l._pendingPullIntos.peek();cn(l,n)&&(mn(l),on(l._controlledReadableByteStream,n))}}function yn(l,n){var u=l._pendingPullIntos.peek();fn(l),"closed"===l._controlledReadableByteStream._state?function(l){var n=l._controlledReadableByteStream;if(kn(n))for(;In(n)>0;)on(n,mn(l))}(l):function(l,n,u){if(dn(0,n,u),!(u.bytesFilled<u.elementSize)){mn(l);var e=u.bytesFilled%u.elementSize;if(e>0){var t=u.byteOffset+u.bytesFilled,r=Yl(u.buffer,t-e,t);sn(l,r,0,r.byteLength)}u.bytesFilled-=e,on(l._controlledReadableByteStream,u),pn(l)}}(l,n,u),tn(l)}function mn(l){return l._pendingPullIntos.shift()}function gn(l){l._pullAlgorithm=void 0,l._cancelAlgorithm=void 0}function bn(l){var n=l._controlledReadableByteStream;if(!l._closeRequested&&"readable"===n._state)if(l._queueTotalSize>0)l._closeRequested=!0;else{if(l._pendingPullIntos.length>0)if(l._pendingPullIntos.peek().bytesFilled>0){var u=new TypeError("Insufficient bytes to fill elements in the given buffer");throw En(l,u),u}gn(l),se(n)}}function vn(l,n){var u=l._controlledReadableByteStream;if(!l._closeRequested&&"readable"===u._state){var e=n.buffer,t=n.byteOffset,r=n.byteLength,o=e;if(l._pendingPullIntos.length>0){var i=l._pendingPullIntos.peek();i.buffer,0,i.buffer=i.buffer}if(fn(l),xl(u))if(0===Nl(u))sn(l,o,t,r);else l._pendingPullIntos.length>0&&mn(l),Ll(u,new Uint8Array(o,t,r),!1);else kn(u)?(sn(l,o,t,r),pn(l)):sn(l,o,t,r);tn(l)}}function En(l,n){var u=l._controlledReadableByteStream;"readable"===u._state&&(rn(l),Zl(l),gn(l),ce(u,n))}function wn(l){if(null===l._byobRequest&&l._pendingPullIntos.length>0){var n=l._pendingPullIntos.peek(),u=new Uint8Array(n.buffer,n.byteOffset+n.bytesFilled,n.byteLength-n.bytesFilled),e=Object.create(ln.prototype);!function(l,n,u){l._associatedReadableByteStreamController=n,l._view=u}(e,l,u),l._byobRequest=e}return l._byobRequest}function _n(l){var n=l._controlledReadableByteStream._state;return"errored"===n?null:"closed"===n?0:l._strategyHWM-l._queueTotalSize}function Sn(l,n){var u=l._pendingPullIntos.peek();if("closed"===l._controlledReadableByteStream._state){if(0!==n)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===n)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(u.bytesFilled+n>u.byteLength)throw new RangeError("bytesWritten out of range")}u.buffer=u.buffer,yn(l,n)}function Tn(l,n){var u=l._pendingPullIntos.peek();if("closed"===l._controlledReadableByteStream._state){if(0!==n.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===n.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(u.byteOffset+u.bytesFilled!==n.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(u.bufferByteLength!==n.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(u.bytesFilled+n.byteLength>u.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");var e=n.byteLength;u.buffer=n.buffer,yn(l,e)}function Rn(l,n,u,e,t,r,o){n._controlledReadableByteStream=l,n._pullAgain=!1,n._pulling=!1,n._byobRequest=null,n._queue=n._queueTotalSize=void 0,Zl(n),n._closeRequested=!1,n._started=!1,n._strategyHWM=r,n._pullAlgorithm=e,n._cancelAlgorithm=t,n._autoAllocateChunkSize=o,n._pendingPullIntos=new il,l._readableStreamController=n,Z(G(u()),(function(){n._started=!0,tn(n)}),(function(l){En(n,l)}))}function On(l){return new TypeError("ReadableStreamBYOBRequest.prototype."+l+" can only be used on a ReadableStreamBYOBRequest")}function An(l){return new TypeError("ReadableByteStreamController.prototype."+l+" can only be used on a ReadableByteStreamController")}function Cn(l){return new Pn(l)}function Fn(l,n){l._reader._readIntoRequests.push(n)}function In(l){return l._reader._readIntoRequests.length}function kn(l){var n=l._reader;return void 0!==n&&!!Ln(n)}Object.defineProperties(nn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(nn.prototype,q.toStringTag,{value:"ReadableByteStreamController",configurable:!0});var Pn=function(){function l(l){if(Rl(l,1,"ReadableStreamBYOBReader"),Il(l,"First parameter"),ie(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!un(l._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");al(this,l),this._readIntoRequests=new il}return Object.defineProperty(l.prototype,"closed",{get:function(){return Ln(this)?this._closedPromise:X(xn("closed"))},enumerable:!1,configurable:!0}),l.prototype.cancel=function(l){return void 0===l&&(l=void 0),Ln(this)?void 0===this._ownerReadableStream?X(dl("cancel")):sl(this,l):X(xn("cancel"))},l.prototype.read=function(l){if(!Ln(this))return X(xn("read"));if(!ArrayBuffer.isView(l))return X(new TypeError("view must be an array buffer view"));if(0===l.byteLength)return X(new TypeError("view must have non-zero byteLength"));if(0===l.buffer.byteLength)return X(new TypeError("view's buffer must have non-zero byteLength"));if(l.buffer,void 0===this._ownerReadableStream)return X(dl("read from"));var n,u,e=Y((function(l,e){n=l,u=e}));return Nn(this,l,{_chunkSteps:function(l){return n({value:l,done:!1})},_closeSteps:function(l){return n({value:l,done:!0})},_errorSteps:function(l){return u(l)}}),e},l.prototype.releaseLock=function(){if(!Ln(this))throw xn("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");cl(this)}},l}();function Ln(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_readIntoRequests")&&l instanceof Pn)}function Nn(l,n,u){var e=l._ownerReadableStream;e._disturbed=!0,"errored"===e._state?u._errorSteps(e._storedError):function(l,n,u){var e=l._controlledReadableByteStream,t=1;n.constructor!==DataView&&(t=n.constructor.BYTES_PER_ELEMENT);var r=n.constructor,o=n.buffer,i={buffer:o,bufferByteLength:o.byteLength,byteOffset:n.byteOffset,byteLength:n.byteLength,bytesFilled:0,elementSize:t,viewConstructor:r,readerType:"byob"};if(l._pendingPullIntos.length>0)return l._pendingPullIntos.push(i),void Fn(e,u);if("closed"!==e._state){if(l._queueTotalSize>0){if(cn(l,i)){var a=an(i);return hn(l),void u._chunkSteps(a)}if(l._closeRequested){var s=new TypeError("Insufficient bytes to fill elements in the given buffer");return En(l,s),void u._errorSteps(s)}}l._pendingPullIntos.push(i),Fn(e,u),tn(l)}else{var c=new r(i.buffer,i.byteOffset,0);u._closeSteps(c)}}(e._readableStreamController,n,u)}function xn(l){return new TypeError("ReadableStreamBYOBReader.prototype."+l+" can only be used on a ReadableStreamBYOBReader")}function Un(l,n){var u=l.highWaterMark;if(void 0===u)return n;if(Hl(u)||u<0)throw new RangeError("Invalid highWaterMark");return u}function Dn(l){var n=l.size;return n||function(){return 1}}function Mn(l,n){_l(l,n);var u=null==l?void 0:l.highWaterMark,e=null==l?void 0:l.size;return{highWaterMark:void 0===u?void 0:Al(u),size:void 0===e?void 0:Bn(e,n+" has member 'size' that")}}function Bn(l,n){return Sl(l,n),function(n){return Al(l(n))}}function qn(l,n,u){return Sl(l,u),function(u){return ol(l,n,[u])}}function jn(l,n,u){return Sl(l,u),function(){return ol(l,n,[])}}function Wn(l,n,u){return Sl(l,u),function(u){return rl(l,n,[u])}}function zn(l,n,u){return Sl(l,u),function(u,e){return ol(l,n,[u,e])}}function Qn(l,n){if(!Jn(l))throw new TypeError(n+" is not a WritableStream.")}Object.defineProperties(Pn.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(Pn.prototype,q.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});var $n="function"==typeof AbortController;var Hn=function(){function l(l,n){void 0===l&&(l={}),void 0===n&&(n={}),void 0===l?l=null:Tl(l,"First parameter");var u,e=Mn(n,"Second parameter"),t=function(l,n){_l(l,n);var u=null==l?void 0:l.abort,e=null==l?void 0:l.close,t=null==l?void 0:l.start,r=null==l?void 0:l.type,o=null==l?void 0:l.write;return{abort:void 0===u?void 0:qn(u,l,n+" has member 'abort' that"),close:void 0===e?void 0:jn(e,l,n+" has member 'close' that"),start:void 0===t?void 0:Wn(t,l,n+" has member 'start' that"),write:void 0===o?void 0:zn(o,l,n+" has member 'write' that"),type:r}}(l,"First parameter");if((u=this)._state="writable",u._storedError=void 0,u._writer=void 0,u._writableStreamController=void 0,u._writeRequests=new il,u._inFlightWriteRequest=void 0,u._closeRequest=void 0,u._inFlightCloseRequest=void 0,u._pendingAbortRequest=void 0,u._backpressure=!1,void 0!==t.type)throw new RangeError("Invalid type is specified");var r=Dn(e);!function(l,n,u,e){var t=Object.create(hu.prototype),r=function(){},o=function(){return G(void 0)},i=function(){return G(void 0)},a=function(){return G(void 0)};void 0!==n.start&&(r=function(){return n.start(t)});void 0!==n.write&&(o=function(l){return n.write(l,t)});void 0!==n.close&&(i=function(){return n.close()});void 0!==n.abort&&(a=function(l){return n.abort(l)});!function(l,n,u,e,t,r,o,i){n._controlledWritableStream=l,l._writableStreamController=n,n._queue=void 0,n._queueTotalSize=void 0,Zl(n),n._abortReason=void 0,n._abortController=function(){if($n)return new AbortController}(),n._started=!1,n._strategySizeAlgorithm=i,n._strategyHWM=o,n._writeAlgorithm=e,n._closeAlgorithm=t,n._abortAlgorithm=r;var a=bu(n);eu(l,a);var s=u();Z(G(s),(function(){n._started=!0,mu(n)}),(function(u){n._started=!0,Kn(l,u)}))}(l,t,r,o,i,a,u,e)}(this,t,Un(e,1),r)}return Object.defineProperty(l.prototype,"locked",{get:function(){if(!Jn(this))throw Eu("locked");return Yn(this)},enumerable:!1,configurable:!0}),l.prototype.abort=function(l){return void 0===l&&(l=void 0),Jn(this)?Yn(this)?X(new TypeError("Cannot abort a stream that already has a writer")):Gn(this,l):X(Eu("abort"))},l.prototype.close=function(){return Jn(this)?Yn(this)?X(new TypeError("Cannot close a stream that already has a writer")):nu(this)?X(new TypeError("Cannot close an already-closing stream")):Xn(this):X(Eu("close"))},l.prototype.getWriter=function(){if(!Jn(this))throw Eu("getWriter");return Vn(this)},l}();function Vn(l){return new tu(l)}function Jn(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_writableStreamController")&&l instanceof Hn)}function Yn(l){return void 0!==l._writer}function Gn(l,n){var u;if("closed"===l._state||"errored"===l._state)return G(void 0);l._writableStreamController._abortReason=n,null===(u=l._writableStreamController._abortController)||void 0===u||u.abort();var e=l._state;if("closed"===e||"errored"===e)return G(void 0);if(void 0!==l._pendingAbortRequest)return l._pendingAbortRequest._promise;var t=!1;"erroring"===e&&(t=!0,n=void 0);var r=Y((function(u,e){l._pendingAbortRequest={_promise:void 0,_resolve:u,_reject:e,_reason:n,_wasAlreadyErroring:t}}));return l._pendingAbortRequest._promise=r,t||Zn(l,n),r}function Xn(l){var n=l._state;if("closed"===n||"errored"===n)return X(new TypeError("The stream (in "+n+" state) is not in the writable state and cannot be closed"));var u,e=Y((function(n,u){var e={_resolve:n,_reject:u};l._closeRequest=e})),t=l._writer;return void 0!==t&&l._backpressure&&"writable"===n&&Pu(t),Kl(u=l._writableStreamController,du,0),mu(u),e}function Kn(l,n){"writable"!==l._state?lu(l):Zn(l,n)}function Zn(l,n){var u=l._writableStreamController;l._state="erroring",l._storedError=n;var e=l._writer;void 0!==e&&au(e,n),!function(l){if(void 0===l._inFlightWriteRequest&&void 0===l._inFlightCloseRequest)return!1;return!0}(l)&&u._started&&lu(l)}function lu(l){l._state="errored",l._writableStreamController[gl]();var n=l._storedError;if(l._writeRequests.forEach((function(l){l._reject(n)})),l._writeRequests=new il,void 0!==l._pendingAbortRequest){var u=l._pendingAbortRequest;if(l._pendingAbortRequest=void 0,u._wasAlreadyErroring)return u._reject(n),void uu(l);Z(l._writableStreamController[ml](u._reason),(function(){u._resolve(),uu(l)}),(function(n){u._reject(n),uu(l)}))}else uu(l)}function nu(l){return void 0!==l._closeRequest||void 0!==l._inFlightCloseRequest}function uu(l){void 0!==l._closeRequest&&(l._closeRequest._reject(l._storedError),l._closeRequest=void 0);var n=l._writer;void 0!==n&&Ou(n,l._storedError)}function eu(l,n){var u=l._writer;void 0!==u&&n!==l._backpressure&&(n?function(l){Cu(l)}(u):Pu(u)),l._backpressure=n}Object.defineProperties(Hn.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(Hn.prototype,q.toStringTag,{value:"WritableStream",configurable:!0});var tu=function(){function l(l){if(Rl(l,1,"WritableStreamDefaultWriter"),Qn(l,"First parameter"),Yn(l))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=l,l._writer=this;var n,u=l._state;if("writable"===u)!nu(l)&&l._backpressure?Cu(this):Iu(this),Tu(this);else if("erroring"===u)Fu(this,l._storedError),Tu(this);else if("closed"===u)Iu(this),Tu(n=this),Au(n);else{var e=l._storedError;Fu(this,e),Ru(this,e)}}return Object.defineProperty(l.prototype,"closed",{get:function(){return ru(this)?this._closedPromise:X(_u("closed"))},enumerable:!1,configurable:!0}),Object.defineProperty(l.prototype,"desiredSize",{get:function(){if(!ru(this))throw _u("desiredSize");if(void 0===this._ownerWritableStream)throw Su("desiredSize");return function(l){var n=l._ownerWritableStream,u=n._state;if("errored"===u||"erroring"===u)return null;if("closed"===u)return 0;return yu(n._writableStreamController)}(this)},enumerable:!1,configurable:!0}),Object.defineProperty(l.prototype,"ready",{get:function(){return ru(this)?this._readyPromise:X(_u("ready"))},enumerable:!1,configurable:!0}),l.prototype.abort=function(l){return void 0===l&&(l=void 0),ru(this)?void 0===this._ownerWritableStream?X(Su("abort")):function(l,n){return Gn(l._ownerWritableStream,n)}(this,l):X(_u("abort"))},l.prototype.close=function(){if(!ru(this))return X(_u("close"));var l=this._ownerWritableStream;return void 0===l?X(Su("close")):nu(l)?X(new TypeError("Cannot close an already-closing stream")):ou(this)},l.prototype.releaseLock=function(){if(!ru(this))throw _u("releaseLock");void 0!==this._ownerWritableStream&&su(this)},l.prototype.write=function(l){return void 0===l&&(l=void 0),ru(this)?void 0===this._ownerWritableStream?X(Su("write to")):cu(this,l):X(_u("write"))},l}();function ru(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_ownerWritableStream")&&l instanceof tu)}function ou(l){return Xn(l._ownerWritableStream)}function iu(l,n){"pending"===l._closedPromiseState?Ou(l,n):function(l,n){Ru(l,n)}(l,n)}function au(l,n){"pending"===l._readyPromiseState?ku(l,n):function(l,n){Fu(l,n)}(l,n)}function su(l){var n=l._ownerWritableStream,u=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");au(l,u),iu(l,u),n._writer=void 0,l._ownerWritableStream=void 0}function cu(l,n){var u=l._ownerWritableStream,e=u._writableStreamController,t=function(l,n){try{return l._strategySizeAlgorithm(n)}catch(n){return gu(l,n),1}}(e,n);if(u!==l._ownerWritableStream)return X(Su("write to"));var r=u._state;if("errored"===r)return X(u._storedError);if(nu(u)||"closed"===r)return X(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===r)return X(u._storedError);var o=function(l){return Y((function(n,u){var e={_resolve:n,_reject:u};l._writeRequests.push(e)}))}(u);return function(l,n,u){try{Kl(l,n,u)}catch(n){return void gu(l,n)}var e=l._controlledWritableStream;if(!nu(e)&&"writable"===e._state){eu(e,bu(l))}mu(l)}(e,n,t),o}Object.defineProperties(tu.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(tu.prototype,q.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});var du={},hu=function(){function l(){throw new TypeError("Illegal constructor")}return Object.defineProperty(l.prototype,"abortReason",{get:function(){if(!fu(this))throw wu("abortReason");return this._abortReason},enumerable:!1,configurable:!0}),Object.defineProperty(l.prototype,"signal",{get:function(){if(!fu(this))throw wu("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal},enumerable:!1,configurable:!0}),l.prototype.error=function(l){if(void 0===l&&(l=void 0),!fu(this))throw wu("error");"writable"===this._controlledWritableStream._state&&vu(this,l)},l.prototype[ml]=function(l){var n=this._abortAlgorithm(l);return pu(this),n},l.prototype[gl]=function(){Zl(this)},l}();function fu(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_controlledWritableStream")&&l instanceof hu)}function pu(l){l._writeAlgorithm=void 0,l._closeAlgorithm=void 0,l._abortAlgorithm=void 0,l._strategySizeAlgorithm=void 0}function yu(l){return l._strategyHWM-l._queueTotalSize}function mu(l){var n=l._controlledWritableStream;if(l._started&&void 0===n._inFlightWriteRequest)if("erroring"!==n._state){if(0!==l._queue.length){var u=l._queue.peek().value;u===du?function(l){var n=l._controlledWritableStream;(function(l){l._inFlightCloseRequest=l._closeRequest,l._closeRequest=void 0})(n),Xl(l);var u=l._closeAlgorithm();pu(l),Z(u,(function(){!function(l){l._inFlightCloseRequest._resolve(void 0),l._inFlightCloseRequest=void 0,"erroring"===l._state&&(l._storedError=void 0,void 0!==l._pendingAbortRequest&&(l._pendingAbortRequest._resolve(),l._pendingAbortRequest=void 0)),l._state="closed";var n=l._writer;void 0!==n&&Au(n)}(n)}),(function(l){!function(l,n){l._inFlightCloseRequest._reject(n),l._inFlightCloseRequest=void 0,void 0!==l._pendingAbortRequest&&(l._pendingAbortRequest._reject(n),l._pendingAbortRequest=void 0),Kn(l,n)}(n,l)}))}(l):function(l,n){var u=l._controlledWritableStream;!function(l){l._inFlightWriteRequest=l._writeRequests.shift()}(u);var e=l._writeAlgorithm(n);Z(e,(function(){!function(l){l._inFlightWriteRequest._resolve(void 0),l._inFlightWriteRequest=void 0}(u);var n=u._state;if(Xl(l),!nu(u)&&"writable"===n){var e=bu(l);eu(u,e)}mu(l)}),(function(n){"writable"===u._state&&pu(l),function(l,n){l._inFlightWriteRequest._reject(n),l._inFlightWriteRequest=void 0,Kn(l,n)}(u,n)}))}(l,u)}}else lu(n)}function gu(l,n){"writable"===l._controlledWritableStream._state&&vu(l,n)}function bu(l){return yu(l)<=0}function vu(l,n){var u=l._controlledWritableStream;pu(l),Zn(u,n)}function Eu(l){return new TypeError("WritableStream.prototype."+l+" can only be used on a WritableStream")}function wu(l){return new TypeError("WritableStreamDefaultController.prototype."+l+" can only be used on a WritableStreamDefaultController")}function _u(l){return new TypeError("WritableStreamDefaultWriter.prototype."+l+" can only be used on a WritableStreamDefaultWriter")}function Su(l){return new TypeError("Cannot "+l+" a stream using a released writer")}function Tu(l){l._closedPromise=Y((function(n,u){l._closedPromise_resolve=n,l._closedPromise_reject=u,l._closedPromiseState="pending"}))}function Ru(l,n){Tu(l),Ou(l,n)}function Ou(l,n){void 0!==l._closedPromise_reject&&(el(l._closedPromise),l._closedPromise_reject(n),l._closedPromise_resolve=void 0,l._closedPromise_reject=void 0,l._closedPromiseState="rejected")}function Au(l){void 0!==l._closedPromise_resolve&&(l._closedPromise_resolve(void 0),l._closedPromise_resolve=void 0,l._closedPromise_reject=void 0,l._closedPromiseState="resolved")}function Cu(l){l._readyPromise=Y((function(n,u){l._readyPromise_resolve=n,l._readyPromise_reject=u})),l._readyPromiseState="pending"}function Fu(l,n){Cu(l),ku(l,n)}function Iu(l){Cu(l),Pu(l)}function ku(l,n){void 0!==l._readyPromise_reject&&(el(l._readyPromise),l._readyPromise_reject(n),l._readyPromise_resolve=void 0,l._readyPromise_reject=void 0,l._readyPromiseState="rejected")}function Pu(l){void 0!==l._readyPromise_resolve&&(l._readyPromise_resolve(void 0),l._readyPromise_resolve=void 0,l._readyPromise_reject=void 0,l._readyPromiseState="fulfilled")}Object.defineProperties(hu.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(hu.prototype,q.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});var Lu="undefined"!=typeof DOMException?DOMException:void 0;var Nu,xu=function(l){if("function"!=typeof l&&"object"!=typeof l)return!1;try{return new l,!0}catch(l){return!1}}(Lu)?Lu:(Nu=function(l,n){this.message=l||"",this.name=n||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)},Nu.prototype=Object.create(Error.prototype),Object.defineProperty(Nu.prototype,"constructor",{value:Nu,writable:!0,configurable:!0}),Nu);function Uu(l,n,u,e,t,r){var o=kl(l),i=Vn(n);l._disturbed=!0;var a=!1,s=G(void 0);return Y((function(c,d){var h,f,p,y;if(void 0!==r){if(h=function(){var u=new xu("Aborted","AbortError"),r=[];e||r.push((function(){return"writable"===n._state?Gn(n,u):G(void 0)})),t||r.push((function(){return"readable"===l._state?ae(l,u):G(void 0)})),v((function(){return Promise.all(r.map((function(l){return l()})))}),!0,u)},r.aborted)return void h();r.addEventListener("abort",h)}if(b(l,o._closedPromise,(function(l){e?E(!0,l):v((function(){return Gn(n,l)}),!0,l)})),b(n,i._closedPromise,(function(n){t?E(!0,n):v((function(){return ae(l,n)}),!0,n)})),f=l,p=o._closedPromise,y=function(){u?E():v((function(){return function(l){var n=l._ownerWritableStream,u=n._state;return nu(n)||"closed"===u?G(void 0):"errored"===u?X(n._storedError):ou(l)}(i)}))},"closed"===f._state?y():ll(p,y),nu(n)||"closed"===n._state){var m=new TypeError("the destination writable stream closed before all data could be piped to it");t?E(!0,m):v((function(){return ae(l,m)}),!0,m)}function g(){var l=s;return K(s,(function(){return l!==s?g():void 0}))}function b(l,n,u){"errored"===l._state?u(l._storedError):nl(n,u)}function v(l,u,e){function t(){Z(l(),(function(){return w(u,e)}),(function(l){return w(!0,l)}))}a||(a=!0,"writable"!==n._state||nu(n)?t():ll(g(),t))}function E(l,u){a||(a=!0,"writable"!==n._state||nu(n)?w(l,u):ll(g(),(function(){return w(l,u)})))}function w(l,n){su(i),cl(o),void 0!==r&&r.removeEventListener("abort",h),l?d(n):c(void 0)}el(Y((function(l,n){!function u(e){e?l():K(a?G(!0):K(i._readyPromise,(function(){return Y((function(l,n){ql(o,{_chunkSteps:function(n){s=K(cu(i,n),void 0,j),l(!1)},_closeSteps:function(){return l(!0)},_errorSteps:n})}))})),u,n)}(!1)})))}))}var Du=function(){function l(){throw new TypeError("Illegal constructor")}return Object.defineProperty(l.prototype,"desiredSize",{get:function(){if(!Mu(this))throw Ju("desiredSize");return $u(this)},enumerable:!1,configurable:!0}),l.prototype.close=function(){if(!Mu(this))throw Ju("close");if(!Hu(this))throw new TypeError("The stream is not in a state that permits close");Wu(this)},l.prototype.enqueue=function(l){if(void 0===l&&(l=void 0),!Mu(this))throw Ju("enqueue");if(!Hu(this))throw new TypeError("The stream is not in a state that permits enqueue");return zu(this,l)},l.prototype.error=function(l){if(void 0===l&&(l=void 0),!Mu(this))throw Ju("error");Qu(this,l)},l.prototype[bl]=function(l){Zl(this);var n=this._cancelAlgorithm(l);return ju(this),n},l.prototype[vl]=function(l){var n=this._controlledReadableStream;if(this._queue.length>0){var u=Xl(this);this._closeRequested&&0===this._queue.length?(ju(this),se(n)):Bu(this),l._chunkSteps(u)}else Pl(n,l),Bu(this)},l}();function Mu(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_controlledReadableStream")&&l instanceof Du)}function Bu(l){qu(l)&&(l._pulling?l._pullAgain=!0:(l._pulling=!0,Z(l._pullAlgorithm(),(function(){l._pulling=!1,l._pullAgain&&(l._pullAgain=!1,Bu(l))}),(function(n){Qu(l,n)}))))}function qu(l){var n=l._controlledReadableStream;return!!Hu(l)&&(!!l._started&&(!!(ie(n)&&Nl(n)>0)||$u(l)>0))}function ju(l){l._pullAlgorithm=void 0,l._cancelAlgorithm=void 0,l._strategySizeAlgorithm=void 0}function Wu(l){if(Hu(l)){var n=l._controlledReadableStream;l._closeRequested=!0,0===l._queue.length&&(ju(l),se(n))}}function zu(l,n){if(Hu(l)){var u=l._controlledReadableStream;if(ie(u)&&Nl(u)>0)Ll(u,n,!1);else{var e=void 0;try{e=l._strategySizeAlgorithm(n)}catch(n){throw Qu(l,n),n}try{Kl(l,n,e)}catch(n){throw Qu(l,n),n}}Bu(l)}}function Qu(l,n){var u=l._controlledReadableStream;"readable"===u._state&&(Zl(l),ju(l),ce(u,n))}function $u(l){var n=l._controlledReadableStream._state;return"errored"===n?null:"closed"===n?0:l._strategyHWM-l._queueTotalSize}function Hu(l){var n=l._controlledReadableStream._state;return!l._closeRequested&&"readable"===n}function Vu(l,n,u,e,t,r,o){n._controlledReadableStream=l,n._queue=void 0,n._queueTotalSize=void 0,Zl(n),n._started=!1,n._closeRequested=!1,n._pullAgain=!1,n._pulling=!1,n._strategySizeAlgorithm=o,n._strategyHWM=r,n._pullAlgorithm=e,n._cancelAlgorithm=t,l._readableStreamController=n,Z(G(u()),(function(){n._started=!0,Bu(n)}),(function(l){Qu(n,l)}))}function Ju(l){return new TypeError("ReadableStreamDefaultController.prototype."+l+" can only be used on a ReadableStreamDefaultController")}function Yu(l,n){return un(l._readableStreamController)?function(l){var n,u,e,t,r,o=kl(l),i=!1,a=!1,s=!1,c=!1,d=!1,h=Y((function(l){r=l}));function f(l){nl(l._closedPromise,(function(n){l===o&&(En(e._readableStreamController,n),En(t._readableStreamController,n),c&&d||r(void 0))}))}function p(){Ln(o)&&(cl(o),f(o=kl(l))),ql(o,{_chunkSteps:function(n){tl((function(){a=!1,s=!1;var u=n,o=n;if(!c&&!d)try{o=Gl(n)}catch(n){return En(e._readableStreamController,n),En(t._readableStreamController,n),void r(ae(l,n))}c||vn(e._readableStreamController,u),d||vn(t._readableStreamController,o),i=!1,a?m():s&&g()}))},_closeSteps:function(){i=!1,c||bn(e._readableStreamController),d||bn(t._readableStreamController),e._readableStreamController._pendingPullIntos.length>0&&Sn(e._readableStreamController,0),t._readableStreamController._pendingPullIntos.length>0&&Sn(t._readableStreamController,0),c&&d||r(void 0)},_errorSteps:function(){i=!1}})}function y(n,u){Bl(o)&&(cl(o),f(o=Cn(l)));var h=u?t:e,p=u?e:t;Nn(o,n,{_chunkSteps:function(n){tl((function(){a=!1,s=!1;var e=u?d:c;if(u?c:d)e||Tn(h._readableStreamController,n);else{var t=void 0;try{t=Gl(n)}catch(n){return En(h._readableStreamController,n),En(p._readableStreamController,n),void r(ae(l,n))}e||Tn(h._readableStreamController,n),vn(p._readableStreamController,t)}i=!1,a?m():s&&g()}))},_closeSteps:function(l){i=!1;var n=u?d:c,e=u?c:d;n||bn(h._readableStreamController),e||bn(p._readableStreamController),void 0!==l&&(n||Tn(h._readableStreamController,l),!e&&p._readableStreamController._pendingPullIntos.length>0&&Sn(p._readableStreamController,0)),n&&e||r(void 0)},_errorSteps:function(){i=!1}})}function m(){if(i)return a=!0,G(void 0);i=!0;var l=wn(e._readableStreamController);return null===l?p():y(l._view,!1),G(void 0)}function g(){if(i)return s=!0,G(void 0);i=!0;var l=wn(t._readableStreamController);return null===l?p():y(l._view,!0),G(void 0)}function b(e){if(c=!0,n=e,d){var t=Vl([n,u]),o=ae(l,t);r(o)}return h}function v(e){if(d=!0,u=e,c){var t=Vl([n,u]),o=ae(l,t);r(o)}return h}function E(){}return e=te(E,m,b),t=te(E,g,v),f(o),[e,t]}(l):function(l){var n,u,e,t,r,o=kl(l),i=!1,a=!1,s=!1,c=!1,d=Y((function(l){r=l}));function h(){return i?(a=!0,G(void 0)):(i=!0,ql(o,{_chunkSteps:function(l){tl((function(){a=!1;var n=l,u=l;s||zu(e._readableStreamController,n),c||zu(t._readableStreamController,u),i=!1,a&&h()}))},_closeSteps:function(){i=!1,s||Wu(e._readableStreamController),c||Wu(t._readableStreamController),s&&c||r(void 0)},_errorSteps:function(){i=!1}}),G(void 0))}function f(e){if(s=!0,n=e,c){var t=Vl([n,u]),o=ae(l,t);r(o)}return d}function p(e){if(c=!0,u=e,s){var t=Vl([n,u]),o=ae(l,t);r(o)}return d}function y(){}return e=ee(y,h,f),t=ee(y,h,p),nl(o._closedPromise,(function(l){Qu(e._readableStreamController,l),Qu(t._readableStreamController,l),s&&c||r(void 0)})),[e,t]}(l)}function Gu(l,n,u){return Sl(l,u),function(u){return ol(l,n,[u])}}function Xu(l,n,u){return Sl(l,u),function(u){return ol(l,n,[u])}}function Ku(l,n,u){return Sl(l,u),function(u){return rl(l,n,[u])}}function Zu(l,n){if("bytes"!==(l=""+l))throw new TypeError(n+" '"+l+"' is not a valid enumeration value for ReadableStreamType");return l}function le(l,n){if("byob"!==(l=""+l))throw new TypeError(n+" '"+l+"' is not a valid enumeration value for ReadableStreamReaderMode");return l}function ne(l,n){_l(l,n);var u=null==l?void 0:l.preventAbort,e=null==l?void 0:l.preventCancel,t=null==l?void 0:l.preventClose,r=null==l?void 0:l.signal;return void 0!==r&&function(l,n){if(!function(l){if("object"!=typeof l||null===l)return!1;try{return"boolean"==typeof l.aborted}catch(l){return!1}}(l))throw new TypeError(n+" is not an AbortSignal.")}(r,n+" has member 'signal' that"),{preventAbort:Boolean(u),preventCancel:Boolean(e),preventClose:Boolean(t),signal:r}}Object.defineProperties(Du.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(Du.prototype,q.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});var ue=function(){function l(l,n){void 0===l&&(l={}),void 0===n&&(n={}),void 0===l?l=null:Tl(l,"First parameter");var u=Mn(n,"Second parameter"),e=function(l,n){_l(l,n);var u=l,e=null==u?void 0:u.autoAllocateChunkSize,t=null==u?void 0:u.cancel,r=null==u?void 0:u.pull,o=null==u?void 0:u.start,i=null==u?void 0:u.type;return{autoAllocateChunkSize:void 0===e?void 0:Fl(e,n+" has member 'autoAllocateChunkSize' that"),cancel:void 0===t?void 0:Gu(t,u,n+" has member 'cancel' that"),pull:void 0===r?void 0:Xu(r,u,n+" has member 'pull' that"),start:void 0===o?void 0:Ku(o,u,n+" has member 'start' that"),type:void 0===i?void 0:Zu(i,n+" has member 'type' that")}}(l,"First parameter");if(re(this),"bytes"===e.type){if(void 0!==u.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(l,n,u){var e=Object.create(nn.prototype),t=function(){},r=function(){return G(void 0)},o=function(){return G(void 0)};void 0!==n.start&&(t=function(){return n.start(e)}),void 0!==n.pull&&(r=function(){return n.pull(e)}),void 0!==n.cancel&&(o=function(l){return n.cancel(l)});var i=n.autoAllocateChunkSize;if(0===i)throw new TypeError("autoAllocateChunkSize must be greater than 0");Rn(l,e,t,r,o,u,i)}(this,e,Un(u,0))}else{var t=Dn(u);!function(l,n,u,e){var t=Object.create(Du.prototype),r=function(){},o=function(){return G(void 0)},i=function(){return G(void 0)};void 0!==n.start&&(r=function(){return n.start(t)}),void 0!==n.pull&&(o=function(){return n.pull(t)}),void 0!==n.cancel&&(i=function(l){return n.cancel(l)}),Vu(l,t,r,o,i,u,e)}(this,e,Un(u,1),t)}}return Object.defineProperty(l.prototype,"locked",{get:function(){if(!oe(this))throw de("locked");return ie(this)},enumerable:!1,configurable:!0}),l.prototype.cancel=function(l){return void 0===l&&(l=void 0),oe(this)?ie(this)?X(new TypeError("Cannot cancel a stream that already has a reader")):ae(this,l):X(de("cancel"))},l.prototype.getReader=function(l){if(void 0===l&&(l=void 0),!oe(this))throw de("getReader");return void 0===function(l,n){_l(l,n);var u=null==l?void 0:l.mode;return{mode:void 0===u?void 0:le(u,n+" has member 'mode' that")}}(l,"First parameter").mode?kl(this):Cn(this)},l.prototype.pipeThrough=function(l,n){if(void 0===n&&(n={}),!oe(this))throw de("pipeThrough");Rl(l,1,"pipeThrough");var u=function(l,n){_l(l,n);var u=null==l?void 0:l.readable;Ol(u,"readable","ReadableWritablePair"),Il(u,n+" has member 'readable' that");var e=null==l?void 0:l.writable;return Ol(e,"writable","ReadableWritablePair"),Qn(e,n+" has member 'writable' that"),{readable:u,writable:e}}(l,"First parameter"),e=ne(n,"Second parameter");if(ie(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Yn(u.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return el(Uu(this,u.writable,e.preventClose,e.preventAbort,e.preventCancel,e.signal)),u.readable},l.prototype.pipeTo=function(l,n){if(void 0===n&&(n={}),!oe(this))return X(de("pipeTo"));if(void 0===l)return X("Parameter 1 is required in 'pipeTo'.");if(!Jn(l))return X(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));var u;try{u=ne(n,"Second parameter")}catch(l){return X(l)}return ie(this)?X(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Yn(l)?X(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Uu(this,l,u.preventClose,u.preventAbort,u.preventCancel,u.signal)},l.prototype.tee=function(){if(!oe(this))throw de("tee");return Vl(Yu(this))},l.prototype.values=function(l){if(void 0===l&&(l=void 0),!oe(this))throw de("values");var n,u,e,t,r,o=function(l,n){_l(l,n);var u=null==l?void 0:l.preventCancel;return{preventCancel:Boolean(u)}}(l,"First parameter");return n=this,u=o.preventCancel,e=kl(n),t=new Wl(e,u),(r=Object.create(zl))._asyncIteratorImpl=t,r},l}();function ee(l,n,u,e,t){void 0===e&&(e=1),void 0===t&&(t=function(){return 1});var r=Object.create(ue.prototype);return re(r),Vu(r,Object.create(Du.prototype),l,n,u,e,t),r}function te(l,n,u){var e=Object.create(ue.prototype);return re(e),Rn(e,Object.create(nn.prototype),l,n,u,0,void 0),e}function re(l){l._state="readable",l._reader=void 0,l._storedError=void 0,l._disturbed=!1}function oe(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_readableStreamController")&&l instanceof ue)}function ie(l){return void 0!==l._reader}function ae(l,n){if(l._disturbed=!0,"closed"===l._state)return G(void 0);if("errored"===l._state)return X(l._storedError);se(l);var u=l._reader;return void 0!==u&&Ln(u)&&(u._readIntoRequests.forEach((function(l){l._closeSteps(void 0)})),u._readIntoRequests=new il),ul(l._readableStreamController[bl](n),j)}function se(l){l._state="closed";var n=l._reader;void 0!==n&&(yl(n),Bl(n)&&(n._readRequests.forEach((function(l){l._closeSteps()})),n._readRequests=new il))}function ce(l,n){l._state="errored",l._storedError=n;var u=l._reader;void 0!==u&&(pl(u,n),Bl(u)?(u._readRequests.forEach((function(l){l._errorSteps(n)})),u._readRequests=new il):(u._readIntoRequests.forEach((function(l){l._errorSteps(n)})),u._readIntoRequests=new il))}function de(l){return new TypeError("ReadableStream.prototype."+l+" can only be used on a ReadableStream")}Object.defineProperties(ue.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(ue.prototype,q.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof q.asyncIterator&&Object.defineProperty(ue.prototype,q.asyncIterator,{value:ue.prototype.values,writable:!0,configurable:!0});try{Object.defineProperty((function(l){return l.byteLength}),"name",{value:"size",configurable:!0})}catch(Ul){}try{Object.defineProperty((function(){return 1}),"name",{value:"size",configurable:!0})}catch(Ul){}function he(l,n){var u;(u=l._transformStreamController)._transformAlgorithm=void 0,u._flushAlgorithm=void 0,gu(l._writable._writableStreamController,n),l._backpressure&&fe(l,!1)}function fe(l,n){void 0!==l._backpressureChangePromise&&l._backpressureChangePromise_resolve(),l._backpressureChangePromise=Y((function(n){l._backpressureChangePromise_resolve=n})),l._backpressure=n}var pe=function(){function l(){throw new TypeError("Illegal constructor")}return Object.defineProperty(l.prototype,"desiredSize",{get:function(){if(!ye(this))throw me("desiredSize");return $u(this._controlledTransformStream._readable._readableStreamController)},enumerable:!1,configurable:!0}),l.prototype.enqueue=function(l){if(void 0===l&&(l=void 0),!ye(this))throw me("enqueue");!function(l,n){var u=l._controlledTransformStream,e=u._readable._readableStreamController;if(!Hu(e))throw new TypeError("Readable side is not in a state that permits enqueue");try{zu(e,n)}catch(l){throw he(u,l),u._readable._storedError}(function(l){return!qu(l)})(e)!==u._backpressure&&fe(u,!0)}(this,l)},l.prototype.error=function(l){if(void 0===l&&(l=void 0),!ye(this))throw me("error");var n;n=l,function(l,n){Qu(l._readable._readableStreamController,n),he(l,n)}(this._controlledTransformStream,n)},l.prototype.terminate=function(){if(!ye(this))throw me("terminate");!function(l){var n=l._controlledTransformStream;Wu(n._readable._readableStreamController);var u=new TypeError("TransformStream terminated");he(n,u)}(this)},l}();function ye(l){return!!z(l)&&(!!Object.prototype.hasOwnProperty.call(l,"_controlledTransformStream")&&l instanceof pe)}function me(l){return new TypeError("TransformStreamDefaultController.prototype."+l+" can only be used on a TransformStreamDefaultController")}Object.defineProperties(pe.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof q.toStringTag&&Object.defineProperty(pe.prototype,q.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});for(var ge={},be={byteLength:function(l){var n=Te(l),u=n[0],e=n[1];return 3*(u+e)/4-e},toByteArray:function(l){var n,u,e=Te(l),t=e[0],r=e[1],o=new we(function(l,n,u){return 3*(n+u)/4-u}(0,t,r)),i=0,a=r>0?t-4:t;for(u=0;u<a;u+=4)n=Ee[l.charCodeAt(u)]<<18|Ee[l.charCodeAt(u+1)]<<12|Ee[l.charCodeAt(u+2)]<<6|Ee[l.charCodeAt(u+3)],o[i++]=n>>16&255,o[i++]=n>>8&255,o[i++]=255&n;2===r&&(n=Ee[l.charCodeAt(u)]<<2|Ee[l.charCodeAt(u+1)]>>4,o[i++]=255&n);1===r&&(n=Ee[l.charCodeAt(u)]<<10|Ee[l.charCodeAt(u+1)]<<4|Ee[l.charCodeAt(u+2)]>>2,o[i++]=n>>8&255,o[i++]=255&n);return o},fromByteArray:function(l){for(var n,u=l.length,e=u%3,t=[],r=16383,o=0,i=u-e;o<i;o+=r)t.push(Re(l,o,o+r>i?i:o+r));1===e?(n=l[u-1],t.push(ve[n>>2]+ve[n<<4&63]+"==")):2===e&&(n=(l[u-2]<<8)+l[u-1],t.push(ve[n>>10]+ve[n>>4&63]+ve[n<<2&63]+"="));return t.join("")}},ve=[],Ee=[],we="undefined"!=typeof Uint8Array?Uint8Array:Array,_e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Se=0;Se<64;++Se)ve[Se]=_e[Se],Ee[_e.charCodeAt(Se)]=Se;function Te(l){var n=l.length;if(n%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var u=l.indexOf("=");return-1===u&&(u=n),[u,u===n?0:4-u%4]}function Re(l,n,u){for(var e,t,r=[],o=n;o<u;o+=3)e=(l[o]<<16&16711680)+(l[o+1]<<8&65280)+(255&l[o+2]),r.push(ve[(t=e)>>18&63]+ve[t>>12&63]+ve[t>>6&63]+ve[63&t]);return r.join("")}Ee["-".charCodeAt(0)]=62,Ee["_".charCodeAt(0)]=63;var Oe={
7
7
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
8
8
  read:function(l,n,u,e,t){var r,o,i=8*t-e-1,a=(1<<i)-1,s=a>>1,c=-7,d=u?t-1:0,h=u?-1:1,f=l[n+d];for(d+=h,r=f&(1<<-c)-1,f>>=-c,c+=i;c>0;r=256*r+l[n+d],d+=h,c-=8);for(o=r&(1<<-c)-1,r>>=-c,c+=e;c>0;o=256*o+l[n+d],d+=h,c-=8);if(0===r)r=1-s;else{if(r===a)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,e),r-=s}return(f?-1:1)*o*Math.pow(2,r-e)},write:function(l,n,u,e,t,r){var o,i,a,s=8*r-t-1,c=(1<<s)-1,d=c>>1,h=23===t?Math.pow(2,-24)-Math.pow(2,-77):0,f=e?0:r-1,p=e?1:-1,y=n<0||0===n&&1/n<0?1:0;for(n=Math.abs(n),isNaN(n)||n===1/0?(i=isNaN(n)?1:0,o=c):(o=Math.floor(Math.log(n)/Math.LN2),n*(a=Math.pow(2,-o))<1&&(o--,a*=2),(n+=o+d>=1?h/a:h*Math.pow(2,1-d))*a>=2&&(o++,a/=2),o+d>=c?(i=0,o=c):o+d>=1?(i=(n*a-1)*Math.pow(2,t),o+=d):(i=n*Math.pow(2,d-1)*Math.pow(2,t),o=0));t>=8;l[u+f]=255&i,f+=p,i/=256,t-=8);for(o=o<<t|i,s+=t;s>0;l[u+f]=255&o,f+=p,o/=256,s-=8);l[u+f-p]|=128*y}};
9
9
  /*!
@@ -19,4 +19,4 @@ read:function(l,n,u,e,t){var r,o,i=8*t-e-1,a=(1<<i)-1,s=a>>1,c=-7,d=u?t-1:0,h=u?
19
19
  * @author Feross Aboukhadijeh <https://feross.org>
20
20
  * @license MIT
21
21
  */
22
- !function(l){var n=be,u=Oe,e="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;l.Buffer=o,l.SlowBuffer=function(l){+l!=l&&(l=0);return o.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,o.prototype),n}function o(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 s(l)}return i(l,n,u)}function i(l,n,u){if("string"==typeof l)return function(l,n){"string"==typeof n&&""!==n||(n="utf8");if(!o.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 d(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 d(l,n,u);if("undefined"!=typeof SharedArrayBuffer&&(B(l,SharedArrayBuffer)||l&&B(l.buffer,SharedArrayBuffer)))return d(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 o.from(e,n,u);var t=function(l){if(o.isBuffer(l)){var n=0|h(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 o.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 a(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 s(l){return a(l),r(l<0?0:0|h(l))}function c(l){for(var n=l.length<0?0:0|h(l.length),u=r(n),e=0;e<n;e+=1)u[e]=255&l[e];return u}function d(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,o.prototype),e}function h(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(o.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 U(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:U(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 C(this,n,u);case"utf8":case"utf-8":return T(this,n,u);case"ascii":return O(this,n,u);case"latin1":case"binary":return A(this,n,u);case"base64":return S(this,n,u);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return F(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=o.from(n,e)),o.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,o=1,i=l.length,a=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;o=2,i/=2,a/=2,u/=2}function s(l,n){return 1===o?l[n]:l.readUInt16BE(n*o)}if(t){var c=-1;for(r=u;r<i;r++)if(s(l,r)===s(n,-1===c?0:r-c)){if(-1===c&&(c=r),r-c+1===a)return c*o}else-1!==c&&(r-=r-c),c=-1}else for(u+a>i&&(u=i-a),r=u;r>=0;r--){for(var d=!0,h=0;h<a;h++)if(s(l,r+h)!==s(n,h)){d=!1;break}if(d)return r}return-1}function b(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 o=0;o<e;++o){var i=parseInt(n.substr(2*o,2),16);if(q(i))return o;l[u+o]=i}return o}function v(l,n,u,e){return M(U(n,l.length-u),l,u,e)}function E(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 w(l,n,u,e){return M(D(n),l,u,e)}function _(l,n,u,e){return M(function(l,n){for(var u,e,t,r=[],o=0;o<l.length&&!((n-=2)<0);++o)e=(u=l.charCodeAt(o))>>8,t=u%256,r.push(t),r.push(e);return r}(n,l.length-u),l,u,e)}function S(l,u,e){return 0===u&&e===l.length?n.fromByteArray(l):n.fromByteArray(l.slice(u,e))}function T(l,n,u){u=Math.min(l.length,u);for(var e=[],t=n;t<u;){var r,o,i,a,s=l[t],c=null,d=s>239?4:s>223?3:s>191?2:1;if(t+d<=u)switch(d){case 1:s<128&&(c=s);break;case 2:128==(192&(r=l[t+1]))&&(a=(31&s)<<6|63&r)>127&&(c=a);break;case 3:r=l[t+1],o=l[t+2],128==(192&r)&&128==(192&o)&&(a=(15&s)<<12|(63&r)<<6|63&o)>2047&&(a<55296||a>57343)&&(c=a);break;case 4:r=l[t+1],o=l[t+2],i=l[t+3],128==(192&r)&&128==(192&o)&&128==(192&i)&&(a=(15&s)<<18|(63&r)<<12|(63&o)<<6|63&i)>65535&&a<1114112&&(c=a)}null===c?(c=65533,d=1):c>65535&&(c-=65536,e.push(c>>>10&1023|55296),c=56320|1023&c),e.push(c),t+=d}return function(l){var n=l.length;if(n<=R)return String.fromCharCode.apply(String,l);var u="",e=0;for(;e<n;)u+=String.fromCharCode.apply(String,l.slice(e,e+=R));return u}(e)}l.kMaxLength=t,o.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}}(),o.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(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),o.poolSize=8192,o.from=function(l,n,u){return i(l,n,u)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array),o.alloc=function(l,n,u){return function(l,n,u){return a(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)},o.allocUnsafe=function(l){return s(l)},o.allocUnsafeSlow=function(l){return s(l)},o.isBuffer=function(l){return null!=l&&!0===l._isBuffer&&l!==o.prototype},o.compare=function(l,n){if(B(l,Uint8Array)&&(l=o.from(l,l.offset,l.byteLength)),B(n,Uint8Array)&&(n=o.from(n,n.offset,n.byteLength)),!o.isBuffer(l)||!o.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},o.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}},o.concat=function(l,n){if(!Array.isArray(l))throw new TypeError('"list" argument must be an Array of Buffers');if(0===l.length)return o.alloc(0);var u;if(void 0===n)for(n=0,u=0;u<l.length;++u)n+=l[u].length;var e=o.allocUnsafe(n),t=0;for(u=0;u<l.length;++u){var r=l[u];if(B(r,Uint8Array))t+r.length>e.length?o.from(r).copy(e,t):Uint8Array.prototype.set.call(e,r,t);else{if(!o.isBuffer(r))throw new TypeError('"list" argument must be an Array of Buffers');r.copy(e,t)}t+=r.length}return e},o.byteLength=f,o.prototype._isBuffer=!0,o.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},o.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},o.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},o.prototype.toString=function(){var l=this.length;return 0===l?"":0===arguments.length?T(this,0,l):p.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(l){if(!o.isBuffer(l))throw new TypeError("Argument must be a Buffer");return this===l||0===o.compare(this,l)},o.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&&(o.prototype[e]=o.prototype.inspect),o.prototype.compare=function(l,n,u,e,t){if(B(l,Uint8Array)&&(l=o.from(l,l.offset,l.byteLength)),!o.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),i=(u>>>=0)-(n>>>=0),a=Math.min(r,i),s=this.slice(e,t),c=l.slice(n,u),d=0;d<a;++d)if(s[d]!==c[d]){r=s[d],i=c[d];break}return r<i?-1:i<r?1:0},o.prototype.includes=function(l,n,u){return-1!==this.indexOf(l,n,u)},o.prototype.indexOf=function(l,n,u){return m(this,l,n,u,!0)},o.prototype.lastIndexOf=function(l,n,u){return m(this,l,n,u,!1)},o.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 b(this,l,n,u);case"utf8":case"utf-8":return v(this,l,n,u);case"ascii":case"latin1":case"binary":return E(this,l,n,u);case"base64":return w(this,l,n,u);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,l,n,u);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(""+e).toLowerCase(),r=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var R=4096;function O(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 A(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 C(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 F(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(!o.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 P(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 L(l,n,e,t,r){return n=+n,e>>>=0,r||P(l,0,e,4),u.write(l,n,e,t,23,4),e+4}function N(l,n,e,t,r){return n=+n,e>>>=0,r||P(l,0,e,8),u.write(l,n,e,t,52,8),e+8}o.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,o.prototype),e},o.prototype.readUintLE=o.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},o.prototype.readUintBE=o.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},o.prototype.readUint8=o.prototype.readUInt8=function(l,n){return l>>>=0,n||I(l,1,this.length),this[l]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(l,n){return l>>>=0,n||I(l,2,this.length),this[l]|this[l+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(l,n){return l>>>=0,n||I(l,2,this.length),this[l]<<8|this[l+1]},o.prototype.readUint32LE=o.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]},o.prototype.readUint32BE=o.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])},o.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},o.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},o.prototype.readInt8=function(l,n){return l>>>=0,n||I(l,1,this.length),128&this[l]?-1*(255-this[l]+1):this[l]},o.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},o.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},o.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},o.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]},o.prototype.readFloatLE=function(l,n){return l>>>=0,n||I(l,4,this.length),u.read(this,l,!0,23,4)},o.prototype.readFloatBE=function(l,n){return l>>>=0,n||I(l,4,this.length),u.read(this,l,!1,23,4)},o.prototype.readDoubleLE=function(l,n){return l>>>=0,n||I(l,8,this.length),u.read(this,l,!0,52,8)},o.prototype.readDoubleBE=function(l,n){return l>>>=0,n||I(l,8,this.length),u.read(this,l,!1,52,8)},o.prototype.writeUintLE=o.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},o.prototype.writeUintBE=o.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},o.prototype.writeUint8=o.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},o.prototype.writeUint16LE=o.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},o.prototype.writeUint16BE=o.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},o.prototype.writeUint32LE=o.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},o.prototype.writeUint32BE=o.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},o.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,o=1,i=0;for(this[n]=255&l;++r<u&&(o*=256);)l<0&&0===i&&0!==this[n+r-1]&&(i=1),this[n+r]=(l/o|0)-i&255;return n+u},o.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,o=1,i=0;for(this[n+r]=255&l;--r>=0&&(o*=256);)l<0&&0===i&&0!==this[n+r+1]&&(i=1),this[n+r]=(l/o|0)-i&255;return n+u},o.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},o.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},o.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},o.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},o.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},o.prototype.writeFloatLE=function(l,n,u){return L(this,l,n,!0,u)},o.prototype.writeFloatBE=function(l,n,u){return L(this,l,n,!1,u)},o.prototype.writeDoubleLE=function(l,n,u){return N(this,l,n,!0,u)},o.prototype.writeDoubleBE=function(l,n,u){return N(this,l,n,!1,u)},o.prototype.copy=function(l,n,u,e){if(!o.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},o.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&&!o.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 i=o.isBuffer(l)?l:o.from(l,e),a=i.length;if(0===a)throw new TypeError('The value "'+l+'" is invalid for argument "value"');for(r=0;r<u-n;++r)this[r+n]=i[r%a]}return this};var x=/[^+/0-9A-Za-z-_]/g;function U(l,n){var u;n=n||1/0;for(var e=l.length,t=null,r=[],o=0;o<e;++o){if((u=l.charCodeAt(o))>55295&&u<57344){if(!t){if(u>56319){(n-=3)>-1&&r.push(239,191,189);continue}if(o+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}()}(xe);var Ue={},De={};!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}}(De),function(l){var n=r&&r.__generator||function(l,n){var u,e,t,r,o={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function i(r){return function(i){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:r[1],done:!1};case 5:o.label++,e=r[1],r=[0];continue;case 7:r=o.ops.pop(),o.trys.pop();continue;default:if(!(t=o.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){o=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){o.label=r[1];break}if(6===r[0]&&o.label<t[1]){o.label=t[1],t=r;break}if(t&&o.label<t[2]){o.label=t[2],o.ops.push(r);break}t[2]&&o.ops.pop(),o.trys.pop();continue}r=n.call(l,o)}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,i])}}};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=De;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 o(l,n,u){return u=l.writeUInt8(n>>>16,u),u=l.writeUInt8(n>>>8&255,u),l.writeUInt8(255&n,u)}function i(l,n){var u=l.readUInt32BE(n),t=l.readUInt32BE(n+4);return u*e+t}function a(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=o,l.readUInt64BE=i,l.writeUInt64BE=a;function s(l){var n=t(l,0);return d(l.slice(3,3+n))}function c(l){var u,e,r,o,i;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),(o=(r=u+3)+e)>l.length?[3,3]:(i=l.slice(r,o),[4,[d(i),u=o]])):[3,3];case 2:return n.sent(),[3,1];case 3:return[2]}}))}function d(n){var e=0,t=n.readInt32BE(e);e+=4;var r=n.readUInt16BE(e);e+=2;var o=r>>>l.FRAME_TYPE_OFFFSET,a=r&l.FLAGS_MASK;switch(o){case u.FrameTypes.SETUP:return function(l,n,e){l.length;var t=6,r=l.readUInt16BE(t);t+=2;var o=l.readUInt16BE(t);t+=2;var i=l.readInt32BE(t);t+=4;var a=l.readInt32BE(t);t+=4;var s=null;if(e&u.Flags.RESUME_ENABLE){var c=l.readInt16BE(t);t+=2,s=l.slice(t,t+c),t+=c}var d=l.readUInt8(t);t+=1;var h=l.toString("ascii",t,t+d);t+=d;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:i,lifetime:a,majorVersion:r,metadata:null,metadataMimeType:h,minorVersion:o,resumeToken:s,streamId:0,type:u.FrameTypes.SETUP};return R(l,y,t),y}(n,0,a);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 R(l,t,6),t}(n,t,a);case u.FrameTypes.ERROR:return function(l,n,e){l.length;var t=6,r=l.readInt32BE(t);t+=4;var o=l.length-t,i="";o>0&&(i=l.toString("utf8",t,t+o),t+=o);return{code:r,flags:e,message:i,streamId:n,type:u.FrameTypes.ERROR}}(n,t,a);case u.FrameTypes.KEEPALIVE:return function(l,n,e){l.length;var t=6,r=i(l,t);t+=8;var o=null;t<l.length&&(o=l.slice(t,l.length));return{data:o,flags:e,lastReceivedPosition:r,streamId:0,type:u.FrameTypes.KEEPALIVE}}(n,0,a);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 R(l,t,6),t}(n,t,a);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 R(l,t,6),t}(n,t,a);case u.FrameTypes.REQUEST_STREAM:return function(l,n,e){l.length;var t=6,r=l.readInt32BE(t);t+=4;var o={data:null,flags:e,metadata:null,requestN:r,streamId:n,type:u.FrameTypes.REQUEST_STREAM};return R(l,o,t),o}(n,t,a);case u.FrameTypes.REQUEST_CHANNEL:return function(l,n,e){l.length;var t=6,r=l.readInt32BE(t);t+=4;var o={data:null,flags:e,metadata:null,requestN:r,streamId:n,type:u.FrameTypes.REQUEST_CHANNEL};return R(l,o,t),o}(n,t,a);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,a);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,a);case u.FrameTypes.RESUME:return function(l,n,e){l.length;var t=6,r=l.readUInt16BE(t);t+=2;var o=l.readUInt16BE(t);t+=2;var a=l.readInt16BE(t);t+=2;var s=l.slice(t,t+a);t+=a;var c=i(l,t);t+=8;var d=i(l,t);return t+=8,{clientPosition:d,flags:e,majorVersion:r,minorVersion:o,resumeToken:s,serverPosition:c,streamId:0,type:u.FrameTypes.RESUME}}(n,0,a);case u.FrameTypes.RESUME_OK:return function(l,n,e){l.length;var t=i(l,6);return{clientPosition:t,flags:e,streamId:0,type:u.FrameTypes.RESUME_OK}}(n,0,a);case u.FrameTypes.CANCEL:return function(l,n,e){return l.length,{flags:e,streamId:n,type:u.FrameTypes.CANCEL}}(n,t,a);case u.FrameTypes.LEASE:return function(l,n,e){var t=6,r=l.readUInt32BE(t);t+=4;var o=l.readUInt32BE(t);t+=4;var i=null;t<l.length&&(i=l.slice(t,l.length));return{flags:e,metadata:i,requestCount:o,streamId:0,ttl:r,type:u.FrameTypes.LEASE}}(n,0,a)}}function h(l){switch(l.type){case u.FrameTypes.SETUP:return function(l){var n=null!=l.resumeToken?l.resumeToken.byteLength:0,e=null!=l.metadataMimeType?xe.Buffer.byteLength(l.metadataMimeType,"ascii"):0,t=null!=l.dataMimeType?xe.Buffer.byteLength(l.dataMimeType,"ascii"):0,r=S(l),o=xe.Buffer.allocUnsafe(6+f+(n?p+n:0)+e+t+r),i=_(l,o);i=o.writeUInt16BE(l.majorVersion,i),i=o.writeUInt16BE(l.minorVersion,i),i=o.writeUInt32BE(l.keepAlive,i),i=o.writeUInt32BE(l.lifetime,i),l.flags&u.Flags.RESUME_ENABLE&&(i=o.writeUInt16BE(n,i),null!=l.resumeToken&&(i+=l.resumeToken.copy(o,i)));i=o.writeUInt8(e,i),null!=l.metadataMimeType&&(i+=o.write(l.metadataMimeType,i,i+e,"ascii"));i=o.writeUInt8(t,i),null!=l.dataMimeType&&(i+=o.write(l.dataMimeType,i,i+t,"ascii"));return T(l,o,i),o}(l);case u.FrameTypes.PAYLOAD:return function(l){var n=S(l),u=xe.Buffer.allocUnsafe(6+n),e=_(l,u);return T(l,u,e),u}(l);case u.FrameTypes.ERROR:return function(l){var n=null!=l.message?xe.Buffer.byteLength(l.message,"utf8"):0,u=xe.Buffer.allocUnsafe(6+y+n),e=_(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=xe.Buffer.allocUnsafe(6+m+n),e=_(l,u);e=a(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=S(l),u=xe.Buffer.allocUnsafe(6+n),e=_(l,u);return T(l,u,e),u}(l);case u.FrameTypes.REQUEST_STREAM:case u.FrameTypes.REQUEST_CHANNEL:return function(l){var n=S(l),u=xe.Buffer.allocUnsafe(6+b+n),e=_(l,u);return e=u.writeUInt32BE(l.requestN,e),T(l,u,e),u}(l);case u.FrameTypes.METADATA_PUSH:return function(l){var n=l.metadata;if(null!=n){var u=_(l,e=xe.Buffer.allocUnsafe(6+n.byteLength));return n.copy(e,u),e}var e;return _(l,e=xe.Buffer.allocUnsafe(6)),e}(l);case u.FrameTypes.REQUEST_N:return function(l){var n=xe.Buffer.allocUnsafe(6+v),u=_(l,n);return n.writeUInt32BE(l.requestN,u),n}(l);case u.FrameTypes.RESUME:return function(l){var n=l.resumeToken.byteLength,u=xe.Buffer.allocUnsafe(6+E+n),e=_(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=a(u,l.serverPosition,e),a(u,l.clientPosition,e),u}(l);case u.FrameTypes.RESUME_OK:return function(l){var n=xe.Buffer.allocUnsafe(6+w),u=_(l,n);return a(n,l.clientPosition,u),n}(l);case u.FrameTypes.CANCEL:return function(l){var n=xe.Buffer.allocUnsafe(6);return _(l,n),n}(l);case u.FrameTypes.LEASE:return function(l){var n=null!=l.metadata?l.metadata.byteLength:0,u=xe.Buffer.allocUnsafe(6+g+n),e=_(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=s,l.deserializeFrames=c,l.serializeFrameWithLength=function(l){var n=h(l),u=xe.Buffer.allocUnsafe(n.length+3);return o(u,n.length,0),n.copy(u,3),u},l.deserializeFrame=d,l.serializeFrame=h,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?xe.Buffer.byteLength(l.metadataMimeType,"ascii"):0,e=null!=l.dataMimeType?xe.Buffer.byteLength(l.dataMimeType,"ascii"):0,t=S(l);return 6+f+(n?p+n:0)+u+e+t}(l);case u.FrameTypes.PAYLOAD:return function(l){var n=S(l);return 6+n}(l);case u.FrameTypes.ERROR:return function(l){var n=null!=l.message?xe.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=S(l);return 6+n}(l);case u.FrameTypes.REQUEST_STREAM:case u.FrameTypes.REQUEST_CHANNEL:return function(l){var n=S(l);return 6+b+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+v;case u.FrameTypes.RESUME:return function(l){var n=l.resumeToken.byteLength;return 6+E+n}(l);case u.FrameTypes.RESUME_OK:return 6+w;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 b=4;var v=4;var E=22;var w=8;function _(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 S(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 T(l,n,e){u.Flags.hasMetadata(l.flags)&&(null!=l.metadata?(e=o(n,l.metadata.byteLength,e),e+=l.metadata.copy(n,e)):e=o(n,0,e));null!=l.data&&l.data.copy(n,e)}function R(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 O=function(){function l(){}return l.prototype.deserializeFrame=function(l){return d(l)},l.prototype.deserializeFrameWithLength=function(l){return s(l)},l.prototype.deserializeFrames=function(l){return c(l)},l}();l.Deserializer=O}(Ue);var Me={};Object.defineProperty(Me,"__esModule",{value:!0});var Be={},qe=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(Be,"__esModule",{value:!0}),Be.Deferred=void 0;var je=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=qe(this.onCloseCallbacks),o=r.next();!o.done;o=r.next()){(0,o.value)(l)}}catch(l){n={error:l}}finally{try{o&&!o.done&&(u=r.return)&&u.call(r)}finally{if(n)throw n.error}}else try{for(var i=qe(this.onCloseCallbacks),a=i.next();!a.done;a=i.next()){(0,a.value)()}}catch(l){e={error:l}}finally{try{a&&!a.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}},l.prototype.onClose=function(l){this._done?l(this._error):this.onCloseCallbacks.push(l)},l}();Be.Deferred=je;var We={};!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"}(We);var ze={};Object.defineProperty(ze,"__esModule",{value:!0});var Qe,$e={},He={};function Ve(){return Qe||(Qe=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 o(l){try{a(e.next(l))}catch(l){r(l)}}function i(l){try{a(e.throw(l))}catch(l){r(l)}}function a(l){var n;l.done?t(l.value):(n=l.value,n instanceof u?n:new u((function(l){l(n)}))).then(o,i)}a((e=e.apply(l,n||[])).next())}))},t=r&&r.__generator||function(l,n){var u,e,t,r,o={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function i(r){return function(i){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:r[1],done:!1};case 5:o.label++,e=r[1],r=[0];continue;case 7:r=o.ops.pop(),o.trys.pop();continue;default:if(!(t=o.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){o=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){o.label=r[1];break}if(6===r[0]&&o.label<t[1]){o.label=t[1],t=r;break}if(t&&o.label<t[2]){o.label=t[2],o.ops.push(r);break}t[2]&&o.ops.pop(),o.trys.pop();continue}r=n.call(l,o)}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,i])}}};Object.defineProperty(l,"__esModule",{value:!0}),l.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer=l.ResumableClientServerInputMultiplexerDemultiplexer=l.ClientServerInputMultiplexerDemultiplexer=l.StreamIdGenerator=void 0;var o=fr(),i=Be,a=We,s=De;!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(s.Frame.isConnection(l)){if(l.type===o.FrameTypes.RESERVED)return;this.connectionFramesHandler.handle(l)}else if(s.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}(i.Deferred);l.ClientServerInputMultiplexerDemultiplexer=c;var d=function(l){function n(n,u,e,t,r,o,a){var s=l.call(this,n,u,new i.Deferred)||this;return s.frameStore=t,s.token=r,s.sessionTimeout=a,o instanceof Function?s.reconnector=o:s.sessionStore=o,e.onClose(s.handleConnectionClose.bind(s)),s}return u(n,l),n.prototype.send=function(n){if(s.Frame.isConnection(n)){if(n.type===o.FrameTypes.KEEPALIVE)n.lastReceivedPosition=this.frameStore.lastReceivedFramePosition;else if(n.type===o.FrameTypes.ERROR)return this.outbound.send(n),this.sessionStore&&delete this.sessionStore[this.token],void l.prototype.close.call(this,new a.RSocketError(n.code,n.message))}else this.frameStore.store(n);this.outbound.send(n)},n.prototype.handle=function(n){if(s.Frame.isConnection(n)){if(n.type===o.FrameTypes.KEEPALIVE)try{this.frameStore.dropTo(n.lastReceivedPosition)}catch(l){this.outbound.send({type:o.FrameTypes.ERROR,streamId:0,flags:o.Flags.NONE,code:l.code,message:l.message}),this.close(l)}else if(n.type===o.FrameTypes.ERROR)return l.prototype.handle.call(this,n),this.sessionStore&&delete this.sessionStore[this.token],void l.prototype.close.call(this,new a.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 o.FrameTypes.RESUME:if(clearTimeout(this.timeoutId),this.frameStore.lastReceivedFramePosition<l.clientPosition){var e=new a.RSocketError(o.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:o.FrameTypes.ERROR,streamId:0,flags:o.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:o.FrameTypes.ERROR,streamId:0,flags:o.Flags.NONE,code:l.code,message:l.message}),void this.close(l)}this.outbound.send({type:o.FrameTypes.RESUME_OK,streamId:0,flags:o.Flags.NONE,clientPosition:this.frameStore.lastReceivedFramePosition});break;case o.FrameTypes.RESUME_OK:try{this.frameStore.dropTo(l.clientPosition)}catch(l){this.outbound.send({type:o.FrameTypes.ERROR,streamId:0,flags:o.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=d;var h=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===o.FrameTypes.RESUME_OK?(this.resumed=!0,void this.delegate.resume(l,this.outbound,this.closeable)):(this.outbound.send({type:o.FrameTypes.ERROR,streamId:0,code:o.ErrorCodes.CONNECTION_ERROR,message:"Incomplete RESUME handshake. Unexpected frame ".concat(l.type," received"),flags:o.Flags.NONE}),this.closeable.close(),void this.closeable.onClose((function(){return n.delegate.close(new a.RSocketError(o.ErrorCodes.CONNECTION_ERROR,"Incomplete RESUME handshake. Unexpected frame ".concat(l.type," received")))})));this.delegate.handle(l)},l}();l.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer=h}(He)),He}var Je={},Ye={},Ge={},Xe=r&&r.__generator||function(l,n){var u,e,t,r,o={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function i(r){return function(i){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:r[1],done:!1};case 5:o.label++,e=r[1],r=[0];continue;case 7:r=o.ops.pop(),o.trys.pop();continue;default:if(!(t=o.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){o=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){o.label=r[1];break}if(6===r[0]&&o.label<t[1]){o.label=t[1],t=r;break}if(t&&o.label<t[2]){o.label=t[2],o.ops.push(r);break}t[2]&&o.ops.pop(),o.trys.pop();continue}r=n.call(l,o)}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,i])}}};Object.defineProperty(Ge,"__esModule",{value:!0}),Ge.fragmentWithRequestN=Ge.fragment=Ge.isFragmentable=void 0;var Ke=De;Ge.isFragmentable=function(l,n,u){return 0!==n&&l.data.byteLength+(l.metadata?l.metadata.byteLength+Ke.Lengths.METADATA:0)+(u==Ke.FrameTypes.REQUEST_STREAM||u==Ke.FrameTypes.REQUEST_CHANNEL?Ke.Lengths.REQUEST:0)>n},Ge.fragment=function(l,n,u,e,t){var r,o,i,a,s,c,d,h,f,p,y,m;return void 0===t&&(t=!1),Xe(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,o=e!==Ke.FrameTypes.PAYLOAD,i=u,n.metadata?0!==(s=n.metadata.byteLength)?[3,1]:(i-=Ke.Lengths.METADATA,a=xe.Buffer.allocUnsafe(0),[3,6]):[3,6];case 1:return c=0,o?(i-=Ke.Lengths.METADATA,d=Math.min(s,c+i),a=n.metadata.slice(c,d),i-=a.byteLength,c=d,0!==i?[3,3]:(o=!1,[4,{type:e,flags:Ke.Flags.FOLLOWS|Ke.Flags.METADATA,data:void 0,metadata:a,streamId:l}])):[3,3];case 2:g.sent(),a=void 0,i=u,g.label=3;case 3:return c<s?(i-=Ke.Lengths.METADATA,d=Math.min(s,c+i),a=n.metadata.slice(c,d),i-=a.byteLength,c=d,0!==i&&0!==r?[3,5]:[4,{type:Ke.FrameTypes.PAYLOAD,flags:Ke.Flags.NEXT|Ke.Flags.METADATA|(c===s&&t&&0===r?Ke.Flags.COMPLETE:Ke.Flags.FOLLOWS),data:void 0,metadata:a,streamId:l}]):[3,6];case 4:g.sent(),a=void 0,i=u,g.label=5;case 5:return[3,3];case 6:return h=0,o?(p=Math.min(r,h+i),f=n.data.slice(h,p),i-=f.byteLength,h=p,[4,{type:e,flags:Ke.Flags.FOLLOWS|(a?Ke.Flags.METADATA:Ke.Flags.NONE),data:f,metadata:a,streamId:l}]):[3,8];case 7:g.sent(),a=void 0,f=void 0,i=u,g.label=8;case 8:return h<r?(p=Math.min(r,h+i),f=n.data.slice(h,p),i-=f.byteLength,h=p,[4,{type:Ke.FrameTypes.PAYLOAD,flags:h===r?(t?Ke.Flags.COMPLETE:Ke.Flags.NONE)|Ke.Flags.NEXT|(a?Ke.Flags.METADATA:0):Ke.Flags.FOLLOWS|Ke.Flags.NEXT|(a?Ke.Flags.METADATA:0),data:f,metadata:a,streamId:l}]):[3,10];case 9:return g.sent(),a=void 0,f=void 0,i=u,[3,8];case 10:return[2]}}))},Ge.fragmentWithRequestN=function(l,n,u,e,t,r){var o,i,a,s,c,d,h,f,p,y,m,g;return void 0===r&&(r=!1),Xe(this,(function(b){switch(b.label){case 0:return o=null!==(g=null===(m=n.data)||void 0===m?void 0:m.byteLength)&&void 0!==g?g:0,i=!0,a=u,n.metadata?0!==(c=n.metadata.byteLength)?[3,1]:(a-=Ke.Lengths.METADATA,s=xe.Buffer.allocUnsafe(0),[3,6]):[3,6];case 1:return d=0,i?(a-=Ke.Lengths.METADATA+Ke.Lengths.REQUEST,h=Math.min(c,d+a),s=n.metadata.slice(d,h),a-=s.byteLength,d=h,0!==a?[3,3]:(i=!1,[4,{type:e,flags:Ke.Flags.FOLLOWS|Ke.Flags.METADATA,data:void 0,requestN:t,metadata:s,streamId:l}])):[3,3];case 2:b.sent(),s=void 0,a=u,b.label=3;case 3:return d<c?(a-=Ke.Lengths.METADATA,h=Math.min(c,d+a),s=n.metadata.slice(d,h),a-=s.byteLength,d=h,0!==a&&0!==o?[3,5]:[4,{type:Ke.FrameTypes.PAYLOAD,flags:Ke.Flags.NEXT|Ke.Flags.METADATA|(d===c&&r&&0===o?Ke.Flags.COMPLETE:Ke.Flags.FOLLOWS),data:void 0,metadata:s,streamId:l}]):[3,6];case 4:b.sent(),s=void 0,a=u,b.label=5;case 5:return[3,3];case 6:return f=0,i?(a-=Ke.Lengths.REQUEST,y=Math.min(o,f+a),p=n.data.slice(f,y),a-=p.byteLength,f=y,[4,{type:e,flags:Ke.Flags.FOLLOWS|(s?Ke.Flags.METADATA:Ke.Flags.NONE),data:p,requestN:t,metadata:s,streamId:l}]):[3,8];case 7:b.sent(),s=void 0,p=void 0,a=u,b.label=8;case 8:return f<o?(y=Math.min(o,f+a),p=n.data.slice(f,y),a-=p.byteLength,f=y,[4,{type:Ke.FrameTypes.PAYLOAD,flags:f===o?(r?Ke.Flags.COMPLETE:Ke.Flags.NONE)|Ke.Flags.NEXT|(s?Ke.Flags.METADATA:0):Ke.Flags.FOLLOWS|Ke.Flags.NEXT|(s?Ke.Flags.METADATA:0),data:p,metadata:s,streamId:l}]):[3,10];case 9:return b.sent(),s=void 0,p=void 0,a=u,[3,8];case 10:return[2]}}))};var Ze={};Object.defineProperty(Ze,"__esModule",{value:!0}),Ze.cancel=Ze.reassemble=Ze.add=void 0,Ze.add=function(l,n,u){return l.hasFragments?(l.data=l.data?xe.Buffer.concat([l.data,n]):n,l.metadata&&u&&(l.metadata=xe.Buffer.concat([l.metadata,u])),!0):(l.hasFragments=!0,l.data=n,u&&(l.metadata=u),!0)},Ze.reassemble=function(l,n,u){l.hasFragments=!1;var e=l.data?xe.Buffer.concat([l.data,n]):n;if(l.data=void 0,l.metadata){var t=u?xe.Buffer.concat([l.metadata,u]):l.metadata;return l.metadata=void 0,{data:e,metadata:t}}return{data:e}},Ze.cancel=function(l){l.hasFragments=!1,l.data=void 0,l.metadata=void 0};var lt=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]}),nt=r&&r.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),ut=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)&&lt(n,l,u);return nt(n,l),n},et=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(Ye,"__esModule",{value:!0}),Ye.RequestChannelResponderStream=Ye.RequestChannelRequesterStream=void 0;var tt=We,rt=Ge,ot=De,it=ut(Ze),at=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=ot.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,rt.isFragmentable)(this.payload,this.fragmentSize,ot.FrameTypes.REQUEST_CHANNEL))try{for(var r=et((0,rt.fragmentWithRequestN)(l,this.payload,this.fragmentSize,ot.FrameTypes.REQUEST_CHANNEL,this.initialRequestN,t)),o=r.next();!o.done;o=r.next()){var i=o.value;this.stream.send(i)}}catch(l){u={error:l}}finally{try{o&&!o.done&&(e=r.return)&&e.call(r)}finally{if(u)throw u.error}}else this.stream.send({type:ot.FrameTypes.REQUEST_CHANNEL,data:this.payload.data,metadata:this.payload.metadata,requestN:this.initialRequestN,flags:(void 0!==this.payload.metadata?ot.Flags.METADATA:ot.Flags.NONE)|(t?ot.Flags.COMPLETE:ot.Flags.NONE),streamId:l});return this.hasExtension&&this.stream.send({type:ot.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 ot.FrameTypes.PAYLOAD:var e=ot.Flags.hasComplete(l.flags),t=ot.Flags.hasNext(l.flags);if(e||!ot.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?it.reassemble(this,l.data,l.metadata):{data:l.data,metadata:l.metadata};return void this.receiver.onNext(r,e)}if(it.add(this,l.data,l.metadata))return;n="Unexpected frame size";break;case ot.FrameTypes.CANCEL:if(this.outboundDone)return;return this.outboundDone=!0,this.inboundDone&&this.stream.disconnect(this),void this.receiver.cancel();case ot.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 ot.FrameTypes.ERROR:var o=this.outboundDone;return this.inboundDone=!0,this.outboundDone=!0,this.stream.disconnect(this),it.cancel(this),o||this.receiver.cancel(),void this.receiver.onError(new tt.RSocketError(l.code,l.message));case ot.FrameTypes.EXT:return void this.receiver.onExtension(l.extendedType,l.extendedContent,ot.Flags.hasIgnore(l.flags));default:n="Unexpected frame type [".concat(u,"]")}this.close(new tt.RSocketError(tt.ErrorCodes.CANCELED,n)),this.stream.send({type:ot.FrameTypes.CANCEL,streamId:this.streamId,flags:ot.Flags.NONE}),this.stream.disconnect(this)},l.prototype.request=function(l){this.inboundDone||(this.streamId?this.stream.send({type:ot.FrameTypes.REQUEST_N,flags:ot.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?ot.FrameTypes.ERROR:ot.FrameTypes.CANCEL,flags:ot.Flags.NONE,streamId:this.streamId,code:tt.ErrorCodes.CANCELED,message:"Cancelled"}),this.stream.disconnect(this),it.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,rt.isFragmentable)(l,this.fragmentSize,ot.FrameTypes.PAYLOAD))try{for(var t=et((0,rt.fragment)(this.streamId,l,this.fragmentSize,ot.FrameTypes.PAYLOAD,n)),r=t.next();!r.done;r=t.next()){var o=r.value;this.stream.send(o)}}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:ot.FrameTypes.PAYLOAD,streamId:this.streamId,flags:ot.Flags.NEXT|(l.metadata?ot.Flags.METADATA:ot.Flags.NONE)|(n?ot.Flags.COMPLETE:ot.Flags.NONE),data:l.data,metadata:l.metadata})},l.prototype.onComplete=function(){this.streamId?this.outboundDone||(this.outboundDone=!0,this.stream.send({type:ot.FrameTypes.PAYLOAD,streamId:this.streamId,flags:ot.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:ot.FrameTypes.ERROR,streamId:this.streamId,flags:ot.Flags.NONE,code:l instanceof tt.RSocketError?l.code:tt.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:ot.FrameTypes.EXT,extendedType:l,extendedContent:n,flags:u?ot.Flags.IGNORE:ot.Flags.NONE}):(this.hasExtension=!0,this.extendedType=l,this.extendedContent=n,void(this.flags=u?ot.Flags.IGNORE:ot.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,it.cancel(this),u||this.receiver.cancel(),n||(l?this.receiver.onError(l):this.receiver.onComplete())}},l}();Ye.RequestChannelRequesterStream=at;var st=function(){function l(l,n,u,e,t){if(this.streamId=l,this.stream=n,this.fragmentSize=u,this.handler=e,this.streamType=ot.FrameTypes.REQUEST_CHANNEL,n.connect(this),ot.Flags.hasFollows(t.flags))return it.add(this,t.data,t.metadata),this.initialRequestN=t.requestN,void(this.isComplete=ot.Flags.hasComplete(t.flags));var r={data:t.data,metadata:t.metadata},o=ot.Flags.hasComplete(t.flags);this.inboundDone=o;try{this.receiver=e(r,t.requestN,o,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 ot.FrameTypes.PAYLOAD:if(ot.Flags.hasFollows(l.flags)){if(it.add(this,l.data,l.metadata))return;n="Unexpected frame size";break}var e=this.hasFragments?it.reassemble(this,l.data,l.metadata):{data:l.data,metadata:l.metadata},t=ot.Flags.hasComplete(l.flags);if(this.receiver){if(t&&(this.inboundDone=!0,this.outboundDone&&this.stream.disconnect(this),!ot.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(i){this.outboundDone&&!this.inboundDone?this.cancel():this.inboundDone=!0,this.onError(i)}}return;case ot.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 ot.FrameTypes.ERROR:case ot.FrameTypes.CANCEL:var r=this.inboundDone,o=this.outboundDone;if(this.inboundDone=!0,this.outboundDone=!0,this.stream.disconnect(this),it.cancel(this),!this.receiver)return;if(o||this.receiver.cancel(),!r){var i=u===ot.FrameTypes.CANCEL?new tt.RSocketError(tt.ErrorCodes.CANCELED,"Cancelled"):new tt.RSocketError(l.code,l.message);this.receiver.onError(i)}return;case ot.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,ot.Flags.hasIgnore(l.flags));default:n="Unexpected frame type [".concat(u,"]")}this.stream.send({type:ot.FrameTypes.ERROR,flags:ot.Flags.NONE,code:tt.ErrorCodes.CANCELED,message:n,streamId:this.streamId}),this.stream.disconnect(this),this.close(new tt.RSocketError(tt.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:ot.FrameTypes.ERROR,flags:ot.Flags.NONE,code:l instanceof tt.RSocketError?l.code:tt.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,rt.isFragmentable)(l,this.fragmentSize,ot.FrameTypes.PAYLOAD))try{for(var t=et((0,rt.fragment)(this.streamId,l,this.fragmentSize,ot.FrameTypes.PAYLOAD,n)),r=t.next();!r.done;r=t.next()){var o=r.value;this.stream.send(o)}}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:ot.FrameTypes.PAYLOAD,flags:ot.Flags.NEXT|(n?ot.Flags.COMPLETE:ot.Flags.NONE)|(l.metadata?ot.Flags.METADATA:ot.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:ot.FrameTypes.PAYLOAD,flags:ot.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:ot.FrameTypes.EXT,streamId:this.streamId,flags:u?ot.Flags.IGNORE:ot.Flags.NONE,extendedType:l,extendedContent:n})},l.prototype.request=function(l){this.inboundDone||this.stream.send({type:ot.FrameTypes.REQUEST_N,flags:ot.Flags.NONE,streamId:this.streamId,requestN:l})},l.prototype.cancel=function(){this.inboundDone||(this.inboundDone=!0,this.stream.send({type:ot.FrameTypes.CANCEL,flags:ot.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,it.cancel(this);var e=this.receiver;e&&(u||e.cancel(),n||(l?e.onError(l):e.onComplete()))}},l}();Ye.RequestChannelResponderStream=st;var ct={},dt=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]}),ht=r&&r.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),ft=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)&&dt(n,l,u);return ht(n,l),n},pt=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(ct,"__esModule",{value:!0}),ct.RequestFnfResponderStream=ct.RequestFnFRequesterStream=void 0;var yt=We,mt=Ge,gt=De,bt=ft(Ze),vt=function(){function l(l,n,u,e){this.payload=l,this.receiver=n,this.fragmentSize=u,this.leaseManager=e,this.streamType=gt.FrameTypes.REQUEST_FNF}return l.prototype.handleReady=function(l,n){var u,e;if(this.done)return!1;if(this.streamId=l,(0,mt.isFragmentable)(this.payload,this.fragmentSize,gt.FrameTypes.REQUEST_FNF))try{for(var t=pt((0,mt.fragment)(l,this.payload,this.fragmentSize,gt.FrameTypes.REQUEST_FNF)),r=t.next();!r.done;r=t.next()){var o=r.value;n.send(o)}}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:gt.FrameTypes.REQUEST_FNF,data:this.payload.data,metadata:this.payload.metadata,flags:this.payload.metadata?gt.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!=gt.FrameTypes.ERROR?this.close(new yt.RSocketError(yt.ErrorCodes.CANCELED,"Received invalid frame")):this.close(new yt.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}();ct.RequestFnFRequesterStream=vt;var Et=function(){function l(l,n,u,e){if(this.streamId=l,this.stream=n,this.handler=u,this.streamType=gt.FrameTypes.REQUEST_FNF,gt.Flags.hasFollows(e.flags))return bt.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==gt.FrameTypes.PAYLOAD){if(!gt.Flags.hasFollows(l.flags)){this.stream.disconnect(this);var u=bt.reassemble(this,l.data,l.metadata);try{this.cancellable=this.handler(u,this)}catch(l){}return}if(bt.add(this,l.data,l.metadata))return;n="Unexpected fragment size"}else n="Unexpected frame type [".concat(l.type,"]");this.done=!0,l.type!=gt.FrameTypes.CANCEL&&l.type!=gt.FrameTypes.ERROR&&this.stream.send({type:gt.FrameTypes.ERROR,streamId:this.streamId,flags:gt.Flags.NONE,code:yt.ErrorCodes.CANCELED,message:n}),this.stream.disconnect(this),bt.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,bt.cancel(this),null===(n=this.cancellable)||void 0===n||n.cancel())},l.prototype.onError=function(l){},l.prototype.onComplete=function(){},l}();ct.RequestFnfResponderStream=Et;var wt={},_t=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]}),St=r&&r.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),Tt=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)&&_t(n,l,u);return St(n,l),n},Rt=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(wt,"__esModule",{value:!0}),wt.RequestResponseResponderStream=wt.RequestResponseRequesterStream=void 0;var Ot=We,At=Ge,Ct=De,Ft=Tt(Ze),It=function(){function l(l,n,u,e){this.payload=l,this.receiver=n,this.fragmentSize=u,this.leaseManager=e,this.streamType=Ct.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,At.isFragmentable)(this.payload,this.fragmentSize,Ct.FrameTypes.REQUEST_RESPONSE))try{for(var t=Rt((0,At.fragment)(l,this.payload,this.fragmentSize,Ct.FrameTypes.REQUEST_RESPONSE)),r=t.next();!r.done;r=t.next()){var o=r.value;this.stream.send(o)}}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:Ct.FrameTypes.REQUEST_RESPONSE,data:this.payload.data,metadata:this.payload.metadata,flags:this.payload.metadata?Ct.Flags.METADATA:0,streamId:l});return this.hasExtension&&this.stream.send({type:Ct.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 Ct.FrameTypes.PAYLOAD:var e=Ct.Flags.hasComplete(l.flags),t=Ct.Flags.hasNext(l.flags);if(e||!Ct.Flags.hasFollows(l.flags)){if(this.done=!0,this.stream.disconnect(this),!t)return void this.receiver.onComplete();var r=this.hasFragments?Ft.reassemble(this,l.data,l.metadata):{data:l.data,metadata:l.metadata};return void this.receiver.onNext(r,!0)}if(!Ft.add(this,l.data,l.metadata)){n="Unexpected fragment size";break}return;case Ct.FrameTypes.ERROR:return this.done=!0,this.stream.disconnect(this),Ft.cancel(this),void this.receiver.onError(new Ot.RSocketError(l.code,l.message));case Ct.FrameTypes.EXT:if(this.hasFragments){n="Unexpected frame type [".concat(u,"] during reassembly");break}return void this.receiver.onExtension(l.extendedType,l.extendedContent,Ct.Flags.hasIgnore(l.flags));default:n="Unexpected frame type [".concat(u,"]")}this.close(new Ot.RSocketError(Ot.ErrorCodes.CANCELED,n)),this.stream.send({type:Ct.FrameTypes.CANCEL,streamId:this.streamId,flags:Ct.Flags.NONE}),this.stream.disconnect(this)},l.prototype.cancel=function(){var l;this.done||(this.done=!0,this.streamId?(this.stream.send({type:Ct.FrameTypes.CANCEL,flags:Ct.Flags.NONE,streamId:this.streamId}),this.stream.disconnect(this),Ft.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:Ct.FrameTypes.EXT,extendedType:l,extendedContent:n,flags:u?Ct.Flags.IGNORE:Ct.Flags.NONE}):(this.hasExtension=!0,this.extendedType=l,this.extendedContent=n,void(this.flags=u?Ct.Flags.IGNORE:Ct.Flags.NONE))},l.prototype.close=function(l){this.done||(this.done=!0,Ft.cancel(this),l?this.receiver.onError(l):this.receiver.onComplete())},l}();wt.RequestResponseRequesterStream=It;var kt=function(){function l(l,n,u,e,t){if(this.streamId=l,this.stream=n,this.fragmentSize=u,this.handler=e,this.streamType=Ct.FrameTypes.REQUEST_RESPONSE,n.connect(this),Ct.Flags.hasFollows(t.flags))Ft.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===Ct.FrameTypes.PAYLOAD){if(!Ct.Flags.hasFollows(l.flags)){var e=Ft.reassemble(this,l.data,l.metadata);try{this.receiver=this.handler(e,this)}catch(l){this.onError(l)}return}if(Ft.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===Ct.FrameTypes.EXT)return void this.receiver.onExtension(l.extendedType,l.extendedContent,Ct.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!==Ct.FrameTypes.CANCEL&&l.type!==Ct.FrameTypes.ERROR&&this.stream.send({type:Ct.FrameTypes.ERROR,flags:Ct.Flags.NONE,code:Ot.ErrorCodes.CANCELED,message:u,streamId:this.streamId}),this.stream.disconnect(this),Ft.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:Ct.FrameTypes.ERROR,flags:Ct.Flags.NONE,code:l instanceof Ot.RSocketError?l.code:Ot.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,At.isFragmentable)(l,this.fragmentSize,Ct.FrameTypes.PAYLOAD))try{for(var t=Rt((0,At.fragment)(this.streamId,l,this.fragmentSize,Ct.FrameTypes.PAYLOAD,!0)),r=t.next();!r.done;r=t.next()){var o=r.value;this.stream.send(o)}}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:Ct.FrameTypes.PAYLOAD,flags:Ct.Flags.NEXT|Ct.Flags.COMPLETE|(l.metadata?Ct.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:Ct.FrameTypes.PAYLOAD,flags:Ct.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:Ct.FrameTypes.EXT,streamId:this.streamId,flags:u?Ct.Flags.IGNORE:Ct.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,"]."):"")):(Ft.cancel(this),null===(n=this.receiver)||void 0===n||n.cancel())},l}();wt.RequestResponseResponderStream=kt;var Pt={},Lt=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]}),Nt=r&&r.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),xt=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)&&Lt(n,l,u);return Nt(n,l),n},Ut=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(Pt,"__esModule",{value:!0}),Pt.RequestStreamResponderStream=Pt.RequestStreamRequesterStream=void 0;var Dt=We,Mt=Ge,Bt=De,qt=xt(Ze),jt=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=Bt.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,Mt.isFragmentable)(this.payload,this.fragmentSize,Bt.FrameTypes.REQUEST_STREAM))try{for(var t=Ut((0,Mt.fragmentWithRequestN)(l,this.payload,this.fragmentSize,Bt.FrameTypes.REQUEST_STREAM,this.initialRequestN)),r=t.next();!r.done;r=t.next()){var o=r.value;this.stream.send(o)}}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:Bt.FrameTypes.REQUEST_STREAM,data:this.payload.data,metadata:this.payload.metadata,requestN:this.initialRequestN,flags:void 0!==this.payload.metadata?Bt.Flags.METADATA:0,streamId:l});return this.hasExtension&&this.stream.send({type:Bt.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 Bt.FrameTypes.PAYLOAD:var e=Bt.Flags.hasComplete(l.flags),t=Bt.Flags.hasNext(l.flags);if(e||!Bt.Flags.hasFollows(l.flags)){if(e&&(this.done=!0,this.stream.disconnect(this),!t))return void this.receiver.onComplete();var r=this.hasFragments?qt.reassemble(this,l.data,l.metadata):{data:l.data,metadata:l.metadata};return void this.receiver.onNext(r,e)}if(!qt.add(this,l.data,l.metadata)){n="Unexpected fragment size";break}return;case Bt.FrameTypes.ERROR:return this.done=!0,this.stream.disconnect(this),qt.cancel(this),void this.receiver.onError(new Dt.RSocketError(l.code,l.message));case Bt.FrameTypes.EXT:if(this.hasFragments){n="Unexpected frame type [".concat(u,"] during reassembly");break}return void this.receiver.onExtension(l.extendedType,l.extendedContent,Bt.Flags.hasIgnore(l.flags));default:n="Unexpected frame type [".concat(u,"]")}this.close(new Dt.RSocketError(Dt.ErrorCodes.CANCELED,n)),this.stream.send({type:Bt.FrameTypes.CANCEL,streamId:this.streamId,flags:Bt.Flags.NONE}),this.stream.disconnect(this)},l.prototype.request=function(l){this.done||(this.streamId?this.stream.send({type:Bt.FrameTypes.REQUEST_N,flags:Bt.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:Bt.FrameTypes.CANCEL,flags:Bt.Flags.NONE,streamId:this.streamId}),this.stream.disconnect(this),qt.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:Bt.FrameTypes.EXT,extendedType:l,extendedContent:n,flags:u?Bt.Flags.IGNORE:Bt.Flags.NONE}):(this.hasExtension=!0,this.extendedType=l,this.extendedContent=n,void(this.flags=u?Bt.Flags.IGNORE:Bt.Flags.NONE))},l.prototype.close=function(l){this.done||(this.done=!0,qt.cancel(this),l?this.receiver.onError(l):this.receiver.onComplete())},l}();Pt.RequestStreamRequesterStream=jt;var Wt=function(){function l(l,n,u,e,t){if(this.streamId=l,this.stream=n,this.fragmentSize=u,this.handler=e,this.streamType=Bt.FrameTypes.REQUEST_STREAM,n.connect(this),Bt.Flags.hasFollows(t.flags))return this.initialRequestN=t.requestN,void qt.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===Bt.FrameTypes.PAYLOAD){if(!Bt.Flags.hasFollows(l.flags)){var e=qt.reassemble(this,l.data,l.metadata);try{this.receiver=this.handler(e,this.initialRequestN,this)}catch(l){this.onError(l)}return}if(qt.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===Bt.FrameTypes.REQUEST_N)return void this.receiver.request(l.requestN);if(l.type===Bt.FrameTypes.EXT)return void this.receiver.onExtension(l.extendedType,l.extendedContent,Bt.Flags.hasIgnore(l.flags));u="Unexpected frame type [".concat(l.type,"]")}this.done=!0,qt.cancel(this),null===(n=this.receiver)||void 0===n||n.cancel(),l.type!==Bt.FrameTypes.CANCEL&&l.type!==Bt.FrameTypes.ERROR&&this.stream.send({type:Bt.FrameTypes.ERROR,flags:Bt.Flags.NONE,code:Dt.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:Bt.FrameTypes.ERROR,flags:Bt.Flags.NONE,code:l instanceof Dt.RSocketError?l.code:Dt.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,Mt.isFragmentable)(l,this.fragmentSize,Bt.FrameTypes.PAYLOAD))try{for(var t=Ut((0,Mt.fragment)(this.streamId,l,this.fragmentSize,Bt.FrameTypes.PAYLOAD,n)),r=t.next();!r.done;r=t.next()){var o=r.value;this.stream.send(o)}}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:Bt.FrameTypes.PAYLOAD,flags:Bt.Flags.NEXT|(n?Bt.Flags.COMPLETE:Bt.Flags.NONE)|(l.metadata?Bt.Flags.METADATA:Bt.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:Bt.FrameTypes.PAYLOAD,flags:Bt.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:Bt.FrameTypes.EXT,streamId:this.streamId,flags:u?Bt.Flags.IGNORE:Bt.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,"]."):"")):(qt.cancel(this),null===(n=this.receiver)||void 0===n||n.cancel())},l}();Pt.RequestStreamResponderStream=Wt,Object.defineProperty(Je,"__esModule",{value:!0}),Je.KeepAliveSender=Je.KeepAliveHandler=Je.DefaultConnectionFrameHandler=Je.DefaultStreamRequestHandler=Je.LeaseHandler=Je.RSocketRequester=void 0;var zt=We,Qt=De,$t=Ye,Ht=ct,Vt=wt,Jt=Pt,Yt=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 Ht.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 Vt.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 Jt.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 $t.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}();Je.RSocketRequester=Yt;var Gt=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 zt.RSocketError(zt.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}();Je.LeaseHandler=Gt;var Xt=function(){function l(l,n){this.rsocket=l,this.fragmentSize=n}return l.prototype.handle=function(l,n){switch(l.type){case Qt.FrameTypes.REQUEST_FNF:return void(this.rsocket.fireAndForget&&new Ht.RequestFnfResponderStream(l.streamId,n,this.rsocket.fireAndForget.bind(this.rsocket),l));case Qt.FrameTypes.REQUEST_RESPONSE:return this.rsocket.requestResponse?void new Vt.RequestResponseResponderStream(l.streamId,n,this.fragmentSize,this.rsocket.requestResponse.bind(this.rsocket),l):void this.rejectRequest(l.streamId,n);case Qt.FrameTypes.REQUEST_STREAM:return this.rsocket.requestStream?void new Jt.RequestStreamResponderStream(l.streamId,n,this.fragmentSize,this.rsocket.requestStream.bind(this.rsocket),l):void this.rejectRequest(l.streamId,n);case Qt.FrameTypes.REQUEST_CHANNEL:return this.rsocket.requestChannel?void new $t.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:Qt.FrameTypes.ERROR,streamId:l,flags:Qt.Flags.NONE,code:zt.ErrorCodes.REJECTED,message:"No available handler found"})},l.prototype.close=function(){},l}();Je.DefaultStreamRequestHandler=Xt;var Kt,Zt=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 Qt.FrameTypes.KEEPALIVE:return void this.keepAliveHandler.handle(l);case Qt.FrameTypes.LEASE:return this.leaseHandler?void this.leaseHandler.handle(l):void 0;case Qt.FrameTypes.ERROR:return void this.connection.close(new zt.RSocketError(l.code,l.message));case Qt.FrameTypes.METADATA_PUSH:return void this.rsocket.metadataPush;default:this.connection.multiplexerDemultiplexer.connectionOutbound.send({type:Qt.FrameTypes.ERROR,streamId:0,flags:Qt.Flags.NONE,message:"Received unknown frame type",code:zt.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}();Je.DefaultConnectionFrameHandler=Zt,function(l){l[l.Paused=0]="Paused",l[l.Running=1]="Running",l[l.Closed=2]="Closed"}(Kt||(Kt={}));var lr,nr=function(){function l(l,n){this.connection=l,this.keepAliveTimeoutDuration=n,this.state=Kt.Paused,this.outbound=l.multiplexerDemultiplexer.connectionOutbound}return l.prototype.handle=function(l){this.keepAliveLastReceivedMillis=Date.now(),Qt.Flags.hasRespond(l.flags)&&this.outbound.send({type:Qt.FrameTypes.KEEPALIVE,streamId:0,data:l.data,flags:l.flags^Qt.Flags.RESPOND,lastReceivedPosition:0})},l.prototype.start=function(){this.state===Kt.Paused&&(this.keepAliveLastReceivedMillis=Date.now(),this.state=Kt.Running,this.activeTimeout=setTimeout(this.timeoutCheck.bind(this),this.keepAliveTimeoutDuration))},l.prototype.pause=function(){this.state===Kt.Running&&(this.state=Kt.Paused,clearTimeout(this.activeTimeout))},l.prototype.close=function(){this.state=Kt.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}();Je.KeepAliveHandler=nr,function(l){l[l.Paused=0]="Paused",l[l.Running=1]="Running",l[l.Closed=2]="Closed"}(lr||(lr={}));var ur=function(){function l(l,n){this.outbound=l,this.keepAlivePeriodDuration=n,this.state=lr.Paused}return l.prototype.sendKeepAlive=function(){this.outbound.send({type:Qt.FrameTypes.KEEPALIVE,streamId:0,data:void 0,flags:Qt.Flags.RESPOND,lastReceivedPosition:0})},l.prototype.start=function(){this.state===lr.Paused&&(this.state=lr.Running,this.activeInterval=setInterval(this.sendKeepAlive.bind(this),this.keepAlivePeriodDuration))},l.prototype.pause=function(){this.state===lr.Running&&(this.state=lr.Paused,clearInterval(this.activeInterval))},l.prototype.close=function(){this.state=lr.Closed,clearInterval(this.activeInterval)},l}();Je.KeepAliveSender=ur;var er,tr,rr={};function or(){if(er)return rr;er=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(rr,"__esModule",{value:!0}),rr.FrameStore=void 0;var n=fr(),u=Ue,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 rr.FrameStore=e,rr}function ir(){if(tr)return $e;tr=1;var l=r&&r.__awaiter||function(l,n,u,e){return new(u||(u=Promise))((function(t,r){function o(l){try{a(e.next(l))}catch(l){r(l)}}function i(l){try{a(e.throw(l))}catch(l){r(l)}}function a(l){var n;l.done?t(l.value):(n=l.value,n instanceof u?n:new u((function(l){l(n)}))).then(o,i)}a((e=e.apply(l,n||[])).next())}))},n=r&&r.__generator||function(l,n){var u,e,t,r,o={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function i(r){return function(i){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:r[1],done:!1};case 5:o.label++,e=r[1],r=[0];continue;case 7:r=o.ops.pop(),o.trys.pop();continue;default:if(!(t=o.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){o=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){o.label=r[1];break}if(6===r[0]&&o.label<t[1]){o.label=t[1],t=r;break}if(t&&o.label<t[2]){o.label=t[2],o.ops.push(r);break}t[2]&&o.ops.pop(),o.trys.pop();continue}r=n.call(l,o)}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,i])}}};Object.defineProperty($e,"__esModule",{value:!0}),$e.RSocketConnector=void 0;var u=Ve(),e=De,t=Je,o=or(),i=function(){function r(l){this.config=l}return r.prototype.connect=function(){var r,i,a,s,c,d,h,f,p,y,m,g,b,v,E,w,_,S,T,R;return l(this,void 0,void 0,(function(){var O,A,C,F,I,k,P,L,N,x=this;return n(this,(function(U){switch(U.label){case 0:return O=this.config,A={type:e.FrameTypes.SETUP,dataMimeType:null!==(i=null===(r=O.setup)||void 0===r?void 0:r.dataMimeType)&&void 0!==i?i:"application/octet-stream",metadataMimeType:null!==(s=null===(a=O.setup)||void 0===a?void 0:a.metadataMimeType)&&void 0!==s?s:"application/octet-stream",keepAlive:null!==(d=null===(c=O.setup)||void 0===c?void 0:c.keepAlive)&&void 0!==d?d:6e4,lifetime:null!==(f=null===(h=O.setup)||void 0===h?void 0:h.lifetime)&&void 0!==f?f:3e5,metadata:null===(y=null===(p=O.setup)||void 0===p?void 0:p.payload)||void 0===y?void 0:y.metadata,data:null===(g=null===(m=O.setup)||void 0===m?void 0:m.payload)||void 0===g?void 0:g.data,resumeToken:null!==(v=null===(b=O.resume)||void 0===b?void 0:b.tokenGenerator())&&void 0!==v?v:null,streamId:0,majorVersion:1,minorVersion:0,flags:((null===(w=null===(E=O.setup)||void 0===E?void 0:E.payload)||void 0===w?void 0:w.metadata)?e.Flags.METADATA:e.Flags.NONE)|(O.lease?e.Flags.LEASE:e.Flags.NONE)|(O.resume?e.Flags.RESUME_ENABLE:e.Flags.NONE)},[4,O.transport.connect((function(t){return O.resume?new u.ResumableClientServerInputMultiplexerDemultiplexer(u.StreamIdGenerator.create(-1),t,t,new o.FrameStore,A.resumeToken.toString(),(function(t,r){return l(x,void 0,void 0,(function(){var l,o,i;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:A.minorVersion,minorVersion:A.majorVersion,resumeToken:A.resumeToken}),new u.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer(l,l,t)},o=-1,[4,(i=function(){return o++,O.resume.reconnectFunction(o).then((function(){return O.transport.connect(l).catch(i)}))})()];case 1:return n.sent(),[2]}}))}))})):new u.ClientServerInputMultiplexerDemultiplexer(u.StreamIdGenerator.create(-1),t,t)}))];case 1:return C=U.sent(),F=new t.KeepAliveSender(C.multiplexerDemultiplexer.connectionOutbound,A.keepAlive),I=new t.KeepAliveHandler(C,A.lifetime),k=O.lease?new t.LeaseHandler(null!==(_=O.lease.maxPendingRequests)&&void 0!==_?_:256,C.multiplexerDemultiplexer):void 0,P=null!==(S=O.responder)&&void 0!==S?S:{},L=new t.DefaultConnectionFrameHandler(C,I,F,k,P),N=new t.DefaultStreamRequestHandler(P,0),C.onClose((function(l){F.close(),I.close(),L.close(l)})),C.multiplexerDemultiplexer.connectionInbound(L),C.multiplexerDemultiplexer.handleRequestStream(N),C.multiplexerDemultiplexer.connectionOutbound.send(A),I.start(),F.start(),[2,new t.RSocketRequester(C,null!==(R=null===(T=O.fragmentation)||void 0===T?void 0:T.maxOutboundFragmentSize)&&void 0!==R?R:0,k)]}}))}))},r}();return $e.RSocketConnector=i,$e}var ar,sr={};function cr(){if(ar)return sr;ar=1;var l=r&&r.__awaiter||function(l,n,u,e){return new(u||(u=Promise))((function(t,r){function o(l){try{a(e.next(l))}catch(l){r(l)}}function i(l){try{a(e.throw(l))}catch(l){r(l)}}function a(l){var n;l.done?t(l.value):(n=l.value,n instanceof u?n:new u((function(l){l(n)}))).then(o,i)}a((e=e.apply(l,n||[])).next())}))},n=r&&r.__generator||function(l,n){var u,e,t,r,o={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function i(r){return function(i){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:r[1],done:!1};case 5:o.label++,e=r[1],r=[0];continue;case 7:r=o.ops.pop(),o.trys.pop();continue;default:if(!(t=o.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){o=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){o.label=r[1];break}if(6===r[0]&&o.label<t[1]){o.label=t[1],t=r;break}if(t&&o.label<t[2]){o.label=t[2],o.ops.push(r);break}t[2]&&o.ops.pop(),o.trys.pop();continue}r=n.call(l,o)}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,i])}}};Object.defineProperty(sr,"__esModule",{value:!0}),sr.RSocketServer=void 0;var u=Ve(),e=We,t=De,o=Je,i=or(),a=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(a){switch(a.label){case 0:return[4,this.transport.bind((function(u,i){return l(r,void 0,void 0,(function(){var l,r,a,s,c,d,h,f,p,y,m,g,b;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"),i.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,flags:t.Flags.NONE,code:l.code,message:l.message}),i.close(l),[2]):t.Flags.hasLease(u.flags)&&!this.lease?(l=new e.RSocketError(e.ErrorCodes.REJECTED_SETUP,"Lease has to be disabled"),i.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,flags:t.Flags.NONE,code:l.code,message:l.message}),i.close(l),[2]):(r=t.Flags.hasLease(u.flags)?new o.LeaseHandler(null!==(y=this.lease.maxPendingRequests)&&void 0!==y?y:256,i.multiplexerDemultiplexer):void 0,a=new o.RSocketRequester(i,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},a)]);case 2:return s=n.sent(),c=new o.KeepAliveHandler(i,u.lifetime),d=this.serverSideKeepAlive?new o.KeepAliveSender(i.multiplexerDemultiplexer.connectionOutbound,u.keepAlive):void 0,h=new o.DefaultConnectionFrameHandler(i,c,d,r,s),f=new o.DefaultStreamRequestHandler(s,0),i.onClose((function(l){null==d||d.close(),c.close(),h.close(l)})),i.multiplexerDemultiplexer.connectionInbound(h),i.multiplexerDemultiplexer.handleRequestStream(f),c.start(),null==d||d.start(),[3,4];case 3:return p=n.sent(),i.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,code:e.ErrorCodes.REJECTED_SETUP,message:null!==(b=p.message)&&void 0!==b?b:"",flags:t.Flags.NONE}),i.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:i.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,code:e.ErrorCodes.UNSUPPORTED_SETUP,message:"Unsupported setup",flags:t.Flags.NONE}),i.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 o=r.sessionStore[l.resumeToken.toString()];return o?(o.resume(l,n,n),o):(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 a=new e.RSocketError(e.ErrorCodes.REJECTED_SETUP,"No resume support");return n.send({type:t.FrameTypes.ERROR,streamId:0,flags:t.Flags.NONE,code:a.code,message:a.message}),void n.close(a)}var s=new u.ResumableClientServerInputMultiplexerDemultiplexer(u.StreamIdGenerator.create(0),n,n,new i.FrameStore,l.resumeToken.toString(),r.sessionStore,r.sessionTimeout);return r.sessionStore[l.resumeToken.toString()]=s,s}return new u.ClientServerInputMultiplexerDemultiplexer(u.StreamIdGenerator.create(0),n,n)}))];case 1:return[2,a.sent()]}}))}))},r}();return sr.RSocketServer=a,sr}var dr,hr={};function fr(){return dr||(dr=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(Ue,l),u(Me,l),u(Be,l),u(We,l),u(De,l),u(ze,l),u(ir(),l),u(cr(),l),u(hr,l)}(Ne)),Ne}Object.defineProperty(hr,"__esModule",{value:!0});var pr=fr(),yr="1.31.0";const mr={highWater:10,lowWater:0};class gr extends _{options;dataQueue;isClosed;processingPromise;logger;constructor(l){if(super(),this.options=l,this.processingPromise=null,this.isClosed=!1,this.dataQueue=[],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??mr.highWater}get lowWatermark(){return this.options?.pressure?.lowWaterMark??mr.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.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})}async processQueue(){if(!this.processingPromise)return this.dataQueue.length>=this.highWatermark&&await this.iterateAsyncErrored((async l=>l.highWater?.())),this.processingPromise=this._processQueue()}map(l){const n=new gr(this.options),u=this.registerListener({data:async u=>{n.enqueueData(l(u))},closed:()=>{n.close(),u?.()}});return n}hasDataReader(){return Array.from(this.listeners.values()).some((l=>!!l.data))}async _processQueue(){if(!this.isClosed&&this.hasDataReader()){if(this.dataQueue.length){const l=this.dataQueue.shift();await this.iterateAsyncErrored((async n=>n.data?.(l)))}this.dataQueue.length<=this.lowWatermark&&await this.iterateAsyncErrored((async l=>l.lowWater?.())),this.processingPromise=null,this.dataQueue.length&&setTimeout((()=>this.processQueue()))}else Promise.resolve().then((()=>this.processingPromise=null))}async iterateAsyncErrored(l){for(let n of Array.from(this.listeners.values()))try{await l(n)}catch(l){this.logger.error(l),this.iterateListeners((n=>n.error?.(l)))}}}var br,vr={},Er=r&&r.__extends||(br=function(l,n){return br=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])},br(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}br(l,n),l.prototype=null===n?Object.create(n):(u.prototype=n.prototype,new u)});Object.defineProperty(vr,"__esModule",{value:!0});var wr=vr.WebsocketDuplexConnection=void 0,_r=fr(),Sr=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=xe.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 Er(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,_r.serializeFrame)(l);this.websocket.send(n)}},n}(_r.Deferred);wr=vr.WebsocketDuplexConnection=Sr;class Tr{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 wr(e,new pr.Deserializer,l))},o=l=>{t(),u(l.error)},i=()=>{t(),u(new Error("WebSocket connection closed while opening"))};t=()=>{e.removeEventListener("open",r),e.removeEventListener("error",o),e.removeEventListener("close",i)},e.addEventListener("open",r),e.addEventListener("error",o),e.addEventListener("close",i)}))}}const Rr=/\/+$/,Or=yr,Ar=y.get("PowerSyncRemote");var Cr;!function(l){l.Buffered="buffered",l.Sequential="sequential"}(Cr||(Cr={}));class Fr{getFetch(){throw new Error("Unspecified fetch implementation")}}const Ir={socketUrlTransformer:l=>l.replace(/^https?:\/\//,(function(l){return"https://"===l?"wss://":"ws://"})),fetchImplementation:new Fr,fetchOptions:{}};class kr{connector;logger;credentials=null;options;constructor(l,n=Ar,u){this.connector=l,this.logger=n,this.options={...Ir,...u??{}}}get fetch(){const{fetchImplementation:l}=this.options;return l instanceof Fr?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(Rr))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/${Or}`}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()}async postStreaming(l,n,u={},e){const t=await this.buildRequest(l),r=await this.fetch(t.url,{method:"POST",headers:{...u,...t.headers},body:JSON.stringify(n),signal:e,cache:"no-store"}).catch((n=>{throw this.logger.error(`Caught ex when POST streaming to ${l}`,n),n}));if(401===r.status&&this.invalidateCredentials(),!r.ok){const n=await r.text();this.logger.error(`Could not POST streaming to ${l} - ${r.status} - ${r.statusText}: ${n}`);const u=new Error(`HTTP ${r.statusText}: ${n}`);throw u.status=r.status,u}return r}createSocket(l){return new WebSocket(l)}async socketStream(l){const{path:n,fetchStrategy:u=Cr.Buffered}=l,e=u==Cr.Buffered?10:1,t=await this.buildRequest(n),r=await this.getBSON(),o=this.getUserAgent();let i;const a=new pr.RSocketConnector({transport:new Tr({url:this.options.socketUrlTransformer(t.url),wsCreator:l=>{const n=this.createSocket(l);return n.addEventListener("error",(l=>{i=new Error("Failed to create connection to websocket: ",l.target.url??""),this.logger.warn("Socket error",l)})),n}}),setup:{keepAlive:2e4,lifetime:3e4,dataMimeType:"application/bson",metadataMimeType:"application/bson",payload:{data:null,metadata:ge.Buffer.from(r.serialize({token:t.headers.Authorization,user_agent:o}))}}});let s;try{s=await a.connect()}catch(l){throw new Error(`Could not connect to PowerSync instance: ${JSON.stringify(l??i)}`)}const c=new gr({logger:this.logger,pressure:{lowWaterMark:5}});let d=!1;s.onClose((()=>d=!0));let h=e;const f=c.registerListener({closed:()=>{d||(d=!0,s.close()),f()}}),p=await new Promise(((u,t)=>{let o=!1;const i=s.requestStream({data:ge.Buffer.from(r.serialize(l.data)),metadata:ge.Buffer.from(r.serialize({path:n}))},e,{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),c.close(),o||t(l)},onNext:l=>{o||(o=!0,u(i));const{data:n}=l;if(h--,!n)return;const e=r.deserialize(n);c.enqueueData(e)},onComplete:()=>{c.close()},onExtension:()=>{}})})),y=c.registerListener({lowWater:async()=>{e-h>0&&(p.request(e-h),h=e)},closed:()=>{y()}});return l.abortSignal?.aborted?c.close():l.abortSignal?.addEventListener("abort",(()=>{c.close()})),c}async postStream(l){const{data:n,path:u,headers:e,abortSignal:t}=l,r=await this.buildRequest(u),o=new AbortController;let i=!1;t?.addEventListener("abort",(()=>{i||o.abort(t.reason??new U("Cancelling network request before it resolves. Abort signal has been received."))}));const a=await this.fetch(r.url,{method:"POST",headers:{...e,...r.headers},body:JSON.stringify(n),signal:o.signal,cache:"no-store",...this.options.fetchOptions??{},...l.fetchOptions}).catch((l=>{if("AbortError"==l.name)throw new U(`Pending fetch request to ${r.url} has been aborted.`);throw l}));if(!a)throw new Error("Fetch request was aborted");if(i=!0,!a.ok||!a.body){const l=await a.text();this.logger.error(`Could not POST streaming to ${u} - ${a.status} - ${a.statusText}: ${l}`);const n=new Error(`HTTP ${a.statusText}: ${l}`);throw n.status=a.status,n}const s=a.body.getReader(),c=async()=>{try{await s.cancel()}catch(l){}s.releaseLock()};t?.addEventListener("abort",(()=>{c()}));const d=new ue({start:l=>{(async()=>{for(;!t?.aborted;)try{const{done:n,value:u}=await s.read();if(n)break;l.enqueue(u)}catch(l){this.logger.error("Caught exception when reading sync stream",l);break}t?.aborted||await c(),l.close()})()}}),h=Le(d),f=new gr({logger:this.logger}),p=h.getReader(),y=f.registerListener({lowWater:async()=>{try{const{done:l,value:n}=await p.read();if(l)return f.close(),void y?.();f.enqueueData(n)}catch(l){throw f.close(),l}},closed:()=>{c(),y?.()}});return f}}function Pr(l){return null!=l.data}function Lr(l){return null!=l.token_expires_in}function Nr(l){return null!=l.checkpoint}function xr(l){return null!=l.checkpoint_complete}function Ur(l){return null!=l.partial_checkpoint_complete}function Dr(l){return null!=l.checkpoint_diff}function Mr(l){return Array.isArray(l.buckets)&&"string"==typeof l.checkpoint_token}function Br(l){return"object"==typeof l.request_checkpoint}var qr,jr;!function(l){l.CRUD="crud",l.SYNC="sync"}(qr||(qr={})),function(l){l.HTTP="http",l.WEB_SOCKET="web-socket"}(jr||(jr={}));const Wr=1e3,zr=5e3,Qr={retryDelayMs:zr,logger:y.get("PowerSyncStream"),crudUploadThrottleMs:Wr},$r={connectionMethod:jr.WEB_SOCKET,fetchStrategy:Cr.Buffered,params:{}};class Hr extends _{_lastSyncedAt;options;abortController;crudUpdateListener;streamingSyncPromise;pendingCrudUpload;syncStatus;triggerCrudUpload;constructor(l){super(),this.options={...Qr,...l},this.syncStatus=new E({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.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:qr.CRUD,callback:async()=>{let l;for(;;){this.updateSyncStatus({dataFlow:{uploading:!0}});try{const n=await this.options.adapter.nextCrudItem();if(!n){await this.options.adapter.updateLocalTarget((()=>this.getWriteCheckpoint()));break}if(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({statusUpdated:u=>{void 0!==u.connected&&(0==u.connected&&this.logger.warn("Initial connect attempt did not successfully connect to server"),n(),l())}})}))}async disconnect(){if(this.abortController){this.abortController.signal.aborted||this.abortController.abort(new U("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 U("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});try{if(l?.aborted)break;await this.streamingSyncIteration(u.signal,n)}catch(l){let n=!0;l instanceof U?(this.logger.warn(l),n=!1):this.logger.error(l),this.updateSyncStatus({dataFlow:{downloadError:l}}),n&&await this.delayRetry()}finally{l.aborted||(u.abort(new U("Closing sync stream network requests before retry.")),u=new AbortController),this.updateSyncStatus({connected:!1,connecting:!0})}}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 streamingSyncIteration(l,n){await this.obtainLock({type:qr.SYNC,signal:l,callback:async()=>{const u={...$r,...n??{}};this.logger.debug("Streaming sync iteration started"),this.options.adapter.startSession();let[e,t]=await this.collectLocalBucketState(),r=null,o=null,i=null;const a=await this.options.adapter.getClientId();if(l.aborted)return;this.logger.debug("Requesting stream from server");const s={path:"/sync/stream",abortSignal:l,data:{buckets:e,include_checksum:!0,raw_data:!0,parameters:u.params,client_id:a}};let c;for(c=u?.connectionMethod==jr.HTTP?await this.options.remote.postStream(s):await this.options.remote.socketStream({...s,fetchStrategy:u.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})),Nr(n)){r=n.checkpoint;const l=new Set(t.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]),t=u,await this.options.adapter.removeBuckets([...l]),await this.options.adapter.setTargetCheckpoint(r),await this.updateSyncStatusForStartingCheckpoint(r)}else if(xr(n)){const n=await this.applyCheckpoint(r,l);if(n.endIteration)return;n.applied&&(i=r),o=r}else if(Ur(n)){const l=n.partial_checkpoint_complete.priority;this.logger.debug("Partial checkpoint complete",l);const u=await this.options.adapter.syncLocalDatabase(r,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(Dr(n)){if(null==r)throw new Error("Checkpoint diff without previous checkpoint");const l=n.checkpoint_diff,u=new Map;for(const l of r.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);r={last_op_id:l.last_op_id,buckets:[...u.values()],write_checkpoint:l.write_checkpoint},await this.updateSyncStatusForStartingCheckpoint(r),t=new Map,u.forEach(((l,n)=>t.set(n,{name:l.bucket,priority:l.priority??3})));const e=l.removed_buckets;e.length>0&&this.logger.debug("Remove buckets",e),await this.options.adapter.removeBuckets(e),await this.options.adapter.setTargetCheckpoint(r)}else if(Pr(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,sinceLast:n.sinceLast+l.data.length})}this.updateSyncStatus({dataFlow:{downloading:!0,downloadProgress:e}}),await this.options.adapter.saveSyncData({buckets:[B.fromRow(l)]})}else if(Lr(n)){const l=n.token_expires_in;if(0==l)return this.logger.debug("Token expiring; reconnect"),this.options.remote.invalidateCredentials(),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"),r===i)this.updateSyncStatus({connected:!0,lastSyncedAt:new Date,priorityStatusEntries:[],dataFlow:{downloadError:void 0}});else if(o===r){const n=await this.applyCheckpoint(r,l);if(n.endIteration)return;n.applied&&(i=r)}}this.logger.debug("Stream input empty")}})}async updateSyncStatusForStartingCheckpoint(l){const n=await this.options.adapter.getBucketOperationProgress(),u={};for(const e of l.buckets){const l=n[e.bucket];u[e.bucket]={priority:e.priority??3,atLast:l?.atLast??0,sinceLast:l?.sinceLast??0,targetCount:e.count??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 E({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(){return new Promise((l=>setTimeout(l,this.options.retryDelayMs)))}}const Vr=/(^ps_data__|^ps_data_local__)/,Jr={clearLocal:!0},Yr={disconnect:!0},Gr=30,Xr={retryDelayMs:5e3,logger:y.get("PowerSyncDatabase"),crudUploadThrottleMs:Wr},Kr=100,Zr=12e4,lo=l=>"object"==typeof l&&O(l.database);class no extends _{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(C(n))this._database=n;else if(A(n))this._database=n.openDB();else{if(!lo(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 E({}),this.options={...Xr,...l},this._schema=u,this.ready=!1,this.sdkVersion="",this.runExclusiveMutex=new t,this.connectionManager=new R({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 E({...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==b?n=l:u.push({priority:e,hasSynced:!0,lastSyncedAt:l})}const e=null!=n,t=new E({...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??zr,crudUploadThrottleMs:l?.crudUploadThrottleMs??this.options.crudUploadThrottleMs??Wr}}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=Jr){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 E({}),this.iterateListeners((l=>l.statusChanged?.(this.currentStatus)))}async close(l=Yr){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 w(l?.count??0,l?.size??0)}{const l=(await n.execute(`SELECT count(*) as count FROM ${I.CRUD}`)).rows.item(0);return new w(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=>N.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 L(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=>N.fromRow(l)))}else e=[N.fromRow(n)];const t=e[e.length-1];return new x(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(),T(no.transactionMutex,(()=>l(this.database)))}async writeLock(l){return await this.waitForReady(),T(no.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");F((async u=>{try{const o=await this.resolveTables(l,n,e),i=await this.executeReadOnly(l,n);t(i),this.onChangeWithCallback({onChange:async()=>{try{const u=await this.executeReadOnly(l,n);t(u)}catch(l){r?.(l)}},onError:r},{...e??{},tables:o,signal:u})}catch(l){r?.(l)}}),this,e)}watchWithAsyncGenerator(l,n,u){return new h((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(Vr,""))}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}`]))),o=new Set,i=t.throttleMs??30,a=new S((async l=>{await u(l)})),s=function(l,n){let u=null;const e=()=>{l(),u=null};return function(){null==u&&(u=setTimeout(e,n))}}((()=>this.handleTableChanges(o,r,(l=>{t?.signal?.aborted||a.schedule({changedTables:l})}))),i),c=this.database.registerListener({tablesUpdated:async l=>{try{this.processTableUpdates(l,o),s()}catch(l){e?.(l)}}});return t.signal?.addEventListener("abort",(()=>{a.dispose(),c()})),()=>c()}onChangeWithAsyncGenerator(l){const n=l??{};return new h((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 uo{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 eo(l,n,u,e){const{onResult:t,onError:r=l=>{}}=u??{};if(!t)throw new Error("onResult is required");F((async u=>{try{const o=n.compile(),i=await l.resolveTables(o.sql,o.parameters,e),a=await n.execute();t(a),l.onChangeWithCallback({onChange:async()=>{try{const l=await n.execute();t(l)}catch(l){r(l)}},onError:r},{...e??{},tables:i,signal:u})}catch(l){r(l)}}),l,e)}const to="9223372036854775807",ro=1e3;class oo extends _{db;mutex;logger;tableNames;pendingBucketDeletes;_hasCompletedSync;updateListener;_clientId;compactCounter=ro;constructor(l,n,u=y.get("SqliteBucketStorage")){super(),this.db=l,this.mutex=n,this.logger=u,this._hasCompletedSync=!1,this.pendingBucketDeletes=!0,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 to}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){await this.writeTransaction((async n=>{let u=0;for(const e of l.buckets){const l=await n.execute("INSERT INTO powersync_operations(op, data) VALUES(?, ?)",["save",JSON.stringify({buckets:[e.toJSON()]})]);this.logger.debug("saveSyncData",JSON.stringify(l)),u+=e.data.length}this.compactCounter+=u}))}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"),this.pendingBucketDeletes=!0}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=>io(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)?(await this.forceCompact(),{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)io(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=>io(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 forceCompact(){this.compactCounter=ro,this.pendingBucketDeletes=!0,await this.autoCompact()}async autoCompact(){await this.deletePendingBuckets(),await this.clearRemoveOps()}async deletePendingBuckets(){!1!==this.pendingBucketDeletes&&(await this.writeTransaction((async l=>{await l.execute("INSERT INTO powersync_operations(op, data) VALUES (?, ?)",["delete_pending_buckets",""])})),this.pendingBucketDeletes=!1)}async clearRemoveOps(){this.compactCounter<ro||(await this.writeTransaction((async l=>{await l.execute("INSERT INTO powersync_operations(op, data) VALUES (?, ?)",["clear_remove_ops",""])})),this.compactCounter=0)}async updateLocalTarget(l){if(!(await this.db.getAll("SELECT target_op FROM ps_buckets WHERE name = '$local' AND target_op = CAST(? as INTEGER)",[to])).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 o=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(o)]),!0}))}async nextCrudItem(){const l=await this.db.getOptional("SELECT * FROM ps_crud ORDER BY id ASC LIMIT 1");if(l)return N.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(N.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){}}function io(l,n){return null!=n.priority&&n.priority<=l}class ao{buckets;static fromJSON(l){return new ao(l.buckets.map((l=>B.fromRow(l))))}constructor(l){this.buckets=l}}var so;!function(l){l.TEXT="TEXT",l.INTEGER="INTEGER",l.REAL="REAL"}(so||(so={}));const co={type:so.TEXT},ho={type:so.INTEGER},fo={type:so.REAL},po=1999,yo={text:co,integer:ho,real:fo};class mo{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 go={ascending:!0};class bo{options;static createAscending(l){return new bo({name:l,ascending:!0})}constructor(l){this.options={...go,...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??so.TEXT}}}const vo={columns:[]};class Eo{options;static createAscending(l,n){return new Eo({...l,columns:n.map((l=>bo.createAscending(l)))})}constructor(l){this.options=l,this.options={...vo,...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 wo{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 _o={indexes:[],insertOnly:!1,localOnly:!1,trackPrevious:!1,trackMetadata:!1,ignoreEmptyUpdates:!1},So=/["'%,.#\s[\]]/;class To{options;_mappedColumns;static createLocalOnly(l){return new To({...l,localOnly:!0,insertOnly:!1})}static createInsertOnly(l){return new To({...l,localOnly:!1,insertOnly:!0})}static createTable(l,n){return new To({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 To({...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 mo({name:l,type:n.type}))),e=Object.entries(n?.indexes??{}).map((([l,n])=>new Eo({name:l,columns:n.map((l=>new bo({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??=_o.insertOnly,this.options.localOnly??=_o.localOnly,this.options.trackPrevious??=_o.trackPrevious,this.options.trackMetadata??=_o.trackMetadata,this.options.ignoreEmptyUpdates??=_o.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??so.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!So.test(this.name)&&(null==this.viewNameOverride||!So.test(this.viewNameOverride))}validate(){if(So.test(this.name))throw new Error(`Invalid characters in table name: ${this.name}`);if(this.viewNameOverride&&So.test(this.viewNameOverride))throw new Error(`Invalid characters in view name: ${this.viewNameOverride}`);if(this.columns.length>po)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(So.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(So.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 Ro extends To{}const Oo=y,Ao={TRACE:Oo.TRACE,DEBUG:Oo.DEBUG,INFO:Oo.INFO,TIME:Oo.TIME,WARN:Oo.WARN,ERROR:Oo.ERROR,OFF:Oo.OFF};function Co(){return y}function Fo(l,n={}){const u=y.get(l);return n.logLevel&&u.setLevel(n.logLevel),u}const Io=(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}};export{U as AbortOperation,no as AbstractPowerSyncDatabase,uo as AbstractPowerSyncDatabaseOpenFactory,kr as AbstractRemote,Hr as AbstractStreamingSyncImplementation,_ as BaseObserver,mo as Column,so as ColumnType,R as ConnectionManager,L as CrudBatch,N as CrudEntry,x as CrudTransaction,Kr as DEFAULT_CRUD_BATCH_LIMIT,Wr as DEFAULT_CRUD_UPLOAD_THROTTLE_MS,go as DEFAULT_INDEX_COLUMN_OPTIONS,vo as DEFAULT_INDEX_OPTIONS,Zr as DEFAULT_LOCK_TIMEOUT_MS,Yr as DEFAULT_POWERSYNC_CLOSE_OPTIONS,Xr as DEFAULT_POWERSYNC_DB_OPTIONS,mr as DEFAULT_PRESSURE_LIMITS,Ar as DEFAULT_REMOTE_LOGGER,Ir as DEFAULT_REMOTE_OPTIONS,zr as DEFAULT_RETRY_DELAY_MS,Qr as DEFAULT_STREAMING_SYNC_OPTIONS,$r as DEFAULT_STREAM_CONNECTION_OPTIONS,_o as DEFAULT_TABLE_OPTIONS,Gr as DEFAULT_WATCH_THROTTLE_MS,gr as DataStream,Fr as FetchImplementationProvider,Cr as FetchStrategy,Eo as Index,bo as IndexedColumn,So as InvalidSQLCharacters,qr as LockType,Ao as LogLevel,po as MAX_AMOUNT_OF_COLUMNS,to as MAX_OP_ID,D as OpType,P as OpTypeEnum,M as OplogEntry,I as PSInternalTable,p as RowUpdateType,wo as Schema,oo as SqliteBucketStorage,ao as SyncDataBatch,B as SyncDataBucket,v as SyncProgress,E as SyncStatus,jr as SyncStreamConnectionMethod,To as Table,Ro as TableV2,k as UpdateType,w as UploadQueueStats,yo as column,eo as compilableQueryWatch,Co as createBaseLogger,Fo as createLogger,g as extractTableUpdates,m as isBatchedUpdateNotification,Mr as isContinueCheckpointRequest,C as isDBAdapter,lo as isPowerSyncDatabaseOptionsWithSettings,A as isSQLOpenFactory,O as isSQLOpenOptions,Lr as isStreamingKeepalive,Nr as isStreamingSyncCheckpoint,xr as isStreamingSyncCheckpointComplete,Dr as isStreamingSyncCheckpointDiff,Ur as isStreamingSyncCheckpointPartiallyComplete,Pr as isStreamingSyncData,Br as isSyncNewCheckpointRequest,Io as parseQuery,F as runOnSchemaChange};
22
+ !function(l){var n=be,u=Oe,e="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;l.Buffer=o,l.SlowBuffer=function(l){+l!=l&&(l=0);return o.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,o.prototype),n}function o(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 s(l)}return i(l,n,u)}function i(l,n,u){if("string"==typeof l)return function(l,n){"string"==typeof n&&""!==n||(n="utf8");if(!o.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 d(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 d(l,n,u);if("undefined"!=typeof SharedArrayBuffer&&(B(l,SharedArrayBuffer)||l&&B(l.buffer,SharedArrayBuffer)))return d(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 o.from(e,n,u);var t=function(l){if(o.isBuffer(l)){var n=0|h(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 o.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 a(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 s(l){return a(l),r(l<0?0:0|h(l))}function c(l){for(var n=l.length<0?0:0|h(l.length),u=r(n),e=0;e<n;e+=1)u[e]=255&l[e];return u}function d(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,o.prototype),e}function h(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(o.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 U(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:U(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 C(this,n,u);case"utf8":case"utf-8":return T(this,n,u);case"ascii":return O(this,n,u);case"latin1":case"binary":return A(this,n,u);case"base64":return S(this,n,u);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return F(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=o.from(n,e)),o.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,o=1,i=l.length,a=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;o=2,i/=2,a/=2,u/=2}function s(l,n){return 1===o?l[n]:l.readUInt16BE(n*o)}if(t){var c=-1;for(r=u;r<i;r++)if(s(l,r)===s(n,-1===c?0:r-c)){if(-1===c&&(c=r),r-c+1===a)return c*o}else-1!==c&&(r-=r-c),c=-1}else for(u+a>i&&(u=i-a),r=u;r>=0;r--){for(var d=!0,h=0;h<a;h++)if(s(l,r+h)!==s(n,h)){d=!1;break}if(d)return r}return-1}function b(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 o=0;o<e;++o){var i=parseInt(n.substr(2*o,2),16);if(q(i))return o;l[u+o]=i}return o}function v(l,n,u,e){return M(U(n,l.length-u),l,u,e)}function E(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 w(l,n,u,e){return M(D(n),l,u,e)}function _(l,n,u,e){return M(function(l,n){for(var u,e,t,r=[],o=0;o<l.length&&!((n-=2)<0);++o)e=(u=l.charCodeAt(o))>>8,t=u%256,r.push(t),r.push(e);return r}(n,l.length-u),l,u,e)}function S(l,u,e){return 0===u&&e===l.length?n.fromByteArray(l):n.fromByteArray(l.slice(u,e))}function T(l,n,u){u=Math.min(l.length,u);for(var e=[],t=n;t<u;){var r,o,i,a,s=l[t],c=null,d=s>239?4:s>223?3:s>191?2:1;if(t+d<=u)switch(d){case 1:s<128&&(c=s);break;case 2:128==(192&(r=l[t+1]))&&(a=(31&s)<<6|63&r)>127&&(c=a);break;case 3:r=l[t+1],o=l[t+2],128==(192&r)&&128==(192&o)&&(a=(15&s)<<12|(63&r)<<6|63&o)>2047&&(a<55296||a>57343)&&(c=a);break;case 4:r=l[t+1],o=l[t+2],i=l[t+3],128==(192&r)&&128==(192&o)&&128==(192&i)&&(a=(15&s)<<18|(63&r)<<12|(63&o)<<6|63&i)>65535&&a<1114112&&(c=a)}null===c?(c=65533,d=1):c>65535&&(c-=65536,e.push(c>>>10&1023|55296),c=56320|1023&c),e.push(c),t+=d}return function(l){var n=l.length;if(n<=R)return String.fromCharCode.apply(String,l);var u="",e=0;for(;e<n;)u+=String.fromCharCode.apply(String,l.slice(e,e+=R));return u}(e)}l.kMaxLength=t,o.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}}(),o.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(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),o.poolSize=8192,o.from=function(l,n,u){return i(l,n,u)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array),o.alloc=function(l,n,u){return function(l,n,u){return a(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)},o.allocUnsafe=function(l){return s(l)},o.allocUnsafeSlow=function(l){return s(l)},o.isBuffer=function(l){return null!=l&&!0===l._isBuffer&&l!==o.prototype},o.compare=function(l,n){if(B(l,Uint8Array)&&(l=o.from(l,l.offset,l.byteLength)),B(n,Uint8Array)&&(n=o.from(n,n.offset,n.byteLength)),!o.isBuffer(l)||!o.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},o.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}},o.concat=function(l,n){if(!Array.isArray(l))throw new TypeError('"list" argument must be an Array of Buffers');if(0===l.length)return o.alloc(0);var u;if(void 0===n)for(n=0,u=0;u<l.length;++u)n+=l[u].length;var e=o.allocUnsafe(n),t=0;for(u=0;u<l.length;++u){var r=l[u];if(B(r,Uint8Array))t+r.length>e.length?o.from(r).copy(e,t):Uint8Array.prototype.set.call(e,r,t);else{if(!o.isBuffer(r))throw new TypeError('"list" argument must be an Array of Buffers');r.copy(e,t)}t+=r.length}return e},o.byteLength=f,o.prototype._isBuffer=!0,o.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},o.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},o.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},o.prototype.toString=function(){var l=this.length;return 0===l?"":0===arguments.length?T(this,0,l):p.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(l){if(!o.isBuffer(l))throw new TypeError("Argument must be a Buffer");return this===l||0===o.compare(this,l)},o.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&&(o.prototype[e]=o.prototype.inspect),o.prototype.compare=function(l,n,u,e,t){if(B(l,Uint8Array)&&(l=o.from(l,l.offset,l.byteLength)),!o.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),i=(u>>>=0)-(n>>>=0),a=Math.min(r,i),s=this.slice(e,t),c=l.slice(n,u),d=0;d<a;++d)if(s[d]!==c[d]){r=s[d],i=c[d];break}return r<i?-1:i<r?1:0},o.prototype.includes=function(l,n,u){return-1!==this.indexOf(l,n,u)},o.prototype.indexOf=function(l,n,u){return m(this,l,n,u,!0)},o.prototype.lastIndexOf=function(l,n,u){return m(this,l,n,u,!1)},o.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 b(this,l,n,u);case"utf8":case"utf-8":return v(this,l,n,u);case"ascii":case"latin1":case"binary":return E(this,l,n,u);case"base64":return w(this,l,n,u);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,l,n,u);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(""+e).toLowerCase(),r=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var R=4096;function O(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 A(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 C(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 F(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(!o.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 P(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 L(l,n,e,t,r){return n=+n,e>>>=0,r||P(l,0,e,4),u.write(l,n,e,t,23,4),e+4}function N(l,n,e,t,r){return n=+n,e>>>=0,r||P(l,0,e,8),u.write(l,n,e,t,52,8),e+8}o.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,o.prototype),e},o.prototype.readUintLE=o.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},o.prototype.readUintBE=o.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},o.prototype.readUint8=o.prototype.readUInt8=function(l,n){return l>>>=0,n||I(l,1,this.length),this[l]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(l,n){return l>>>=0,n||I(l,2,this.length),this[l]|this[l+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(l,n){return l>>>=0,n||I(l,2,this.length),this[l]<<8|this[l+1]},o.prototype.readUint32LE=o.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]},o.prototype.readUint32BE=o.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])},o.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},o.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},o.prototype.readInt8=function(l,n){return l>>>=0,n||I(l,1,this.length),128&this[l]?-1*(255-this[l]+1):this[l]},o.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},o.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},o.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},o.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]},o.prototype.readFloatLE=function(l,n){return l>>>=0,n||I(l,4,this.length),u.read(this,l,!0,23,4)},o.prototype.readFloatBE=function(l,n){return l>>>=0,n||I(l,4,this.length),u.read(this,l,!1,23,4)},o.prototype.readDoubleLE=function(l,n){return l>>>=0,n||I(l,8,this.length),u.read(this,l,!0,52,8)},o.prototype.readDoubleBE=function(l,n){return l>>>=0,n||I(l,8,this.length),u.read(this,l,!1,52,8)},o.prototype.writeUintLE=o.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},o.prototype.writeUintBE=o.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},o.prototype.writeUint8=o.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},o.prototype.writeUint16LE=o.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},o.prototype.writeUint16BE=o.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},o.prototype.writeUint32LE=o.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},o.prototype.writeUint32BE=o.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},o.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,o=1,i=0;for(this[n]=255&l;++r<u&&(o*=256);)l<0&&0===i&&0!==this[n+r-1]&&(i=1),this[n+r]=(l/o|0)-i&255;return n+u},o.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,o=1,i=0;for(this[n+r]=255&l;--r>=0&&(o*=256);)l<0&&0===i&&0!==this[n+r+1]&&(i=1),this[n+r]=(l/o|0)-i&255;return n+u},o.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},o.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},o.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},o.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},o.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},o.prototype.writeFloatLE=function(l,n,u){return L(this,l,n,!0,u)},o.prototype.writeFloatBE=function(l,n,u){return L(this,l,n,!1,u)},o.prototype.writeDoubleLE=function(l,n,u){return N(this,l,n,!0,u)},o.prototype.writeDoubleBE=function(l,n,u){return N(this,l,n,!1,u)},o.prototype.copy=function(l,n,u,e){if(!o.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},o.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&&!o.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 i=o.isBuffer(l)?l:o.from(l,e),a=i.length;if(0===a)throw new TypeError('The value "'+l+'" is invalid for argument "value"');for(r=0;r<u-n;++r)this[r+n]=i[r%a]}return this};var x=/[^+/0-9A-Za-z-_]/g;function U(l,n){var u;n=n||1/0;for(var e=l.length,t=null,r=[],o=0;o<e;++o){if((u=l.charCodeAt(o))>55295&&u<57344){if(!t){if(u>56319){(n-=3)>-1&&r.push(239,191,189);continue}if(o+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}()}(xe);var Ue={},De={};!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}}(De),function(l){var n=r&&r.__generator||function(l,n){var u,e,t,r,o={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function i(r){return function(i){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:r[1],done:!1};case 5:o.label++,e=r[1],r=[0];continue;case 7:r=o.ops.pop(),o.trys.pop();continue;default:if(!(t=o.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){o=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){o.label=r[1];break}if(6===r[0]&&o.label<t[1]){o.label=t[1],t=r;break}if(t&&o.label<t[2]){o.label=t[2],o.ops.push(r);break}t[2]&&o.ops.pop(),o.trys.pop();continue}r=n.call(l,o)}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,i])}}};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=De;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 o(l,n,u){return u=l.writeUInt8(n>>>16,u),u=l.writeUInt8(n>>>8&255,u),l.writeUInt8(255&n,u)}function i(l,n){var u=l.readUInt32BE(n),t=l.readUInt32BE(n+4);return u*e+t}function a(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=o,l.readUInt64BE=i,l.writeUInt64BE=a;function s(l){var n=t(l,0);return d(l.slice(3,3+n))}function c(l){var u,e,r,o,i;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),(o=(r=u+3)+e)>l.length?[3,3]:(i=l.slice(r,o),[4,[d(i),u=o]])):[3,3];case 2:return n.sent(),[3,1];case 3:return[2]}}))}function d(n){var e=0,t=n.readInt32BE(e);e+=4;var r=n.readUInt16BE(e);e+=2;var o=r>>>l.FRAME_TYPE_OFFFSET,a=r&l.FLAGS_MASK;switch(o){case u.FrameTypes.SETUP:return function(l,n,e){l.length;var t=6,r=l.readUInt16BE(t);t+=2;var o=l.readUInt16BE(t);t+=2;var i=l.readInt32BE(t);t+=4;var a=l.readInt32BE(t);t+=4;var s=null;if(e&u.Flags.RESUME_ENABLE){var c=l.readInt16BE(t);t+=2,s=l.slice(t,t+c),t+=c}var d=l.readUInt8(t);t+=1;var h=l.toString("ascii",t,t+d);t+=d;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:i,lifetime:a,majorVersion:r,metadata:null,metadataMimeType:h,minorVersion:o,resumeToken:s,streamId:0,type:u.FrameTypes.SETUP};return R(l,y,t),y}(n,0,a);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 R(l,t,6),t}(n,t,a);case u.FrameTypes.ERROR:return function(l,n,e){l.length;var t=6,r=l.readInt32BE(t);t+=4;var o=l.length-t,i="";o>0&&(i=l.toString("utf8",t,t+o),t+=o);return{code:r,flags:e,message:i,streamId:n,type:u.FrameTypes.ERROR}}(n,t,a);case u.FrameTypes.KEEPALIVE:return function(l,n,e){l.length;var t=6,r=i(l,t);t+=8;var o=null;t<l.length&&(o=l.slice(t,l.length));return{data:o,flags:e,lastReceivedPosition:r,streamId:0,type:u.FrameTypes.KEEPALIVE}}(n,0,a);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 R(l,t,6),t}(n,t,a);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 R(l,t,6),t}(n,t,a);case u.FrameTypes.REQUEST_STREAM:return function(l,n,e){l.length;var t=6,r=l.readInt32BE(t);t+=4;var o={data:null,flags:e,metadata:null,requestN:r,streamId:n,type:u.FrameTypes.REQUEST_STREAM};return R(l,o,t),o}(n,t,a);case u.FrameTypes.REQUEST_CHANNEL:return function(l,n,e){l.length;var t=6,r=l.readInt32BE(t);t+=4;var o={data:null,flags:e,metadata:null,requestN:r,streamId:n,type:u.FrameTypes.REQUEST_CHANNEL};return R(l,o,t),o}(n,t,a);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,a);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,a);case u.FrameTypes.RESUME:return function(l,n,e){l.length;var t=6,r=l.readUInt16BE(t);t+=2;var o=l.readUInt16BE(t);t+=2;var a=l.readInt16BE(t);t+=2;var s=l.slice(t,t+a);t+=a;var c=i(l,t);t+=8;var d=i(l,t);return t+=8,{clientPosition:d,flags:e,majorVersion:r,minorVersion:o,resumeToken:s,serverPosition:c,streamId:0,type:u.FrameTypes.RESUME}}(n,0,a);case u.FrameTypes.RESUME_OK:return function(l,n,e){l.length;var t=i(l,6);return{clientPosition:t,flags:e,streamId:0,type:u.FrameTypes.RESUME_OK}}(n,0,a);case u.FrameTypes.CANCEL:return function(l,n,e){return l.length,{flags:e,streamId:n,type:u.FrameTypes.CANCEL}}(n,t,a);case u.FrameTypes.LEASE:return function(l,n,e){var t=6,r=l.readUInt32BE(t);t+=4;var o=l.readUInt32BE(t);t+=4;var i=null;t<l.length&&(i=l.slice(t,l.length));return{flags:e,metadata:i,requestCount:o,streamId:0,ttl:r,type:u.FrameTypes.LEASE}}(n,0,a)}}function h(l){switch(l.type){case u.FrameTypes.SETUP:return function(l){var n=null!=l.resumeToken?l.resumeToken.byteLength:0,e=null!=l.metadataMimeType?xe.Buffer.byteLength(l.metadataMimeType,"ascii"):0,t=null!=l.dataMimeType?xe.Buffer.byteLength(l.dataMimeType,"ascii"):0,r=S(l),o=xe.Buffer.allocUnsafe(6+f+(n?p+n:0)+e+t+r),i=_(l,o);i=o.writeUInt16BE(l.majorVersion,i),i=o.writeUInt16BE(l.minorVersion,i),i=o.writeUInt32BE(l.keepAlive,i),i=o.writeUInt32BE(l.lifetime,i),l.flags&u.Flags.RESUME_ENABLE&&(i=o.writeUInt16BE(n,i),null!=l.resumeToken&&(i+=l.resumeToken.copy(o,i)));i=o.writeUInt8(e,i),null!=l.metadataMimeType&&(i+=o.write(l.metadataMimeType,i,i+e,"ascii"));i=o.writeUInt8(t,i),null!=l.dataMimeType&&(i+=o.write(l.dataMimeType,i,i+t,"ascii"));return T(l,o,i),o}(l);case u.FrameTypes.PAYLOAD:return function(l){var n=S(l),u=xe.Buffer.allocUnsafe(6+n),e=_(l,u);return T(l,u,e),u}(l);case u.FrameTypes.ERROR:return function(l){var n=null!=l.message?xe.Buffer.byteLength(l.message,"utf8"):0,u=xe.Buffer.allocUnsafe(6+y+n),e=_(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=xe.Buffer.allocUnsafe(6+m+n),e=_(l,u);e=a(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=S(l),u=xe.Buffer.allocUnsafe(6+n),e=_(l,u);return T(l,u,e),u}(l);case u.FrameTypes.REQUEST_STREAM:case u.FrameTypes.REQUEST_CHANNEL:return function(l){var n=S(l),u=xe.Buffer.allocUnsafe(6+b+n),e=_(l,u);return e=u.writeUInt32BE(l.requestN,e),T(l,u,e),u}(l);case u.FrameTypes.METADATA_PUSH:return function(l){var n=l.metadata;if(null!=n){var u=_(l,e=xe.Buffer.allocUnsafe(6+n.byteLength));return n.copy(e,u),e}var e;return _(l,e=xe.Buffer.allocUnsafe(6)),e}(l);case u.FrameTypes.REQUEST_N:return function(l){var n=xe.Buffer.allocUnsafe(6+v),u=_(l,n);return n.writeUInt32BE(l.requestN,u),n}(l);case u.FrameTypes.RESUME:return function(l){var n=l.resumeToken.byteLength,u=xe.Buffer.allocUnsafe(6+E+n),e=_(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=a(u,l.serverPosition,e),a(u,l.clientPosition,e),u}(l);case u.FrameTypes.RESUME_OK:return function(l){var n=xe.Buffer.allocUnsafe(6+w),u=_(l,n);return a(n,l.clientPosition,u),n}(l);case u.FrameTypes.CANCEL:return function(l){var n=xe.Buffer.allocUnsafe(6);return _(l,n),n}(l);case u.FrameTypes.LEASE:return function(l){var n=null!=l.metadata?l.metadata.byteLength:0,u=xe.Buffer.allocUnsafe(6+g+n),e=_(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=s,l.deserializeFrames=c,l.serializeFrameWithLength=function(l){var n=h(l),u=xe.Buffer.allocUnsafe(n.length+3);return o(u,n.length,0),n.copy(u,3),u},l.deserializeFrame=d,l.serializeFrame=h,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?xe.Buffer.byteLength(l.metadataMimeType,"ascii"):0,e=null!=l.dataMimeType?xe.Buffer.byteLength(l.dataMimeType,"ascii"):0,t=S(l);return 6+f+(n?p+n:0)+u+e+t}(l);case u.FrameTypes.PAYLOAD:return function(l){var n=S(l);return 6+n}(l);case u.FrameTypes.ERROR:return function(l){var n=null!=l.message?xe.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=S(l);return 6+n}(l);case u.FrameTypes.REQUEST_STREAM:case u.FrameTypes.REQUEST_CHANNEL:return function(l){var n=S(l);return 6+b+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+v;case u.FrameTypes.RESUME:return function(l){var n=l.resumeToken.byteLength;return 6+E+n}(l);case u.FrameTypes.RESUME_OK:return 6+w;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 b=4;var v=4;var E=22;var w=8;function _(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 S(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 T(l,n,e){u.Flags.hasMetadata(l.flags)&&(null!=l.metadata?(e=o(n,l.metadata.byteLength,e),e+=l.metadata.copy(n,e)):e=o(n,0,e));null!=l.data&&l.data.copy(n,e)}function R(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 O=function(){function l(){}return l.prototype.deserializeFrame=function(l){return d(l)},l.prototype.deserializeFrameWithLength=function(l){return s(l)},l.prototype.deserializeFrames=function(l){return c(l)},l}();l.Deserializer=O}(Ue);var Me={};Object.defineProperty(Me,"__esModule",{value:!0});var Be={},qe=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(Be,"__esModule",{value:!0}),Be.Deferred=void 0;var je=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=qe(this.onCloseCallbacks),o=r.next();!o.done;o=r.next()){(0,o.value)(l)}}catch(l){n={error:l}}finally{try{o&&!o.done&&(u=r.return)&&u.call(r)}finally{if(n)throw n.error}}else try{for(var i=qe(this.onCloseCallbacks),a=i.next();!a.done;a=i.next()){(0,a.value)()}}catch(l){e={error:l}}finally{try{a&&!a.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}},l.prototype.onClose=function(l){this._done?l(this._error):this.onCloseCallbacks.push(l)},l}();Be.Deferred=je;var We={};!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"}(We);var ze={};Object.defineProperty(ze,"__esModule",{value:!0});var Qe,$e={},He={};function Ve(){return Qe||(Qe=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 o(l){try{a(e.next(l))}catch(l){r(l)}}function i(l){try{a(e.throw(l))}catch(l){r(l)}}function a(l){var n;l.done?t(l.value):(n=l.value,n instanceof u?n:new u((function(l){l(n)}))).then(o,i)}a((e=e.apply(l,n||[])).next())}))},t=r&&r.__generator||function(l,n){var u,e,t,r,o={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function i(r){return function(i){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:r[1],done:!1};case 5:o.label++,e=r[1],r=[0];continue;case 7:r=o.ops.pop(),o.trys.pop();continue;default:if(!(t=o.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){o=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){o.label=r[1];break}if(6===r[0]&&o.label<t[1]){o.label=t[1],t=r;break}if(t&&o.label<t[2]){o.label=t[2],o.ops.push(r);break}t[2]&&o.ops.pop(),o.trys.pop();continue}r=n.call(l,o)}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,i])}}};Object.defineProperty(l,"__esModule",{value:!0}),l.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer=l.ResumableClientServerInputMultiplexerDemultiplexer=l.ClientServerInputMultiplexerDemultiplexer=l.StreamIdGenerator=void 0;var o=fr(),i=Be,a=We,s=De;!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(s.Frame.isConnection(l)){if(l.type===o.FrameTypes.RESERVED)return;this.connectionFramesHandler.handle(l)}else if(s.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}(i.Deferred);l.ClientServerInputMultiplexerDemultiplexer=c;var d=function(l){function n(n,u,e,t,r,o,a){var s=l.call(this,n,u,new i.Deferred)||this;return s.frameStore=t,s.token=r,s.sessionTimeout=a,o instanceof Function?s.reconnector=o:s.sessionStore=o,e.onClose(s.handleConnectionClose.bind(s)),s}return u(n,l),n.prototype.send=function(n){if(s.Frame.isConnection(n)){if(n.type===o.FrameTypes.KEEPALIVE)n.lastReceivedPosition=this.frameStore.lastReceivedFramePosition;else if(n.type===o.FrameTypes.ERROR)return this.outbound.send(n),this.sessionStore&&delete this.sessionStore[this.token],void l.prototype.close.call(this,new a.RSocketError(n.code,n.message))}else this.frameStore.store(n);this.outbound.send(n)},n.prototype.handle=function(n){if(s.Frame.isConnection(n)){if(n.type===o.FrameTypes.KEEPALIVE)try{this.frameStore.dropTo(n.lastReceivedPosition)}catch(l){this.outbound.send({type:o.FrameTypes.ERROR,streamId:0,flags:o.Flags.NONE,code:l.code,message:l.message}),this.close(l)}else if(n.type===o.FrameTypes.ERROR)return l.prototype.handle.call(this,n),this.sessionStore&&delete this.sessionStore[this.token],void l.prototype.close.call(this,new a.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 o.FrameTypes.RESUME:if(clearTimeout(this.timeoutId),this.frameStore.lastReceivedFramePosition<l.clientPosition){var e=new a.RSocketError(o.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:o.FrameTypes.ERROR,streamId:0,flags:o.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:o.FrameTypes.ERROR,streamId:0,flags:o.Flags.NONE,code:l.code,message:l.message}),void this.close(l)}this.outbound.send({type:o.FrameTypes.RESUME_OK,streamId:0,flags:o.Flags.NONE,clientPosition:this.frameStore.lastReceivedFramePosition});break;case o.FrameTypes.RESUME_OK:try{this.frameStore.dropTo(l.clientPosition)}catch(l){this.outbound.send({type:o.FrameTypes.ERROR,streamId:0,flags:o.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=d;var h=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===o.FrameTypes.RESUME_OK?(this.resumed=!0,void this.delegate.resume(l,this.outbound,this.closeable)):(this.outbound.send({type:o.FrameTypes.ERROR,streamId:0,code:o.ErrorCodes.CONNECTION_ERROR,message:"Incomplete RESUME handshake. Unexpected frame ".concat(l.type," received"),flags:o.Flags.NONE}),this.closeable.close(),void this.closeable.onClose((function(){return n.delegate.close(new a.RSocketError(o.ErrorCodes.CONNECTION_ERROR,"Incomplete RESUME handshake. Unexpected frame ".concat(l.type," received")))})));this.delegate.handle(l)},l}();l.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer=h}(He)),He}var Je={},Ye={},Ge={},Xe=r&&r.__generator||function(l,n){var u,e,t,r,o={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function i(r){return function(i){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:r[1],done:!1};case 5:o.label++,e=r[1],r=[0];continue;case 7:r=o.ops.pop(),o.trys.pop();continue;default:if(!(t=o.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){o=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){o.label=r[1];break}if(6===r[0]&&o.label<t[1]){o.label=t[1],t=r;break}if(t&&o.label<t[2]){o.label=t[2],o.ops.push(r);break}t[2]&&o.ops.pop(),o.trys.pop();continue}r=n.call(l,o)}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,i])}}};Object.defineProperty(Ge,"__esModule",{value:!0}),Ge.fragmentWithRequestN=Ge.fragment=Ge.isFragmentable=void 0;var Ke=De;Ge.isFragmentable=function(l,n,u){return 0!==n&&l.data.byteLength+(l.metadata?l.metadata.byteLength+Ke.Lengths.METADATA:0)+(u==Ke.FrameTypes.REQUEST_STREAM||u==Ke.FrameTypes.REQUEST_CHANNEL?Ke.Lengths.REQUEST:0)>n},Ge.fragment=function(l,n,u,e,t){var r,o,i,a,s,c,d,h,f,p,y,m;return void 0===t&&(t=!1),Xe(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,o=e!==Ke.FrameTypes.PAYLOAD,i=u,n.metadata?0!==(s=n.metadata.byteLength)?[3,1]:(i-=Ke.Lengths.METADATA,a=xe.Buffer.allocUnsafe(0),[3,6]):[3,6];case 1:return c=0,o?(i-=Ke.Lengths.METADATA,d=Math.min(s,c+i),a=n.metadata.slice(c,d),i-=a.byteLength,c=d,0!==i?[3,3]:(o=!1,[4,{type:e,flags:Ke.Flags.FOLLOWS|Ke.Flags.METADATA,data:void 0,metadata:a,streamId:l}])):[3,3];case 2:g.sent(),a=void 0,i=u,g.label=3;case 3:return c<s?(i-=Ke.Lengths.METADATA,d=Math.min(s,c+i),a=n.metadata.slice(c,d),i-=a.byteLength,c=d,0!==i&&0!==r?[3,5]:[4,{type:Ke.FrameTypes.PAYLOAD,flags:Ke.Flags.NEXT|Ke.Flags.METADATA|(c===s&&t&&0===r?Ke.Flags.COMPLETE:Ke.Flags.FOLLOWS),data:void 0,metadata:a,streamId:l}]):[3,6];case 4:g.sent(),a=void 0,i=u,g.label=5;case 5:return[3,3];case 6:return h=0,o?(p=Math.min(r,h+i),f=n.data.slice(h,p),i-=f.byteLength,h=p,[4,{type:e,flags:Ke.Flags.FOLLOWS|(a?Ke.Flags.METADATA:Ke.Flags.NONE),data:f,metadata:a,streamId:l}]):[3,8];case 7:g.sent(),a=void 0,f=void 0,i=u,g.label=8;case 8:return h<r?(p=Math.min(r,h+i),f=n.data.slice(h,p),i-=f.byteLength,h=p,[4,{type:Ke.FrameTypes.PAYLOAD,flags:h===r?(t?Ke.Flags.COMPLETE:Ke.Flags.NONE)|Ke.Flags.NEXT|(a?Ke.Flags.METADATA:0):Ke.Flags.FOLLOWS|Ke.Flags.NEXT|(a?Ke.Flags.METADATA:0),data:f,metadata:a,streamId:l}]):[3,10];case 9:return g.sent(),a=void 0,f=void 0,i=u,[3,8];case 10:return[2]}}))},Ge.fragmentWithRequestN=function(l,n,u,e,t,r){var o,i,a,s,c,d,h,f,p,y,m,g;return void 0===r&&(r=!1),Xe(this,(function(b){switch(b.label){case 0:return o=null!==(g=null===(m=n.data)||void 0===m?void 0:m.byteLength)&&void 0!==g?g:0,i=!0,a=u,n.metadata?0!==(c=n.metadata.byteLength)?[3,1]:(a-=Ke.Lengths.METADATA,s=xe.Buffer.allocUnsafe(0),[3,6]):[3,6];case 1:return d=0,i?(a-=Ke.Lengths.METADATA+Ke.Lengths.REQUEST,h=Math.min(c,d+a),s=n.metadata.slice(d,h),a-=s.byteLength,d=h,0!==a?[3,3]:(i=!1,[4,{type:e,flags:Ke.Flags.FOLLOWS|Ke.Flags.METADATA,data:void 0,requestN:t,metadata:s,streamId:l}])):[3,3];case 2:b.sent(),s=void 0,a=u,b.label=3;case 3:return d<c?(a-=Ke.Lengths.METADATA,h=Math.min(c,d+a),s=n.metadata.slice(d,h),a-=s.byteLength,d=h,0!==a&&0!==o?[3,5]:[4,{type:Ke.FrameTypes.PAYLOAD,flags:Ke.Flags.NEXT|Ke.Flags.METADATA|(d===c&&r&&0===o?Ke.Flags.COMPLETE:Ke.Flags.FOLLOWS),data:void 0,metadata:s,streamId:l}]):[3,6];case 4:b.sent(),s=void 0,a=u,b.label=5;case 5:return[3,3];case 6:return f=0,i?(a-=Ke.Lengths.REQUEST,y=Math.min(o,f+a),p=n.data.slice(f,y),a-=p.byteLength,f=y,[4,{type:e,flags:Ke.Flags.FOLLOWS|(s?Ke.Flags.METADATA:Ke.Flags.NONE),data:p,requestN:t,metadata:s,streamId:l}]):[3,8];case 7:b.sent(),s=void 0,p=void 0,a=u,b.label=8;case 8:return f<o?(y=Math.min(o,f+a),p=n.data.slice(f,y),a-=p.byteLength,f=y,[4,{type:Ke.FrameTypes.PAYLOAD,flags:f===o?(r?Ke.Flags.COMPLETE:Ke.Flags.NONE)|Ke.Flags.NEXT|(s?Ke.Flags.METADATA:0):Ke.Flags.FOLLOWS|Ke.Flags.NEXT|(s?Ke.Flags.METADATA:0),data:p,metadata:s,streamId:l}]):[3,10];case 9:return b.sent(),s=void 0,p=void 0,a=u,[3,8];case 10:return[2]}}))};var Ze={};Object.defineProperty(Ze,"__esModule",{value:!0}),Ze.cancel=Ze.reassemble=Ze.add=void 0,Ze.add=function(l,n,u){return l.hasFragments?(l.data=l.data?xe.Buffer.concat([l.data,n]):n,l.metadata&&u&&(l.metadata=xe.Buffer.concat([l.metadata,u])),!0):(l.hasFragments=!0,l.data=n,u&&(l.metadata=u),!0)},Ze.reassemble=function(l,n,u){l.hasFragments=!1;var e=l.data?xe.Buffer.concat([l.data,n]):n;if(l.data=void 0,l.metadata){var t=u?xe.Buffer.concat([l.metadata,u]):l.metadata;return l.metadata=void 0,{data:e,metadata:t}}return{data:e}},Ze.cancel=function(l){l.hasFragments=!1,l.data=void 0,l.metadata=void 0};var lt=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]}),nt=r&&r.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),ut=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)&&lt(n,l,u);return nt(n,l),n},et=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(Ye,"__esModule",{value:!0}),Ye.RequestChannelResponderStream=Ye.RequestChannelRequesterStream=void 0;var tt=We,rt=Ge,ot=De,it=ut(Ze),at=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=ot.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,rt.isFragmentable)(this.payload,this.fragmentSize,ot.FrameTypes.REQUEST_CHANNEL))try{for(var r=et((0,rt.fragmentWithRequestN)(l,this.payload,this.fragmentSize,ot.FrameTypes.REQUEST_CHANNEL,this.initialRequestN,t)),o=r.next();!o.done;o=r.next()){var i=o.value;this.stream.send(i)}}catch(l){u={error:l}}finally{try{o&&!o.done&&(e=r.return)&&e.call(r)}finally{if(u)throw u.error}}else this.stream.send({type:ot.FrameTypes.REQUEST_CHANNEL,data:this.payload.data,metadata:this.payload.metadata,requestN:this.initialRequestN,flags:(void 0!==this.payload.metadata?ot.Flags.METADATA:ot.Flags.NONE)|(t?ot.Flags.COMPLETE:ot.Flags.NONE),streamId:l});return this.hasExtension&&this.stream.send({type:ot.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 ot.FrameTypes.PAYLOAD:var e=ot.Flags.hasComplete(l.flags),t=ot.Flags.hasNext(l.flags);if(e||!ot.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?it.reassemble(this,l.data,l.metadata):{data:l.data,metadata:l.metadata};return void this.receiver.onNext(r,e)}if(it.add(this,l.data,l.metadata))return;n="Unexpected frame size";break;case ot.FrameTypes.CANCEL:if(this.outboundDone)return;return this.outboundDone=!0,this.inboundDone&&this.stream.disconnect(this),void this.receiver.cancel();case ot.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 ot.FrameTypes.ERROR:var o=this.outboundDone;return this.inboundDone=!0,this.outboundDone=!0,this.stream.disconnect(this),it.cancel(this),o||this.receiver.cancel(),void this.receiver.onError(new tt.RSocketError(l.code,l.message));case ot.FrameTypes.EXT:return void this.receiver.onExtension(l.extendedType,l.extendedContent,ot.Flags.hasIgnore(l.flags));default:n="Unexpected frame type [".concat(u,"]")}this.close(new tt.RSocketError(tt.ErrorCodes.CANCELED,n)),this.stream.send({type:ot.FrameTypes.CANCEL,streamId:this.streamId,flags:ot.Flags.NONE}),this.stream.disconnect(this)},l.prototype.request=function(l){this.inboundDone||(this.streamId?this.stream.send({type:ot.FrameTypes.REQUEST_N,flags:ot.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?ot.FrameTypes.ERROR:ot.FrameTypes.CANCEL,flags:ot.Flags.NONE,streamId:this.streamId,code:tt.ErrorCodes.CANCELED,message:"Cancelled"}),this.stream.disconnect(this),it.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,rt.isFragmentable)(l,this.fragmentSize,ot.FrameTypes.PAYLOAD))try{for(var t=et((0,rt.fragment)(this.streamId,l,this.fragmentSize,ot.FrameTypes.PAYLOAD,n)),r=t.next();!r.done;r=t.next()){var o=r.value;this.stream.send(o)}}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:ot.FrameTypes.PAYLOAD,streamId:this.streamId,flags:ot.Flags.NEXT|(l.metadata?ot.Flags.METADATA:ot.Flags.NONE)|(n?ot.Flags.COMPLETE:ot.Flags.NONE),data:l.data,metadata:l.metadata})},l.prototype.onComplete=function(){this.streamId?this.outboundDone||(this.outboundDone=!0,this.stream.send({type:ot.FrameTypes.PAYLOAD,streamId:this.streamId,flags:ot.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:ot.FrameTypes.ERROR,streamId:this.streamId,flags:ot.Flags.NONE,code:l instanceof tt.RSocketError?l.code:tt.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:ot.FrameTypes.EXT,extendedType:l,extendedContent:n,flags:u?ot.Flags.IGNORE:ot.Flags.NONE}):(this.hasExtension=!0,this.extendedType=l,this.extendedContent=n,void(this.flags=u?ot.Flags.IGNORE:ot.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,it.cancel(this),u||this.receiver.cancel(),n||(l?this.receiver.onError(l):this.receiver.onComplete())}},l}();Ye.RequestChannelRequesterStream=at;var st=function(){function l(l,n,u,e,t){if(this.streamId=l,this.stream=n,this.fragmentSize=u,this.handler=e,this.streamType=ot.FrameTypes.REQUEST_CHANNEL,n.connect(this),ot.Flags.hasFollows(t.flags))return it.add(this,t.data,t.metadata),this.initialRequestN=t.requestN,void(this.isComplete=ot.Flags.hasComplete(t.flags));var r={data:t.data,metadata:t.metadata},o=ot.Flags.hasComplete(t.flags);this.inboundDone=o;try{this.receiver=e(r,t.requestN,o,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 ot.FrameTypes.PAYLOAD:if(ot.Flags.hasFollows(l.flags)){if(it.add(this,l.data,l.metadata))return;n="Unexpected frame size";break}var e=this.hasFragments?it.reassemble(this,l.data,l.metadata):{data:l.data,metadata:l.metadata},t=ot.Flags.hasComplete(l.flags);if(this.receiver){if(t&&(this.inboundDone=!0,this.outboundDone&&this.stream.disconnect(this),!ot.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(i){this.outboundDone&&!this.inboundDone?this.cancel():this.inboundDone=!0,this.onError(i)}}return;case ot.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 ot.FrameTypes.ERROR:case ot.FrameTypes.CANCEL:var r=this.inboundDone,o=this.outboundDone;if(this.inboundDone=!0,this.outboundDone=!0,this.stream.disconnect(this),it.cancel(this),!this.receiver)return;if(o||this.receiver.cancel(),!r){var i=u===ot.FrameTypes.CANCEL?new tt.RSocketError(tt.ErrorCodes.CANCELED,"Cancelled"):new tt.RSocketError(l.code,l.message);this.receiver.onError(i)}return;case ot.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,ot.Flags.hasIgnore(l.flags));default:n="Unexpected frame type [".concat(u,"]")}this.stream.send({type:ot.FrameTypes.ERROR,flags:ot.Flags.NONE,code:tt.ErrorCodes.CANCELED,message:n,streamId:this.streamId}),this.stream.disconnect(this),this.close(new tt.RSocketError(tt.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:ot.FrameTypes.ERROR,flags:ot.Flags.NONE,code:l instanceof tt.RSocketError?l.code:tt.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,rt.isFragmentable)(l,this.fragmentSize,ot.FrameTypes.PAYLOAD))try{for(var t=et((0,rt.fragment)(this.streamId,l,this.fragmentSize,ot.FrameTypes.PAYLOAD,n)),r=t.next();!r.done;r=t.next()){var o=r.value;this.stream.send(o)}}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:ot.FrameTypes.PAYLOAD,flags:ot.Flags.NEXT|(n?ot.Flags.COMPLETE:ot.Flags.NONE)|(l.metadata?ot.Flags.METADATA:ot.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:ot.FrameTypes.PAYLOAD,flags:ot.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:ot.FrameTypes.EXT,streamId:this.streamId,flags:u?ot.Flags.IGNORE:ot.Flags.NONE,extendedType:l,extendedContent:n})},l.prototype.request=function(l){this.inboundDone||this.stream.send({type:ot.FrameTypes.REQUEST_N,flags:ot.Flags.NONE,streamId:this.streamId,requestN:l})},l.prototype.cancel=function(){this.inboundDone||(this.inboundDone=!0,this.stream.send({type:ot.FrameTypes.CANCEL,flags:ot.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,it.cancel(this);var e=this.receiver;e&&(u||e.cancel(),n||(l?e.onError(l):e.onComplete()))}},l}();Ye.RequestChannelResponderStream=st;var ct={},dt=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]}),ht=r&&r.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),ft=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)&&dt(n,l,u);return ht(n,l),n},pt=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(ct,"__esModule",{value:!0}),ct.RequestFnfResponderStream=ct.RequestFnFRequesterStream=void 0;var yt=We,mt=Ge,gt=De,bt=ft(Ze),vt=function(){function l(l,n,u,e){this.payload=l,this.receiver=n,this.fragmentSize=u,this.leaseManager=e,this.streamType=gt.FrameTypes.REQUEST_FNF}return l.prototype.handleReady=function(l,n){var u,e;if(this.done)return!1;if(this.streamId=l,(0,mt.isFragmentable)(this.payload,this.fragmentSize,gt.FrameTypes.REQUEST_FNF))try{for(var t=pt((0,mt.fragment)(l,this.payload,this.fragmentSize,gt.FrameTypes.REQUEST_FNF)),r=t.next();!r.done;r=t.next()){var o=r.value;n.send(o)}}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:gt.FrameTypes.REQUEST_FNF,data:this.payload.data,metadata:this.payload.metadata,flags:this.payload.metadata?gt.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!=gt.FrameTypes.ERROR?this.close(new yt.RSocketError(yt.ErrorCodes.CANCELED,"Received invalid frame")):this.close(new yt.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}();ct.RequestFnFRequesterStream=vt;var Et=function(){function l(l,n,u,e){if(this.streamId=l,this.stream=n,this.handler=u,this.streamType=gt.FrameTypes.REQUEST_FNF,gt.Flags.hasFollows(e.flags))return bt.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==gt.FrameTypes.PAYLOAD){if(!gt.Flags.hasFollows(l.flags)){this.stream.disconnect(this);var u=bt.reassemble(this,l.data,l.metadata);try{this.cancellable=this.handler(u,this)}catch(l){}return}if(bt.add(this,l.data,l.metadata))return;n="Unexpected fragment size"}else n="Unexpected frame type [".concat(l.type,"]");this.done=!0,l.type!=gt.FrameTypes.CANCEL&&l.type!=gt.FrameTypes.ERROR&&this.stream.send({type:gt.FrameTypes.ERROR,streamId:this.streamId,flags:gt.Flags.NONE,code:yt.ErrorCodes.CANCELED,message:n}),this.stream.disconnect(this),bt.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,bt.cancel(this),null===(n=this.cancellable)||void 0===n||n.cancel())},l.prototype.onError=function(l){},l.prototype.onComplete=function(){},l}();ct.RequestFnfResponderStream=Et;var wt={},_t=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]}),St=r&&r.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),Tt=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)&&_t(n,l,u);return St(n,l),n},Rt=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(wt,"__esModule",{value:!0}),wt.RequestResponseResponderStream=wt.RequestResponseRequesterStream=void 0;var Ot=We,At=Ge,Ct=De,Ft=Tt(Ze),It=function(){function l(l,n,u,e){this.payload=l,this.receiver=n,this.fragmentSize=u,this.leaseManager=e,this.streamType=Ct.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,At.isFragmentable)(this.payload,this.fragmentSize,Ct.FrameTypes.REQUEST_RESPONSE))try{for(var t=Rt((0,At.fragment)(l,this.payload,this.fragmentSize,Ct.FrameTypes.REQUEST_RESPONSE)),r=t.next();!r.done;r=t.next()){var o=r.value;this.stream.send(o)}}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:Ct.FrameTypes.REQUEST_RESPONSE,data:this.payload.data,metadata:this.payload.metadata,flags:this.payload.metadata?Ct.Flags.METADATA:0,streamId:l});return this.hasExtension&&this.stream.send({type:Ct.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 Ct.FrameTypes.PAYLOAD:var e=Ct.Flags.hasComplete(l.flags),t=Ct.Flags.hasNext(l.flags);if(e||!Ct.Flags.hasFollows(l.flags)){if(this.done=!0,this.stream.disconnect(this),!t)return void this.receiver.onComplete();var r=this.hasFragments?Ft.reassemble(this,l.data,l.metadata):{data:l.data,metadata:l.metadata};return void this.receiver.onNext(r,!0)}if(!Ft.add(this,l.data,l.metadata)){n="Unexpected fragment size";break}return;case Ct.FrameTypes.ERROR:return this.done=!0,this.stream.disconnect(this),Ft.cancel(this),void this.receiver.onError(new Ot.RSocketError(l.code,l.message));case Ct.FrameTypes.EXT:if(this.hasFragments){n="Unexpected frame type [".concat(u,"] during reassembly");break}return void this.receiver.onExtension(l.extendedType,l.extendedContent,Ct.Flags.hasIgnore(l.flags));default:n="Unexpected frame type [".concat(u,"]")}this.close(new Ot.RSocketError(Ot.ErrorCodes.CANCELED,n)),this.stream.send({type:Ct.FrameTypes.CANCEL,streamId:this.streamId,flags:Ct.Flags.NONE}),this.stream.disconnect(this)},l.prototype.cancel=function(){var l;this.done||(this.done=!0,this.streamId?(this.stream.send({type:Ct.FrameTypes.CANCEL,flags:Ct.Flags.NONE,streamId:this.streamId}),this.stream.disconnect(this),Ft.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:Ct.FrameTypes.EXT,extendedType:l,extendedContent:n,flags:u?Ct.Flags.IGNORE:Ct.Flags.NONE}):(this.hasExtension=!0,this.extendedType=l,this.extendedContent=n,void(this.flags=u?Ct.Flags.IGNORE:Ct.Flags.NONE))},l.prototype.close=function(l){this.done||(this.done=!0,Ft.cancel(this),l?this.receiver.onError(l):this.receiver.onComplete())},l}();wt.RequestResponseRequesterStream=It;var kt=function(){function l(l,n,u,e,t){if(this.streamId=l,this.stream=n,this.fragmentSize=u,this.handler=e,this.streamType=Ct.FrameTypes.REQUEST_RESPONSE,n.connect(this),Ct.Flags.hasFollows(t.flags))Ft.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===Ct.FrameTypes.PAYLOAD){if(!Ct.Flags.hasFollows(l.flags)){var e=Ft.reassemble(this,l.data,l.metadata);try{this.receiver=this.handler(e,this)}catch(l){this.onError(l)}return}if(Ft.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===Ct.FrameTypes.EXT)return void this.receiver.onExtension(l.extendedType,l.extendedContent,Ct.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!==Ct.FrameTypes.CANCEL&&l.type!==Ct.FrameTypes.ERROR&&this.stream.send({type:Ct.FrameTypes.ERROR,flags:Ct.Flags.NONE,code:Ot.ErrorCodes.CANCELED,message:u,streamId:this.streamId}),this.stream.disconnect(this),Ft.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:Ct.FrameTypes.ERROR,flags:Ct.Flags.NONE,code:l instanceof Ot.RSocketError?l.code:Ot.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,At.isFragmentable)(l,this.fragmentSize,Ct.FrameTypes.PAYLOAD))try{for(var t=Rt((0,At.fragment)(this.streamId,l,this.fragmentSize,Ct.FrameTypes.PAYLOAD,!0)),r=t.next();!r.done;r=t.next()){var o=r.value;this.stream.send(o)}}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:Ct.FrameTypes.PAYLOAD,flags:Ct.Flags.NEXT|Ct.Flags.COMPLETE|(l.metadata?Ct.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:Ct.FrameTypes.PAYLOAD,flags:Ct.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:Ct.FrameTypes.EXT,streamId:this.streamId,flags:u?Ct.Flags.IGNORE:Ct.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,"]."):"")):(Ft.cancel(this),null===(n=this.receiver)||void 0===n||n.cancel())},l}();wt.RequestResponseResponderStream=kt;var Pt={},Lt=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]}),Nt=r&&r.__setModuleDefault||(Object.create?function(l,n){Object.defineProperty(l,"default",{enumerable:!0,value:n})}:function(l,n){l.default=n}),xt=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)&&Lt(n,l,u);return Nt(n,l),n},Ut=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(Pt,"__esModule",{value:!0}),Pt.RequestStreamResponderStream=Pt.RequestStreamRequesterStream=void 0;var Dt=We,Mt=Ge,Bt=De,qt=xt(Ze),jt=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=Bt.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,Mt.isFragmentable)(this.payload,this.fragmentSize,Bt.FrameTypes.REQUEST_STREAM))try{for(var t=Ut((0,Mt.fragmentWithRequestN)(l,this.payload,this.fragmentSize,Bt.FrameTypes.REQUEST_STREAM,this.initialRequestN)),r=t.next();!r.done;r=t.next()){var o=r.value;this.stream.send(o)}}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:Bt.FrameTypes.REQUEST_STREAM,data:this.payload.data,metadata:this.payload.metadata,requestN:this.initialRequestN,flags:void 0!==this.payload.metadata?Bt.Flags.METADATA:0,streamId:l});return this.hasExtension&&this.stream.send({type:Bt.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 Bt.FrameTypes.PAYLOAD:var e=Bt.Flags.hasComplete(l.flags),t=Bt.Flags.hasNext(l.flags);if(e||!Bt.Flags.hasFollows(l.flags)){if(e&&(this.done=!0,this.stream.disconnect(this),!t))return void this.receiver.onComplete();var r=this.hasFragments?qt.reassemble(this,l.data,l.metadata):{data:l.data,metadata:l.metadata};return void this.receiver.onNext(r,e)}if(!qt.add(this,l.data,l.metadata)){n="Unexpected fragment size";break}return;case Bt.FrameTypes.ERROR:return this.done=!0,this.stream.disconnect(this),qt.cancel(this),void this.receiver.onError(new Dt.RSocketError(l.code,l.message));case Bt.FrameTypes.EXT:if(this.hasFragments){n="Unexpected frame type [".concat(u,"] during reassembly");break}return void this.receiver.onExtension(l.extendedType,l.extendedContent,Bt.Flags.hasIgnore(l.flags));default:n="Unexpected frame type [".concat(u,"]")}this.close(new Dt.RSocketError(Dt.ErrorCodes.CANCELED,n)),this.stream.send({type:Bt.FrameTypes.CANCEL,streamId:this.streamId,flags:Bt.Flags.NONE}),this.stream.disconnect(this)},l.prototype.request=function(l){this.done||(this.streamId?this.stream.send({type:Bt.FrameTypes.REQUEST_N,flags:Bt.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:Bt.FrameTypes.CANCEL,flags:Bt.Flags.NONE,streamId:this.streamId}),this.stream.disconnect(this),qt.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:Bt.FrameTypes.EXT,extendedType:l,extendedContent:n,flags:u?Bt.Flags.IGNORE:Bt.Flags.NONE}):(this.hasExtension=!0,this.extendedType=l,this.extendedContent=n,void(this.flags=u?Bt.Flags.IGNORE:Bt.Flags.NONE))},l.prototype.close=function(l){this.done||(this.done=!0,qt.cancel(this),l?this.receiver.onError(l):this.receiver.onComplete())},l}();Pt.RequestStreamRequesterStream=jt;var Wt=function(){function l(l,n,u,e,t){if(this.streamId=l,this.stream=n,this.fragmentSize=u,this.handler=e,this.streamType=Bt.FrameTypes.REQUEST_STREAM,n.connect(this),Bt.Flags.hasFollows(t.flags))return this.initialRequestN=t.requestN,void qt.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===Bt.FrameTypes.PAYLOAD){if(!Bt.Flags.hasFollows(l.flags)){var e=qt.reassemble(this,l.data,l.metadata);try{this.receiver=this.handler(e,this.initialRequestN,this)}catch(l){this.onError(l)}return}if(qt.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===Bt.FrameTypes.REQUEST_N)return void this.receiver.request(l.requestN);if(l.type===Bt.FrameTypes.EXT)return void this.receiver.onExtension(l.extendedType,l.extendedContent,Bt.Flags.hasIgnore(l.flags));u="Unexpected frame type [".concat(l.type,"]")}this.done=!0,qt.cancel(this),null===(n=this.receiver)||void 0===n||n.cancel(),l.type!==Bt.FrameTypes.CANCEL&&l.type!==Bt.FrameTypes.ERROR&&this.stream.send({type:Bt.FrameTypes.ERROR,flags:Bt.Flags.NONE,code:Dt.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:Bt.FrameTypes.ERROR,flags:Bt.Flags.NONE,code:l instanceof Dt.RSocketError?l.code:Dt.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,Mt.isFragmentable)(l,this.fragmentSize,Bt.FrameTypes.PAYLOAD))try{for(var t=Ut((0,Mt.fragment)(this.streamId,l,this.fragmentSize,Bt.FrameTypes.PAYLOAD,n)),r=t.next();!r.done;r=t.next()){var o=r.value;this.stream.send(o)}}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:Bt.FrameTypes.PAYLOAD,flags:Bt.Flags.NEXT|(n?Bt.Flags.COMPLETE:Bt.Flags.NONE)|(l.metadata?Bt.Flags.METADATA:Bt.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:Bt.FrameTypes.PAYLOAD,flags:Bt.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:Bt.FrameTypes.EXT,streamId:this.streamId,flags:u?Bt.Flags.IGNORE:Bt.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,"]."):"")):(qt.cancel(this),null===(n=this.receiver)||void 0===n||n.cancel())},l}();Pt.RequestStreamResponderStream=Wt,Object.defineProperty(Je,"__esModule",{value:!0}),Je.KeepAliveSender=Je.KeepAliveHandler=Je.DefaultConnectionFrameHandler=Je.DefaultStreamRequestHandler=Je.LeaseHandler=Je.RSocketRequester=void 0;var zt=We,Qt=De,$t=Ye,Ht=ct,Vt=wt,Jt=Pt,Yt=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 Ht.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 Vt.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 Jt.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 $t.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}();Je.RSocketRequester=Yt;var Gt=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 zt.RSocketError(zt.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}();Je.LeaseHandler=Gt;var Xt=function(){function l(l,n){this.rsocket=l,this.fragmentSize=n}return l.prototype.handle=function(l,n){switch(l.type){case Qt.FrameTypes.REQUEST_FNF:return void(this.rsocket.fireAndForget&&new Ht.RequestFnfResponderStream(l.streamId,n,this.rsocket.fireAndForget.bind(this.rsocket),l));case Qt.FrameTypes.REQUEST_RESPONSE:return this.rsocket.requestResponse?void new Vt.RequestResponseResponderStream(l.streamId,n,this.fragmentSize,this.rsocket.requestResponse.bind(this.rsocket),l):void this.rejectRequest(l.streamId,n);case Qt.FrameTypes.REQUEST_STREAM:return this.rsocket.requestStream?void new Jt.RequestStreamResponderStream(l.streamId,n,this.fragmentSize,this.rsocket.requestStream.bind(this.rsocket),l):void this.rejectRequest(l.streamId,n);case Qt.FrameTypes.REQUEST_CHANNEL:return this.rsocket.requestChannel?void new $t.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:Qt.FrameTypes.ERROR,streamId:l,flags:Qt.Flags.NONE,code:zt.ErrorCodes.REJECTED,message:"No available handler found"})},l.prototype.close=function(){},l}();Je.DefaultStreamRequestHandler=Xt;var Kt,Zt=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 Qt.FrameTypes.KEEPALIVE:return void this.keepAliveHandler.handle(l);case Qt.FrameTypes.LEASE:return this.leaseHandler?void this.leaseHandler.handle(l):void 0;case Qt.FrameTypes.ERROR:return void this.connection.close(new zt.RSocketError(l.code,l.message));case Qt.FrameTypes.METADATA_PUSH:return void this.rsocket.metadataPush;default:this.connection.multiplexerDemultiplexer.connectionOutbound.send({type:Qt.FrameTypes.ERROR,streamId:0,flags:Qt.Flags.NONE,message:"Received unknown frame type",code:zt.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}();Je.DefaultConnectionFrameHandler=Zt,function(l){l[l.Paused=0]="Paused",l[l.Running=1]="Running",l[l.Closed=2]="Closed"}(Kt||(Kt={}));var lr,nr=function(){function l(l,n){this.connection=l,this.keepAliveTimeoutDuration=n,this.state=Kt.Paused,this.outbound=l.multiplexerDemultiplexer.connectionOutbound}return l.prototype.handle=function(l){this.keepAliveLastReceivedMillis=Date.now(),Qt.Flags.hasRespond(l.flags)&&this.outbound.send({type:Qt.FrameTypes.KEEPALIVE,streamId:0,data:l.data,flags:l.flags^Qt.Flags.RESPOND,lastReceivedPosition:0})},l.prototype.start=function(){this.state===Kt.Paused&&(this.keepAliveLastReceivedMillis=Date.now(),this.state=Kt.Running,this.activeTimeout=setTimeout(this.timeoutCheck.bind(this),this.keepAliveTimeoutDuration))},l.prototype.pause=function(){this.state===Kt.Running&&(this.state=Kt.Paused,clearTimeout(this.activeTimeout))},l.prototype.close=function(){this.state=Kt.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}();Je.KeepAliveHandler=nr,function(l){l[l.Paused=0]="Paused",l[l.Running=1]="Running",l[l.Closed=2]="Closed"}(lr||(lr={}));var ur=function(){function l(l,n){this.outbound=l,this.keepAlivePeriodDuration=n,this.state=lr.Paused}return l.prototype.sendKeepAlive=function(){this.outbound.send({type:Qt.FrameTypes.KEEPALIVE,streamId:0,data:void 0,flags:Qt.Flags.RESPOND,lastReceivedPosition:0})},l.prototype.start=function(){this.state===lr.Paused&&(this.state=lr.Running,this.activeInterval=setInterval(this.sendKeepAlive.bind(this),this.keepAlivePeriodDuration))},l.prototype.pause=function(){this.state===lr.Running&&(this.state=lr.Paused,clearInterval(this.activeInterval))},l.prototype.close=function(){this.state=lr.Closed,clearInterval(this.activeInterval)},l}();Je.KeepAliveSender=ur;var er,tr,rr={};function or(){if(er)return rr;er=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(rr,"__esModule",{value:!0}),rr.FrameStore=void 0;var n=fr(),u=Ue,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 rr.FrameStore=e,rr}function ir(){if(tr)return $e;tr=1;var l=r&&r.__awaiter||function(l,n,u,e){return new(u||(u=Promise))((function(t,r){function o(l){try{a(e.next(l))}catch(l){r(l)}}function i(l){try{a(e.throw(l))}catch(l){r(l)}}function a(l){var n;l.done?t(l.value):(n=l.value,n instanceof u?n:new u((function(l){l(n)}))).then(o,i)}a((e=e.apply(l,n||[])).next())}))},n=r&&r.__generator||function(l,n){var u,e,t,r,o={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function i(r){return function(i){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:r[1],done:!1};case 5:o.label++,e=r[1],r=[0];continue;case 7:r=o.ops.pop(),o.trys.pop();continue;default:if(!(t=o.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){o=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){o.label=r[1];break}if(6===r[0]&&o.label<t[1]){o.label=t[1],t=r;break}if(t&&o.label<t[2]){o.label=t[2],o.ops.push(r);break}t[2]&&o.ops.pop(),o.trys.pop();continue}r=n.call(l,o)}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,i])}}};Object.defineProperty($e,"__esModule",{value:!0}),$e.RSocketConnector=void 0;var u=Ve(),e=De,t=Je,o=or(),i=function(){function r(l){this.config=l}return r.prototype.connect=function(){var r,i,a,s,c,d,h,f,p,y,m,g,b,v,E,w,_,S,T,R;return l(this,void 0,void 0,(function(){var O,A,C,F,I,k,P,L,N,x=this;return n(this,(function(U){switch(U.label){case 0:return O=this.config,A={type:e.FrameTypes.SETUP,dataMimeType:null!==(i=null===(r=O.setup)||void 0===r?void 0:r.dataMimeType)&&void 0!==i?i:"application/octet-stream",metadataMimeType:null!==(s=null===(a=O.setup)||void 0===a?void 0:a.metadataMimeType)&&void 0!==s?s:"application/octet-stream",keepAlive:null!==(d=null===(c=O.setup)||void 0===c?void 0:c.keepAlive)&&void 0!==d?d:6e4,lifetime:null!==(f=null===(h=O.setup)||void 0===h?void 0:h.lifetime)&&void 0!==f?f:3e5,metadata:null===(y=null===(p=O.setup)||void 0===p?void 0:p.payload)||void 0===y?void 0:y.metadata,data:null===(g=null===(m=O.setup)||void 0===m?void 0:m.payload)||void 0===g?void 0:g.data,resumeToken:null!==(v=null===(b=O.resume)||void 0===b?void 0:b.tokenGenerator())&&void 0!==v?v:null,streamId:0,majorVersion:1,minorVersion:0,flags:((null===(w=null===(E=O.setup)||void 0===E?void 0:E.payload)||void 0===w?void 0:w.metadata)?e.Flags.METADATA:e.Flags.NONE)|(O.lease?e.Flags.LEASE:e.Flags.NONE)|(O.resume?e.Flags.RESUME_ENABLE:e.Flags.NONE)},[4,O.transport.connect((function(t){return O.resume?new u.ResumableClientServerInputMultiplexerDemultiplexer(u.StreamIdGenerator.create(-1),t,t,new o.FrameStore,A.resumeToken.toString(),(function(t,r){return l(x,void 0,void 0,(function(){var l,o,i;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:A.minorVersion,minorVersion:A.majorVersion,resumeToken:A.resumeToken}),new u.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer(l,l,t)},o=-1,[4,(i=function(){return o++,O.resume.reconnectFunction(o).then((function(){return O.transport.connect(l).catch(i)}))})()];case 1:return n.sent(),[2]}}))}))})):new u.ClientServerInputMultiplexerDemultiplexer(u.StreamIdGenerator.create(-1),t,t)}))];case 1:return C=U.sent(),F=new t.KeepAliveSender(C.multiplexerDemultiplexer.connectionOutbound,A.keepAlive),I=new t.KeepAliveHandler(C,A.lifetime),k=O.lease?new t.LeaseHandler(null!==(_=O.lease.maxPendingRequests)&&void 0!==_?_:256,C.multiplexerDemultiplexer):void 0,P=null!==(S=O.responder)&&void 0!==S?S:{},L=new t.DefaultConnectionFrameHandler(C,I,F,k,P),N=new t.DefaultStreamRequestHandler(P,0),C.onClose((function(l){F.close(),I.close(),L.close(l)})),C.multiplexerDemultiplexer.connectionInbound(L),C.multiplexerDemultiplexer.handleRequestStream(N),C.multiplexerDemultiplexer.connectionOutbound.send(A),I.start(),F.start(),[2,new t.RSocketRequester(C,null!==(R=null===(T=O.fragmentation)||void 0===T?void 0:T.maxOutboundFragmentSize)&&void 0!==R?R:0,k)]}}))}))},r}();return $e.RSocketConnector=i,$e}var ar,sr={};function cr(){if(ar)return sr;ar=1;var l=r&&r.__awaiter||function(l,n,u,e){return new(u||(u=Promise))((function(t,r){function o(l){try{a(e.next(l))}catch(l){r(l)}}function i(l){try{a(e.throw(l))}catch(l){r(l)}}function a(l){var n;l.done?t(l.value):(n=l.value,n instanceof u?n:new u((function(l){l(n)}))).then(o,i)}a((e=e.apply(l,n||[])).next())}))},n=r&&r.__generator||function(l,n){var u,e,t,r,o={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return r={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function i(r){return function(i){return function(r){if(u)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:r[1],done:!1};case 5:o.label++,e=r[1],r=[0];continue;case 7:r=o.ops.pop(),o.trys.pop();continue;default:if(!(t=o.trys,(t=t.length>0&&t[t.length-1])||6!==r[0]&&2!==r[0])){o=0;continue}if(3===r[0]&&(!t||r[1]>t[0]&&r[1]<t[3])){o.label=r[1];break}if(6===r[0]&&o.label<t[1]){o.label=t[1],t=r;break}if(t&&o.label<t[2]){o.label=t[2],o.ops.push(r);break}t[2]&&o.ops.pop(),o.trys.pop();continue}r=n.call(l,o)}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,i])}}};Object.defineProperty(sr,"__esModule",{value:!0}),sr.RSocketServer=void 0;var u=Ve(),e=We,t=De,o=Je,i=or(),a=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(a){switch(a.label){case 0:return[4,this.transport.bind((function(u,i){return l(r,void 0,void 0,(function(){var l,r,a,s,c,d,h,f,p,y,m,g,b;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"),i.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,flags:t.Flags.NONE,code:l.code,message:l.message}),i.close(l),[2]):t.Flags.hasLease(u.flags)&&!this.lease?(l=new e.RSocketError(e.ErrorCodes.REJECTED_SETUP,"Lease has to be disabled"),i.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,flags:t.Flags.NONE,code:l.code,message:l.message}),i.close(l),[2]):(r=t.Flags.hasLease(u.flags)?new o.LeaseHandler(null!==(y=this.lease.maxPendingRequests)&&void 0!==y?y:256,i.multiplexerDemultiplexer):void 0,a=new o.RSocketRequester(i,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},a)]);case 2:return s=n.sent(),c=new o.KeepAliveHandler(i,u.lifetime),d=this.serverSideKeepAlive?new o.KeepAliveSender(i.multiplexerDemultiplexer.connectionOutbound,u.keepAlive):void 0,h=new o.DefaultConnectionFrameHandler(i,c,d,r,s),f=new o.DefaultStreamRequestHandler(s,0),i.onClose((function(l){null==d||d.close(),c.close(),h.close(l)})),i.multiplexerDemultiplexer.connectionInbound(h),i.multiplexerDemultiplexer.handleRequestStream(f),c.start(),null==d||d.start(),[3,4];case 3:return p=n.sent(),i.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,code:e.ErrorCodes.REJECTED_SETUP,message:null!==(b=p.message)&&void 0!==b?b:"",flags:t.Flags.NONE}),i.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:i.multiplexerDemultiplexer.connectionOutbound.send({type:t.FrameTypes.ERROR,streamId:0,code:e.ErrorCodes.UNSUPPORTED_SETUP,message:"Unsupported setup",flags:t.Flags.NONE}),i.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 o=r.sessionStore[l.resumeToken.toString()];return o?(o.resume(l,n,n),o):(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 a=new e.RSocketError(e.ErrorCodes.REJECTED_SETUP,"No resume support");return n.send({type:t.FrameTypes.ERROR,streamId:0,flags:t.Flags.NONE,code:a.code,message:a.message}),void n.close(a)}var s=new u.ResumableClientServerInputMultiplexerDemultiplexer(u.StreamIdGenerator.create(0),n,n,new i.FrameStore,l.resumeToken.toString(),r.sessionStore,r.sessionTimeout);return r.sessionStore[l.resumeToken.toString()]=s,s}return new u.ClientServerInputMultiplexerDemultiplexer(u.StreamIdGenerator.create(0),n,n)}))];case 1:return[2,a.sent()]}}))}))},r}();return sr.RSocketServer=a,sr}var dr,hr={};function fr(){return dr||(dr=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(Ue,l),u(Me,l),u(Be,l),u(We,l),u(De,l),u(ze,l),u(ir(),l),u(cr(),l),u(hr,l)}(Ne)),Ne}Object.defineProperty(hr,"__esModule",{value:!0});var pr=fr(),yr="1.31.1";const mr={highWater:10,lowWater:0};class gr extends _{options;dataQueue;isClosed;processingPromise;logger;constructor(l){if(super(),this.options=l,this.processingPromise=null,this.isClosed=!1,this.dataQueue=[],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??mr.highWater}get lowWatermark(){return this.options?.pressure?.lowWaterMark??mr.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.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})}async processQueue(){if(!this.processingPromise)return this.dataQueue.length>=this.highWatermark&&await this.iterateAsyncErrored((async l=>l.highWater?.())),this.processingPromise=this._processQueue()}map(l){const n=new gr(this.options),u=this.registerListener({data:async u=>{n.enqueueData(l(u))},closed:()=>{n.close(),u?.()}});return n}hasDataReader(){return Array.from(this.listeners.values()).some((l=>!!l.data))}async _processQueue(){if(!this.isClosed&&this.hasDataReader()){if(this.dataQueue.length){const l=this.dataQueue.shift();await this.iterateAsyncErrored((async n=>n.data?.(l)))}this.dataQueue.length<=this.lowWatermark&&await this.iterateAsyncErrored((async l=>l.lowWater?.())),this.processingPromise=null,this.dataQueue.length&&setTimeout((()=>this.processQueue()))}else Promise.resolve().then((()=>this.processingPromise=null))}async iterateAsyncErrored(l){for(let n of Array.from(this.listeners.values()))try{await l(n)}catch(l){this.logger.error(l),this.iterateListeners((n=>n.error?.(l)))}}}var br,vr={},Er=r&&r.__extends||(br=function(l,n){return br=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])},br(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}br(l,n),l.prototype=null===n?Object.create(n):(u.prototype=n.prototype,new u)});Object.defineProperty(vr,"__esModule",{value:!0});var wr=vr.WebsocketDuplexConnection=void 0,_r=fr(),Sr=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=xe.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 Er(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,_r.serializeFrame)(l);this.websocket.send(n)}},n}(_r.Deferred);wr=vr.WebsocketDuplexConnection=Sr;class Tr{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 wr(e,new pr.Deserializer,l))},o=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}`))},i=()=>{t(),u(new Error("WebSocket connection closed while opening"))};t=()=>{e.removeEventListener("open",r),e.removeEventListener("error",o),e.removeEventListener("close",i)},e.addEventListener("open",r),e.addEventListener("error",o),e.addEventListener("close",i)}))}}const Rr=/\/+$/,Or=yr,Ar=y.get("PowerSyncRemote");var Cr;!function(l){l.Buffered="buffered",l.Sequential="sequential"}(Cr||(Cr={}));class Fr{getFetch(){throw new Error("Unspecified fetch implementation")}}const Ir={socketUrlTransformer:l=>l.replace(/^https?:\/\//,(function(l){return"https://"===l?"wss://":"ws://"})),fetchImplementation:new Fr,fetchOptions:{}};class kr{connector;logger;credentials=null;options;constructor(l,n=Ar,u){this.connector=l,this.logger=n,this.options={...Ir,...u??{}}}get fetch(){const{fetchImplementation:l}=this.options;return l instanceof Fr?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(Rr))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/${Or}`}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()}async postStreaming(l,n,u={},e){const t=await this.buildRequest(l),r=await this.fetch(t.url,{method:"POST",headers:{...u,...t.headers},body:JSON.stringify(n),signal:e,cache:"no-store"}).catch((n=>{throw this.logger.error(`Caught ex when POST streaming to ${l}`,n),n}));if(401===r.status&&this.invalidateCredentials(),!r.ok){const n=await r.text();this.logger.error(`Could not POST streaming to ${l} - ${r.status} - ${r.statusText}: ${n}`);const u=new Error(`HTTP ${r.statusText}: ${n}`);throw u.status=r.status,u}return r}createSocket(l){return new WebSocket(l)}async socketStream(l){const{path:n,fetchStrategy:u=Cr.Buffered}=l,e=u==Cr.Buffered?10:1,t=await this.buildRequest(n),r=await this.getBSON(),o=this.getUserAgent(),i=this.options.socketUrlTransformer(t.url),a=new pr.RSocketConnector({transport:new Tr({url:i,wsCreator:l=>this.createSocket(l)}),setup:{keepAlive:2e4,lifetime:3e4,dataMimeType:"application/bson",metadataMimeType:"application/bson",payload:{data:null,metadata:ge.Buffer.from(r.serialize({token:t.headers.Authorization,user_agent:o}))}}});let s;try{s=await a.connect()}catch(l){throw this.logger.error("Failed to connect WebSocket",l),l}const c=new gr({logger:this.logger,pressure:{lowWaterMark:5}});let d=!1;s.onClose((()=>d=!0));let h=e;const f=c.registerListener({closed:()=>{d||(d=!0,s.close()),f()}}),p=await new Promise(((u,t)=>{let o=!1;const i=s.requestStream({data:ge.Buffer.from(r.serialize(l.data)),metadata:ge.Buffer.from(r.serialize({path:n}))},e,{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),c.close(),o||t(l)},onNext:l=>{o||(o=!0,u(i));const{data:n}=l;if(h--,!n)return;const e=r.deserialize(n);c.enqueueData(e)},onComplete:()=>{c.close()},onExtension:()=>{}})})),y=c.registerListener({lowWater:async()=>{e-h>0&&(p.request(e-h),h=e)},closed:()=>{y()}});return l.abortSignal?.aborted?c.close():l.abortSignal?.addEventListener("abort",(()=>{c.close()})),c}async postStream(l){const{data:n,path:u,headers:e,abortSignal:t}=l,r=await this.buildRequest(u),o=new AbortController;let i=!1;t?.addEventListener("abort",(()=>{i||o.abort(t.reason??new U("Cancelling network request before it resolves. Abort signal has been received."))}));const a=await this.fetch(r.url,{method:"POST",headers:{...e,...r.headers},body:JSON.stringify(n),signal:o.signal,cache:"no-store",...this.options.fetchOptions??{},...l.fetchOptions}).catch((l=>{if("AbortError"==l.name)throw new U(`Pending fetch request to ${r.url} has been aborted.`);throw l}));if(!a)throw new Error("Fetch request was aborted");if(i=!0,!a.ok||!a.body){const l=await a.text();this.logger.error(`Could not POST streaming to ${u} - ${a.status} - ${a.statusText}: ${l}`);const n=new Error(`HTTP ${a.statusText}: ${l}`);throw n.status=a.status,n}const s=a.body.getReader(),c=async()=>{try{await s.cancel()}catch(l){}s.releaseLock()};t?.addEventListener("abort",(()=>{c()}));const d=new ue({start:l=>{(async()=>{for(;!t?.aborted;)try{const{done:n,value:u}=await s.read();if(n)break;l.enqueue(u)}catch(l){this.logger.error("Caught exception when reading sync stream",l);break}t?.aborted||await c(),l.close()})()}}),h=Le(d),f=new gr({logger:this.logger}),p=h.getReader(),y=f.registerListener({lowWater:async()=>{try{const{done:l,value:n}=await p.read();if(l)return f.close(),void y?.();f.enqueueData(n)}catch(l){throw f.close(),l}},closed:()=>{c(),y?.()}});return f}}function Pr(l){return null!=l.data}function Lr(l){return null!=l.token_expires_in}function Nr(l){return null!=l.checkpoint}function xr(l){return null!=l.checkpoint_complete}function Ur(l){return null!=l.partial_checkpoint_complete}function Dr(l){return null!=l.checkpoint_diff}function Mr(l){return Array.isArray(l.buckets)&&"string"==typeof l.checkpoint_token}function Br(l){return"object"==typeof l.request_checkpoint}var qr,jr;!function(l){l.CRUD="crud",l.SYNC="sync"}(qr||(qr={})),function(l){l.HTTP="http",l.WEB_SOCKET="web-socket"}(jr||(jr={}));const Wr=1e3,zr=5e3,Qr={retryDelayMs:zr,logger:y.get("PowerSyncStream"),crudUploadThrottleMs:Wr},$r={connectionMethod:jr.WEB_SOCKET,fetchStrategy:Cr.Buffered,params:{}};class Hr extends _{_lastSyncedAt;options;abortController;crudUpdateListener;streamingSyncPromise;pendingCrudUpload;syncStatus;triggerCrudUpload;constructor(l){super(),this.options={...Qr,...l},this.syncStatus=new E({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.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:qr.CRUD,callback:async()=>{let l;for(;;){this.updateSyncStatus({dataFlow:{uploading:!0}});try{const n=await this.options.adapter.nextCrudItem();if(!n){await this.options.adapter.updateLocalTarget((()=>this.getWriteCheckpoint()));break}if(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({statusUpdated:u=>{void 0!==u.connected&&(0==u.connected&&this.logger.warn("Initial connect attempt did not successfully connect to server"),n(),l())}})}))}async disconnect(){if(this.abortController){this.abortController.signal.aborted||this.abortController.abort(new U("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 U("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 U?(this.logger.warn(l),e=!1):this.logger.error(l),this.updateSyncStatus({dataFlow:{downloadError:l}})}finally{l.aborted||(u.abort(new U("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 streamingSyncIteration(l,n){await this.obtainLock({type:qr.SYNC,signal:l,callback:async()=>{const u={...$r,...n??{}};this.logger.debug("Streaming sync iteration started"),this.options.adapter.startSession();let[e,t]=await this.collectLocalBucketState(),r=null,o=null,i=null;const a=await this.options.adapter.getClientId();if(l.aborted)return;this.logger.debug("Requesting stream from server");const s={path:"/sync/stream",abortSignal:l,data:{buckets:e,include_checksum:!0,raw_data:!0,parameters:u.params,client_id:a}};let c;for(c=u?.connectionMethod==jr.HTTP?await this.options.remote.postStream(s):await this.options.remote.socketStream({...s,fetchStrategy:u.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})),Nr(n)){r=n.checkpoint;const l=new Set(t.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]),t=u,await this.options.adapter.removeBuckets([...l]),await this.options.adapter.setTargetCheckpoint(r),await this.updateSyncStatusForStartingCheckpoint(r)}else if(xr(n)){const n=await this.applyCheckpoint(r,l);if(n.endIteration)return;n.applied&&(i=r),o=r}else if(Ur(n)){const l=n.partial_checkpoint_complete.priority;this.logger.debug("Partial checkpoint complete",l);const u=await this.options.adapter.syncLocalDatabase(r,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(Dr(n)){if(null==r)throw new Error("Checkpoint diff without previous checkpoint");const l=n.checkpoint_diff,u=new Map;for(const l of r.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);r={last_op_id:l.last_op_id,buckets:[...u.values()],write_checkpoint:l.write_checkpoint},await this.updateSyncStatusForStartingCheckpoint(r),t=new Map,u.forEach(((l,n)=>t.set(n,{name:l.bucket,priority:l.priority??3})));const e=l.removed_buckets;e.length>0&&this.logger.debug("Remove buckets",e),await this.options.adapter.removeBuckets(e),await this.options.adapter.setTargetCheckpoint(r)}else if(Pr(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,sinceLast:Math.min(n.sinceLast+l.data.length,n.targetCount-n.atLast)})}this.updateSyncStatus({dataFlow:{downloading:!0,downloadProgress:e}}),await this.options.adapter.saveSyncData({buckets:[B.fromRow(l)]})}else if(Lr(n)){const l=n.token_expires_in;if(0==l)return this.logger.debug("Token expiring; reconnect"),this.options.remote.invalidateCredentials(),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"),r===i)this.updateSyncStatus({connected:!0,lastSyncedAt:new Date,priorityStatusEntries:[],dataFlow:{downloadError:void 0}});else if(o===r){const n=await this.applyCheckpoint(r,l);if(n.endIteration)return;n.applied&&(i=r)}}this.logger.debug("Stream input empty")}})}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,o=l?.sinceLast??0;u[t.bucket]={priority:t.priority??3,atLast:r,sinceLast:o,targetCount:t.count??0},null!=t.count&&t.count<r+o&&(e=!0)}if(e)for(const l in u){const n=u[l];n.atLast=0,n.sinceLast=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 E({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 Vr=/(^ps_data__|^ps_data_local__)/,Jr={clearLocal:!0},Yr={disconnect:!0},Gr=30,Xr={retryDelayMs:5e3,logger:y.get("PowerSyncDatabase"),crudUploadThrottleMs:Wr},Kr=100,Zr=12e4,lo=l=>"object"==typeof l&&O(l.database);class no extends _{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(C(n))this._database=n;else if(A(n))this._database=n.openDB();else{if(!lo(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 E({}),this.options={...Xr,...l},this._schema=u,this.ready=!1,this.sdkVersion="",this.runExclusiveMutex=new t,this.connectionManager=new R({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 E({...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==b?n=l:u.push({priority:e,hasSynced:!0,lastSyncedAt:l})}const e=null!=n,t=new E({...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??zr,crudUploadThrottleMs:l?.crudUploadThrottleMs??this.options.crudUploadThrottleMs??Wr}}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=Jr){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 E({}),this.iterateListeners((l=>l.statusChanged?.(this.currentStatus)))}async close(l=Yr){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 w(l?.count??0,l?.size??0)}{const l=(await n.execute(`SELECT count(*) as count FROM ${I.CRUD}`)).rows.item(0);return new w(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=>N.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 L(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=>N.fromRow(l)))}else e=[N.fromRow(n)];const t=e[e.length-1];return new x(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(),T(no.transactionMutex,(()=>l(this.database)))}async writeLock(l){return await this.waitForReady(),T(no.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");F((async u=>{try{const o=await this.resolveTables(l,n,e),i=await this.executeReadOnly(l,n);t(i),this.onChangeWithCallback({onChange:async()=>{try{const u=await this.executeReadOnly(l,n);t(u)}catch(l){r?.(l)}},onError:r},{...e??{},tables:o,signal:u})}catch(l){r?.(l)}}),this,e)}watchWithAsyncGenerator(l,n,u){return new h((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(Vr,""))}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}`]))),o=new Set,i=t.throttleMs??30,a=new S((async l=>{await u(l)})),s=function(l,n){let u=null;const e=()=>{l(),u=null};return function(){null==u&&(u=setTimeout(e,n))}}((()=>this.handleTableChanges(o,r,(l=>{t?.signal?.aborted||a.schedule({changedTables:l})}))),i),c=this.database.registerListener({tablesUpdated:async l=>{try{this.processTableUpdates(l,o),s()}catch(l){e?.(l)}}});return t.signal?.addEventListener("abort",(()=>{a.dispose(),c()})),()=>c()}onChangeWithAsyncGenerator(l){const n=l??{};return new h((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 uo{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 eo(l,n,u,e){const{onResult:t,onError:r=l=>{}}=u??{};if(!t)throw new Error("onResult is required");F((async u=>{try{const o=n.compile(),i=await l.resolveTables(o.sql,o.parameters,e),a=await n.execute();t(a),l.onChangeWithCallback({onChange:async()=>{try{const l=await n.execute();t(l)}catch(l){r(l)}},onError:r},{...e??{},tables:i,signal:u})}catch(l){r(l)}}),l,e)}const to="9223372036854775807",ro=1e3;class oo extends _{db;mutex;logger;tableNames;pendingBucketDeletes;_hasCompletedSync;updateListener;_clientId;compactCounter=ro;constructor(l,n,u=y.get("SqliteBucketStorage")){super(),this.db=l,this.mutex=n,this.logger=u,this._hasCompletedSync=!1,this.pendingBucketDeletes=!0,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 to}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){await this.writeTransaction((async n=>{let u=0;for(const e of l.buckets){const l=await n.execute("INSERT INTO powersync_operations(op, data) VALUES(?, ?)",["save",JSON.stringify({buckets:[e.toJSON()]})]);this.logger.debug("saveSyncData",JSON.stringify(l)),u+=e.data.length}this.compactCounter+=u}))}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"),this.pendingBucketDeletes=!0}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=>io(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)?(await this.forceCompact(),{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)io(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=>io(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 forceCompact(){this.compactCounter=ro,this.pendingBucketDeletes=!0,await this.autoCompact()}async autoCompact(){await this.deletePendingBuckets(),await this.clearRemoveOps()}async deletePendingBuckets(){!1!==this.pendingBucketDeletes&&(await this.writeTransaction((async l=>{await l.execute("INSERT INTO powersync_operations(op, data) VALUES (?, ?)",["delete_pending_buckets",""])})),this.pendingBucketDeletes=!1)}async clearRemoveOps(){this.compactCounter<ro||(await this.writeTransaction((async l=>{await l.execute("INSERT INTO powersync_operations(op, data) VALUES (?, ?)",["clear_remove_ops",""])})),this.compactCounter=0)}async updateLocalTarget(l){if(!(await this.db.getAll("SELECT target_op FROM ps_buckets WHERE name = '$local' AND target_op = CAST(? as INTEGER)",[to])).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 o=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(o)]),!0}))}async nextCrudItem(){const l=await this.db.getOptional("SELECT * FROM ps_crud ORDER BY id ASC LIMIT 1");if(l)return N.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(N.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){}}function io(l,n){return null!=n.priority&&n.priority<=l}class ao{buckets;static fromJSON(l){return new ao(l.buckets.map((l=>B.fromRow(l))))}constructor(l){this.buckets=l}}var so;!function(l){l.TEXT="TEXT",l.INTEGER="INTEGER",l.REAL="REAL"}(so||(so={}));const co={type:so.TEXT},ho={type:so.INTEGER},fo={type:so.REAL},po=1999,yo={text:co,integer:ho,real:fo};class mo{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 go={ascending:!0};class bo{options;static createAscending(l){return new bo({name:l,ascending:!0})}constructor(l){this.options={...go,...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??so.TEXT}}}const vo={columns:[]};class Eo{options;static createAscending(l,n){return new Eo({...l,columns:n.map((l=>bo.createAscending(l)))})}constructor(l){this.options=l,this.options={...vo,...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 wo{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 _o={indexes:[],insertOnly:!1,localOnly:!1,trackPrevious:!1,trackMetadata:!1,ignoreEmptyUpdates:!1},So=/["'%,.#\s[\]]/;class To{options;_mappedColumns;static createLocalOnly(l){return new To({...l,localOnly:!0,insertOnly:!1})}static createInsertOnly(l){return new To({...l,localOnly:!1,insertOnly:!0})}static createTable(l,n){return new To({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 To({...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 mo({name:l,type:n.type}))),e=Object.entries(n?.indexes??{}).map((([l,n])=>new Eo({name:l,columns:n.map((l=>new bo({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??=_o.insertOnly,this.options.localOnly??=_o.localOnly,this.options.trackPrevious??=_o.trackPrevious,this.options.trackMetadata??=_o.trackMetadata,this.options.ignoreEmptyUpdates??=_o.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??so.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!So.test(this.name)&&(null==this.viewNameOverride||!So.test(this.viewNameOverride))}validate(){if(So.test(this.name))throw new Error(`Invalid characters in table name: ${this.name}`);if(this.viewNameOverride&&So.test(this.viewNameOverride))throw new Error(`Invalid characters in view name: ${this.viewNameOverride}`);if(this.columns.length>po)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(So.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(So.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 Ro extends To{}const Oo=y,Ao={TRACE:Oo.TRACE,DEBUG:Oo.DEBUG,INFO:Oo.INFO,TIME:Oo.TIME,WARN:Oo.WARN,ERROR:Oo.ERROR,OFF:Oo.OFF};function Co(){return y}function Fo(l,n={}){const u=y.get(l);return n.logLevel&&u.setLevel(n.logLevel),u}const Io=(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}};export{U as AbortOperation,no as AbstractPowerSyncDatabase,uo as AbstractPowerSyncDatabaseOpenFactory,kr as AbstractRemote,Hr as AbstractStreamingSyncImplementation,_ as BaseObserver,mo as Column,so as ColumnType,R as ConnectionManager,L as CrudBatch,N as CrudEntry,x as CrudTransaction,Kr as DEFAULT_CRUD_BATCH_LIMIT,Wr as DEFAULT_CRUD_UPLOAD_THROTTLE_MS,go as DEFAULT_INDEX_COLUMN_OPTIONS,vo as DEFAULT_INDEX_OPTIONS,Zr as DEFAULT_LOCK_TIMEOUT_MS,Yr as DEFAULT_POWERSYNC_CLOSE_OPTIONS,Xr as DEFAULT_POWERSYNC_DB_OPTIONS,mr as DEFAULT_PRESSURE_LIMITS,Ar as DEFAULT_REMOTE_LOGGER,Ir as DEFAULT_REMOTE_OPTIONS,zr as DEFAULT_RETRY_DELAY_MS,Qr as DEFAULT_STREAMING_SYNC_OPTIONS,$r as DEFAULT_STREAM_CONNECTION_OPTIONS,_o as DEFAULT_TABLE_OPTIONS,Gr as DEFAULT_WATCH_THROTTLE_MS,gr as DataStream,Fr as FetchImplementationProvider,Cr as FetchStrategy,Eo as Index,bo as IndexedColumn,So as InvalidSQLCharacters,qr as LockType,Ao as LogLevel,po as MAX_AMOUNT_OF_COLUMNS,to as MAX_OP_ID,D as OpType,P as OpTypeEnum,M as OplogEntry,I as PSInternalTable,p as RowUpdateType,wo as Schema,oo as SqliteBucketStorage,ao as SyncDataBatch,B as SyncDataBucket,v as SyncProgress,E as SyncStatus,jr as SyncStreamConnectionMethod,To as Table,Ro as TableV2,k as UpdateType,w as UploadQueueStats,yo as column,eo as compilableQueryWatch,Co as createBaseLogger,Fo as createLogger,g as extractTableUpdates,m as isBatchedUpdateNotification,Mr as isContinueCheckpointRequest,C as isDBAdapter,lo as isPowerSyncDatabaseOptionsWithSettings,A as isSQLOpenFactory,O as isSQLOpenOptions,Lr as isStreamingKeepalive,Nr as isStreamingSyncCheckpoint,xr as isStreamingSyncCheckpointComplete,Dr as isStreamingSyncCheckpointDiff,Ur as isStreamingSyncCheckpointPartiallyComplete,Pr as isStreamingSyncData,Br as isSyncNewCheckpointRequest,Io as parseQuery,F as runOnSchemaChange};