@weavy/uikit-react 18.0.1 → 18.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/changelog.md +7 -0
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/types/client/WeavyClient.d.ts +4 -2
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/types/client/WeavyClient.d.ts +4 -2
- package/dist/index.d.ts +3 -1
- package/package.json +1 -1
- package/src/client/WeavyClient.ts +235 -180
package/dist/esm/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import*as React from"react";import React__default,{createContext,useState,Children,useRef,useCallback,useEffect,useContext,useLayoutEffect,forwardRef,useImperativeHandle,useMemo,useReducer,Fragment}from"react";import*as ReactDOM from"react-dom";import ReactDOM__default from"react-dom";import{jsx}from"react/jsx-runtime";class HttpError extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class TimeoutError extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class AbortError extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class UnsupportedTransportError extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=n}}class DisabledTransportError extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=n}}class FailedToStartTransportError extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=n}}class FailedToNegotiateWithServerError extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class AggregateErrors extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.innerErrors=t,this.__proto__=n}}class HttpResponse{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class HttpClient{get(e,t){return this.send({...t,method:"GET",url:e})}post(e,t){return this.send({...t,method:"POST",url:e})}delete(e,t){return this.send({...t,method:"DELETE",url:e})}getCookieString(e){return""}}var LogLevel;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"}(LogLevel||(LogLevel={}));class NullLogger{constructor(){}log(e,t){}}NullLogger.instance=new NullLogger;const VERSION="7.0.10";class Arg{static isRequired(e,t){if(null==e)throw new Error(`The '${t}' argument is required.`)}static isNotEmpty(e,t){if(!e||e.match(/^\s*$/))throw new Error(`The '${t}' argument should not be empty.`)}static isIn(e,t,n){if(!(e in t))throw new Error(`Unknown ${n} value: ${e}.`)}}class Platform{static get isBrowser(){return"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isReactNative(){return"object"==typeof window&&void 0===window.document}static get isNode(){return!this.isBrowser&&!this.isWebWorker&&!this.isReactNative}}function getDataDetail(e,t){let n="";return isArrayBuffer(e)?(n=`Binary data of length ${e.byteLength}`,t&&(n+=`. Content: '${formatArrayBuffer(e)}'`)):"string"==typeof e&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function formatArrayBuffer(e){const t=new Uint8Array(e);let n="";return t.forEach((e=>{n+=`0x${e<16?"0":""}${e.toString(16)} `})),n.substr(0,n.length-1)}function isArrayBuffer(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function sendMessage(e,t,n,i,r,s){const a={},[o,l]=getUserAgentHeader();a[o]=l,e.log(LogLevel.Trace,`(${t} transport) sending data. ${getDataDetail(r,s.logMessageContent)}.`);const c=isArrayBuffer(r)?"arraybuffer":"text",d=await n.post(i,{content:r,headers:{...a,...s.headers},responseType:c,timeout:s.timeout,withCredentials:s.withCredentials});e.log(LogLevel.Trace,`(${t} transport) request complete. Response status: ${d.statusCode}.`)}function createLogger(e){return void 0===e?new ConsoleLogger(LogLevel.Information):null===e?NullLogger.instance:void 0!==e.log?e:new ConsoleLogger(e)}class SubjectSubscription{constructor(e,t){this._subject=e,this._observer=t}dispose(){const e=this._subject.observers.indexOf(this._observer);e>-1&&this._subject.observers.splice(e,1),0===this._subject.observers.length&&this._subject.cancelCallback&&this._subject.cancelCallback().catch((e=>{}))}}class ConsoleLogger{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${LogLevel[e]}: ${t}`;switch(e){case LogLevel.Critical:case LogLevel.Error:this.out.error(n);break;case LogLevel.Warning:this.out.warn(n);break;case LogLevel.Information:this.out.info(n);break;default:this.out.log(n)}}}}function getUserAgentHeader(){let e="X-SignalR-User-Agent";return Platform.isNode&&(e="User-Agent"),[e,constructUserAgent(VERSION,getOsName(),getRuntime(),getRuntimeVersion())]}function constructUserAgent(e,t,n,i){let r="Microsoft SignalR/";const s=e.split(".");return r+=`${s[0]}.${s[1]}`,r+=` (${e}; `,r+=t&&""!==t?`${t}; `:"Unknown OS; ",r+=`${n}`,r+=i?`; ${i}`:"; Unknown Runtime Version",r+=")",r}function getOsName(){if(!Platform.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function getRuntimeVersion(){if(Platform.isNode)return process.versions.node}function getRuntime(){return Platform.isNode?"NodeJS":"Browser"}function getErrorString(e){return e.stack?e.stack:e.message?e.message:`${e}`}function getGlobalThis(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("could not find global")}class FetchHttpClient extends HttpClient{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e="function"==typeof __webpack_require__?__non_webpack_require__:require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar)}else this._fetchType=fetch.bind(getGlobalThis());if("undefined"==typeof AbortController){const e="function"==typeof __webpack_require__?__non_webpack_require__:require;this._abortControllerType=e("abort-controller")}else this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new AbortError;if(!e.method)throw new Error("No method defined.");if(!e.url)throw new Error("No url defined.");const t=new this._abortControllerType;let n;e.abortSignal&&(e.abortSignal.onabort=()=>{t.abort(),n=new AbortError});let i,r=null;if(e.timeout){const i=e.timeout;r=setTimeout((()=>{t.abort(),this._logger.log(LogLevel.Warning,"Timeout from HTTP request."),n=new TimeoutError}),i)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},isArrayBuffer(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");try{i=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...e.headers},method:e.method,mode:"cors",redirect:"follow",signal:t.signal})}catch(e){if(n)throw n;throw this._logger.log(LogLevel.Warning,`Error from HTTP request. ${e}.`),e}finally{r&&clearTimeout(r),e.abortSignal&&(e.abortSignal.onabort=null)}if(!i.ok){const e=await deserializeContent(i,"text");throw new HttpError(e||i.statusText,i.status)}const s=deserializeContent(i,e.responseType),a=await s;return new HttpResponse(i.status,i.statusText,a)}getCookieString(e){let t="";return Platform.isNode&&this._jar&&this._jar.getCookies(e,((e,n)=>t=n.join("; "))),t}}function deserializeContent(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":default:n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`)}return n}class XhrHttpClient extends HttpClient{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new AbortError):e.method?e.url?new Promise(((t,n)=>{const i=new XMLHttpRequest;i.open(e.method,e.url,!0),i.withCredentials=void 0===e.withCredentials||e.withCredentials,i.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===e.content&&(e.content=void 0),e.content&&(isArrayBuffer(e.content)?i.setRequestHeader("Content-Type","application/octet-stream"):i.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const r=e.headers;r&&Object.keys(r).forEach((e=>{i.setRequestHeader(e,r[e])})),e.responseType&&(i.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{i.abort(),n(new AbortError)}),e.timeout&&(i.timeout=e.timeout),i.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),i.status>=200&&i.status<300?t(new HttpResponse(i.status,i.statusText,i.response||i.responseText)):n(new HttpError(i.response||i.responseText||i.statusText,i.status))},i.onerror=()=>{this._logger.log(LogLevel.Warning,`Error from HTTP request. ${i.status}: ${i.statusText}.`),n(new HttpError(i.statusText,i.status))},i.ontimeout=()=>{this._logger.log(LogLevel.Warning,"Timeout from HTTP request."),n(new TimeoutError)},i.send(e.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class DefaultHttpClient extends HttpClient{constructor(e){if(super(),"undefined"!=typeof fetch||Platform.isNode)this._httpClient=new FetchHttpClient(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new XhrHttpClient(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new AbortError):e.method?e.url?this._httpClient.send(e):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(e){return this._httpClient.getCookieString(e)}}class TextMessageFormat{static write(e){return`${e}${TextMessageFormat.RecordSeparator}`}static parse(e){if(e[e.length-1]!==TextMessageFormat.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(TextMessageFormat.RecordSeparator);return t.pop(),t}}TextMessageFormat.RecordSeparatorCode=30,TextMessageFormat.RecordSeparator=String.fromCharCode(TextMessageFormat.RecordSeparatorCode);class HandshakeProtocol{writeHandshakeRequest(e){return TextMessageFormat.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(isArrayBuffer(e)){const i=new Uint8Array(e),r=i.indexOf(TextMessageFormat.RecordSeparatorCode);if(-1===r)throw new Error("Message is incomplete.");const s=r+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(i.slice(0,s))),n=i.byteLength>s?i.slice(s).buffer:null}else{const i=e,r=i.indexOf(TextMessageFormat.RecordSeparator);if(-1===r)throw new Error("Message is incomplete.");const s=r+1;t=i.substring(0,s),n=i.length>s?i.substring(s):null}const i=TextMessageFormat.parse(t),r=JSON.parse(i[0]);if(r.type)throw new Error("Expected a handshake response from the server.");return[n,r]}}var MessageType;!function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close"}(MessageType||(MessageType={}));class Subject{constructor(){this.observers=[]}next(e){for(const t of this.observers)t.next(e)}error(e){for(const t of this.observers)t.error&&t.error(e)}complete(){for(const e of this.observers)e.complete&&e.complete()}subscribe(e){return this.observers.push(e),new SubjectSubscription(this,e)}}const DEFAULT_TIMEOUT_IN_MS=3e4,DEFAULT_PING_INTERVAL_IN_MS=15e3;var HubConnectionState;!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(HubConnectionState||(HubConnectionState={}));class HubConnection{constructor(e,t,n,i){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(LogLevel.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://docs.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},Arg.isRequired(e,"connection"),Arg.isRequired(t,"logger"),Arg.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=DEFAULT_TIMEOUT_IN_MS,this.keepAliveIntervalInMilliseconds=DEFAULT_PING_INTERVAL_IN_MS,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=i,this._handshakeProtocol=new HandshakeProtocol,this.connection.onreceive=e=>this._processIncomingData(e),this.connection.onclose=e=>this._connectionClosed(e),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=HubConnectionState.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:MessageType.Ping})}static create(e,t,n,i){return new HubConnection(e,t,n,i)}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(e){if(this._connectionState!==HubConnectionState.Disconnected&&this._connectionState!==HubConnectionState.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!e)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=e}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==HubConnectionState.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=HubConnectionState.Connecting,this._logger.log(LogLevel.Debug,"Starting HubConnection.");try{await this._startInternal(),Platform.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=HubConnectionState.Connected,this._connectionStarted=!0,this._logger.log(LogLevel.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=HubConnectionState.Disconnected,this._logger.log(LogLevel.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise(((e,t)=>{this._handshakeResolver=e,this._handshakeRejecter=t}));await this.connection.start(this._protocol.transferFormat);try{const t={protocol:this._protocol.name,version:this._protocol.version};if(this._logger.log(LogLevel.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(LogLevel.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError;this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(e){throw this._logger.log(LogLevel.Debug,`Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(e),e}}async stop(){const e=this._startPromise;this._stopPromise=this._stopInternal(),await this._stopPromise;try{await e}catch(e){}}_stopInternal(e){return this._connectionState===HubConnectionState.Disconnected?(this._logger.log(LogLevel.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===HubConnectionState.Disconnecting?(this._logger.log(LogLevel.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=HubConnectionState.Disconnecting,this._logger.log(LogLevel.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(LogLevel.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new AbortError("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,i]=this._replaceStreamingParams(t),r=this._createStreamInvocation(e,t,i);let s;const a=new Subject;return a.cancelCallback=()=>{const e=this._createCancelInvocation(r.invocationId);return delete this._callbacks[r.invocationId],s.then((()=>this._sendWithProtocol(e)))},this._callbacks[r.invocationId]=(e,t)=>{t?a.error(t):e&&(e.type===MessageType.Completion?e.error?a.error(new Error(e.error)):a.complete():a.next(e.item))},s=this._sendWithProtocol(r).catch((e=>{a.error(e),delete this._callbacks[r.invocationId]})),this._launchStreams(n,s),a}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return this._sendMessage(this._protocol.writeMessage(e))}send(e,...t){const[n,i]=this._replaceStreamingParams(t),r=this._sendWithProtocol(this._createInvocation(e,t,!0,i));return this._launchStreams(n,r),r}invoke(e,...t){const[n,i]=this._replaceStreamingParams(t),r=this._createInvocation(e,t,!1,i);return new Promise(((e,t)=>{this._callbacks[r.invocationId]=(n,i)=>{i?t(i):n&&(n.type===MessageType.Completion?n.error?t(new Error(n.error)):e(n.result):t(new Error(`Unexpected message type: ${n.type}`)))};const i=this._sendWithProtocol(r).catch((e=>{t(e),delete this._callbacks[r.invocationId]}));this._launchStreams(n,i)}))}on(e,t){e&&t&&(e=e.toLowerCase(),this._methods[e]||(this._methods[e]=[]),-1===this._methods[e].indexOf(t)&&this._methods[e].push(t))}off(e,t){if(!e)return;e=e.toLowerCase();const n=this._methods[e];if(n)if(t){const i=n.indexOf(t);-1!==i&&(n.splice(i,1),0===n.length&&delete this._methods[e])}else delete this._methods[e]}onclose(e){e&&this._closedCallbacks.push(e)}onreconnecting(e){e&&this._reconnectingCallbacks.push(e)}onreconnected(e){e&&this._reconnectedCallbacks.push(e)}_processIncomingData(e){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(e=this._processHandshakeResponse(e),this._receivedHandshakeResponse=!0),e){const t=this._protocol.parseMessages(e,this._logger);for(const e of t)switch(e.type){case MessageType.Invocation:this._invokeClientMethod(e);break;case MessageType.StreamItem:case MessageType.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===MessageType.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(LogLevel.Error,`Stream callback threw error: ${getErrorString(e)}`)}}break}case MessageType.Ping:break;case MessageType.Close:{this._logger.log(LogLevel.Information,"Close message received from server.");const t=e.error?new Error("Server returned an error on close: "+e.error):void 0;!0===e.allowReconnect?this.connection.stop(t):this._stopPromise=this._stopInternal(t);break}default:this._logger.log(LogLevel.Warning,`Invalid message type: ${e.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let t,n;try{[n,t]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(e){const t="Error parsing handshake response: "+e;this._logger.log(LogLevel.Error,t);const n=new Error(t);throw this._handshakeRejecter(n),n}if(t.error){const e="Server returned handshake error: "+t.error;this._logger.log(LogLevel.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(LogLevel.Debug,"Server handshake complete."),this._handshakeResolver(),n}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this._timeoutHandle=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this._pingServerHandle))){let e=this._nextKeepAlive-(new Date).getTime();e<0&&(e=0),this._pingServerHandle=setTimeout((async()=>{if(this._connectionState===HubConnectionState.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}),e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(e){const t=e.target.toLowerCase(),n=this._methods[t];if(!n)return this._logger.log(LogLevel.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(LogLevel.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null))));const i=n.slice(),r=!!e.invocationId;let s,a,o;for(const n of i)try{const i=s;s=await n.apply(this,e.arguments),r&&s&&i&&(this._logger.log(LogLevel.Error,`Multiple results provided for '${t}'. Sending error to server.`),o=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),a=void 0}catch(e){a=e,this._logger.log(LogLevel.Error,`A callback for the method '${t}' threw error '${e}'.`)}o?await this._sendWithProtocol(o):r?(a?o=this._createCompletionMessage(e.invocationId,`${a}`,null):void 0!==s?o=this._createCompletionMessage(e.invocationId,null,s):(this._logger.log(LogLevel.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),o=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(o)):s&&this._logger.log(LogLevel.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(LogLevel.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new AbortError("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(e||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===HubConnectionState.Disconnecting?this._completeClose(e):this._connectionState===HubConnectionState.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===HubConnectionState.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=HubConnectionState.Disconnected,this._connectionStarted=!1,Platform.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(LogLevel.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let n=0,i=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),r=this._getNextRetryDelay(n++,0,i);if(null===r)return this._logger.log(LogLevel.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=HubConnectionState.Reconnecting,e?this._logger.log(LogLevel.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(LogLevel.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(LogLevel.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==HubConnectionState.Reconnecting)return void this._logger.log(LogLevel.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this._logger.log(LogLevel.Information,`Reconnect attempt number ${n} will start in ${r} ms.`),await new Promise((e=>{this._reconnectDelayHandle=setTimeout(e,r)})),this._reconnectDelayHandle=void 0,this._connectionState!==HubConnectionState.Reconnecting)return void this._logger.log(LogLevel.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=HubConnectionState.Connected,this._logger.log(LogLevel.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(LogLevel.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(LogLevel.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==HubConnectionState.Reconnecting)return this._logger.log(LogLevel.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===HubConnectionState.Disconnecting&&this._completeClose());i=e instanceof Error?e:new Error(e.toString()),r=this._getNextRetryDelay(n++,Date.now()-t,i)}}this._logger.log(LogLevel.Information,`Reconnect retries have been exhausted after ${Date.now()-t} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(e,t,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:t,previousRetryCount:e,retryReason:n})}catch(n){return this._logger.log(LogLevel.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{const i=t[n];try{i(null,e)}catch(t){this._logger.log(LogLevel.Error,`Stream 'error' callback called with '${e}' threw error: ${getErrorString(t)}`)}}))}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,t,n,i){if(n)return 0!==i.length?{arguments:t,streamIds:i,target:e,type:MessageType.Invocation}:{arguments:t,target:e,type:MessageType.Invocation};{const n=this._invocationId;return this._invocationId++,0!==i.length?{arguments:t,invocationId:n.toString(),streamIds:i,target:e,type:MessageType.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:MessageType.Invocation}}}_launchStreams(e,t){if(0!==e.length){t||(t=Promise.resolve());for(const n in e)e[n].subscribe({complete:()=>{t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n))))},error:e=>{let i;i=e instanceof Error?e.message:e&&e.toString?e.toString():"Unknown error",t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n,i))))},next:e=>{t=t.then((()=>this._sendWithProtocol(this._createStreamItemMessage(n,e))))}})}}_replaceStreamingParams(e){const t=[],n=[];for(let i=0;i<e.length;i++){const r=e[i];if(this._isObservable(r)){const s=this._invocationId;this._invocationId++,t[s]=r,n.push(s.toString()),e.splice(i,1)}}return[t,n]}_isObservable(e){return e&&e.subscribe&&"function"==typeof e.subscribe}_createStreamInvocation(e,t,n){const i=this._invocationId;return this._invocationId++,0!==n.length?{arguments:t,invocationId:i.toString(),streamIds:n,target:e,type:MessageType.StreamInvocation}:{arguments:t,invocationId:i.toString(),target:e,type:MessageType.StreamInvocation}}_createCancelInvocation(e){return{invocationId:e,type:MessageType.CancelInvocation}}_createStreamItemMessage(e,t){return{invocationId:e,item:t,type:MessageType.StreamItem}}_createCompletionMessage(e,t,n){return t?{error:t,invocationId:e,type:MessageType.Completion}:{invocationId:e,result:n,type:MessageType.Completion}}}const DEFAULT_RETRY_DELAYS_IN_MILLISECONDS=[0,2e3,1e4,3e4,null];class DefaultReconnectPolicy{constructor(e){this._retryDelays=void 0!==e?[...e,null]:DEFAULT_RETRY_DELAYS_IN_MILLISECONDS}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class HeaderNames{}HeaderNames.Authorization="Authorization",HeaderNames.Cookie="Cookie";class AccessTokenHttpClient extends HttpClient{constructor(e,t){super(),this._innerClient=e,this._accessTokenFactory=t}async send(e){let t=!0;this._accessTokenFactory&&(!this._accessToken||e.url&&e.url.indexOf("/negotiate?")>0)&&(t=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(e);const n=await this._innerClient.send(e);return t&&401===n.statusCode&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(e),await this._innerClient.send(e)):n}_setAuthorizationHeader(e){e.headers||(e.headers={}),this._accessToken?e.headers[HeaderNames.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[HeaderNames.Authorization]&&delete e.headers[HeaderNames.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}var HttpTransportType,TransferFormat;!function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(HttpTransportType||(HttpTransportType={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(TransferFormat||(TransferFormat={}));let AbortController$1=class{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}};class LongPollingTransport{constructor(e,t,n){this._httpClient=e,this._logger=t,this._pollAbort=new AbortController$1,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Arg.isRequired(e,"url"),Arg.isRequired(t,"transferFormat"),Arg.isIn(t,TransferFormat,"transferFormat"),this._url=e,this._logger.log(LogLevel.Trace,"(LongPolling transport) Connecting."),t===TransferFormat.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,i]=getUserAgentHeader(),r={[n]:i,...this._options.headers},s={abortSignal:this._pollAbort.signal,headers:r,timeout:1e5,withCredentials:this._options.withCredentials};t===TransferFormat.Binary&&(s.responseType="arraybuffer");const a=`${e}&_=${Date.now()}`;this._logger.log(LogLevel.Trace,`(LongPolling transport) polling: ${a}.`);const o=await this._httpClient.get(a,s);200!==o.statusCode?(this._logger.log(LogLevel.Error,`(LongPolling transport) Unexpected response code: ${o.statusCode}.`),this._closeError=new HttpError(o.statusText||"",o.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,s)}async _poll(e,t){try{for(;this._running;)try{const n=`${e}&_=${Date.now()}`;this._logger.log(LogLevel.Trace,`(LongPolling transport) polling: ${n}.`);const i=await this._httpClient.get(n,t);204===i.statusCode?(this._logger.log(LogLevel.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==i.statusCode?(this._logger.log(LogLevel.Error,`(LongPolling transport) Unexpected response code: ${i.statusCode}.`),this._closeError=new HttpError(i.statusText||"",i.statusCode),this._running=!1):i.content?(this._logger.log(LogLevel.Trace,`(LongPolling transport) data received. ${getDataDetail(i.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(i.content)):this._logger.log(LogLevel.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof TimeoutError?this._logger.log(LogLevel.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(LogLevel.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(LogLevel.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?sendMessage(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(LogLevel.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(LogLevel.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=getUserAgentHeader();e[t]=n;const i={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};await this._httpClient.delete(this._url,i),this._logger.log(LogLevel.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(LogLevel.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(LogLevel.Trace,e),this.onclose(this._closeError)}}}class ServerSentEventsTransport{constructor(e,t,n,i){this._httpClient=e,this._accessToken=t,this._logger=n,this._options=i,this.onreceive=null,this.onclose=null}async connect(e,t){return Arg.isRequired(e,"url"),Arg.isRequired(t,"transferFormat"),Arg.isIn(t,TransferFormat,"transferFormat"),this._logger.log(LogLevel.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((n,i)=>{let r,s=!1;if(t===TransferFormat.Text){if(Platform.isBrowser||Platform.isWebWorker)r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[i,s]=getUserAgentHeader();n[i]=s,r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:{...n,...this._options.headers}})}try{r.onmessage=e=>{if(this.onreceive)try{this._logger.log(LogLevel.Trace,`(SSE transport) data received. ${getDataDetail(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},r.onerror=e=>{s?this._close():i(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this._logger.log(LogLevel.Information,`SSE connected to ${this._url}`),this._eventSource=r,s=!0,n()}}catch(e){return void i(e)}}else i(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(e){return this._eventSource?sendMessage(this._logger,"SSE",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(e){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(e))}}class WebSocketTransport{constructor(e,t,n,i,r,s){this._logger=n,this._accessTokenFactory=t,this._logMessageContent=i,this._webSocketConstructor=r,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=s}async connect(e,t){let n;return Arg.isRequired(e,"url"),Arg.isRequired(t,"transferFormat"),Arg.isIn(t,TransferFormat,"transferFormat"),this._logger.log(LogLevel.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise(((i,r)=>{let s;e=e.replace(/^http/,"ws");const a=this._httpClient.getCookieString(e);let o=!1;if(Platform.isNode||Platform.isReactNative){const t={},[i,r]=getUserAgentHeader();t[i]=r,n&&(t[HeaderNames.Authorization]=`Bearer ${n}`),a&&(t[HeaderNames.Cookie]=a),s=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else n&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);s||(s=new this._webSocketConstructor(e)),t===TransferFormat.Binary&&(s.binaryType="arraybuffer"),s.onopen=t=>{this._logger.log(LogLevel.Information,`WebSocket connected to ${e}.`),this._webSocket=s,o=!0,i()},s.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(LogLevel.Information,`(WebSockets transport) ${t}.`)},s.onmessage=e=>{if(this._logger.log(LogLevel.Trace,`(WebSockets transport) data received. ${getDataDetail(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},s.onclose=e=>{if(o)this._close(e);else{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(t))}}}))}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(LogLevel.Trace,`(WebSockets transport) sending data. ${getDataDetail(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(LogLevel.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this._isCloseEvent(e)||!1!==e.wasClean&&1e3===e.code?e instanceof Error?this.onclose(e):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)))}_isCloseEvent(e){return e&&"boolean"==typeof e.wasClean&&"number"==typeof e.code}}const MAX_REDIRECTS=100;class HttpConnection{constructor(e,t={}){if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Arg.isRequired(e,"url"),this._logger=createLogger(t.logger),this.baseUrl=this._resolveUrl(e),(t=t||{}).logMessageContent=void 0!==t.logMessageContent&&t.logMessageContent,"boolean"!=typeof t.withCredentials&&void 0!==t.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");t.withCredentials=void 0===t.withCredentials||t.withCredentials,t.timeout=void 0===t.timeout?1e5:t.timeout;let n=null,i=null;if(Platform.isNode&&"undefined"!=typeof require){const e="function"==typeof __webpack_require__?__non_webpack_require__:require;n=e("ws"),i=e("eventsource")}Platform.isNode||"undefined"==typeof WebSocket||t.WebSocket?Platform.isNode&&!t.WebSocket&&n&&(t.WebSocket=n):t.WebSocket=WebSocket,Platform.isNode||"undefined"==typeof EventSource||t.EventSource?Platform.isNode&&!t.EventSource&&void 0!==i&&(t.EventSource=i):t.EventSource=EventSource,this._httpClient=new AccessTokenHttpClient(t.httpClient||new DefaultHttpClient(this._logger),t.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||TransferFormat.Binary,Arg.isIn(e,TransferFormat,"transferFormat"),this._logger.log(LogLevel.Debug,`Starting connection with transfer format '${TransferFormat[e]}'.`),"Disconnected"!==this._connectionState)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(e),await this._startInternalPromise,"Disconnecting"===this._connectionState){const e="Failed to start the HttpConnection before stop() was called.";return this._logger.log(LogLevel.Error,e),await this._stopPromise,Promise.reject(new AbortError(e))}if("Connected"!==this._connectionState){const e="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(LogLevel.Error,e),Promise.reject(new AbortError(e))}this._connectionStarted=!0}send(e){return"Connected"!==this._connectionState?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new TransportSendQueue(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(LogLevel.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(LogLevel.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState="Disconnecting",this._stopPromise=new Promise((e=>{this._stopPromiseResolver=e})),await this._stopInternal(e),void await this._stopPromise)}async _stopInternal(e){this._stopError=e;try{await this._startInternalPromise}catch(e){}if(this.transport){try{await this.transport.stop()}catch(e){this._logger.log(LogLevel.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(LogLevel.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==HttpTransportType.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(HttpTransportType.WebSockets),await this._startTransport(t,e)}else{let n=null,i=0;do{if(n=await this._getNegotiationResponse(t),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new AbortError("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(n.url&&(t=n.url),n.accessToken){const e=n.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}i++}while(n.url&&i<MAX_REDIRECTS);if(i===MAX_REDIRECTS&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(t,this._options.transport,n,e)}this.transport instanceof LongPollingTransport&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(LogLevel.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(LogLevel.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={},[n,i]=getUserAgentHeader();t[n]=i;const r=this._resolveNegotiateUrl(e);this._logger.log(LogLevel.Debug,`Sending negotiation request: ${r}.`);try{const e=await this._httpClient.post(r,{content:"",headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(200!==e.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${e.statusCode}'`));const n=JSON.parse(e.content);return(!n.negotiateVersion||n.negotiateVersion<1)&&(n.connectionToken=n.connectionId),n}catch(e){let t="Failed to complete negotiation with the server: "+e;return e instanceof HttpError&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(LogLevel.Error,t),Promise.reject(new FailedToNegotiateWithServerError(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,t,n,i){let r=this._createConnectUrl(e,n.connectionToken);if(this._isITransport(t))return this._logger.log(LogLevel.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=t,await this._startTransport(r,i),void(this.connectionId=n.connectionId);const s=[],a=n.availableTransports||[];let o=n;for(const n of a){const a=this._resolveTransportOrError(n,t,i);if(a instanceof Error)s.push(`${n.transport} failed:`),s.push(a);else if(this._isITransport(a)){if(this.transport=a,!o){try{o=await this._getNegotiationResponse(e)}catch(e){return Promise.reject(e)}r=this._createConnectUrl(e,o.connectionToken)}try{return await this._startTransport(r,i),void(this.connectionId=o.connectionId)}catch(e){if(this._logger.log(LogLevel.Error,`Failed to start the transport '${n.transport}': ${e}`),o=void 0,s.push(new FailedToStartTransportError(`${n.transport} failed: ${e}`,HttpTransportType[n.transport])),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(LogLevel.Debug,e),Promise.reject(new AbortError(e))}}}}return s.length>0?Promise.reject(new AggregateErrors(`Unable to connect to the server with any of the available transports. ${s.join(" ")}`,s)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case HttpTransportType.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new WebSocketTransport(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case HttpTransportType.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new ServerSentEventsTransport(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case HttpTransportType.LongPolling:return new LongPollingTransport(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,t){return this.transport.onreceive=this.onreceive,this.transport.onclose=e=>this._stopConnection(e),this.transport.connect(e,t)}_resolveTransportOrError(e,t,n){const i=HttpTransportType[e.transport];if(null==i)return this._logger.log(LogLevel.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(!transportMatches(t,i))return this._logger.log(LogLevel.Debug,`Skipping transport '${HttpTransportType[i]}' because it was disabled by the client.`),new DisabledTransportError(`'${HttpTransportType[i]}' is disabled by the client.`,i);if(!(e.transferFormats.map((e=>TransferFormat[e])).indexOf(n)>=0))return this._logger.log(LogLevel.Debug,`Skipping transport '${HttpTransportType[i]}' because it does not support the requested transfer format '${TransferFormat[n]}'.`),new Error(`'${HttpTransportType[i]}' does not support ${TransferFormat[n]}.`);if(i===HttpTransportType.WebSockets&&!this._options.WebSocket||i===HttpTransportType.ServerSentEvents&&!this._options.EventSource)return this._logger.log(LogLevel.Debug,`Skipping transport '${HttpTransportType[i]}' because it is not supported in your environment.'`),new UnsupportedTransportError(`'${HttpTransportType[i]}' is not supported in your environment.`,i);this._logger.log(LogLevel.Debug,`Selecting transport '${HttpTransportType[i]}'.`);try{return this._constructTransport(i)}catch(e){return e}}_isITransport(e){return e&&"object"==typeof e&&"connect"in e}_stopConnection(e){if(this._logger.log(LogLevel.Debug,`HttpConnection.stopConnection(${e}) called while in state ${this._connectionState}.`),this.transport=void 0,e=this._stopError||e,this._stopError=void 0,"Disconnected"!==this._connectionState){if("Connecting"===this._connectionState)throw this._logger.log(LogLevel.Warning,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${e}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this._connectionState&&this._stopPromiseResolver(),e?this._logger.log(LogLevel.Error,`Connection disconnected with error '${e}'.`):this._logger.log(LogLevel.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(LogLevel.Error,`TransportSendQueue.stop() threw error '${e}'.`)})),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(e)}catch(t){this._logger.log(LogLevel.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(LogLevel.Debug,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is already in the disconnected state.`)}_resolveUrl(e){if(0===e.lastIndexOf("https://",0)||0===e.lastIndexOf("http://",0))return e;if(!Platform.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(LogLevel.Information,`Normalizing '${e}' to '${t.href}'.`),t.href}_resolveNegotiateUrl(e){const t=e.indexOf("?");let n=e.substring(0,-1===t?e.length:t);return"/"!==n[n.length-1]&&(n+="/"),n+="negotiate",n+=-1===t?"":e.substring(t),-1===n.indexOf("negotiateVersion")&&(n+=-1===t?"?":"&",n+="negotiateVersion="+this._negotiateVersion),n}}function transportMatches(e,t){return!e||0!=(t&e)}class TransportSendQueue{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new PromiseSource,this._transportResult=new PromiseSource,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new PromiseSource),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(e){if(this._buffer.length&&typeof this._buffer[0]!=typeof e)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof e}`);this._buffer.push(e),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new PromiseSource;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):TransportSendQueue._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(t),e.resolve()}catch(t){e.reject(t)}}}static _concatBuffers(e){const t=e.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),n=new Uint8Array(t);let i=0;for(const t of e)n.set(new Uint8Array(t),i),i+=t.byteLength;return n.buffer}}class PromiseSource{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}const JSON_HUB_PROTOCOL_NAME="json";class JsonHubProtocol{constructor(){this.name=JSON_HUB_PROTOCOL_NAME,this.version=1,this.transferFormat=TransferFormat.Text}parseMessages(e,t){if("string"!=typeof e)throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!e)return[];null===t&&(t=NullLogger.instance);const n=TextMessageFormat.parse(e),i=[];for(const e of n){const n=JSON.parse(e);if("number"!=typeof n.type)throw new Error("Invalid payload.");switch(n.type){case MessageType.Invocation:this._isInvocationMessage(n);break;case MessageType.StreamItem:this._isStreamItemMessage(n);break;case MessageType.Completion:this._isCompletionMessage(n);break;case MessageType.Ping:case MessageType.Close:break;default:t.log(LogLevel.Information,"Unknown message type '"+n.type+"' ignored.");continue}i.push(n)}return i}writeMessage(e){return TextMessageFormat.write(JSON.stringify(e))}_isInvocationMessage(e){this._assertNotEmptyString(e.target,"Invalid payload for Invocation message."),void 0!==e.invocationId&&this._assertNotEmptyString(e.invocationId,"Invalid payload for Invocation message.")}_isStreamItemMessage(e){if(this._assertNotEmptyString(e.invocationId,"Invalid payload for StreamItem message."),void 0===e.item)throw new Error("Invalid payload for StreamItem message.")}_isCompletionMessage(e){if(e.result&&e.error)throw new Error("Invalid payload for Completion message.");!e.result&&e.error&&this._assertNotEmptyString(e.error,"Invalid payload for Completion message."),this._assertNotEmptyString(e.invocationId,"Invalid payload for Completion message.")}_assertNotEmptyString(e,t){if("string"!=typeof e||""===e)throw new Error(t)}}const LogLevelNameMapping={trace:LogLevel.Trace,debug:LogLevel.Debug,info:LogLevel.Information,information:LogLevel.Information,warn:LogLevel.Warning,warning:LogLevel.Warning,error:LogLevel.Error,critical:LogLevel.Critical,none:LogLevel.None};function parseLogLevel(e){const t=LogLevelNameMapping[e.toLowerCase()];if(void 0!==t)return t;throw new Error(`Unknown log level: ${e}`)}class HubConnectionBuilder{configureLogging(e){if(Arg.isRequired(e,"logging"),isLogger(e))this.logger=e;else if("string"==typeof e){const t=parseLogLevel(e);this.logger=new ConsoleLogger(t)}else this.logger=new ConsoleLogger(e);return this}withUrl(e,t){return Arg.isRequired(e,"url"),Arg.isNotEmpty(e,"url"),this.url=e,this.httpConnectionOptions="object"==typeof t?{...this.httpConnectionOptions,...t}:{...this.httpConnectionOptions,transport:t},this}withHubProtocol(e){return Arg.isRequired(e,"protocol"),this.protocol=e,this}withAutomaticReconnect(e){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return e?Array.isArray(e)?this.reconnectPolicy=new DefaultReconnectPolicy(e):this.reconnectPolicy=e:this.reconnectPolicy=new DefaultReconnectPolicy,this}build(){const e=this.httpConnectionOptions||{};if(void 0===e.logger&&(e.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const t=new HttpConnection(this.url,e);return HubConnection.create(t,this.logger||NullLogger.instance,this.protocol||new JsonHubProtocol,this.reconnectPolicy)}}function isLogger(e){return void 0!==e.log}class WeavyClient{constructor(e){this.groups=[],this.connectionEvents=[],this.token="",this.EVENT_NAMESPACE=".connection",this.EVENT_CLOSE="close",this.EVENT_RECONNECTING="reconnecting",this.EVENT_RECONNECTED="reconnected",this.url=e.url,this.tokenFactory=e.tokenFactory,this.tokenPromise=null,this.connection=(new HubConnectionBuilder).configureLogging(LogLevel.None).withUrl(this.url+"/hubs/rtm",{accessTokenFactory:()=>this.tokenFactoryInternal.call(this,!0,!0)}).withAutomaticReconnect().build(),this.isConnectionStarted=this.connection.start(),this.connection.onclose((e=>this.triggerHandler(this.EVENT_CLOSE,e))),this.connection.onreconnecting((e=>this.triggerHandler(this.EVENT_RECONNECTING,e))),this.connection.onreconnected((e=>this.triggerHandler(this.EVENT_RECONNECTED,e)))}async get(e,t=!0){const n=await fetch(this.url+e,{headers:{"content-type":"application/json",Authorization:"Bearer "+await this.tokenFactoryInternal()}});if(!n.ok){if((401===n.status||403===n.status)&&t)return await this.tokenFactoryInternal(!0),await this.get(e,!1);console.error(`Error calling endpoint ${e}`,n)}return n}async post(e,t,n,i="application/json",r=!0){let s={Authorization:"Bearer "+await this.tokenFactoryInternal()};""!==i&&(s["content-type"]=i);const a=await fetch(this.url+e,{method:t,body:n,headers:s});return a.ok||401!==a.status&&403!==a.status||!r?a:(await this.tokenFactoryInternal(!0),await this.post(e,t,n,i,!1))}async upload(e,t,n,i="application/json",r,s=!0){const a=this,o=await a.tokenFactoryInternal();return await new Promise((function(l,c){let d=new XMLHttpRequest;d.open(t,a.url+e,!0),d.setRequestHeader("Authorization","Bearer "+o),""!==i&&d.setRequestHeader("content-type",i),r&&d.upload.addEventListener("progress",(e=>{r(e.loaded/e.total*100||100)})),d.onload=o=>{!s||401!==d.status&&401!==d.status?l(new Response(d.response,{status:d.status,statusText:d.statusText})):a.tokenFactoryInternal(!0).then((()=>a.upload(e,t,n,i,r,!1))).then(l).catch(c)},d.onerror=c,d.send(n)}))}async getToken(e){return this.token&&!e||(this.token=await this.tokenFactory(!0)),this.token}async tokenFactoryInternal(e=!1,t=!1){if(this.token&&!e)return this.token;if(this.tokenPromise)return this.tokenPromise;{this.tokenPromise=this.tokenFactory(e);let t=await this.tokenPromise;return this.tokenPromise=null,this.token=t,this.token}}async subscribe(e,t,n){await this.isConnectionStarted;try{var i=e?e+":"+t:t;await this.connection.invoke("Subscribe",i),this.groups.push(i),this.connection.on(i,n)}catch(e){console.warn("Error in Subscribe:",e)}}async unsubscribe(e,t,n){await this.isConnectionStarted;var i=e?e+":"+t:t;const r=this.groups.findIndex((e=>e===i));if(-1!==r){this.groups=this.groups.splice(r,1);try{this.groups.find((e=>e===i))||await this.connection.invoke("Unsubscribe",i)}catch(e){console.warn("Error in Unsubscribe:",e)}}this.connection.off(i,n)}destroy(){this.connection.stop()}triggerHandler(e,...t){e=e.endsWith(this.EVENT_NAMESPACE)?e:e+this.EVENT_NAMESPACE;let n=new CustomEvent(e,{cancelable:!1});if(console.debug("triggerHandler",e),this.connectionEvents.forEach((i=>{i.name===e&&i.handler(n,...t)})),e===this.EVENT_RECONNECTED+this.EVENT_NAMESPACE)for(var i=0;i<this.groups.length;i++)this.connection.invoke("Subscribe",this.groups[i])}}function _setPrototypeOf(e,t){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},_setPrototypeOf(e,t)}function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,_setPrototypeOf(e,t)}var Subscribable=function(){function e(){this.listeners=[]}var t=e.prototype;return t.subscribe=function(e){var t=this,n=e||function(){};return this.listeners.push(n),this.onSubscribe(),function(){t.listeners=t.listeners.filter((function(e){return e!==n})),t.onUnsubscribe()}},t.hasListeners=function(){return this.listeners.length>0},t.onSubscribe=function(){},t.onUnsubscribe=function(){},e}();function _extends$1(){return _extends$1=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},_extends$1.apply(this,arguments)}var isServer="undefined"==typeof window;function noop$1(){}function functionalUpdate(e,t){return"function"==typeof e?e(t):e}function isValidTimeout(e){return"number"==typeof e&&e>=0&&e!==1/0}function ensureQueryKeyArray(e){return Array.isArray(e)?e:[e]}function timeUntilStale(e,t){return Math.max(e+(t||0)-Date.now(),0)}function parseQueryArgs(e,t,n){return isQueryKey(e)?"function"==typeof t?_extends$1({},n,{queryKey:e,queryFn:t}):_extends$1({},t,{queryKey:e}):e}function parseMutationArgs(e,t,n){return isQueryKey(e)?"function"==typeof t?_extends$1({},n,{mutationKey:e,mutationFn:t}):_extends$1({},t,{mutationKey:e}):"function"==typeof e?_extends$1({},t,{mutationFn:e}):_extends$1({},e)}function parseFilterArgs(e,t,n){return isQueryKey(e)?[_extends$1({},t,{queryKey:e}),n]:[e||{},t]}function mapQueryStatusFilter(e,t){return!0===e&&!0===t||null==e&&null==t?"all":!1===e&&!1===t?"none":(null!=e?e:!t)?"active":"inactive"}function matchQuery(e,t){var n=e.active,i=e.exact,r=e.fetching,s=e.inactive,a=e.predicate,o=e.queryKey,l=e.stale;if(isQueryKey(o))if(i){if(t.queryHash!==hashQueryKeyByOptions(o,t.options))return!1}else if(!partialMatchKey(t.queryKey,o))return!1;var c=mapQueryStatusFilter(n,s);if("none"===c)return!1;if("all"!==c){var d=t.isActive();if("active"===c&&!d)return!1;if("inactive"===c&&d)return!1}return("boolean"!=typeof l||t.isStale()===l)&&(("boolean"!=typeof r||t.isFetching()===r)&&!(a&&!a(t)))}function matchMutation(e,t){var n=e.exact,i=e.fetching,r=e.predicate,s=e.mutationKey;if(isQueryKey(s)){if(!t.options.mutationKey)return!1;if(n){if(hashQueryKey(t.options.mutationKey)!==hashQueryKey(s))return!1}else if(!partialMatchKey(t.options.mutationKey,s))return!1}return("boolean"!=typeof i||"loading"===t.state.status===i)&&!(r&&!r(t))}function hashQueryKeyByOptions(e,t){return((null==t?void 0:t.queryKeyHashFn)||hashQueryKey)(e)}function hashQueryKey(e){return stableValueHash(ensureQueryKeyArray(e))}function stableValueHash(e){return JSON.stringify(e,(function(e,t){return isPlainObject$1(t)?Object.keys(t).sort().reduce((function(e,n){return e[n]=t[n],e}),{}):t}))}function partialMatchKey(e,t){return partialDeepEqual(ensureQueryKeyArray(e),ensureQueryKeyArray(t))}function partialDeepEqual(e,t){return e===t||typeof e==typeof t&&(!(!e||!t||"object"!=typeof e||"object"!=typeof t)&&!Object.keys(t).some((function(n){return!partialDeepEqual(e[n],t[n])})))}function replaceEqualDeep(e,t){if(e===t)return e;var n=Array.isArray(e)&&Array.isArray(t);if(n||isPlainObject$1(e)&&isPlainObject$1(t)){for(var i=n?e.length:Object.keys(e).length,r=n?t:Object.keys(t),s=r.length,a=n?[]:{},o=0,l=0;l<s;l++){var c=n?l:r[l];a[c]=replaceEqualDeep(e[c],t[c]),a[c]===e[c]&&o++}return i===s&&o===i?e:a}return t}function shallowEqualObjects(e,t){if(e&&!t||t&&!e)return!1;for(var n in e)if(e[n]!==t[n])return!1;return!0}function isPlainObject$1(e){if(!hasObjectPrototype(e))return!1;var t=e.constructor;if(void 0===t)return!0;var n=t.prototype;return!!hasObjectPrototype(n)&&!!n.hasOwnProperty("isPrototypeOf")}function hasObjectPrototype(e){return"[object Object]"===Object.prototype.toString.call(e)}function isQueryKey(e){return"string"==typeof e||Array.isArray(e)}function sleep(e){return new Promise((function(t){setTimeout(t,e)}))}function scheduleMicrotask(e){Promise.resolve().then(e).catch((function(e){return setTimeout((function(){throw e}))}))}function getAbortController(){if("function"==typeof AbortController)return new AbortController}var FocusManager=function(e){function t(){var t;return(t=e.call(this)||this).setup=function(e){var t;if(!isServer&&(null==(t=window)?void 0:t.addEventListener)){var n=function(){return e()};return window.addEventListener("visibilitychange",n,!1),window.addEventListener("focus",n,!1),function(){window.removeEventListener("visibilitychange",n),window.removeEventListener("focus",n)}}},t}_inheritsLoose(t,e);var n=t.prototype;return n.onSubscribe=function(){this.cleanup||this.setEventListener(this.setup)},n.onUnsubscribe=function(){var e;this.hasListeners()||(null==(e=this.cleanup)||e.call(this),this.cleanup=void 0)},n.setEventListener=function(e){var t,n=this;this.setup=e,null==(t=this.cleanup)||t.call(this),this.cleanup=e((function(e){"boolean"==typeof e?n.setFocused(e):n.onFocus()}))},n.setFocused=function(e){this.focused=e,e&&this.onFocus()},n.onFocus=function(){this.listeners.forEach((function(e){e()}))},n.isFocused=function(){return"boolean"==typeof this.focused?this.focused:"undefined"==typeof document||[void 0,"visible","prerender"].includes(document.visibilityState)},t}(Subscribable),focusManager$1=new FocusManager,OnlineManager=function(e){function t(){var t;return(t=e.call(this)||this).setup=function(e){var t;if(!isServer&&(null==(t=window)?void 0:t.addEventListener)){var n=function(){return e()};return window.addEventListener("online",n,!1),window.addEventListener("offline",n,!1),function(){window.removeEventListener("online",n),window.removeEventListener("offline",n)}}},t}_inheritsLoose(t,e);var n=t.prototype;return n.onSubscribe=function(){this.cleanup||this.setEventListener(this.setup)},n.onUnsubscribe=function(){var e;this.hasListeners()||(null==(e=this.cleanup)||e.call(this),this.cleanup=void 0)},n.setEventListener=function(e){var t,n=this;this.setup=e,null==(t=this.cleanup)||t.call(this),this.cleanup=e((function(e){"boolean"==typeof e?n.setOnline(e):n.onOnline()}))},n.setOnline=function(e){this.online=e,e&&this.onOnline()},n.onOnline=function(){this.listeners.forEach((function(e){e()}))},n.isOnline=function(){return"boolean"==typeof this.online?this.online:"undefined"==typeof navigator||void 0===navigator.onLine||navigator.onLine},t}(Subscribable),onlineManager=new OnlineManager;function defaultRetryDelay(e){return Math.min(1e3*Math.pow(2,e),3e4)}function isCancelable(e){return"function"==typeof(null==e?void 0:e.cancel)}var CancelledError=function(e){this.revert=null==e?void 0:e.revert,this.silent=null==e?void 0:e.silent};function isCancelledError(e){return e instanceof CancelledError}var Retryer=function(e){var t,n,i,r,s=this,a=!1;this.abort=e.abort,this.cancel=function(e){return null==t?void 0:t(e)},this.cancelRetry=function(){a=!0},this.continueRetry=function(){a=!1},this.continue=function(){return null==n?void 0:n()},this.failureCount=0,this.isPaused=!1,this.isResolved=!1,this.isTransportCancelable=!1,this.promise=new Promise((function(e,t){i=e,r=t}));var o=function(t){s.isResolved||(s.isResolved=!0,null==e.onSuccess||e.onSuccess(t),null==n||n(),i(t))},l=function(t){s.isResolved||(s.isResolved=!0,null==e.onError||e.onError(t),null==n||n(),r(t))};!function i(){if(!s.isResolved){var r;try{r=e.fn()}catch(e){r=Promise.reject(e)}t=function(e){if(!s.isResolved&&(l(new CancelledError(e)),null==s.abort||s.abort(),isCancelable(r)))try{r.cancel()}catch(e){}},s.isTransportCancelable=isCancelable(r),Promise.resolve(r).then(o).catch((function(t){var r,o;if(!s.isResolved){var c=null!=(r=e.retry)?r:3,d=null!=(o=e.retryDelay)?o:defaultRetryDelay,u="function"==typeof d?d(s.failureCount,t):d,h=!0===c||"number"==typeof c&&s.failureCount<c||"function"==typeof c&&c(s.failureCount,t);!a&&h?(s.failureCount++,null==e.onFail||e.onFail(s.failureCount,t),sleep(u).then((function(){if(!focusManager$1.isFocused()||!onlineManager.isOnline())return new Promise((function(t){n=t,s.isPaused=!0,null==e.onPause||e.onPause()})).then((function(){n=void 0,s.isPaused=!1,null==e.onContinue||e.onContinue()}))})).then((function(){a?l(t):i()}))):l(t)}}))}}()},NotifyManager=function(){function e(){this.queue=[],this.transactions=0,this.notifyFn=function(e){e()},this.batchNotifyFn=function(e){e()}}var t=e.prototype;return t.batch=function(e){var t;this.transactions++;try{t=e()}finally{this.transactions--,this.transactions||this.flush()}return t},t.schedule=function(e){var t=this;this.transactions?this.queue.push(e):scheduleMicrotask((function(){t.notifyFn(e)}))},t.batchCalls=function(e){var t=this;return function(){for(var n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];t.schedule((function(){e.apply(void 0,i)}))}},t.flush=function(){var e=this,t=this.queue;this.queue=[],t.length&&scheduleMicrotask((function(){e.batchNotifyFn((function(){t.forEach((function(t){e.notifyFn(t)}))}))}))},t.setNotifyFunction=function(e){this.notifyFn=e},t.setBatchNotifyFunction=function(e){this.batchNotifyFn=e},e}(),notifyManager=new NotifyManager,logger$1=console;function getLogger(){return logger$1}function setLogger(e){logger$1=e}var Query=function(){function e(e){this.abortSignalConsumed=!1,this.hadObservers=!1,this.defaultOptions=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.cache=e.cache,this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.initialState=e.state||this.getDefaultState(this.options),this.state=this.initialState,this.meta=e.meta,this.scheduleGc()}var t=e.prototype;return t.setOptions=function(e){var t;this.options=_extends$1({},this.defaultOptions,e),this.meta=null==e?void 0:e.meta,this.cacheTime=Math.max(this.cacheTime||0,null!=(t=this.options.cacheTime)?t:3e5)},t.setDefaultOptions=function(e){this.defaultOptions=e},t.scheduleGc=function(){var e=this;this.clearGcTimeout(),isValidTimeout(this.cacheTime)&&(this.gcTimeout=setTimeout((function(){e.optionalRemove()}),this.cacheTime))},t.clearGcTimeout=function(){this.gcTimeout&&(clearTimeout(this.gcTimeout),this.gcTimeout=void 0)},t.optionalRemove=function(){this.observers.length||(this.state.isFetching?this.hadObservers&&this.scheduleGc():this.cache.remove(this))},t.setData=function(e,t){var n,i,r=this.state.data,s=functionalUpdate(e,r);return(null==(n=(i=this.options).isDataEqual)?void 0:n.call(i,r,s))?s=r:!1!==this.options.structuralSharing&&(s=replaceEqualDeep(r,s)),this.dispatch({data:s,type:"success",dataUpdatedAt:null==t?void 0:t.updatedAt}),s},t.setState=function(e,t){this.dispatch({type:"setState",state:e,setStateOptions:t})},t.cancel=function(e){var t,n=this.promise;return null==(t=this.retryer)||t.cancel(e),n?n.then(noop$1).catch(noop$1):Promise.resolve()},t.destroy=function(){this.clearGcTimeout(),this.cancel({silent:!0})},t.reset=function(){this.destroy(),this.setState(this.initialState)},t.isActive=function(){return this.observers.some((function(e){return!1!==e.options.enabled}))},t.isFetching=function(){return this.state.isFetching},t.isStale=function(){return this.state.isInvalidated||!this.state.dataUpdatedAt||this.observers.some((function(e){return e.getCurrentResult().isStale}))},t.isStaleByTime=function(e){return void 0===e&&(e=0),this.state.isInvalidated||!this.state.dataUpdatedAt||!timeUntilStale(this.state.dataUpdatedAt,e)},t.onFocus=function(){var e,t=this.observers.find((function(e){return e.shouldFetchOnWindowFocus()}));t&&t.refetch(),null==(e=this.retryer)||e.continue()},t.onOnline=function(){var e,t=this.observers.find((function(e){return e.shouldFetchOnReconnect()}));t&&t.refetch(),null==(e=this.retryer)||e.continue()},t.addObserver=function(e){-1===this.observers.indexOf(e)&&(this.observers.push(e),this.hadObservers=!0,this.clearGcTimeout(),this.cache.notify({type:"observerAdded",query:this,observer:e}))},t.removeObserver=function(e){-1!==this.observers.indexOf(e)&&(this.observers=this.observers.filter((function(t){return t!==e})),this.observers.length||(this.retryer&&(this.retryer.isTransportCancelable||this.abortSignalConsumed?this.retryer.cancel({revert:!0}):this.retryer.cancelRetry()),this.cacheTime?this.scheduleGc():this.cache.remove(this)),this.cache.notify({type:"observerRemoved",query:this,observer:e}))},t.getObserversCount=function(){return this.observers.length},t.invalidate=function(){this.state.isInvalidated||this.dispatch({type:"invalidate"})},t.fetch=function(e,t){var n,i,r,s=this;if(this.state.isFetching)if(this.state.dataUpdatedAt&&(null==t?void 0:t.cancelRefetch))this.cancel({silent:!0});else if(this.promise){var a;return null==(a=this.retryer)||a.continueRetry(),this.promise}if(e&&this.setOptions(e),!this.options.queryFn){var o=this.observers.find((function(e){return e.options.queryFn}));o&&this.setOptions(o.options)}var l=ensureQueryKeyArray(this.queryKey),c=getAbortController(),d={queryKey:l,pageParam:void 0,meta:this.meta};Object.defineProperty(d,"signal",{enumerable:!0,get:function(){if(c)return s.abortSignalConsumed=!0,c.signal}});var u,h,p={fetchOptions:t,options:this.options,queryKey:l,state:this.state,fetchFn:function(){return s.options.queryFn?(s.abortSignalConsumed=!1,s.options.queryFn(d)):Promise.reject("Missing queryFn")},meta:this.meta};(null==(n=this.options.behavior)?void 0:n.onFetch)&&(null==(u=this.options.behavior)||u.onFetch(p));(this.revertState=this.state,this.state.isFetching&&this.state.fetchMeta===(null==(i=p.fetchOptions)?void 0:i.meta))||this.dispatch({type:"fetch",meta:null==(h=p.fetchOptions)?void 0:h.meta});return this.retryer=new Retryer({fn:p.fetchFn,abort:null==c||null==(r=c.abort)?void 0:r.bind(c),onSuccess:function(e){s.setData(e),null==s.cache.config.onSuccess||s.cache.config.onSuccess(e,s),0===s.cacheTime&&s.optionalRemove()},onError:function(e){isCancelledError(e)&&e.silent||s.dispatch({type:"error",error:e}),isCancelledError(e)||(null==s.cache.config.onError||s.cache.config.onError(e,s),getLogger().error(e)),0===s.cacheTime&&s.optionalRemove()},onFail:function(){s.dispatch({type:"failed"})},onPause:function(){s.dispatch({type:"pause"})},onContinue:function(){s.dispatch({type:"continue"})},retry:p.options.retry,retryDelay:p.options.retryDelay}),this.promise=this.retryer.promise,this.promise},t.dispatch=function(e){var t=this;this.state=this.reducer(this.state,e),notifyManager.batch((function(){t.observers.forEach((function(t){t.onQueryUpdate(e)})),t.cache.notify({query:t,type:"queryUpdated",action:e})}))},t.getDefaultState=function(e){var t="function"==typeof e.initialData?e.initialData():e.initialData,n=void 0!==e.initialData?"function"==typeof e.initialDataUpdatedAt?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0,i=void 0!==t;return{data:t,dataUpdateCount:0,dataUpdatedAt:i?null!=n?n:Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchMeta:null,isFetching:!1,isInvalidated:!1,isPaused:!1,status:i?"success":"idle"}},t.reducer=function(e,t){var n,i;switch(t.type){case"failed":return _extends$1({},e,{fetchFailureCount:e.fetchFailureCount+1});case"pause":return _extends$1({},e,{isPaused:!0});case"continue":return _extends$1({},e,{isPaused:!1});case"fetch":return _extends$1({},e,{fetchFailureCount:0,fetchMeta:null!=(n=t.meta)?n:null,isFetching:!0,isPaused:!1},!e.dataUpdatedAt&&{error:null,status:"loading"});case"success":return _extends$1({},e,{data:t.data,dataUpdateCount:e.dataUpdateCount+1,dataUpdatedAt:null!=(i=t.dataUpdatedAt)?i:Date.now(),error:null,fetchFailureCount:0,isFetching:!1,isInvalidated:!1,isPaused:!1,status:"success"});case"error":var r=t.error;return isCancelledError(r)&&r.revert&&this.revertState?_extends$1({},this.revertState):_extends$1({},e,{error:r,errorUpdateCount:e.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:e.fetchFailureCount+1,isFetching:!1,isPaused:!1,status:"error"});case"invalidate":return _extends$1({},e,{isInvalidated:!0});case"setState":return _extends$1({},e,t.state);default:return e}},e}(),QueryCache=function(e){function t(t){var n;return(n=e.call(this)||this).config=t||{},n.queries=[],n.queriesMap={},n}_inheritsLoose(t,e);var n=t.prototype;return n.build=function(e,t,n){var i,r=t.queryKey,s=null!=(i=t.queryHash)?i:hashQueryKeyByOptions(r,t),a=this.get(s);return a||(a=new Query({cache:this,queryKey:r,queryHash:s,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r),meta:t.meta}),this.add(a)),a},n.add=function(e){this.queriesMap[e.queryHash]||(this.queriesMap[e.queryHash]=e,this.queries.push(e),this.notify({type:"queryAdded",query:e}))},n.remove=function(e){var t=this.queriesMap[e.queryHash];t&&(e.destroy(),this.queries=this.queries.filter((function(t){return t!==e})),t===e&&delete this.queriesMap[e.queryHash],this.notify({type:"queryRemoved",query:e}))},n.clear=function(){var e=this;notifyManager.batch((function(){e.queries.forEach((function(t){e.remove(t)}))}))},n.get=function(e){return this.queriesMap[e]},n.getAll=function(){return this.queries},n.find=function(e,t){var n=parseFilterArgs(e,t)[0];return void 0===n.exact&&(n.exact=!0),this.queries.find((function(e){return matchQuery(n,e)}))},n.findAll=function(e,t){var n=parseFilterArgs(e,t)[0];return Object.keys(n).length>0?this.queries.filter((function(e){return matchQuery(n,e)})):this.queries},n.notify=function(e){var t=this;notifyManager.batch((function(){t.listeners.forEach((function(t){t(e)}))}))},n.onFocus=function(){var e=this;notifyManager.batch((function(){e.queries.forEach((function(e){e.onFocus()}))}))},n.onOnline=function(){var e=this;notifyManager.batch((function(){e.queries.forEach((function(e){e.onOnline()}))}))},t}(Subscribable),Mutation=function(){function e(e){this.options=_extends$1({},e.defaultOptions,e.options),this.mutationId=e.mutationId,this.mutationCache=e.mutationCache,this.observers=[],this.state=e.state||getDefaultState(),this.meta=e.meta}var t=e.prototype;return t.setState=function(e){this.dispatch({type:"setState",state:e})},t.addObserver=function(e){-1===this.observers.indexOf(e)&&this.observers.push(e)},t.removeObserver=function(e){this.observers=this.observers.filter((function(t){return t!==e}))},t.cancel=function(){return this.retryer?(this.retryer.cancel(),this.retryer.promise.then(noop$1).catch(noop$1)):Promise.resolve()},t.continue=function(){return this.retryer?(this.retryer.continue(),this.retryer.promise):this.execute()},t.execute=function(){var e,t=this,n="loading"===this.state.status,i=Promise.resolve();return n||(this.dispatch({type:"loading",variables:this.options.variables}),i=i.then((function(){null==t.mutationCache.config.onMutate||t.mutationCache.config.onMutate(t.state.variables,t)})).then((function(){return null==t.options.onMutate?void 0:t.options.onMutate(t.state.variables)})).then((function(e){e!==t.state.context&&t.dispatch({type:"loading",context:e,variables:t.state.variables})}))),i.then((function(){return t.executeMutation()})).then((function(n){e=n,null==t.mutationCache.config.onSuccess||t.mutationCache.config.onSuccess(e,t.state.variables,t.state.context,t)})).then((function(){return null==t.options.onSuccess?void 0:t.options.onSuccess(e,t.state.variables,t.state.context)})).then((function(){return null==t.options.onSettled?void 0:t.options.onSettled(e,null,t.state.variables,t.state.context)})).then((function(){return t.dispatch({type:"success",data:e}),e})).catch((function(e){return null==t.mutationCache.config.onError||t.mutationCache.config.onError(e,t.state.variables,t.state.context,t),getLogger().error(e),Promise.resolve().then((function(){return null==t.options.onError?void 0:t.options.onError(e,t.state.variables,t.state.context)})).then((function(){return null==t.options.onSettled?void 0:t.options.onSettled(void 0,e,t.state.variables,t.state.context)})).then((function(){throw t.dispatch({type:"error",error:e}),e}))}))},t.executeMutation=function(){var e,t=this;return this.retryer=new Retryer({fn:function(){return t.options.mutationFn?t.options.mutationFn(t.state.variables):Promise.reject("No mutationFn found")},onFail:function(){t.dispatch({type:"failed"})},onPause:function(){t.dispatch({type:"pause"})},onContinue:function(){t.dispatch({type:"continue"})},retry:null!=(e=this.options.retry)?e:0,retryDelay:this.options.retryDelay}),this.retryer.promise},t.dispatch=function(e){var t=this;this.state=reducer$1(this.state,e),notifyManager.batch((function(){t.observers.forEach((function(t){t.onMutationUpdate(e)})),t.mutationCache.notify(t)}))},e}();function getDefaultState(){return{context:void 0,data:void 0,error:null,failureCount:0,isPaused:!1,status:"idle",variables:void 0}}function reducer$1(e,t){switch(t.type){case"failed":return _extends$1({},e,{failureCount:e.failureCount+1});case"pause":return _extends$1({},e,{isPaused:!0});case"continue":return _extends$1({},e,{isPaused:!1});case"loading":return _extends$1({},e,{context:t.context,data:void 0,error:null,isPaused:!1,status:"loading",variables:t.variables});case"success":return _extends$1({},e,{data:t.data,error:null,status:"success",isPaused:!1});case"error":return _extends$1({},e,{data:void 0,error:t.error,failureCount:e.failureCount+1,isPaused:!1,status:"error"});case"setState":return _extends$1({},e,t.state);default:return e}}var MutationCache=function(e){function t(t){var n;return(n=e.call(this)||this).config=t||{},n.mutations=[],n.mutationId=0,n}_inheritsLoose(t,e);var n=t.prototype;return n.build=function(e,t,n){var i=new Mutation({mutationCache:this,mutationId:++this.mutationId,options:e.defaultMutationOptions(t),state:n,defaultOptions:t.mutationKey?e.getMutationDefaults(t.mutationKey):void 0,meta:t.meta});return this.add(i),i},n.add=function(e){this.mutations.push(e),this.notify(e)},n.remove=function(e){this.mutations=this.mutations.filter((function(t){return t!==e})),e.cancel(),this.notify(e)},n.clear=function(){var e=this;notifyManager.batch((function(){e.mutations.forEach((function(t){e.remove(t)}))}))},n.getAll=function(){return this.mutations},n.find=function(e){return void 0===e.exact&&(e.exact=!0),this.mutations.find((function(t){return matchMutation(e,t)}))},n.findAll=function(e){return this.mutations.filter((function(t){return matchMutation(e,t)}))},n.notify=function(e){var t=this;notifyManager.batch((function(){t.listeners.forEach((function(t){t(e)}))}))},n.onFocus=function(){this.resumePausedMutations()},n.onOnline=function(){this.resumePausedMutations()},n.resumePausedMutations=function(){var e=this.mutations.filter((function(e){return e.state.isPaused}));return notifyManager.batch((function(){return e.reduce((function(e,t){return e.then((function(){return t.continue().catch(noop$1)}))}),Promise.resolve())}))},t}(Subscribable);function infiniteQueryBehavior(){return{onFetch:function(e){e.fetchFn=function(){var t,n,i,r,s,a,o,l=null==(t=e.fetchOptions)||null==(n=t.meta)?void 0:n.refetchPage,c=null==(i=e.fetchOptions)||null==(r=i.meta)?void 0:r.fetchMore,d=null==c?void 0:c.pageParam,u="forward"===(null==c?void 0:c.direction),h="backward"===(null==c?void 0:c.direction),p=(null==(s=e.state.data)?void 0:s.pages)||[],f=(null==(a=e.state.data)?void 0:a.pageParams)||[],m=getAbortController(),g=null==m?void 0:m.signal,O=f,y=!1,v=e.options.queryFn||function(){return Promise.reject("Missing queryFn")},b=function(e,t,n,i){return O=i?[t].concat(O):[].concat(O,[t]),i?[n].concat(e):[].concat(e,[n])},_=function(t,n,i,r){if(y)return Promise.reject("Cancelled");if(void 0===i&&!n&&t.length)return Promise.resolve(t);var s={queryKey:e.queryKey,signal:g,pageParam:i,meta:e.meta},a=v(s),o=Promise.resolve(a).then((function(e){return b(t,i,e,r)}));isCancelable(a)&&(o.cancel=a.cancel);return o};if(p.length)if(u){var S=void 0!==d,w=S?d:getNextPageParam(e.options,p);o=_(p,S,w)}else if(h){var x=void 0!==d,C=x?d:getPreviousPageParam(e.options,p);o=_(p,x,C,!0)}else!function(){O=[];var t=void 0===e.options.getNextPageParam,n=!l||!p[0]||l(p[0],0,p);o=n?_([],t,f[0]):Promise.resolve(b([],f[0],p[0]));for(var i=function(n){o=o.then((function(i){if(!l||!p[n]||l(p[n],n,p)){var r=t?f[n]:getNextPageParam(e.options,i);return _(i,t,r)}return Promise.resolve(b(i,f[n],p[n]))}))},r=1;r<p.length;r++)i(r)}();else o=_([]);var P=o.then((function(e){return{pages:e,pageParams:O}}));return P.cancel=function(){y=!0,null==m||m.abort(),isCancelable(o)&&o.cancel()},P}}}}function getNextPageParam(e,t){return null==e.getNextPageParam?void 0:e.getNextPageParam(t[t.length-1],t)}function getPreviousPageParam(e,t){return null==e.getPreviousPageParam?void 0:e.getPreviousPageParam(t[0],t)}function hasNextPage(e,t){if(e.getNextPageParam&&Array.isArray(t)){var n=getNextPageParam(e,t);return null!=n&&!1!==n}}function hasPreviousPage(e,t){if(e.getPreviousPageParam&&Array.isArray(t)){var n=getPreviousPageParam(e,t);return null!=n&&!1!==n}}var QueryClient=function(){function e(e){void 0===e&&(e={}),this.queryCache=e.queryCache||new QueryCache,this.mutationCache=e.mutationCache||new MutationCache,this.defaultOptions=e.defaultOptions||{},this.queryDefaults=[],this.mutationDefaults=[]}var t=e.prototype;return t.mount=function(){var e=this;this.unsubscribeFocus=focusManager$1.subscribe((function(){focusManager$1.isFocused()&&onlineManager.isOnline()&&(e.mutationCache.onFocus(),e.queryCache.onFocus())})),this.unsubscribeOnline=onlineManager.subscribe((function(){focusManager$1.isFocused()&&onlineManager.isOnline()&&(e.mutationCache.onOnline(),e.queryCache.onOnline())}))},t.unmount=function(){var e,t;null==(e=this.unsubscribeFocus)||e.call(this),null==(t=this.unsubscribeOnline)||t.call(this)},t.isFetching=function(e,t){var n=parseFilterArgs(e,t)[0];return n.fetching=!0,this.queryCache.findAll(n).length},t.isMutating=function(e){return this.mutationCache.findAll(_extends$1({},e,{fetching:!0})).length},t.getQueryData=function(e,t){var n;return null==(n=this.queryCache.find(e,t))?void 0:n.state.data},t.getQueriesData=function(e){return this.getQueryCache().findAll(e).map((function(e){return[e.queryKey,e.state.data]}))},t.setQueryData=function(e,t,n){var i=parseQueryArgs(e),r=this.defaultQueryOptions(i);return this.queryCache.build(this,r).setData(t,n)},t.setQueriesData=function(e,t,n){var i=this;return notifyManager.batch((function(){return i.getQueryCache().findAll(e).map((function(e){var r=e.queryKey;return[r,i.setQueryData(r,t,n)]}))}))},t.getQueryState=function(e,t){var n;return null==(n=this.queryCache.find(e,t))?void 0:n.state},t.removeQueries=function(e,t){var n=parseFilterArgs(e,t)[0],i=this.queryCache;notifyManager.batch((function(){i.findAll(n).forEach((function(e){i.remove(e)}))}))},t.resetQueries=function(e,t,n){var i=this,r=parseFilterArgs(e,t,n),s=r[0],a=r[1],o=this.queryCache,l=_extends$1({},s,{active:!0});return notifyManager.batch((function(){return o.findAll(s).forEach((function(e){e.reset()})),i.refetchQueries(l,a)}))},t.cancelQueries=function(e,t,n){var i=this,r=parseFilterArgs(e,t,n),s=r[0],a=r[1],o=void 0===a?{}:a;void 0===o.revert&&(o.revert=!0);var l=notifyManager.batch((function(){return i.queryCache.findAll(s).map((function(e){return e.cancel(o)}))}));return Promise.all(l).then(noop$1).catch(noop$1)},t.invalidateQueries=function(e,t,n){var i,r,s,a=this,o=parseFilterArgs(e,t,n),l=o[0],c=o[1],d=_extends$1({},l,{active:null==(i=null!=(r=l.refetchActive)?r:l.active)||i,inactive:null!=(s=l.refetchInactive)&&s});return notifyManager.batch((function(){return a.queryCache.findAll(l).forEach((function(e){e.invalidate()})),a.refetchQueries(d,c)}))},t.refetchQueries=function(e,t,n){var i=this,r=parseFilterArgs(e,t,n),s=r[0],a=r[1],o=notifyManager.batch((function(){return i.queryCache.findAll(s).map((function(e){return e.fetch(void 0,_extends$1({},a,{meta:{refetchPage:null==s?void 0:s.refetchPage}}))}))})),l=Promise.all(o).then(noop$1);return(null==a?void 0:a.throwOnError)||(l=l.catch(noop$1)),l},t.fetchQuery=function(e,t,n){var i=parseQueryArgs(e,t,n),r=this.defaultQueryOptions(i);void 0===r.retry&&(r.retry=!1);var s=this.queryCache.build(this,r);return s.isStaleByTime(r.staleTime)?s.fetch(r):Promise.resolve(s.state.data)},t.prefetchQuery=function(e,t,n){return this.fetchQuery(e,t,n).then(noop$1).catch(noop$1)},t.fetchInfiniteQuery=function(e,t,n){var i=parseQueryArgs(e,t,n);return i.behavior=infiniteQueryBehavior(),this.fetchQuery(i)},t.prefetchInfiniteQuery=function(e,t,n){return this.fetchInfiniteQuery(e,t,n).then(noop$1).catch(noop$1)},t.cancelMutations=function(){var e=this,t=notifyManager.batch((function(){return e.mutationCache.getAll().map((function(e){return e.cancel()}))}));return Promise.all(t).then(noop$1).catch(noop$1)},t.resumePausedMutations=function(){return this.getMutationCache().resumePausedMutations()},t.executeMutation=function(e){return this.mutationCache.build(this,e).execute()},t.getQueryCache=function(){return this.queryCache},t.getMutationCache=function(){return this.mutationCache},t.getDefaultOptions=function(){return this.defaultOptions},t.setDefaultOptions=function(e){this.defaultOptions=e},t.setQueryDefaults=function(e,t){var n=this.queryDefaults.find((function(t){return hashQueryKey(e)===hashQueryKey(t.queryKey)}));n?n.defaultOptions=t:this.queryDefaults.push({queryKey:e,defaultOptions:t})},t.getQueryDefaults=function(e){var t;return e?null==(t=this.queryDefaults.find((function(t){return partialMatchKey(e,t.queryKey)})))?void 0:t.defaultOptions:void 0},t.setMutationDefaults=function(e,t){var n=this.mutationDefaults.find((function(t){return hashQueryKey(e)===hashQueryKey(t.mutationKey)}));n?n.defaultOptions=t:this.mutationDefaults.push({mutationKey:e,defaultOptions:t})},t.getMutationDefaults=function(e){var t;return e?null==(t=this.mutationDefaults.find((function(t){return partialMatchKey(e,t.mutationKey)})))?void 0:t.defaultOptions:void 0},t.defaultQueryOptions=function(e){if(null==e?void 0:e._defaulted)return e;var t=_extends$1({},this.defaultOptions.queries,this.getQueryDefaults(null==e?void 0:e.queryKey),e,{_defaulted:!0});return!t.queryHash&&t.queryKey&&(t.queryHash=hashQueryKeyByOptions(t.queryKey,t)),t},t.defaultQueryObserverOptions=function(e){return this.defaultQueryOptions(e)},t.defaultMutationOptions=function(e){return(null==e?void 0:e._defaulted)?e:_extends$1({},this.defaultOptions.mutations,this.getMutationDefaults(null==e?void 0:e.mutationKey),e,{_defaulted:!0})},t.clear=function(){this.queryCache.clear(),this.mutationCache.clear()},e}(),QueryObserver=function(e){function t(t,n){var i;return(i=e.call(this)||this).client=t,i.options=n,i.trackedProps=[],i.selectError=null,i.bindMethods(),i.setOptions(n),i}_inheritsLoose(t,e);var n=t.prototype;return n.bindMethods=function(){this.remove=this.remove.bind(this),this.refetch=this.refetch.bind(this)},n.onSubscribe=function(){1===this.listeners.length&&(this.currentQuery.addObserver(this),shouldFetchOnMount(this.currentQuery,this.options)&&this.executeFetch(),this.updateTimers())},n.onUnsubscribe=function(){this.listeners.length||this.destroy()},n.shouldFetchOnReconnect=function(){return shouldFetchOn(this.currentQuery,this.options,this.options.refetchOnReconnect)},n.shouldFetchOnWindowFocus=function(){return shouldFetchOn(this.currentQuery,this.options,this.options.refetchOnWindowFocus)},n.destroy=function(){this.listeners=[],this.clearTimers(),this.currentQuery.removeObserver(this)},n.setOptions=function(e,t){var n=this.options,i=this.currentQuery;if(this.options=this.client.defaultQueryObserverOptions(e),void 0!==this.options.enabled&&"boolean"!=typeof this.options.enabled)throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=n.queryKey),this.updateQuery();var r=this.hasListeners();r&&shouldFetchOptionally(this.currentQuery,i,this.options,n)&&this.executeFetch(),this.updateResult(t),!r||this.currentQuery===i&&this.options.enabled===n.enabled&&this.options.staleTime===n.staleTime||this.updateStaleTimeout();var s=this.computeRefetchInterval();!r||this.currentQuery===i&&this.options.enabled===n.enabled&&s===this.currentRefetchInterval||this.updateRefetchInterval(s)},n.getOptimisticResult=function(e){var t=this.client.defaultQueryObserverOptions(e),n=this.client.getQueryCache().build(this.client,t);return this.createResult(n,t)},n.getCurrentResult=function(){return this.currentResult},n.trackResult=function(e,t){var n=this,i={},r=function(e){n.trackedProps.includes(e)||n.trackedProps.push(e)};return Object.keys(e).forEach((function(t){Object.defineProperty(i,t,{configurable:!1,enumerable:!0,get:function(){return r(t),e[t]}})})),(t.useErrorBoundary||t.suspense)&&r("error"),i},n.getNextResult=function(e){var t=this;return new Promise((function(n,i){var r=t.subscribe((function(t){t.isFetching||(r(),t.isError&&(null==e?void 0:e.throwOnError)?i(t.error):n(t))}))}))},n.getCurrentQuery=function(){return this.currentQuery},n.remove=function(){this.client.getQueryCache().remove(this.currentQuery)},n.refetch=function(e){return this.fetch(_extends$1({},e,{meta:{refetchPage:null==e?void 0:e.refetchPage}}))},n.fetchOptimistic=function(e){var t=this,n=this.client.defaultQueryObserverOptions(e),i=this.client.getQueryCache().build(this.client,n);return i.fetch().then((function(){return t.createResult(i,n)}))},n.fetch=function(e){var t=this;return this.executeFetch(e).then((function(){return t.updateResult(),t.currentResult}))},n.executeFetch=function(e){this.updateQuery();var t=this.currentQuery.fetch(this.options,e);return(null==e?void 0:e.throwOnError)||(t=t.catch(noop$1)),t},n.updateStaleTimeout=function(){var e=this;if(this.clearStaleTimeout(),!isServer&&!this.currentResult.isStale&&isValidTimeout(this.options.staleTime)){var t=timeUntilStale(this.currentResult.dataUpdatedAt,this.options.staleTime)+1;this.staleTimeoutId=setTimeout((function(){e.currentResult.isStale||e.updateResult()}),t)}},n.computeRefetchInterval=function(){var e;return"function"==typeof this.options.refetchInterval?this.options.refetchInterval(this.currentResult.data,this.currentQuery):null!=(e=this.options.refetchInterval)&&e},n.updateRefetchInterval=function(e){var t=this;this.clearRefetchInterval(),this.currentRefetchInterval=e,!isServer&&!1!==this.options.enabled&&isValidTimeout(this.currentRefetchInterval)&&0!==this.currentRefetchInterval&&(this.refetchIntervalId=setInterval((function(){(t.options.refetchIntervalInBackground||focusManager$1.isFocused())&&t.executeFetch()}),this.currentRefetchInterval))},n.updateTimers=function(){this.updateStaleTimeout(),this.updateRefetchInterval(this.computeRefetchInterval())},n.clearTimers=function(){this.clearStaleTimeout(),this.clearRefetchInterval()},n.clearStaleTimeout=function(){this.staleTimeoutId&&(clearTimeout(this.staleTimeoutId),this.staleTimeoutId=void 0)},n.clearRefetchInterval=function(){this.refetchIntervalId&&(clearInterval(this.refetchIntervalId),this.refetchIntervalId=void 0)},n.createResult=function(e,t){var n,i=this.currentQuery,r=this.options,s=this.currentResult,a=this.currentResultState,o=this.currentResultOptions,l=e!==i,c=l?e.state:this.currentQueryInitialState,d=l?this.currentResult:this.previousQueryResult,u=e.state,h=u.dataUpdatedAt,p=u.error,f=u.errorUpdatedAt,m=u.isFetching,g=u.status,O=!1,y=!1;if(t.optimisticResults){var v=this.hasListeners(),b=!v&&shouldFetchOnMount(e,t),_=v&&shouldFetchOptionally(e,i,t,r);(b||_)&&(m=!0,h||(g="loading"))}if(t.keepPreviousData&&!u.dataUpdateCount&&(null==d?void 0:d.isSuccess)&&"error"!==g)n=d.data,h=d.dataUpdatedAt,g=d.status,O=!0;else if(t.select&&void 0!==u.data)if(s&&u.data===(null==a?void 0:a.data)&&t.select===this.selectFn)n=this.selectResult;else try{this.selectFn=t.select,n=t.select(u.data),!1!==t.structuralSharing&&(n=replaceEqualDeep(null==s?void 0:s.data,n)),this.selectResult=n,this.selectError=null}catch(e){getLogger().error(e),this.selectError=e}else n=u.data;if(void 0!==t.placeholderData&&void 0===n&&("loading"===g||"idle"===g)){var S;if((null==s?void 0:s.isPlaceholderData)&&t.placeholderData===(null==o?void 0:o.placeholderData))S=s.data;else if(S="function"==typeof t.placeholderData?t.placeholderData():t.placeholderData,t.select&&void 0!==S)try{S=t.select(S),!1!==t.structuralSharing&&(S=replaceEqualDeep(null==s?void 0:s.data,S)),this.selectError=null}catch(e){getLogger().error(e),this.selectError=e}void 0!==S&&(g="success",n=S,y=!0)}return this.selectError&&(p=this.selectError,n=this.selectResult,f=Date.now(),g="error"),{status:g,isLoading:"loading"===g,isSuccess:"success"===g,isError:"error"===g,isIdle:"idle"===g,data:n,dataUpdatedAt:h,error:p,errorUpdatedAt:f,failureCount:u.fetchFailureCount,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>c.dataUpdateCount||u.errorUpdateCount>c.errorUpdateCount,isFetching:m,isRefetching:m&&"loading"!==g,isLoadingError:"error"===g&&0===u.dataUpdatedAt,isPlaceholderData:y,isPreviousData:O,isRefetchError:"error"===g&&0!==u.dataUpdatedAt,isStale:isStale(e,t),refetch:this.refetch,remove:this.remove}},n.shouldNotifyListeners=function(e,t){if(!t)return!0;var n=this.options,i=n.notifyOnChangeProps,r=n.notifyOnChangePropsExclusions;if(!i&&!r)return!0;if("tracked"===i&&!this.trackedProps.length)return!0;var s="tracked"===i?this.trackedProps:i;return Object.keys(e).some((function(n){var i=n,a=e[i]!==t[i],o=null==s?void 0:s.some((function(e){return e===n})),l=null==r?void 0:r.some((function(e){return e===n}));return a&&!l&&(!s||o)}))},n.updateResult=function(e){var t=this.currentResult;if(this.currentResult=this.createResult(this.currentQuery,this.options),this.currentResultState=this.currentQuery.state,this.currentResultOptions=this.options,!shallowEqualObjects(this.currentResult,t)){var n={cache:!0};!1!==(null==e?void 0:e.listeners)&&this.shouldNotifyListeners(this.currentResult,t)&&(n.listeners=!0),this.notify(_extends$1({},n,e))}},n.updateQuery=function(){var e=this.client.getQueryCache().build(this.client,this.options);if(e!==this.currentQuery){var t=this.currentQuery;this.currentQuery=e,this.currentQueryInitialState=e.state,this.previousQueryResult=this.currentResult,this.hasListeners()&&(null==t||t.removeObserver(this),e.addObserver(this))}},n.onQueryUpdate=function(e){var t={};"success"===e.type?t.onSuccess=!0:"error"!==e.type||isCancelledError(e.error)||(t.onError=!0),this.updateResult(t),this.hasListeners()&&this.updateTimers()},n.notify=function(e){var t=this;notifyManager.batch((function(){e.onSuccess?(null==t.options.onSuccess||t.options.onSuccess(t.currentResult.data),null==t.options.onSettled||t.options.onSettled(t.currentResult.data,null)):e.onError&&(null==t.options.onError||t.options.onError(t.currentResult.error),null==t.options.onSettled||t.options.onSettled(void 0,t.currentResult.error)),e.listeners&&t.listeners.forEach((function(e){e(t.currentResult)})),e.cache&&t.client.getQueryCache().notify({query:t.currentQuery,type:"observerResultsUpdated"})}))},t}(Subscribable);function shouldLoadOnMount(e,t){return!(!1===t.enabled||e.state.dataUpdatedAt||"error"===e.state.status&&!1===t.retryOnMount)}function shouldFetchOnMount(e,t){return shouldLoadOnMount(e,t)||e.state.dataUpdatedAt>0&&shouldFetchOn(e,t,t.refetchOnMount)}function shouldFetchOn(e,t,n){if(!1!==t.enabled){var i="function"==typeof n?n(e):n;return"always"===i||!1!==i&&isStale(e,t)}return!1}function shouldFetchOptionally(e,t,n,i){return!1!==n.enabled&&(e!==t||!1===i.enabled)&&(!n.suspense||"error"!==e.state.status)&&isStale(e,n)}function isStale(e,t){return e.isStaleByTime(t.staleTime)}var InfiniteQueryObserver=function(e){function t(t,n){return e.call(this,t,n)||this}_inheritsLoose(t,e);var n=t.prototype;return n.bindMethods=function(){e.prototype.bindMethods.call(this),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)},n.setOptions=function(t,n){e.prototype.setOptions.call(this,_extends$1({},t,{behavior:infiniteQueryBehavior()}),n)},n.getOptimisticResult=function(t){return t.behavior=infiniteQueryBehavior(),e.prototype.getOptimisticResult.call(this,t)},n.fetchNextPage=function(e){var t;return this.fetch({cancelRefetch:null==(t=null==e?void 0:e.cancelRefetch)||t,throwOnError:null==e?void 0:e.throwOnError,meta:{fetchMore:{direction:"forward",pageParam:null==e?void 0:e.pageParam}}})},n.fetchPreviousPage=function(e){var t;return this.fetch({cancelRefetch:null==(t=null==e?void 0:e.cancelRefetch)||t,throwOnError:null==e?void 0:e.throwOnError,meta:{fetchMore:{direction:"backward",pageParam:null==e?void 0:e.pageParam}}})},n.createResult=function(t,n){var i,r,s,a,o,l,c=t.state;return _extends$1({},e.prototype.createResult.call(this,t,n),{fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:hasNextPage(n,null==(i=c.data)?void 0:i.pages),hasPreviousPage:hasPreviousPage(n,null==(r=c.data)?void 0:r.pages),isFetchingNextPage:c.isFetching&&"forward"===(null==(s=c.fetchMeta)||null==(a=s.fetchMore)?void 0:a.direction),isFetchingPreviousPage:c.isFetching&&"backward"===(null==(o=c.fetchMeta)||null==(l=o.fetchMore)?void 0:l.direction)})},t}(QueryObserver),MutationObserver$1=function(e){function t(t,n){var i;return(i=e.call(this)||this).client=t,i.setOptions(n),i.bindMethods(),i.updateResult(),i}_inheritsLoose(t,e);var n=t.prototype;return n.bindMethods=function(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)},n.setOptions=function(e){this.options=this.client.defaultMutationOptions(e)},n.onUnsubscribe=function(){var e;this.listeners.length||(null==(e=this.currentMutation)||e.removeObserver(this))},n.onMutationUpdate=function(e){this.updateResult();var t={listeners:!0};"success"===e.type?t.onSuccess=!0:"error"===e.type&&(t.onError=!0),this.notify(t)},n.getCurrentResult=function(){return this.currentResult},n.reset=function(){this.currentMutation=void 0,this.updateResult(),this.notify({listeners:!0})},n.mutate=function(e,t){return this.mutateOptions=t,this.currentMutation&&this.currentMutation.removeObserver(this),this.currentMutation=this.client.getMutationCache().build(this.client,_extends$1({},this.options,{variables:void 0!==e?e:this.options.variables})),this.currentMutation.addObserver(this),this.currentMutation.execute()},n.updateResult=function(){var e=this.currentMutation?this.currentMutation.state:getDefaultState(),t=_extends$1({},e,{isLoading:"loading"===e.status,isSuccess:"success"===e.status,isError:"error"===e.status,isIdle:"idle"===e.status,mutate:this.mutate,reset:this.reset});this.currentResult=t},n.notify=function(e){var t=this;notifyManager.batch((function(){t.mutateOptions&&(e.onSuccess?(null==t.mutateOptions.onSuccess||t.mutateOptions.onSuccess(t.currentResult.data,t.currentResult.variables,t.currentResult.context),null==t.mutateOptions.onSettled||t.mutateOptions.onSettled(t.currentResult.data,null,t.currentResult.variables,t.currentResult.context)):e.onError&&(null==t.mutateOptions.onError||t.mutateOptions.onError(t.currentResult.error,t.currentResult.variables,t.currentResult.context),null==t.mutateOptions.onSettled||t.mutateOptions.onSettled(void 0,t.currentResult.error,t.currentResult.variables,t.currentResult.context))),e.listeners&&t.listeners.forEach((function(e){e(t.currentResult)}))}))},t}(Subscribable),unstable_batchedUpdates=ReactDOM__default.unstable_batchedUpdates;notifyManager.setBatchNotifyFunction(unstable_batchedUpdates);var logger=console;setLogger(logger);var defaultContext=React__default.createContext(void 0),QueryClientSharingContext=React__default.createContext(!1);function getQueryClientContext(e){return e&&"undefined"!=typeof window?(window.ReactQueryClientContext||(window.ReactQueryClientContext=defaultContext),window.ReactQueryClientContext):defaultContext}var useQueryClient=function(){var e=React__default.useContext(getQueryClientContext(React__default.useContext(QueryClientSharingContext)));if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},QueryClientProvider=function(e){var t=e.client,n=e.contextSharing,i=void 0!==n&&n,r=e.children;React__default.useEffect((function(){return t.mount(),function(){t.unmount()}}),[t]);var s=getQueryClientContext(i);return React__default.createElement(QueryClientSharingContext.Provider,{value:i},React__default.createElement(s.Provider,{value:t},r))};function createValue(){var e=!1;return{clearReset:function(){e=!1},reset:function(){e=!0},isReset:function(){return e}}}var QueryErrorResetBoundaryContext=React__default.createContext(createValue()),useQueryErrorResetBoundary=function(){return React__default.useContext(QueryErrorResetBoundaryContext)};function shouldThrowError(e,t,n){return"function"==typeof t?t.apply(void 0,n):"boolean"==typeof t?t:!!e}function useMutation(e,t,n){var i=React__default.useRef(!1),r=React__default.useState(0)[1],s=parseMutationArgs(e,t,n),a=useQueryClient(),o=React__default.useRef();o.current?o.current.setOptions(s):o.current=new MutationObserver$1(a,s);var l=o.current.getCurrentResult();React__default.useEffect((function(){i.current=!0;var e=o.current.subscribe(notifyManager.batchCalls((function(){i.current&&r((function(e){return e+1}))})));return function(){i.current=!1,e()}}),[]);var c=React__default.useCallback((function(e,t){o.current.mutate(e,t).catch(noop$1)}),[]);if(l.error&&shouldThrowError(void 0,o.current.options.useErrorBoundary,[l.error]))throw l.error;return _extends$1({},l,{mutate:c,mutateAsync:l.mutate})}function useBaseQuery(e,t){var n=React__default.useRef(!1),i=React__default.useState(0)[1],r=useQueryClient(),s=useQueryErrorResetBoundary(),a=r.defaultQueryObserverOptions(e);a.optimisticResults=!0,a.onError&&(a.onError=notifyManager.batchCalls(a.onError)),a.onSuccess&&(a.onSuccess=notifyManager.batchCalls(a.onSuccess)),a.onSettled&&(a.onSettled=notifyManager.batchCalls(a.onSettled)),a.suspense&&("number"!=typeof a.staleTime&&(a.staleTime=1e3),0===a.cacheTime&&(a.cacheTime=1)),(a.suspense||a.useErrorBoundary)&&(s.isReset()||(a.retryOnMount=!1));var o=React__default.useState((function(){return new t(r,a)}))[0],l=o.getOptimisticResult(a);if(React__default.useEffect((function(){n.current=!0,s.clearReset();var e=o.subscribe(notifyManager.batchCalls((function(){n.current&&i((function(e){return e+1}))})));return o.updateResult(),function(){n.current=!1,e()}}),[s,o]),React__default.useEffect((function(){o.setOptions(a,{listeners:!1})}),[a,o]),a.suspense&&l.isLoading)throw o.fetchOptimistic(a).then((function(e){var t=e.data;null==a.onSuccess||a.onSuccess(t),null==a.onSettled||a.onSettled(t,null)})).catch((function(e){s.clearReset(),null==a.onError||a.onError(e),null==a.onSettled||a.onSettled(void 0,e)}));if(l.isError&&!s.isReset()&&!l.isFetching&&shouldThrowError(a.suspense,a.useErrorBoundary,[l.error,o.getCurrentQuery()]))throw l.error;return"tracked"===a.notifyOnChangeProps&&(l=o.trackResult(l,a)),l}function useQuery(e,t,n){return useBaseQuery(parseQueryArgs(e,t,n),QueryObserver)}function useInfiniteQuery(e,t,n){return useBaseQuery(parseQueryArgs(e,t,n),InfiniteQueryObserver)}function useUser(e){if(!e)throw new Error("useUser must be used within an WeavyProvider");return useQuery("user",(async()=>{try{const t=await e.get("/api/user");return t.ok?await t.json():(console.error("Could not load Weavy user data..."),null)}catch(t){console.error(`Could not connect to the Weavy backend. Please make sure ${e.url} is up and running!`)}}))}const UserContext=createContext({user:{id:-1,uid:"",username:"anonymous",name:"Anonymous",email:"",display_name:"",presence:"",avatar_url:""}}),UserProvider=({children:e,client:t})=>{const{isLoading:n,data:i}=useUser(t);return React__default.createElement(React__default.Fragment,null,!n&&i&&React__default.createElement(UserContext.Provider,{value:{user:i}},e))};var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function getAugmentedNamespace(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var n=function e(){if(this instanceof e){var n=[null];return n.push.apply(n,arguments),new(Function.bind.apply(t,n))}return t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var i=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,i.get?i:{enumerable:!0,get:function(){return e[t]}})})),n}var dayjs_minExports={},dayjs_min={get exports(){return dayjs_minExports},set exports(e){dayjs_minExports=e}};dayjs_min.exports=function(){var e=1e3,t=6e4,n=36e5,i="millisecond",r="second",s="minute",a="hour",o="day",l="week",c="month",d="quarter",u="year",h="date",p="Invalid Date",f=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,m=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,g={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(e){var t=["th","st","nd","rd"],n=e%100;return"["+e+(t[(n-20)%10]||t[n]||t[0])+"]"}},O=function(e,t,n){var i=String(e);return!i||i.length>=t?e:""+Array(t+1-i.length).join(n)+e},y={s:O,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),i=Math.floor(n/60),r=n%60;return(t<=0?"+":"-")+O(i,2,"0")+":"+O(r,2,"0")},m:function e(t,n){if(t.date()<n.date())return-e(n,t);var i=12*(n.year()-t.year())+(n.month()-t.month()),r=t.clone().add(i,c),s=n-r<0,a=t.clone().add(i+(s?-1:1),c);return+(-(i+(n-r)/(s?r-a:a-r))||0)},a:function(e){return e<0?Math.ceil(e)||0:Math.floor(e)},p:function(e){return{M:c,y:u,w:l,d:o,D:h,h:a,m:s,s:r,ms:i,Q:d}[e]||String(e||"").toLowerCase().replace(/s$/,"")},u:function(e){return void 0===e}},v="en",b={};b[v]=g;var _=function(e){return e instanceof C},S=function e(t,n,i){var r;if(!t)return v;if("string"==typeof t){var s=t.toLowerCase();b[s]&&(r=s),n&&(b[s]=n,r=s);var a=t.split("-");if(!r&&a.length>1)return e(a[0])}else{var o=t.name;b[o]=t,r=o}return!i&&r&&(v=r),r||!i&&v},w=function(e,t){if(_(e))return e.clone();var n="object"==typeof t?t:{};return n.date=e,n.args=arguments,new C(n)},x=y;x.l=S,x.i=_,x.w=function(e,t){return w(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var C=function(){function g(e){this.$L=S(e.locale,null,!0),this.parse(e)}var O=g.prototype;return O.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(null===t)return new Date(NaN);if(x.u(t))return new Date;if(t instanceof Date)return new Date(t);if("string"==typeof t&&!/Z$/i.test(t)){var i=t.match(f);if(i){var r=i[2]-1||0,s=(i[7]||"0").substring(0,3);return n?new Date(Date.UTC(i[1],r,i[3]||1,i[4]||0,i[5]||0,i[6]||0,s)):new Date(i[1],r,i[3]||1,i[4]||0,i[5]||0,i[6]||0,s)}}return new Date(t)}(e),this.$x=e.x||{},this.init()},O.init=function(){var e=this.$d;this.$y=e.getFullYear(),this.$M=e.getMonth(),this.$D=e.getDate(),this.$W=e.getDay(),this.$H=e.getHours(),this.$m=e.getMinutes(),this.$s=e.getSeconds(),this.$ms=e.getMilliseconds()},O.$utils=function(){return x},O.isValid=function(){return!(this.$d.toString()===p)},O.isSame=function(e,t){var n=w(e);return this.startOf(t)<=n&&n<=this.endOf(t)},O.isAfter=function(e,t){return w(e)<this.startOf(t)},O.isBefore=function(e,t){return this.endOf(t)<w(e)},O.$g=function(e,t,n){return x.u(e)?this[t]:this.set(n,e)},O.unix=function(){return Math.floor(this.valueOf()/1e3)},O.valueOf=function(){return this.$d.getTime()},O.startOf=function(e,t){var n=this,i=!!x.u(t)||t,d=x.p(e),p=function(e,t){var r=x.w(n.$u?Date.UTC(n.$y,t,e):new Date(n.$y,t,e),n);return i?r:r.endOf(o)},f=function(e,t){return x.w(n.toDate()[e].apply(n.toDate("s"),(i?[0,0,0,0]:[23,59,59,999]).slice(t)),n)},m=this.$W,g=this.$M,O=this.$D,y="set"+(this.$u?"UTC":"");switch(d){case u:return i?p(1,0):p(31,11);case c:return i?p(1,g):p(0,g+1);case l:var v=this.$locale().weekStart||0,b=(m<v?m+7:m)-v;return p(i?O-b:O+(6-b),g);case o:case h:return f(y+"Hours",0);case a:return f(y+"Minutes",1);case s:return f(y+"Seconds",2);case r:return f(y+"Milliseconds",3);default:return this.clone()}},O.endOf=function(e){return this.startOf(e,!1)},O.$set=function(e,t){var n,l=x.p(e),d="set"+(this.$u?"UTC":""),p=(n={},n[o]=d+"Date",n[h]=d+"Date",n[c]=d+"Month",n[u]=d+"FullYear",n[a]=d+"Hours",n[s]=d+"Minutes",n[r]=d+"Seconds",n[i]=d+"Milliseconds",n)[l],f=l===o?this.$D+(t-this.$W):t;if(l===c||l===u){var m=this.clone().set(h,1);m.$d[p](f),m.init(),this.$d=m.set(h,Math.min(this.$D,m.daysInMonth())).$d}else p&&this.$d[p](f);return this.init(),this},O.set=function(e,t){return this.clone().$set(e,t)},O.get=function(e){return this[x.p(e)]()},O.add=function(i,d){var h,p=this;i=Number(i);var f=x.p(d),m=function(e){var t=w(p);return x.w(t.date(t.date()+Math.round(e*i)),p)};if(f===c)return this.set(c,this.$M+i);if(f===u)return this.set(u,this.$y+i);if(f===o)return m(1);if(f===l)return m(7);var g=(h={},h[s]=t,h[a]=n,h[r]=e,h)[f]||1,O=this.$d.getTime()+i*g;return x.w(O,this)},O.subtract=function(e,t){return this.add(-1*e,t)},O.format=function(e){var t=this,n=this.$locale();if(!this.isValid())return n.invalidDate||p;var i=e||"YYYY-MM-DDTHH:mm:ssZ",r=x.z(this),s=this.$H,a=this.$m,o=this.$M,l=n.weekdays,c=n.months,d=n.meridiem,u=function(e,n,r,s){return e&&(e[n]||e(t,i))||r[n].slice(0,s)},h=function(e){return x.s(s%12||12,e,"0")},f=d||function(e,t,n){var i=e<12?"AM":"PM";return n?i.toLowerCase():i};return i.replace(m,(function(e,i){return i||function(e){switch(e){case"YY":return String(t.$y).slice(-2);case"YYYY":return x.s(t.$y,4,"0");case"M":return o+1;case"MM":return x.s(o+1,2,"0");case"MMM":return u(n.monthsShort,o,c,3);case"MMMM":return u(c,o);case"D":return t.$D;case"DD":return x.s(t.$D,2,"0");case"d":return String(t.$W);case"dd":return u(n.weekdaysMin,t.$W,l,2);case"ddd":return u(n.weekdaysShort,t.$W,l,3);case"dddd":return l[t.$W];case"H":return String(s);case"HH":return x.s(s,2,"0");case"h":return h(1);case"hh":return h(2);case"a":return f(s,a,!0);case"A":return f(s,a,!1);case"m":return String(a);case"mm":return x.s(a,2,"0");case"s":return String(t.$s);case"ss":return x.s(t.$s,2,"0");case"SSS":return x.s(t.$ms,3,"0");case"Z":return r}return null}(e)||r.replace(":","")}))},O.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},O.diff=function(i,h,p){var f,m=this,g=x.p(h),O=w(i),y=(O.utcOffset()-this.utcOffset())*t,v=this-O,b=function(){return x.m(m,O)};switch(g){case u:f=b()/12;break;case c:f=b();break;case d:f=b()/3;break;case l:f=(v-y)/6048e5;break;case o:f=(v-y)/864e5;break;case a:f=v/n;break;case s:f=v/t;break;case r:f=v/e;break;default:f=v}return p?f:x.a(f)},O.daysInMonth=function(){return this.endOf(c).$D},O.$locale=function(){return b[this.$L]},O.locale=function(e,t){if(!e)return this.$L;var n=this.clone(),i=S(e,t,!0);return i&&(n.$L=i),n},O.clone=function(){return x.w(this.$d,this)},O.toDate=function(){return new Date(this.valueOf())},O.toJSON=function(){return this.isValid()?this.toISOString():null},O.toISOString=function(){return this.$d.toISOString()},O.toString=function(){return this.$d.toUTCString()},g}(),P=C.prototype;return w.prototype=P,[["$ms",i],["$s",r],["$m",s],["$H",a],["$W",o],["$M",c],["$y",u],["$D",h]].forEach((function(e){P[e[1]]=function(t){return this.$g(t,e[0],e[1])}})),w.extend=function(e,t){return e.$i||(e(t,C,w),e.$i=!0),w},w.locale=S,w.isDayjs=_,w.unix=function(e){return w(1e3*e)},w.en=b[v],w.Ls=b,w.p={},w}();var dayjs=dayjs_minExports,relativeTimeExports={},relativeTime$1={get exports(){return relativeTimeExports},set exports(e){relativeTimeExports=e}};relativeTime$1.exports=function(e,t,n){e=e||{};var i=t.prototype,r={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function s(e,t,n,r){return i.fromToBase(e,t,n,r)}n.en.relativeTime=r,i.fromToBase=function(t,i,s,a,o){for(var l,c,d,u=s.$locale().relativeTime||r,h=e.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],p=h.length,f=0;f<p;f+=1){var m=h[f];m.d&&(l=a?n(t).diff(s,m.d,!0):s.diff(t,m.d,!0));var g=(e.rounding||Math.round)(Math.abs(l));if(d=l>0,g<=m.r||!m.r){g<=1&&f>0&&(m=h[f-1]);var O=u[m.l];o&&(g=o(""+g)),c="string"==typeof O?O.replace("%d",g):O(g,i,m.l,d);break}}if(i)return c;var y=d?u.future:u.past;return"function"==typeof y?y(c):y.replace("%s",c)},i.to=function(e,t){return s(e,t,this,!0)},i.from=function(e,t){return s(e,t,this)};var a=function(e){return e.$u?n.utc():n()};i.toNow=function(e){return this.to(a(this),e)},i.fromNow=function(e){return this.from(a(this),e)}};var relativeTime=relativeTimeExports,utcExports={},utc$1={get exports(){return utcExports},set exports(e){utcExports=e}};utc$1.exports=function(){var e="minute",t=/[+-]\d\d(?::?\d\d)?/g,n=/([+-]|\d\d)/g;return function(i,r,s){var a=r.prototype;s.utc=function(e){return new r({date:e,utc:!0,args:arguments})},a.utc=function(t){var n=s(this.toDate(),{locale:this.$L,utc:!0});return t?n.add(this.utcOffset(),e):n},a.local=function(){return s(this.toDate(),{locale:this.$L,utc:!1})};var o=a.parse;a.parse=function(e){e.utc&&(this.$u=!0),this.$utils().u(e.$offset)||(this.$offset=e.$offset),o.call(this,e)};var l=a.init;a.init=function(){if(this.$u){var e=this.$d;this.$y=e.getUTCFullYear(),this.$M=e.getUTCMonth(),this.$D=e.getUTCDate(),this.$W=e.getUTCDay(),this.$H=e.getUTCHours(),this.$m=e.getUTCMinutes(),this.$s=e.getUTCSeconds(),this.$ms=e.getUTCMilliseconds()}else l.call(this)};var c=a.utcOffset;a.utcOffset=function(i,r){var s=this.$utils().u;if(s(i))return this.$u?0:s(this.$offset)?c.call(this):this.$offset;if("string"==typeof i&&(i=function(e){void 0===e&&(e="");var i=e.match(t);if(!i)return null;var r=(""+i[0]).match(n)||["-",0,0],s=r[0],a=60*+r[1]+ +r[2];return 0===a?0:"+"===s?a:-a}(i),null===i))return this;var a=Math.abs(i)<=16?60*i:i,o=this;if(r)return o.$offset=a,o.$u=0===i,o;if(0!==i){var l=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(o=this.local().add(a+l,e)).$offset=a,o.$x.$localOffset=l}else o=this.utc();return o};var d=a.format;a.format=function(e){var t=e||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return d.call(this,t)},a.valueOf=function(){var e=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*e},a.isUTC=function(){return!!this.$u},a.toISOString=function(){return this.toDate().toISOString()},a.toString=function(){return this.toDate().toUTCString()};var u=a.toDate;a.toDate=function(e){return"s"===e&&this.$offset?s(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():u.call(this)};var h=a.diff;a.diff=function(e,t,n){if(e&&this.$u===e.$u)return h.call(this,e,t,n);var i=this.local(),r=s(e).local();return h.call(i,r,t,n)}}}();var utc=utcExports,timezoneExports={},timezone$1={get exports(){return timezoneExports},set exports(e){timezoneExports=e}};timezone$1.exports=function(){var e={year:0,month:1,day:2,hour:3,minute:4,second:5},t={};return function(n,i,r){var s,a=function(e,n,i){void 0===i&&(i={});var r=new Date(e),s=function(e,n){void 0===n&&(n={});var i=n.timeZoneName||"short",r=e+"|"+i,s=t[r];return s||(s=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:i}),t[r]=s),s}(n,i);return s.formatToParts(r)},o=function(t,n){for(var i=a(t,n),s=[],o=0;o<i.length;o+=1){var l=i[o],c=l.type,d=l.value,u=e[c];u>=0&&(s[u]=parseInt(d,10))}var h=s[3],p=24===h?0:h,f=s[0]+"-"+s[1]+"-"+s[2]+" "+p+":"+s[4]+":"+s[5]+":000",m=+t;return(r.utc(f).valueOf()-(m-=m%1e3))/6e4},l=i.prototype;l.tz=function(e,t){void 0===e&&(e=s);var n=this.utcOffset(),i=this.toDate(),a=i.toLocaleString("en-US",{timeZone:e}),o=Math.round((i-new Date(a))/1e3/60),l=r(a).$set("millisecond",this.$ms).utcOffset(15*-Math.round(i.getTimezoneOffset()/15)-o,!0);if(t){var c=l.utcOffset();l=l.add(n-c,"minute")}return l.$x.$timezone=e,l},l.offsetName=function(e){var t=this.$x.$timezone||r.tz.guess(),n=a(this.valueOf(),t,{timeZoneName:e}).find((function(e){return"timezonename"===e.type.toLowerCase()}));return n&&n.value};var c=l.startOf;l.startOf=function(e,t){if(!this.$x||!this.$x.$timezone)return c.call(this,e,t);var n=r(this.format("YYYY-MM-DD HH:mm:ss:SSS"));return c.call(n,e,t).tz(this.$x.$timezone,!0)},r.tz=function(e,t,n){var i=n&&t,a=n||t||s,l=o(+r(),a);if("string"!=typeof e)return r(e).tz(a);var c=function(e,t,n){var i=e-60*t*1e3,r=o(i,n);if(t===r)return[i,t];var s=o(i-=60*(r-t)*1e3,n);return r===s?[i,r]:[e-60*Math.min(r,s)*1e3,Math.max(r,s)]}(r.utc(e,i).valueOf(),l,a),d=c[0],u=c[1],h=r(d).utcOffset(u);return h.$x.$timezone=a,h},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(e){s=e}}}();var timezone=timezoneExports,localizedFormatExports={},localizedFormat$1={get exports(){return localizedFormatExports},set exports(e){localizedFormatExports=e}},e;localizedFormat$1.exports=(e={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},function(t,n,i){var r=n.prototype,s=r.format;i.en.formats=e,r.format=function(t){void 0===t&&(t="YYYY-MM-DDTHH:mm:ssZ");var n=this.$locale().formats,i=function(t,n){return t.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,(function(t,i,r){var s=r&&r.toUpperCase();return i||n[r]||e[r]||n[s].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,(function(e,t,n){return t||n.slice(1)}))}))}(t,void 0===n?{}:n);return s.call(this,i)}});var localizedFormat=localizedFormatExports,libExports={},lib={get exports(){return libExports},set exports(e){libExports=e}},Modal$2={},propTypesExports$1={},propTypes={get exports(){return propTypesExports$1},set exports(e){propTypesExports$1=e}},reactIsExports={},reactIs={get exports(){return reactIsExports},set exports(e){reactIsExports=e}},reactIs_production_min={},hasRequiredReactIs_production_min;function requireReactIs_production_min(){if(hasRequiredReactIs_production_min)return reactIs_production_min;hasRequiredReactIs_production_min=1;var e="function"==typeof Symbol&&Symbol.for,t=e?Symbol.for("react.element"):60103,n=e?Symbol.for("react.portal"):60106,i=e?Symbol.for("react.fragment"):60107,r=e?Symbol.for("react.strict_mode"):60108,s=e?Symbol.for("react.profiler"):60114,a=e?Symbol.for("react.provider"):60109,o=e?Symbol.for("react.context"):60110,l=e?Symbol.for("react.async_mode"):60111,c=e?Symbol.for("react.concurrent_mode"):60111,d=e?Symbol.for("react.forward_ref"):60112,u=e?Symbol.for("react.suspense"):60113,h=e?Symbol.for("react.suspense_list"):60120,p=e?Symbol.for("react.memo"):60115,f=e?Symbol.for("react.lazy"):60116,m=e?Symbol.for("react.block"):60121,g=e?Symbol.for("react.fundamental"):60117,O=e?Symbol.for("react.responder"):60118,y=e?Symbol.for("react.scope"):60119;function v(e){if("object"==typeof e&&null!==e){var h=e.$$typeof;switch(h){case t:switch(e=e.type){case l:case c:case i:case s:case r:case u:return e;default:switch(e=e&&e.$$typeof){case o:case d:case f:case p:case a:return e;default:return h}}case n:return h}}}function b(e){return v(e)===c}return reactIs_production_min.AsyncMode=l,reactIs_production_min.ConcurrentMode=c,reactIs_production_min.ContextConsumer=o,reactIs_production_min.ContextProvider=a,reactIs_production_min.Element=t,reactIs_production_min.ForwardRef=d,reactIs_production_min.Fragment=i,reactIs_production_min.Lazy=f,reactIs_production_min.Memo=p,reactIs_production_min.Portal=n,reactIs_production_min.Profiler=s,reactIs_production_min.StrictMode=r,reactIs_production_min.Suspense=u,reactIs_production_min.isAsyncMode=function(e){return b(e)||v(e)===l},reactIs_production_min.isConcurrentMode=b,reactIs_production_min.isContextConsumer=function(e){return v(e)===o},reactIs_production_min.isContextProvider=function(e){return v(e)===a},reactIs_production_min.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===t},reactIs_production_min.isForwardRef=function(e){return v(e)===d},reactIs_production_min.isFragment=function(e){return v(e)===i},reactIs_production_min.isLazy=function(e){return v(e)===f},reactIs_production_min.isMemo=function(e){return v(e)===p},reactIs_production_min.isPortal=function(e){return v(e)===n},reactIs_production_min.isProfiler=function(e){return v(e)===s},reactIs_production_min.isStrictMode=function(e){return v(e)===r},reactIs_production_min.isSuspense=function(e){return v(e)===u},reactIs_production_min.isValidElementType=function(e){return"string"==typeof e||"function"==typeof e||e===i||e===c||e===s||e===r||e===u||e===h||"object"==typeof e&&null!==e&&(e.$$typeof===f||e.$$typeof===p||e.$$typeof===a||e.$$typeof===o||e.$$typeof===d||e.$$typeof===g||e.$$typeof===O||e.$$typeof===y||e.$$typeof===m)},reactIs_production_min.typeOf=v,reactIs_production_min}var reactIs_development={},hasRequiredReactIs_development,hasRequiredReactIs,objectAssign,hasRequiredObjectAssign,ReactPropTypesSecret_1,hasRequiredReactPropTypesSecret,has,hasRequiredHas,checkPropTypes_1,hasRequiredCheckPropTypes,factoryWithTypeCheckers,hasRequiredFactoryWithTypeCheckers,factoryWithThrowingShims,hasRequiredFactoryWithThrowingShims,hasRequiredPropTypes;
|
|
1
|
+
import*as React from"react";import React__default,{createContext,useState,Children,useRef,useCallback,useEffect,useContext,useLayoutEffect,forwardRef,useImperativeHandle,useMemo,useReducer,Fragment}from"react";import*as ReactDOM from"react-dom";import ReactDOM__default from"react-dom";import{jsx}from"react/jsx-runtime";class HttpError extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class TimeoutError extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class AbortError extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class UnsupportedTransportError extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=n}}class DisabledTransportError extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=n}}class FailedToStartTransportError extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=n}}class FailedToNegotiateWithServerError extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class AggregateErrors extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.innerErrors=t,this.__proto__=n}}class HttpResponse{constructor(e,t,n){this.statusCode=e,this.statusText=t,this.content=n}}class HttpClient{get(e,t){return this.send({...t,method:"GET",url:e})}post(e,t){return this.send({...t,method:"POST",url:e})}delete(e,t){return this.send({...t,method:"DELETE",url:e})}getCookieString(e){return""}}var LogLevel;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"}(LogLevel||(LogLevel={}));class NullLogger{constructor(){}log(e,t){}}NullLogger.instance=new NullLogger;const VERSION="7.0.10";class Arg{static isRequired(e,t){if(null==e)throw new Error(`The '${t}' argument is required.`)}static isNotEmpty(e,t){if(!e||e.match(/^\s*$/))throw new Error(`The '${t}' argument should not be empty.`)}static isIn(e,t,n){if(!(e in t))throw new Error(`Unknown ${n} value: ${e}.`)}}class Platform{static get isBrowser(){return"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isReactNative(){return"object"==typeof window&&void 0===window.document}static get isNode(){return!this.isBrowser&&!this.isWebWorker&&!this.isReactNative}}function getDataDetail(e,t){let n="";return isArrayBuffer(e)?(n=`Binary data of length ${e.byteLength}`,t&&(n+=`. Content: '${formatArrayBuffer(e)}'`)):"string"==typeof e&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function formatArrayBuffer(e){const t=new Uint8Array(e);let n="";return t.forEach((e=>{n+=`0x${e<16?"0":""}${e.toString(16)} `})),n.substr(0,n.length-1)}function isArrayBuffer(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function sendMessage(e,t,n,i,r,s){const a={},[o,l]=getUserAgentHeader();a[o]=l,e.log(LogLevel.Trace,`(${t} transport) sending data. ${getDataDetail(r,s.logMessageContent)}.`);const c=isArrayBuffer(r)?"arraybuffer":"text",d=await n.post(i,{content:r,headers:{...a,...s.headers},responseType:c,timeout:s.timeout,withCredentials:s.withCredentials});e.log(LogLevel.Trace,`(${t} transport) request complete. Response status: ${d.statusCode}.`)}function createLogger(e){return void 0===e?new ConsoleLogger(LogLevel.Information):null===e?NullLogger.instance:void 0!==e.log?e:new ConsoleLogger(e)}class SubjectSubscription{constructor(e,t){this._subject=e,this._observer=t}dispose(){const e=this._subject.observers.indexOf(this._observer);e>-1&&this._subject.observers.splice(e,1),0===this._subject.observers.length&&this._subject.cancelCallback&&this._subject.cancelCallback().catch((e=>{}))}}class ConsoleLogger{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${LogLevel[e]}: ${t}`;switch(e){case LogLevel.Critical:case LogLevel.Error:this.out.error(n);break;case LogLevel.Warning:this.out.warn(n);break;case LogLevel.Information:this.out.info(n);break;default:this.out.log(n)}}}}function getUserAgentHeader(){let e="X-SignalR-User-Agent";return Platform.isNode&&(e="User-Agent"),[e,constructUserAgent(VERSION,getOsName(),getRuntime(),getRuntimeVersion())]}function constructUserAgent(e,t,n,i){let r="Microsoft SignalR/";const s=e.split(".");return r+=`${s[0]}.${s[1]}`,r+=` (${e}; `,r+=t&&""!==t?`${t}; `:"Unknown OS; ",r+=`${n}`,r+=i?`; ${i}`:"; Unknown Runtime Version",r+=")",r}function getOsName(){if(!Platform.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function getRuntimeVersion(){if(Platform.isNode)return process.versions.node}function getRuntime(){return Platform.isNode?"NodeJS":"Browser"}function getErrorString(e){return e.stack?e.stack:e.message?e.message:`${e}`}function getGlobalThis(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("could not find global")}class FetchHttpClient extends HttpClient{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch){const e="function"==typeof __webpack_require__?__non_webpack_require__:require;this._jar=new(e("tough-cookie").CookieJar),this._fetchType=e("node-fetch"),this._fetchType=e("fetch-cookie")(this._fetchType,this._jar)}else this._fetchType=fetch.bind(getGlobalThis());if("undefined"==typeof AbortController){const e="function"==typeof __webpack_require__?__non_webpack_require__:require;this._abortControllerType=e("abort-controller")}else this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new AbortError;if(!e.method)throw new Error("No method defined.");if(!e.url)throw new Error("No url defined.");const t=new this._abortControllerType;let n;e.abortSignal&&(e.abortSignal.onabort=()=>{t.abort(),n=new AbortError});let i,r=null;if(e.timeout){const i=e.timeout;r=setTimeout((()=>{t.abort(),this._logger.log(LogLevel.Warning,"Timeout from HTTP request."),n=new TimeoutError}),i)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},isArrayBuffer(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");try{i=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...e.headers},method:e.method,mode:"cors",redirect:"follow",signal:t.signal})}catch(e){if(n)throw n;throw this._logger.log(LogLevel.Warning,`Error from HTTP request. ${e}.`),e}finally{r&&clearTimeout(r),e.abortSignal&&(e.abortSignal.onabort=null)}if(!i.ok){const e=await deserializeContent(i,"text");throw new HttpError(e||i.statusText,i.status)}const s=deserializeContent(i,e.responseType),a=await s;return new HttpResponse(i.status,i.statusText,a)}getCookieString(e){let t="";return Platform.isNode&&this._jar&&this._jar.getCookies(e,((e,n)=>t=n.join("; "))),t}}function deserializeContent(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":default:n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`)}return n}class XhrHttpClient extends HttpClient{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new AbortError):e.method?e.url?new Promise(((t,n)=>{const i=new XMLHttpRequest;i.open(e.method,e.url,!0),i.withCredentials=void 0===e.withCredentials||e.withCredentials,i.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===e.content&&(e.content=void 0),e.content&&(isArrayBuffer(e.content)?i.setRequestHeader("Content-Type","application/octet-stream"):i.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const r=e.headers;r&&Object.keys(r).forEach((e=>{i.setRequestHeader(e,r[e])})),e.responseType&&(i.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{i.abort(),n(new AbortError)}),e.timeout&&(i.timeout=e.timeout),i.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),i.status>=200&&i.status<300?t(new HttpResponse(i.status,i.statusText,i.response||i.responseText)):n(new HttpError(i.response||i.responseText||i.statusText,i.status))},i.onerror=()=>{this._logger.log(LogLevel.Warning,`Error from HTTP request. ${i.status}: ${i.statusText}.`),n(new HttpError(i.statusText,i.status))},i.ontimeout=()=>{this._logger.log(LogLevel.Warning,"Timeout from HTTP request."),n(new TimeoutError)},i.send(e.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class DefaultHttpClient extends HttpClient{constructor(e){if(super(),"undefined"!=typeof fetch||Platform.isNode)this._httpClient=new FetchHttpClient(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new XhrHttpClient(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new AbortError):e.method?e.url?this._httpClient.send(e):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(e){return this._httpClient.getCookieString(e)}}class TextMessageFormat{static write(e){return`${e}${TextMessageFormat.RecordSeparator}`}static parse(e){if(e[e.length-1]!==TextMessageFormat.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(TextMessageFormat.RecordSeparator);return t.pop(),t}}TextMessageFormat.RecordSeparatorCode=30,TextMessageFormat.RecordSeparator=String.fromCharCode(TextMessageFormat.RecordSeparatorCode);class HandshakeProtocol{writeHandshakeRequest(e){return TextMessageFormat.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(isArrayBuffer(e)){const i=new Uint8Array(e),r=i.indexOf(TextMessageFormat.RecordSeparatorCode);if(-1===r)throw new Error("Message is incomplete.");const s=r+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(i.slice(0,s))),n=i.byteLength>s?i.slice(s).buffer:null}else{const i=e,r=i.indexOf(TextMessageFormat.RecordSeparator);if(-1===r)throw new Error("Message is incomplete.");const s=r+1;t=i.substring(0,s),n=i.length>s?i.substring(s):null}const i=TextMessageFormat.parse(t),r=JSON.parse(i[0]);if(r.type)throw new Error("Expected a handshake response from the server.");return[n,r]}}var MessageType;!function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close"}(MessageType||(MessageType={}));class Subject{constructor(){this.observers=[]}next(e){for(const t of this.observers)t.next(e)}error(e){for(const t of this.observers)t.error&&t.error(e)}complete(){for(const e of this.observers)e.complete&&e.complete()}subscribe(e){return this.observers.push(e),new SubjectSubscription(this,e)}}const DEFAULT_TIMEOUT_IN_MS=3e4,DEFAULT_PING_INTERVAL_IN_MS=15e3;var HubConnectionState;!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(HubConnectionState||(HubConnectionState={}));class HubConnection{constructor(e,t,n,i){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(LogLevel.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://docs.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},Arg.isRequired(e,"connection"),Arg.isRequired(t,"logger"),Arg.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=DEFAULT_TIMEOUT_IN_MS,this.keepAliveIntervalInMilliseconds=DEFAULT_PING_INTERVAL_IN_MS,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=i,this._handshakeProtocol=new HandshakeProtocol,this.connection.onreceive=e=>this._processIncomingData(e),this.connection.onclose=e=>this._connectionClosed(e),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=HubConnectionState.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:MessageType.Ping})}static create(e,t,n,i){return new HubConnection(e,t,n,i)}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(e){if(this._connectionState!==HubConnectionState.Disconnected&&this._connectionState!==HubConnectionState.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!e)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=e}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==HubConnectionState.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=HubConnectionState.Connecting,this._logger.log(LogLevel.Debug,"Starting HubConnection.");try{await this._startInternal(),Platform.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=HubConnectionState.Connected,this._connectionStarted=!0,this._logger.log(LogLevel.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=HubConnectionState.Disconnected,this._logger.log(LogLevel.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise(((e,t)=>{this._handshakeResolver=e,this._handshakeRejecter=t}));await this.connection.start(this._protocol.transferFormat);try{const t={protocol:this._protocol.name,version:this._protocol.version};if(this._logger.log(LogLevel.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(t)),this._logger.log(LogLevel.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError;this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(e){throw this._logger.log(LogLevel.Debug,`Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(e),e}}async stop(){const e=this._startPromise;this._stopPromise=this._stopInternal(),await this._stopPromise;try{await e}catch(e){}}_stopInternal(e){return this._connectionState===HubConnectionState.Disconnected?(this._logger.log(LogLevel.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve()):this._connectionState===HubConnectionState.Disconnecting?(this._logger.log(LogLevel.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState=HubConnectionState.Disconnecting,this._logger.log(LogLevel.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(LogLevel.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new AbortError("The connection was stopped before the hub handshake could complete."),this.connection.stop(e)))}stream(e,...t){const[n,i]=this._replaceStreamingParams(t),r=this._createStreamInvocation(e,t,i);let s;const a=new Subject;return a.cancelCallback=()=>{const e=this._createCancelInvocation(r.invocationId);return delete this._callbacks[r.invocationId],s.then((()=>this._sendWithProtocol(e)))},this._callbacks[r.invocationId]=(e,t)=>{t?a.error(t):e&&(e.type===MessageType.Completion?e.error?a.error(new Error(e.error)):a.complete():a.next(e.item))},s=this._sendWithProtocol(r).catch((e=>{a.error(e),delete this._callbacks[r.invocationId]})),this._launchStreams(n,s),a}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return this._sendMessage(this._protocol.writeMessage(e))}send(e,...t){const[n,i]=this._replaceStreamingParams(t),r=this._sendWithProtocol(this._createInvocation(e,t,!0,i));return this._launchStreams(n,r),r}invoke(e,...t){const[n,i]=this._replaceStreamingParams(t),r=this._createInvocation(e,t,!1,i);return new Promise(((e,t)=>{this._callbacks[r.invocationId]=(n,i)=>{i?t(i):n&&(n.type===MessageType.Completion?n.error?t(new Error(n.error)):e(n.result):t(new Error(`Unexpected message type: ${n.type}`)))};const i=this._sendWithProtocol(r).catch((e=>{t(e),delete this._callbacks[r.invocationId]}));this._launchStreams(n,i)}))}on(e,t){e&&t&&(e=e.toLowerCase(),this._methods[e]||(this._methods[e]=[]),-1===this._methods[e].indexOf(t)&&this._methods[e].push(t))}off(e,t){if(!e)return;e=e.toLowerCase();const n=this._methods[e];if(n)if(t){const i=n.indexOf(t);-1!==i&&(n.splice(i,1),0===n.length&&delete this._methods[e])}else delete this._methods[e]}onclose(e){e&&this._closedCallbacks.push(e)}onreconnecting(e){e&&this._reconnectingCallbacks.push(e)}onreconnected(e){e&&this._reconnectedCallbacks.push(e)}_processIncomingData(e){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(e=this._processHandshakeResponse(e),this._receivedHandshakeResponse=!0),e){const t=this._protocol.parseMessages(e,this._logger);for(const e of t)switch(e.type){case MessageType.Invocation:this._invokeClientMethod(e);break;case MessageType.StreamItem:case MessageType.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===MessageType.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(LogLevel.Error,`Stream callback threw error: ${getErrorString(e)}`)}}break}case MessageType.Ping:break;case MessageType.Close:{this._logger.log(LogLevel.Information,"Close message received from server.");const t=e.error?new Error("Server returned an error on close: "+e.error):void 0;!0===e.allowReconnect?this.connection.stop(t):this._stopPromise=this._stopInternal(t);break}default:this._logger.log(LogLevel.Warning,`Invalid message type: ${e.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let t,n;try{[n,t]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(e){const t="Error parsing handshake response: "+e;this._logger.log(LogLevel.Error,t);const n=new Error(t);throw this._handshakeRejecter(n),n}if(t.error){const e="Server returned handshake error: "+t.error;this._logger.log(LogLevel.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(LogLevel.Debug,"Server handshake complete."),this._handshakeResolver(),n}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this._timeoutHandle=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this._pingServerHandle))){let e=this._nextKeepAlive-(new Date).getTime();e<0&&(e=0),this._pingServerHandle=setTimeout((async()=>{if(this._connectionState===HubConnectionState.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}),e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(e){const t=e.target.toLowerCase(),n=this._methods[t];if(!n)return this._logger.log(LogLevel.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(LogLevel.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null))));const i=n.slice(),r=!!e.invocationId;let s,a,o;for(const n of i)try{const i=s;s=await n.apply(this,e.arguments),r&&s&&i&&(this._logger.log(LogLevel.Error,`Multiple results provided for '${t}'. Sending error to server.`),o=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),a=void 0}catch(e){a=e,this._logger.log(LogLevel.Error,`A callback for the method '${t}' threw error '${e}'.`)}o?await this._sendWithProtocol(o):r?(a?o=this._createCompletionMessage(e.invocationId,`${a}`,null):void 0!==s?o=this._createCompletionMessage(e.invocationId,null,s):(this._logger.log(LogLevel.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),o=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(o)):s&&this._logger.log(LogLevel.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(LogLevel.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new AbortError("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(e||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===HubConnectionState.Disconnecting?this._completeClose(e):this._connectionState===HubConnectionState.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===HubConnectionState.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=HubConnectionState.Disconnected,this._connectionStarted=!1,Platform.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(LogLevel.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let n=0,i=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),r=this._getNextRetryDelay(n++,0,i);if(null===r)return this._logger.log(LogLevel.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=HubConnectionState.Reconnecting,e?this._logger.log(LogLevel.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(LogLevel.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(LogLevel.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==HubConnectionState.Reconnecting)return void this._logger.log(LogLevel.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this._logger.log(LogLevel.Information,`Reconnect attempt number ${n} will start in ${r} ms.`),await new Promise((e=>{this._reconnectDelayHandle=setTimeout(e,r)})),this._reconnectDelayHandle=void 0,this._connectionState!==HubConnectionState.Reconnecting)return void this._logger.log(LogLevel.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=HubConnectionState.Connected,this._logger.log(LogLevel.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(LogLevel.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(LogLevel.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==HubConnectionState.Reconnecting)return this._logger.log(LogLevel.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===HubConnectionState.Disconnecting&&this._completeClose());i=e instanceof Error?e:new Error(e.toString()),r=this._getNextRetryDelay(n++,Date.now()-t,i)}}this._logger.log(LogLevel.Information,`Reconnect retries have been exhausted after ${Date.now()-t} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(e,t,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:t,previousRetryCount:e,retryReason:n})}catch(n){return this._logger.log(LogLevel.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{const i=t[n];try{i(null,e)}catch(t){this._logger.log(LogLevel.Error,`Stream 'error' callback called with '${e}' threw error: ${getErrorString(t)}`)}}))}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,t,n,i){if(n)return 0!==i.length?{arguments:t,streamIds:i,target:e,type:MessageType.Invocation}:{arguments:t,target:e,type:MessageType.Invocation};{const n=this._invocationId;return this._invocationId++,0!==i.length?{arguments:t,invocationId:n.toString(),streamIds:i,target:e,type:MessageType.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:MessageType.Invocation}}}_launchStreams(e,t){if(0!==e.length){t||(t=Promise.resolve());for(const n in e)e[n].subscribe({complete:()=>{t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n))))},error:e=>{let i;i=e instanceof Error?e.message:e&&e.toString?e.toString():"Unknown error",t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n,i))))},next:e=>{t=t.then((()=>this._sendWithProtocol(this._createStreamItemMessage(n,e))))}})}}_replaceStreamingParams(e){const t=[],n=[];for(let i=0;i<e.length;i++){const r=e[i];if(this._isObservable(r)){const s=this._invocationId;this._invocationId++,t[s]=r,n.push(s.toString()),e.splice(i,1)}}return[t,n]}_isObservable(e){return e&&e.subscribe&&"function"==typeof e.subscribe}_createStreamInvocation(e,t,n){const i=this._invocationId;return this._invocationId++,0!==n.length?{arguments:t,invocationId:i.toString(),streamIds:n,target:e,type:MessageType.StreamInvocation}:{arguments:t,invocationId:i.toString(),target:e,type:MessageType.StreamInvocation}}_createCancelInvocation(e){return{invocationId:e,type:MessageType.CancelInvocation}}_createStreamItemMessage(e,t){return{invocationId:e,item:t,type:MessageType.StreamItem}}_createCompletionMessage(e,t,n){return t?{error:t,invocationId:e,type:MessageType.Completion}:{invocationId:e,result:n,type:MessageType.Completion}}}const DEFAULT_RETRY_DELAYS_IN_MILLISECONDS=[0,2e3,1e4,3e4,null];class DefaultReconnectPolicy{constructor(e){this._retryDelays=void 0!==e?[...e,null]:DEFAULT_RETRY_DELAYS_IN_MILLISECONDS}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class HeaderNames{}HeaderNames.Authorization="Authorization",HeaderNames.Cookie="Cookie";class AccessTokenHttpClient extends HttpClient{constructor(e,t){super(),this._innerClient=e,this._accessTokenFactory=t}async send(e){let t=!0;this._accessTokenFactory&&(!this._accessToken||e.url&&e.url.indexOf("/negotiate?")>0)&&(t=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(e);const n=await this._innerClient.send(e);return t&&401===n.statusCode&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(e),await this._innerClient.send(e)):n}_setAuthorizationHeader(e){e.headers||(e.headers={}),this._accessToken?e.headers[HeaderNames.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[HeaderNames.Authorization]&&delete e.headers[HeaderNames.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}var HttpTransportType,TransferFormat;!function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(HttpTransportType||(HttpTransportType={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(TransferFormat||(TransferFormat={}));let AbortController$1=class{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}};class LongPollingTransport{constructor(e,t,n){this._httpClient=e,this._logger=t,this._pollAbort=new AbortController$1,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._pollAbort.aborted}async connect(e,t){if(Arg.isRequired(e,"url"),Arg.isRequired(t,"transferFormat"),Arg.isIn(t,TransferFormat,"transferFormat"),this._url=e,this._logger.log(LogLevel.Trace,"(LongPolling transport) Connecting."),t===TransferFormat.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,i]=getUserAgentHeader(),r={[n]:i,...this._options.headers},s={abortSignal:this._pollAbort.signal,headers:r,timeout:1e5,withCredentials:this._options.withCredentials};t===TransferFormat.Binary&&(s.responseType="arraybuffer");const a=`${e}&_=${Date.now()}`;this._logger.log(LogLevel.Trace,`(LongPolling transport) polling: ${a}.`);const o=await this._httpClient.get(a,s);200!==o.statusCode?(this._logger.log(LogLevel.Error,`(LongPolling transport) Unexpected response code: ${o.statusCode}.`),this._closeError=new HttpError(o.statusText||"",o.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,s)}async _poll(e,t){try{for(;this._running;)try{const n=`${e}&_=${Date.now()}`;this._logger.log(LogLevel.Trace,`(LongPolling transport) polling: ${n}.`);const i=await this._httpClient.get(n,t);204===i.statusCode?(this._logger.log(LogLevel.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==i.statusCode?(this._logger.log(LogLevel.Error,`(LongPolling transport) Unexpected response code: ${i.statusCode}.`),this._closeError=new HttpError(i.statusText||"",i.statusCode),this._running=!1):i.content?(this._logger.log(LogLevel.Trace,`(LongPolling transport) data received. ${getDataDetail(i.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(i.content)):this._logger.log(LogLevel.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof TimeoutError?this._logger.log(LogLevel.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(LogLevel.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(LogLevel.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?sendMessage(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(LogLevel.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(LogLevel.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=getUserAgentHeader();e[t]=n;const i={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};await this._httpClient.delete(this._url,i),this._logger.log(LogLevel.Trace,"(LongPolling transport) DELETE request sent.")}finally{this._logger.log(LogLevel.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(LogLevel.Trace,e),this.onclose(this._closeError)}}}class ServerSentEventsTransport{constructor(e,t,n,i){this._httpClient=e,this._accessToken=t,this._logger=n,this._options=i,this.onreceive=null,this.onclose=null}async connect(e,t){return Arg.isRequired(e,"url"),Arg.isRequired(t,"transferFormat"),Arg.isIn(t,TransferFormat,"transferFormat"),this._logger.log(LogLevel.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((n,i)=>{let r,s=!1;if(t===TransferFormat.Text){if(Platform.isBrowser||Platform.isWebWorker)r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[i,s]=getUserAgentHeader();n[i]=s,r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:{...n,...this._options.headers}})}try{r.onmessage=e=>{if(this.onreceive)try{this._logger.log(LogLevel.Trace,`(SSE transport) data received. ${getDataDetail(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},r.onerror=e=>{s?this._close():i(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this._logger.log(LogLevel.Information,`SSE connected to ${this._url}`),this._eventSource=r,s=!0,n()}}catch(e){return void i(e)}}else i(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(e){return this._eventSource?sendMessage(this._logger,"SSE",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(e){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(e))}}class WebSocketTransport{constructor(e,t,n,i,r,s){this._logger=n,this._accessTokenFactory=t,this._logMessageContent=i,this._webSocketConstructor=r,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=s}async connect(e,t){let n;return Arg.isRequired(e,"url"),Arg.isRequired(t,"transferFormat"),Arg.isIn(t,TransferFormat,"transferFormat"),this._logger.log(LogLevel.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise(((i,r)=>{let s;e=e.replace(/^http/,"ws");const a=this._httpClient.getCookieString(e);let o=!1;if(Platform.isNode||Platform.isReactNative){const t={},[i,r]=getUserAgentHeader();t[i]=r,n&&(t[HeaderNames.Authorization]=`Bearer ${n}`),a&&(t[HeaderNames.Cookie]=a),s=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else n&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);s||(s=new this._webSocketConstructor(e)),t===TransferFormat.Binary&&(s.binaryType="arraybuffer"),s.onopen=t=>{this._logger.log(LogLevel.Information,`WebSocket connected to ${e}.`),this._webSocket=s,o=!0,i()},s.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(LogLevel.Information,`(WebSockets transport) ${t}.`)},s.onmessage=e=>{if(this._logger.log(LogLevel.Trace,`(WebSockets transport) data received. ${getDataDetail(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},s.onclose=e=>{if(o)this._close(e);else{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(t))}}}))}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(LogLevel.Trace,`(WebSockets transport) sending data. ${getDataDetail(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(LogLevel.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this._isCloseEvent(e)||!1!==e.wasClean&&1e3===e.code?e instanceof Error?this.onclose(e):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)))}_isCloseEvent(e){return e&&"boolean"==typeof e.wasClean&&"number"==typeof e.code}}const MAX_REDIRECTS=100;class HttpConnection{constructor(e,t={}){if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Arg.isRequired(e,"url"),this._logger=createLogger(t.logger),this.baseUrl=this._resolveUrl(e),(t=t||{}).logMessageContent=void 0!==t.logMessageContent&&t.logMessageContent,"boolean"!=typeof t.withCredentials&&void 0!==t.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");t.withCredentials=void 0===t.withCredentials||t.withCredentials,t.timeout=void 0===t.timeout?1e5:t.timeout;let n=null,i=null;if(Platform.isNode&&"undefined"!=typeof require){const e="function"==typeof __webpack_require__?__non_webpack_require__:require;n=e("ws"),i=e("eventsource")}Platform.isNode||"undefined"==typeof WebSocket||t.WebSocket?Platform.isNode&&!t.WebSocket&&n&&(t.WebSocket=n):t.WebSocket=WebSocket,Platform.isNode||"undefined"==typeof EventSource||t.EventSource?Platform.isNode&&!t.EventSource&&void 0!==i&&(t.EventSource=i):t.EventSource=EventSource,this._httpClient=new AccessTokenHttpClient(t.httpClient||new DefaultHttpClient(this._logger),t.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||TransferFormat.Binary,Arg.isIn(e,TransferFormat,"transferFormat"),this._logger.log(LogLevel.Debug,`Starting connection with transfer format '${TransferFormat[e]}'.`),"Disconnected"!==this._connectionState)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(e),await this._startInternalPromise,"Disconnecting"===this._connectionState){const e="Failed to start the HttpConnection before stop() was called.";return this._logger.log(LogLevel.Error,e),await this._stopPromise,Promise.reject(new AbortError(e))}if("Connected"!==this._connectionState){const e="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(LogLevel.Error,e),Promise.reject(new AbortError(e))}this._connectionStarted=!0}send(e){return"Connected"!==this._connectionState?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new TransportSendQueue(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(LogLevel.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(LogLevel.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState="Disconnecting",this._stopPromise=new Promise((e=>{this._stopPromiseResolver=e})),await this._stopInternal(e),void await this._stopPromise)}async _stopInternal(e){this._stopError=e;try{await this._startInternalPromise}catch(e){}if(this.transport){try{await this.transport.stop()}catch(e){this._logger.log(LogLevel.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(LogLevel.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==HttpTransportType.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(HttpTransportType.WebSockets),await this._startTransport(t,e)}else{let n=null,i=0;do{if(n=await this._getNegotiationResponse(t),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new AbortError("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(n.url&&(t=n.url),n.accessToken){const e=n.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}i++}while(n.url&&i<MAX_REDIRECTS);if(i===MAX_REDIRECTS&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(t,this._options.transport,n,e)}this.transport instanceof LongPollingTransport&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(LogLevel.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(LogLevel.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={},[n,i]=getUserAgentHeader();t[n]=i;const r=this._resolveNegotiateUrl(e);this._logger.log(LogLevel.Debug,`Sending negotiation request: ${r}.`);try{const e=await this._httpClient.post(r,{content:"",headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(200!==e.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${e.statusCode}'`));const n=JSON.parse(e.content);return(!n.negotiateVersion||n.negotiateVersion<1)&&(n.connectionToken=n.connectionId),n}catch(e){let t="Failed to complete negotiation with the server: "+e;return e instanceof HttpError&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(LogLevel.Error,t),Promise.reject(new FailedToNegotiateWithServerError(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,t,n,i){let r=this._createConnectUrl(e,n.connectionToken);if(this._isITransport(t))return this._logger.log(LogLevel.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=t,await this._startTransport(r,i),void(this.connectionId=n.connectionId);const s=[],a=n.availableTransports||[];let o=n;for(const n of a){const a=this._resolveTransportOrError(n,t,i);if(a instanceof Error)s.push(`${n.transport} failed:`),s.push(a);else if(this._isITransport(a)){if(this.transport=a,!o){try{o=await this._getNegotiationResponse(e)}catch(e){return Promise.reject(e)}r=this._createConnectUrl(e,o.connectionToken)}try{return await this._startTransport(r,i),void(this.connectionId=o.connectionId)}catch(e){if(this._logger.log(LogLevel.Error,`Failed to start the transport '${n.transport}': ${e}`),o=void 0,s.push(new FailedToStartTransportError(`${n.transport} failed: ${e}`,HttpTransportType[n.transport])),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(LogLevel.Debug,e),Promise.reject(new AbortError(e))}}}}return s.length>0?Promise.reject(new AggregateErrors(`Unable to connect to the server with any of the available transports. ${s.join(" ")}`,s)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case HttpTransportType.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new WebSocketTransport(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case HttpTransportType.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new ServerSentEventsTransport(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case HttpTransportType.LongPolling:return new LongPollingTransport(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,t){return this.transport.onreceive=this.onreceive,this.transport.onclose=e=>this._stopConnection(e),this.transport.connect(e,t)}_resolveTransportOrError(e,t,n){const i=HttpTransportType[e.transport];if(null==i)return this._logger.log(LogLevel.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(!transportMatches(t,i))return this._logger.log(LogLevel.Debug,`Skipping transport '${HttpTransportType[i]}' because it was disabled by the client.`),new DisabledTransportError(`'${HttpTransportType[i]}' is disabled by the client.`,i);if(!(e.transferFormats.map((e=>TransferFormat[e])).indexOf(n)>=0))return this._logger.log(LogLevel.Debug,`Skipping transport '${HttpTransportType[i]}' because it does not support the requested transfer format '${TransferFormat[n]}'.`),new Error(`'${HttpTransportType[i]}' does not support ${TransferFormat[n]}.`);if(i===HttpTransportType.WebSockets&&!this._options.WebSocket||i===HttpTransportType.ServerSentEvents&&!this._options.EventSource)return this._logger.log(LogLevel.Debug,`Skipping transport '${HttpTransportType[i]}' because it is not supported in your environment.'`),new UnsupportedTransportError(`'${HttpTransportType[i]}' is not supported in your environment.`,i);this._logger.log(LogLevel.Debug,`Selecting transport '${HttpTransportType[i]}'.`);try{return this._constructTransport(i)}catch(e){return e}}_isITransport(e){return e&&"object"==typeof e&&"connect"in e}_stopConnection(e){if(this._logger.log(LogLevel.Debug,`HttpConnection.stopConnection(${e}) called while in state ${this._connectionState}.`),this.transport=void 0,e=this._stopError||e,this._stopError=void 0,"Disconnected"!==this._connectionState){if("Connecting"===this._connectionState)throw this._logger.log(LogLevel.Warning,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${e}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this._connectionState&&this._stopPromiseResolver(),e?this._logger.log(LogLevel.Error,`Connection disconnected with error '${e}'.`):this._logger.log(LogLevel.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(LogLevel.Error,`TransportSendQueue.stop() threw error '${e}'.`)})),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(e)}catch(t){this._logger.log(LogLevel.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(LogLevel.Debug,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is already in the disconnected state.`)}_resolveUrl(e){if(0===e.lastIndexOf("https://",0)||0===e.lastIndexOf("http://",0))return e;if(!Platform.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(LogLevel.Information,`Normalizing '${e}' to '${t.href}'.`),t.href}_resolveNegotiateUrl(e){const t=e.indexOf("?");let n=e.substring(0,-1===t?e.length:t);return"/"!==n[n.length-1]&&(n+="/"),n+="negotiate",n+=-1===t?"":e.substring(t),-1===n.indexOf("negotiateVersion")&&(n+=-1===t?"?":"&",n+="negotiateVersion="+this._negotiateVersion),n}}function transportMatches(e,t){return!e||0!=(t&e)}class TransportSendQueue{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new PromiseSource,this._transportResult=new PromiseSource,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new PromiseSource),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(e){if(this._buffer.length&&typeof this._buffer[0]!=typeof e)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof e}`);this._buffer.push(e),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new PromiseSource;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):TransportSendQueue._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(t),e.resolve()}catch(t){e.reject(t)}}}static _concatBuffers(e){const t=e.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),n=new Uint8Array(t);let i=0;for(const t of e)n.set(new Uint8Array(t),i),i+=t.byteLength;return n.buffer}}class PromiseSource{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}const JSON_HUB_PROTOCOL_NAME="json";class JsonHubProtocol{constructor(){this.name=JSON_HUB_PROTOCOL_NAME,this.version=1,this.transferFormat=TransferFormat.Text}parseMessages(e,t){if("string"!=typeof e)throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!e)return[];null===t&&(t=NullLogger.instance);const n=TextMessageFormat.parse(e),i=[];for(const e of n){const n=JSON.parse(e);if("number"!=typeof n.type)throw new Error("Invalid payload.");switch(n.type){case MessageType.Invocation:this._isInvocationMessage(n);break;case MessageType.StreamItem:this._isStreamItemMessage(n);break;case MessageType.Completion:this._isCompletionMessage(n);break;case MessageType.Ping:case MessageType.Close:break;default:t.log(LogLevel.Information,"Unknown message type '"+n.type+"' ignored.");continue}i.push(n)}return i}writeMessage(e){return TextMessageFormat.write(JSON.stringify(e))}_isInvocationMessage(e){this._assertNotEmptyString(e.target,"Invalid payload for Invocation message."),void 0!==e.invocationId&&this._assertNotEmptyString(e.invocationId,"Invalid payload for Invocation message.")}_isStreamItemMessage(e){if(this._assertNotEmptyString(e.invocationId,"Invalid payload for StreamItem message."),void 0===e.item)throw new Error("Invalid payload for StreamItem message.")}_isCompletionMessage(e){if(e.result&&e.error)throw new Error("Invalid payload for Completion message.");!e.result&&e.error&&this._assertNotEmptyString(e.error,"Invalid payload for Completion message."),this._assertNotEmptyString(e.invocationId,"Invalid payload for Completion message.")}_assertNotEmptyString(e,t){if("string"!=typeof e||""===e)throw new Error(t)}}const LogLevelNameMapping={trace:LogLevel.Trace,debug:LogLevel.Debug,info:LogLevel.Information,information:LogLevel.Information,warn:LogLevel.Warning,warning:LogLevel.Warning,error:LogLevel.Error,critical:LogLevel.Critical,none:LogLevel.None};function parseLogLevel(e){const t=LogLevelNameMapping[e.toLowerCase()];if(void 0!==t)return t;throw new Error(`Unknown log level: ${e}`)}class HubConnectionBuilder{configureLogging(e){if(Arg.isRequired(e,"logging"),isLogger(e))this.logger=e;else if("string"==typeof e){const t=parseLogLevel(e);this.logger=new ConsoleLogger(t)}else this.logger=new ConsoleLogger(e);return this}withUrl(e,t){return Arg.isRequired(e,"url"),Arg.isNotEmpty(e,"url"),this.url=e,this.httpConnectionOptions="object"==typeof t?{...this.httpConnectionOptions,...t}:{...this.httpConnectionOptions,transport:t},this}withHubProtocol(e){return Arg.isRequired(e,"protocol"),this.protocol=e,this}withAutomaticReconnect(e){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return e?Array.isArray(e)?this.reconnectPolicy=new DefaultReconnectPolicy(e):this.reconnectPolicy=e:this.reconnectPolicy=new DefaultReconnectPolicy,this}build(){const e=this.httpConnectionOptions||{};if(void 0===e.logger&&(e.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const t=new HttpConnection(this.url,e);return HubConnection.create(t,this.logger||NullLogger.instance,this.protocol||new JsonHubProtocol,this.reconnectPolicy)}}function isLogger(e){return void 0!==e.log}class WeavyClient{constructor(e){this.groups=[],this.connectionEvents=[],this.signalRAccessTokenRefresh=!1,this.token="",this.EVENT_NAMESPACE=".connection",this.EVENT_CLOSE="close",this.EVENT_RECONNECTING="reconnecting",this.EVENT_RECONNECTED="reconnected",this.url=e.url,this.tokenFactory=e.tokenFactory,this.tokenPromise=null,this.connection=(new HubConnectionBuilder).configureLogging(LogLevel.None).withUrl(this.url+"/hubs/rtm",{accessTokenFactory:async()=>{if(this.signalRAccessTokenRefresh){console.error("SignalR retrying with refreshed token.");const e=await this.tokenFactoryInternal(!0);return this.signalRAccessTokenRefresh=!1,e}return await this.tokenFactoryInternal()}}).withAutomaticReconnect().build(),this.connect(),this.connection.onclose((e=>this.triggerHandler(this.EVENT_CLOSE,e))),this.connection.onreconnecting((e=>this.triggerHandler(this.EVENT_RECONNECTING,e))),this.connection.onreconnected((e=>this.triggerHandler(this.EVENT_RECONNECTED,e)))}async connect(){try{this.isConnectionStarted=this.connection.start(),await this.isConnectionStarted}catch(e){console.log("Could not start SignalR."),this.signalRAccessTokenRefresh||(this.signalRAccessTokenRefresh=!0,this.isConnectionStarted=this.connection.start(),await this.isConnectionStarted)}this.signalRAccessTokenRefresh=!1,console.log("SignalR connected.")}async get(e,t=!0){const n=await fetch(this.url+e,{headers:{"content-type":"application/json",Authorization:"Bearer "+await this.tokenFactoryInternal()}});if(!n.ok){if((401===n.status||403===n.status)&&t)return await this.tokenFactoryInternal(!0),await this.get(e,!1);console.error(`Error calling endpoint ${e}`,n)}return n}async post(e,t,n,i="application/json",r=!0){let s={Authorization:"Bearer "+await this.tokenFactoryInternal()};""!==i&&(s["content-type"]=i);const a=await fetch(this.url+e,{method:t,body:n,headers:s});return a.ok||401!==a.status&&403!==a.status||!r?a:(await this.tokenFactoryInternal(!0),await this.post(e,t,n,i,!1))}async upload(e,t,n,i="application/json",r,s=!0){const a=this,o=await a.tokenFactoryInternal();return await new Promise((function(l,c){let d=new XMLHttpRequest;d.open(t,a.url+e,!0),d.setRequestHeader("Authorization","Bearer "+o),""!==i&&d.setRequestHeader("content-type",i),r&&d.upload.addEventListener("progress",(e=>{r(e.loaded/e.total*100||100)})),d.onload=o=>{!s||401!==d.status&&401!==d.status?l(new Response(d.response,{status:d.status,statusText:d.statusText})):a.tokenFactoryInternal(!0).then((()=>a.upload(e,t,n,i,r,!1))).then(l).catch(c)},d.onerror=c,d.send(n)}))}async getToken(e){return this.token&&!e||(this.token=await this.tokenFactory(!0)),this.token}async tokenFactoryInternal(e=!1){if(this.token&&!e)return this.token;if(this.tokenPromise)return this.tokenPromise;{this.tokenPromise=this.tokenFactory(e);let t=await this.tokenPromise;return this.tokenPromise=null,this.token=t,this.token}}async subscribe(e,t,n){await this.isConnectionStarted;try{var i=e?e+":"+t:t;await this.connection.invoke("Subscribe",i),this.groups.push(i),this.connection.on(i,n)}catch(e){console.warn("Error in Subscribe:",e)}}async unsubscribe(e,t,n){await this.isConnectionStarted;var i=e?e+":"+t:t;const r=this.groups.findIndex((e=>e===i));if(-1!==r){this.groups=this.groups.splice(r,1);try{this.groups.find((e=>e===i))||await this.connection.invoke("Unsubscribe",i)}catch(e){console.warn("Error in Unsubscribe:",e)}}this.connection.off(i,n)}destroy(){this.connection.stop()}triggerHandler(e,...t){e=e.endsWith(this.EVENT_NAMESPACE)?e:e+this.EVENT_NAMESPACE;let n=new CustomEvent(e,{cancelable:!1});if(console.debug("triggerHandler",e),this.connectionEvents.forEach((i=>{i.name===e&&i.handler(n,...t)})),e===this.EVENT_RECONNECTED+this.EVENT_NAMESPACE)for(var i=0;i<this.groups.length;i++)this.connection.invoke("Subscribe",this.groups[i])}}function _setPrototypeOf(e,t){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},_setPrototypeOf(e,t)}function _inheritsLoose(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,_setPrototypeOf(e,t)}var Subscribable=function(){function e(){this.listeners=[]}var t=e.prototype;return t.subscribe=function(e){var t=this,n=e||function(){};return this.listeners.push(n),this.onSubscribe(),function(){t.listeners=t.listeners.filter((function(e){return e!==n})),t.onUnsubscribe()}},t.hasListeners=function(){return this.listeners.length>0},t.onSubscribe=function(){},t.onUnsubscribe=function(){},e}();function _extends$1(){return _extends$1=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},_extends$1.apply(this,arguments)}var isServer="undefined"==typeof window;function noop$1(){}function functionalUpdate(e,t){return"function"==typeof e?e(t):e}function isValidTimeout(e){return"number"==typeof e&&e>=0&&e!==1/0}function ensureQueryKeyArray(e){return Array.isArray(e)?e:[e]}function timeUntilStale(e,t){return Math.max(e+(t||0)-Date.now(),0)}function parseQueryArgs(e,t,n){return isQueryKey(e)?"function"==typeof t?_extends$1({},n,{queryKey:e,queryFn:t}):_extends$1({},t,{queryKey:e}):e}function parseMutationArgs(e,t,n){return isQueryKey(e)?"function"==typeof t?_extends$1({},n,{mutationKey:e,mutationFn:t}):_extends$1({},t,{mutationKey:e}):"function"==typeof e?_extends$1({},t,{mutationFn:e}):_extends$1({},e)}function parseFilterArgs(e,t,n){return isQueryKey(e)?[_extends$1({},t,{queryKey:e}),n]:[e||{},t]}function mapQueryStatusFilter(e,t){return!0===e&&!0===t||null==e&&null==t?"all":!1===e&&!1===t?"none":(null!=e?e:!t)?"active":"inactive"}function matchQuery(e,t){var n=e.active,i=e.exact,r=e.fetching,s=e.inactive,a=e.predicate,o=e.queryKey,l=e.stale;if(isQueryKey(o))if(i){if(t.queryHash!==hashQueryKeyByOptions(o,t.options))return!1}else if(!partialMatchKey(t.queryKey,o))return!1;var c=mapQueryStatusFilter(n,s);if("none"===c)return!1;if("all"!==c){var d=t.isActive();if("active"===c&&!d)return!1;if("inactive"===c&&d)return!1}return("boolean"!=typeof l||t.isStale()===l)&&(("boolean"!=typeof r||t.isFetching()===r)&&!(a&&!a(t)))}function matchMutation(e,t){var n=e.exact,i=e.fetching,r=e.predicate,s=e.mutationKey;if(isQueryKey(s)){if(!t.options.mutationKey)return!1;if(n){if(hashQueryKey(t.options.mutationKey)!==hashQueryKey(s))return!1}else if(!partialMatchKey(t.options.mutationKey,s))return!1}return("boolean"!=typeof i||"loading"===t.state.status===i)&&!(r&&!r(t))}function hashQueryKeyByOptions(e,t){return((null==t?void 0:t.queryKeyHashFn)||hashQueryKey)(e)}function hashQueryKey(e){return stableValueHash(ensureQueryKeyArray(e))}function stableValueHash(e){return JSON.stringify(e,(function(e,t){return isPlainObject$1(t)?Object.keys(t).sort().reduce((function(e,n){return e[n]=t[n],e}),{}):t}))}function partialMatchKey(e,t){return partialDeepEqual(ensureQueryKeyArray(e),ensureQueryKeyArray(t))}function partialDeepEqual(e,t){return e===t||typeof e==typeof t&&(!(!e||!t||"object"!=typeof e||"object"!=typeof t)&&!Object.keys(t).some((function(n){return!partialDeepEqual(e[n],t[n])})))}function replaceEqualDeep(e,t){if(e===t)return e;var n=Array.isArray(e)&&Array.isArray(t);if(n||isPlainObject$1(e)&&isPlainObject$1(t)){for(var i=n?e.length:Object.keys(e).length,r=n?t:Object.keys(t),s=r.length,a=n?[]:{},o=0,l=0;l<s;l++){var c=n?l:r[l];a[c]=replaceEqualDeep(e[c],t[c]),a[c]===e[c]&&o++}return i===s&&o===i?e:a}return t}function shallowEqualObjects(e,t){if(e&&!t||t&&!e)return!1;for(var n in e)if(e[n]!==t[n])return!1;return!0}function isPlainObject$1(e){if(!hasObjectPrototype(e))return!1;var t=e.constructor;if(void 0===t)return!0;var n=t.prototype;return!!hasObjectPrototype(n)&&!!n.hasOwnProperty("isPrototypeOf")}function hasObjectPrototype(e){return"[object Object]"===Object.prototype.toString.call(e)}function isQueryKey(e){return"string"==typeof e||Array.isArray(e)}function sleep(e){return new Promise((function(t){setTimeout(t,e)}))}function scheduleMicrotask(e){Promise.resolve().then(e).catch((function(e){return setTimeout((function(){throw e}))}))}function getAbortController(){if("function"==typeof AbortController)return new AbortController}var FocusManager=function(e){function t(){var t;return(t=e.call(this)||this).setup=function(e){var t;if(!isServer&&(null==(t=window)?void 0:t.addEventListener)){var n=function(){return e()};return window.addEventListener("visibilitychange",n,!1),window.addEventListener("focus",n,!1),function(){window.removeEventListener("visibilitychange",n),window.removeEventListener("focus",n)}}},t}_inheritsLoose(t,e);var n=t.prototype;return n.onSubscribe=function(){this.cleanup||this.setEventListener(this.setup)},n.onUnsubscribe=function(){var e;this.hasListeners()||(null==(e=this.cleanup)||e.call(this),this.cleanup=void 0)},n.setEventListener=function(e){var t,n=this;this.setup=e,null==(t=this.cleanup)||t.call(this),this.cleanup=e((function(e){"boolean"==typeof e?n.setFocused(e):n.onFocus()}))},n.setFocused=function(e){this.focused=e,e&&this.onFocus()},n.onFocus=function(){this.listeners.forEach((function(e){e()}))},n.isFocused=function(){return"boolean"==typeof this.focused?this.focused:"undefined"==typeof document||[void 0,"visible","prerender"].includes(document.visibilityState)},t}(Subscribable),focusManager$1=new FocusManager,OnlineManager=function(e){function t(){var t;return(t=e.call(this)||this).setup=function(e){var t;if(!isServer&&(null==(t=window)?void 0:t.addEventListener)){var n=function(){return e()};return window.addEventListener("online",n,!1),window.addEventListener("offline",n,!1),function(){window.removeEventListener("online",n),window.removeEventListener("offline",n)}}},t}_inheritsLoose(t,e);var n=t.prototype;return n.onSubscribe=function(){this.cleanup||this.setEventListener(this.setup)},n.onUnsubscribe=function(){var e;this.hasListeners()||(null==(e=this.cleanup)||e.call(this),this.cleanup=void 0)},n.setEventListener=function(e){var t,n=this;this.setup=e,null==(t=this.cleanup)||t.call(this),this.cleanup=e((function(e){"boolean"==typeof e?n.setOnline(e):n.onOnline()}))},n.setOnline=function(e){this.online=e,e&&this.onOnline()},n.onOnline=function(){this.listeners.forEach((function(e){e()}))},n.isOnline=function(){return"boolean"==typeof this.online?this.online:"undefined"==typeof navigator||void 0===navigator.onLine||navigator.onLine},t}(Subscribable),onlineManager=new OnlineManager;function defaultRetryDelay(e){return Math.min(1e3*Math.pow(2,e),3e4)}function isCancelable(e){return"function"==typeof(null==e?void 0:e.cancel)}var CancelledError=function(e){this.revert=null==e?void 0:e.revert,this.silent=null==e?void 0:e.silent};function isCancelledError(e){return e instanceof CancelledError}var Retryer=function(e){var t,n,i,r,s=this,a=!1;this.abort=e.abort,this.cancel=function(e){return null==t?void 0:t(e)},this.cancelRetry=function(){a=!0},this.continueRetry=function(){a=!1},this.continue=function(){return null==n?void 0:n()},this.failureCount=0,this.isPaused=!1,this.isResolved=!1,this.isTransportCancelable=!1,this.promise=new Promise((function(e,t){i=e,r=t}));var o=function(t){s.isResolved||(s.isResolved=!0,null==e.onSuccess||e.onSuccess(t),null==n||n(),i(t))},l=function(t){s.isResolved||(s.isResolved=!0,null==e.onError||e.onError(t),null==n||n(),r(t))};!function i(){if(!s.isResolved){var r;try{r=e.fn()}catch(e){r=Promise.reject(e)}t=function(e){if(!s.isResolved&&(l(new CancelledError(e)),null==s.abort||s.abort(),isCancelable(r)))try{r.cancel()}catch(e){}},s.isTransportCancelable=isCancelable(r),Promise.resolve(r).then(o).catch((function(t){var r,o;if(!s.isResolved){var c=null!=(r=e.retry)?r:3,d=null!=(o=e.retryDelay)?o:defaultRetryDelay,u="function"==typeof d?d(s.failureCount,t):d,h=!0===c||"number"==typeof c&&s.failureCount<c||"function"==typeof c&&c(s.failureCount,t);!a&&h?(s.failureCount++,null==e.onFail||e.onFail(s.failureCount,t),sleep(u).then((function(){if(!focusManager$1.isFocused()||!onlineManager.isOnline())return new Promise((function(t){n=t,s.isPaused=!0,null==e.onPause||e.onPause()})).then((function(){n=void 0,s.isPaused=!1,null==e.onContinue||e.onContinue()}))})).then((function(){a?l(t):i()}))):l(t)}}))}}()},NotifyManager=function(){function e(){this.queue=[],this.transactions=0,this.notifyFn=function(e){e()},this.batchNotifyFn=function(e){e()}}var t=e.prototype;return t.batch=function(e){var t;this.transactions++;try{t=e()}finally{this.transactions--,this.transactions||this.flush()}return t},t.schedule=function(e){var t=this;this.transactions?this.queue.push(e):scheduleMicrotask((function(){t.notifyFn(e)}))},t.batchCalls=function(e){var t=this;return function(){for(var n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];t.schedule((function(){e.apply(void 0,i)}))}},t.flush=function(){var e=this,t=this.queue;this.queue=[],t.length&&scheduleMicrotask((function(){e.batchNotifyFn((function(){t.forEach((function(t){e.notifyFn(t)}))}))}))},t.setNotifyFunction=function(e){this.notifyFn=e},t.setBatchNotifyFunction=function(e){this.batchNotifyFn=e},e}(),notifyManager=new NotifyManager,logger$1=console;function getLogger(){return logger$1}function setLogger(e){logger$1=e}var Query=function(){function e(e){this.abortSignalConsumed=!1,this.hadObservers=!1,this.defaultOptions=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.cache=e.cache,this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.initialState=e.state||this.getDefaultState(this.options),this.state=this.initialState,this.meta=e.meta,this.scheduleGc()}var t=e.prototype;return t.setOptions=function(e){var t;this.options=_extends$1({},this.defaultOptions,e),this.meta=null==e?void 0:e.meta,this.cacheTime=Math.max(this.cacheTime||0,null!=(t=this.options.cacheTime)?t:3e5)},t.setDefaultOptions=function(e){this.defaultOptions=e},t.scheduleGc=function(){var e=this;this.clearGcTimeout(),isValidTimeout(this.cacheTime)&&(this.gcTimeout=setTimeout((function(){e.optionalRemove()}),this.cacheTime))},t.clearGcTimeout=function(){this.gcTimeout&&(clearTimeout(this.gcTimeout),this.gcTimeout=void 0)},t.optionalRemove=function(){this.observers.length||(this.state.isFetching?this.hadObservers&&this.scheduleGc():this.cache.remove(this))},t.setData=function(e,t){var n,i,r=this.state.data,s=functionalUpdate(e,r);return(null==(n=(i=this.options).isDataEqual)?void 0:n.call(i,r,s))?s=r:!1!==this.options.structuralSharing&&(s=replaceEqualDeep(r,s)),this.dispatch({data:s,type:"success",dataUpdatedAt:null==t?void 0:t.updatedAt}),s},t.setState=function(e,t){this.dispatch({type:"setState",state:e,setStateOptions:t})},t.cancel=function(e){var t,n=this.promise;return null==(t=this.retryer)||t.cancel(e),n?n.then(noop$1).catch(noop$1):Promise.resolve()},t.destroy=function(){this.clearGcTimeout(),this.cancel({silent:!0})},t.reset=function(){this.destroy(),this.setState(this.initialState)},t.isActive=function(){return this.observers.some((function(e){return!1!==e.options.enabled}))},t.isFetching=function(){return this.state.isFetching},t.isStale=function(){return this.state.isInvalidated||!this.state.dataUpdatedAt||this.observers.some((function(e){return e.getCurrentResult().isStale}))},t.isStaleByTime=function(e){return void 0===e&&(e=0),this.state.isInvalidated||!this.state.dataUpdatedAt||!timeUntilStale(this.state.dataUpdatedAt,e)},t.onFocus=function(){var e,t=this.observers.find((function(e){return e.shouldFetchOnWindowFocus()}));t&&t.refetch(),null==(e=this.retryer)||e.continue()},t.onOnline=function(){var e,t=this.observers.find((function(e){return e.shouldFetchOnReconnect()}));t&&t.refetch(),null==(e=this.retryer)||e.continue()},t.addObserver=function(e){-1===this.observers.indexOf(e)&&(this.observers.push(e),this.hadObservers=!0,this.clearGcTimeout(),this.cache.notify({type:"observerAdded",query:this,observer:e}))},t.removeObserver=function(e){-1!==this.observers.indexOf(e)&&(this.observers=this.observers.filter((function(t){return t!==e})),this.observers.length||(this.retryer&&(this.retryer.isTransportCancelable||this.abortSignalConsumed?this.retryer.cancel({revert:!0}):this.retryer.cancelRetry()),this.cacheTime?this.scheduleGc():this.cache.remove(this)),this.cache.notify({type:"observerRemoved",query:this,observer:e}))},t.getObserversCount=function(){return this.observers.length},t.invalidate=function(){this.state.isInvalidated||this.dispatch({type:"invalidate"})},t.fetch=function(e,t){var n,i,r,s=this;if(this.state.isFetching)if(this.state.dataUpdatedAt&&(null==t?void 0:t.cancelRefetch))this.cancel({silent:!0});else if(this.promise){var a;return null==(a=this.retryer)||a.continueRetry(),this.promise}if(e&&this.setOptions(e),!this.options.queryFn){var o=this.observers.find((function(e){return e.options.queryFn}));o&&this.setOptions(o.options)}var l=ensureQueryKeyArray(this.queryKey),c=getAbortController(),d={queryKey:l,pageParam:void 0,meta:this.meta};Object.defineProperty(d,"signal",{enumerable:!0,get:function(){if(c)return s.abortSignalConsumed=!0,c.signal}});var u,h,p={fetchOptions:t,options:this.options,queryKey:l,state:this.state,fetchFn:function(){return s.options.queryFn?(s.abortSignalConsumed=!1,s.options.queryFn(d)):Promise.reject("Missing queryFn")},meta:this.meta};(null==(n=this.options.behavior)?void 0:n.onFetch)&&(null==(u=this.options.behavior)||u.onFetch(p));(this.revertState=this.state,this.state.isFetching&&this.state.fetchMeta===(null==(i=p.fetchOptions)?void 0:i.meta))||this.dispatch({type:"fetch",meta:null==(h=p.fetchOptions)?void 0:h.meta});return this.retryer=new Retryer({fn:p.fetchFn,abort:null==c||null==(r=c.abort)?void 0:r.bind(c),onSuccess:function(e){s.setData(e),null==s.cache.config.onSuccess||s.cache.config.onSuccess(e,s),0===s.cacheTime&&s.optionalRemove()},onError:function(e){isCancelledError(e)&&e.silent||s.dispatch({type:"error",error:e}),isCancelledError(e)||(null==s.cache.config.onError||s.cache.config.onError(e,s),getLogger().error(e)),0===s.cacheTime&&s.optionalRemove()},onFail:function(){s.dispatch({type:"failed"})},onPause:function(){s.dispatch({type:"pause"})},onContinue:function(){s.dispatch({type:"continue"})},retry:p.options.retry,retryDelay:p.options.retryDelay}),this.promise=this.retryer.promise,this.promise},t.dispatch=function(e){var t=this;this.state=this.reducer(this.state,e),notifyManager.batch((function(){t.observers.forEach((function(t){t.onQueryUpdate(e)})),t.cache.notify({query:t,type:"queryUpdated",action:e})}))},t.getDefaultState=function(e){var t="function"==typeof e.initialData?e.initialData():e.initialData,n=void 0!==e.initialData?"function"==typeof e.initialDataUpdatedAt?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0,i=void 0!==t;return{data:t,dataUpdateCount:0,dataUpdatedAt:i?null!=n?n:Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchMeta:null,isFetching:!1,isInvalidated:!1,isPaused:!1,status:i?"success":"idle"}},t.reducer=function(e,t){var n,i;switch(t.type){case"failed":return _extends$1({},e,{fetchFailureCount:e.fetchFailureCount+1});case"pause":return _extends$1({},e,{isPaused:!0});case"continue":return _extends$1({},e,{isPaused:!1});case"fetch":return _extends$1({},e,{fetchFailureCount:0,fetchMeta:null!=(n=t.meta)?n:null,isFetching:!0,isPaused:!1},!e.dataUpdatedAt&&{error:null,status:"loading"});case"success":return _extends$1({},e,{data:t.data,dataUpdateCount:e.dataUpdateCount+1,dataUpdatedAt:null!=(i=t.dataUpdatedAt)?i:Date.now(),error:null,fetchFailureCount:0,isFetching:!1,isInvalidated:!1,isPaused:!1,status:"success"});case"error":var r=t.error;return isCancelledError(r)&&r.revert&&this.revertState?_extends$1({},this.revertState):_extends$1({},e,{error:r,errorUpdateCount:e.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:e.fetchFailureCount+1,isFetching:!1,isPaused:!1,status:"error"});case"invalidate":return _extends$1({},e,{isInvalidated:!0});case"setState":return _extends$1({},e,t.state);default:return e}},e}(),QueryCache=function(e){function t(t){var n;return(n=e.call(this)||this).config=t||{},n.queries=[],n.queriesMap={},n}_inheritsLoose(t,e);var n=t.prototype;return n.build=function(e,t,n){var i,r=t.queryKey,s=null!=(i=t.queryHash)?i:hashQueryKeyByOptions(r,t),a=this.get(s);return a||(a=new Query({cache:this,queryKey:r,queryHash:s,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r),meta:t.meta}),this.add(a)),a},n.add=function(e){this.queriesMap[e.queryHash]||(this.queriesMap[e.queryHash]=e,this.queries.push(e),this.notify({type:"queryAdded",query:e}))},n.remove=function(e){var t=this.queriesMap[e.queryHash];t&&(e.destroy(),this.queries=this.queries.filter((function(t){return t!==e})),t===e&&delete this.queriesMap[e.queryHash],this.notify({type:"queryRemoved",query:e}))},n.clear=function(){var e=this;notifyManager.batch((function(){e.queries.forEach((function(t){e.remove(t)}))}))},n.get=function(e){return this.queriesMap[e]},n.getAll=function(){return this.queries},n.find=function(e,t){var n=parseFilterArgs(e,t)[0];return void 0===n.exact&&(n.exact=!0),this.queries.find((function(e){return matchQuery(n,e)}))},n.findAll=function(e,t){var n=parseFilterArgs(e,t)[0];return Object.keys(n).length>0?this.queries.filter((function(e){return matchQuery(n,e)})):this.queries},n.notify=function(e){var t=this;notifyManager.batch((function(){t.listeners.forEach((function(t){t(e)}))}))},n.onFocus=function(){var e=this;notifyManager.batch((function(){e.queries.forEach((function(e){e.onFocus()}))}))},n.onOnline=function(){var e=this;notifyManager.batch((function(){e.queries.forEach((function(e){e.onOnline()}))}))},t}(Subscribable),Mutation=function(){function e(e){this.options=_extends$1({},e.defaultOptions,e.options),this.mutationId=e.mutationId,this.mutationCache=e.mutationCache,this.observers=[],this.state=e.state||getDefaultState(),this.meta=e.meta}var t=e.prototype;return t.setState=function(e){this.dispatch({type:"setState",state:e})},t.addObserver=function(e){-1===this.observers.indexOf(e)&&this.observers.push(e)},t.removeObserver=function(e){this.observers=this.observers.filter((function(t){return t!==e}))},t.cancel=function(){return this.retryer?(this.retryer.cancel(),this.retryer.promise.then(noop$1).catch(noop$1)):Promise.resolve()},t.continue=function(){return this.retryer?(this.retryer.continue(),this.retryer.promise):this.execute()},t.execute=function(){var e,t=this,n="loading"===this.state.status,i=Promise.resolve();return n||(this.dispatch({type:"loading",variables:this.options.variables}),i=i.then((function(){null==t.mutationCache.config.onMutate||t.mutationCache.config.onMutate(t.state.variables,t)})).then((function(){return null==t.options.onMutate?void 0:t.options.onMutate(t.state.variables)})).then((function(e){e!==t.state.context&&t.dispatch({type:"loading",context:e,variables:t.state.variables})}))),i.then((function(){return t.executeMutation()})).then((function(n){e=n,null==t.mutationCache.config.onSuccess||t.mutationCache.config.onSuccess(e,t.state.variables,t.state.context,t)})).then((function(){return null==t.options.onSuccess?void 0:t.options.onSuccess(e,t.state.variables,t.state.context)})).then((function(){return null==t.options.onSettled?void 0:t.options.onSettled(e,null,t.state.variables,t.state.context)})).then((function(){return t.dispatch({type:"success",data:e}),e})).catch((function(e){return null==t.mutationCache.config.onError||t.mutationCache.config.onError(e,t.state.variables,t.state.context,t),getLogger().error(e),Promise.resolve().then((function(){return null==t.options.onError?void 0:t.options.onError(e,t.state.variables,t.state.context)})).then((function(){return null==t.options.onSettled?void 0:t.options.onSettled(void 0,e,t.state.variables,t.state.context)})).then((function(){throw t.dispatch({type:"error",error:e}),e}))}))},t.executeMutation=function(){var e,t=this;return this.retryer=new Retryer({fn:function(){return t.options.mutationFn?t.options.mutationFn(t.state.variables):Promise.reject("No mutationFn found")},onFail:function(){t.dispatch({type:"failed"})},onPause:function(){t.dispatch({type:"pause"})},onContinue:function(){t.dispatch({type:"continue"})},retry:null!=(e=this.options.retry)?e:0,retryDelay:this.options.retryDelay}),this.retryer.promise},t.dispatch=function(e){var t=this;this.state=reducer$1(this.state,e),notifyManager.batch((function(){t.observers.forEach((function(t){t.onMutationUpdate(e)})),t.mutationCache.notify(t)}))},e}();function getDefaultState(){return{context:void 0,data:void 0,error:null,failureCount:0,isPaused:!1,status:"idle",variables:void 0}}function reducer$1(e,t){switch(t.type){case"failed":return _extends$1({},e,{failureCount:e.failureCount+1});case"pause":return _extends$1({},e,{isPaused:!0});case"continue":return _extends$1({},e,{isPaused:!1});case"loading":return _extends$1({},e,{context:t.context,data:void 0,error:null,isPaused:!1,status:"loading",variables:t.variables});case"success":return _extends$1({},e,{data:t.data,error:null,status:"success",isPaused:!1});case"error":return _extends$1({},e,{data:void 0,error:t.error,failureCount:e.failureCount+1,isPaused:!1,status:"error"});case"setState":return _extends$1({},e,t.state);default:return e}}var MutationCache=function(e){function t(t){var n;return(n=e.call(this)||this).config=t||{},n.mutations=[],n.mutationId=0,n}_inheritsLoose(t,e);var n=t.prototype;return n.build=function(e,t,n){var i=new Mutation({mutationCache:this,mutationId:++this.mutationId,options:e.defaultMutationOptions(t),state:n,defaultOptions:t.mutationKey?e.getMutationDefaults(t.mutationKey):void 0,meta:t.meta});return this.add(i),i},n.add=function(e){this.mutations.push(e),this.notify(e)},n.remove=function(e){this.mutations=this.mutations.filter((function(t){return t!==e})),e.cancel(),this.notify(e)},n.clear=function(){var e=this;notifyManager.batch((function(){e.mutations.forEach((function(t){e.remove(t)}))}))},n.getAll=function(){return this.mutations},n.find=function(e){return void 0===e.exact&&(e.exact=!0),this.mutations.find((function(t){return matchMutation(e,t)}))},n.findAll=function(e){return this.mutations.filter((function(t){return matchMutation(e,t)}))},n.notify=function(e){var t=this;notifyManager.batch((function(){t.listeners.forEach((function(t){t(e)}))}))},n.onFocus=function(){this.resumePausedMutations()},n.onOnline=function(){this.resumePausedMutations()},n.resumePausedMutations=function(){var e=this.mutations.filter((function(e){return e.state.isPaused}));return notifyManager.batch((function(){return e.reduce((function(e,t){return e.then((function(){return t.continue().catch(noop$1)}))}),Promise.resolve())}))},t}(Subscribable);function infiniteQueryBehavior(){return{onFetch:function(e){e.fetchFn=function(){var t,n,i,r,s,a,o,l=null==(t=e.fetchOptions)||null==(n=t.meta)?void 0:n.refetchPage,c=null==(i=e.fetchOptions)||null==(r=i.meta)?void 0:r.fetchMore,d=null==c?void 0:c.pageParam,u="forward"===(null==c?void 0:c.direction),h="backward"===(null==c?void 0:c.direction),p=(null==(s=e.state.data)?void 0:s.pages)||[],f=(null==(a=e.state.data)?void 0:a.pageParams)||[],m=getAbortController(),g=null==m?void 0:m.signal,O=f,y=!1,v=e.options.queryFn||function(){return Promise.reject("Missing queryFn")},b=function(e,t,n,i){return O=i?[t].concat(O):[].concat(O,[t]),i?[n].concat(e):[].concat(e,[n])},_=function(t,n,i,r){if(y)return Promise.reject("Cancelled");if(void 0===i&&!n&&t.length)return Promise.resolve(t);var s={queryKey:e.queryKey,signal:g,pageParam:i,meta:e.meta},a=v(s),o=Promise.resolve(a).then((function(e){return b(t,i,e,r)}));isCancelable(a)&&(o.cancel=a.cancel);return o};if(p.length)if(u){var S=void 0!==d,w=S?d:getNextPageParam(e.options,p);o=_(p,S,w)}else if(h){var x=void 0!==d,C=x?d:getPreviousPageParam(e.options,p);o=_(p,x,C,!0)}else!function(){O=[];var t=void 0===e.options.getNextPageParam,n=!l||!p[0]||l(p[0],0,p);o=n?_([],t,f[0]):Promise.resolve(b([],f[0],p[0]));for(var i=function(n){o=o.then((function(i){if(!l||!p[n]||l(p[n],n,p)){var r=t?f[n]:getNextPageParam(e.options,i);return _(i,t,r)}return Promise.resolve(b(i,f[n],p[n]))}))},r=1;r<p.length;r++)i(r)}();else o=_([]);var P=o.then((function(e){return{pages:e,pageParams:O}}));return P.cancel=function(){y=!0,null==m||m.abort(),isCancelable(o)&&o.cancel()},P}}}}function getNextPageParam(e,t){return null==e.getNextPageParam?void 0:e.getNextPageParam(t[t.length-1],t)}function getPreviousPageParam(e,t){return null==e.getPreviousPageParam?void 0:e.getPreviousPageParam(t[0],t)}function hasNextPage(e,t){if(e.getNextPageParam&&Array.isArray(t)){var n=getNextPageParam(e,t);return null!=n&&!1!==n}}function hasPreviousPage(e,t){if(e.getPreviousPageParam&&Array.isArray(t)){var n=getPreviousPageParam(e,t);return null!=n&&!1!==n}}var QueryClient=function(){function e(e){void 0===e&&(e={}),this.queryCache=e.queryCache||new QueryCache,this.mutationCache=e.mutationCache||new MutationCache,this.defaultOptions=e.defaultOptions||{},this.queryDefaults=[],this.mutationDefaults=[]}var t=e.prototype;return t.mount=function(){var e=this;this.unsubscribeFocus=focusManager$1.subscribe((function(){focusManager$1.isFocused()&&onlineManager.isOnline()&&(e.mutationCache.onFocus(),e.queryCache.onFocus())})),this.unsubscribeOnline=onlineManager.subscribe((function(){focusManager$1.isFocused()&&onlineManager.isOnline()&&(e.mutationCache.onOnline(),e.queryCache.onOnline())}))},t.unmount=function(){var e,t;null==(e=this.unsubscribeFocus)||e.call(this),null==(t=this.unsubscribeOnline)||t.call(this)},t.isFetching=function(e,t){var n=parseFilterArgs(e,t)[0];return n.fetching=!0,this.queryCache.findAll(n).length},t.isMutating=function(e){return this.mutationCache.findAll(_extends$1({},e,{fetching:!0})).length},t.getQueryData=function(e,t){var n;return null==(n=this.queryCache.find(e,t))?void 0:n.state.data},t.getQueriesData=function(e){return this.getQueryCache().findAll(e).map((function(e){return[e.queryKey,e.state.data]}))},t.setQueryData=function(e,t,n){var i=parseQueryArgs(e),r=this.defaultQueryOptions(i);return this.queryCache.build(this,r).setData(t,n)},t.setQueriesData=function(e,t,n){var i=this;return notifyManager.batch((function(){return i.getQueryCache().findAll(e).map((function(e){var r=e.queryKey;return[r,i.setQueryData(r,t,n)]}))}))},t.getQueryState=function(e,t){var n;return null==(n=this.queryCache.find(e,t))?void 0:n.state},t.removeQueries=function(e,t){var n=parseFilterArgs(e,t)[0],i=this.queryCache;notifyManager.batch((function(){i.findAll(n).forEach((function(e){i.remove(e)}))}))},t.resetQueries=function(e,t,n){var i=this,r=parseFilterArgs(e,t,n),s=r[0],a=r[1],o=this.queryCache,l=_extends$1({},s,{active:!0});return notifyManager.batch((function(){return o.findAll(s).forEach((function(e){e.reset()})),i.refetchQueries(l,a)}))},t.cancelQueries=function(e,t,n){var i=this,r=parseFilterArgs(e,t,n),s=r[0],a=r[1],o=void 0===a?{}:a;void 0===o.revert&&(o.revert=!0);var l=notifyManager.batch((function(){return i.queryCache.findAll(s).map((function(e){return e.cancel(o)}))}));return Promise.all(l).then(noop$1).catch(noop$1)},t.invalidateQueries=function(e,t,n){var i,r,s,a=this,o=parseFilterArgs(e,t,n),l=o[0],c=o[1],d=_extends$1({},l,{active:null==(i=null!=(r=l.refetchActive)?r:l.active)||i,inactive:null!=(s=l.refetchInactive)&&s});return notifyManager.batch((function(){return a.queryCache.findAll(l).forEach((function(e){e.invalidate()})),a.refetchQueries(d,c)}))},t.refetchQueries=function(e,t,n){var i=this,r=parseFilterArgs(e,t,n),s=r[0],a=r[1],o=notifyManager.batch((function(){return i.queryCache.findAll(s).map((function(e){return e.fetch(void 0,_extends$1({},a,{meta:{refetchPage:null==s?void 0:s.refetchPage}}))}))})),l=Promise.all(o).then(noop$1);return(null==a?void 0:a.throwOnError)||(l=l.catch(noop$1)),l},t.fetchQuery=function(e,t,n){var i=parseQueryArgs(e,t,n),r=this.defaultQueryOptions(i);void 0===r.retry&&(r.retry=!1);var s=this.queryCache.build(this,r);return s.isStaleByTime(r.staleTime)?s.fetch(r):Promise.resolve(s.state.data)},t.prefetchQuery=function(e,t,n){return this.fetchQuery(e,t,n).then(noop$1).catch(noop$1)},t.fetchInfiniteQuery=function(e,t,n){var i=parseQueryArgs(e,t,n);return i.behavior=infiniteQueryBehavior(),this.fetchQuery(i)},t.prefetchInfiniteQuery=function(e,t,n){return this.fetchInfiniteQuery(e,t,n).then(noop$1).catch(noop$1)},t.cancelMutations=function(){var e=this,t=notifyManager.batch((function(){return e.mutationCache.getAll().map((function(e){return e.cancel()}))}));return Promise.all(t).then(noop$1).catch(noop$1)},t.resumePausedMutations=function(){return this.getMutationCache().resumePausedMutations()},t.executeMutation=function(e){return this.mutationCache.build(this,e).execute()},t.getQueryCache=function(){return this.queryCache},t.getMutationCache=function(){return this.mutationCache},t.getDefaultOptions=function(){return this.defaultOptions},t.setDefaultOptions=function(e){this.defaultOptions=e},t.setQueryDefaults=function(e,t){var n=this.queryDefaults.find((function(t){return hashQueryKey(e)===hashQueryKey(t.queryKey)}));n?n.defaultOptions=t:this.queryDefaults.push({queryKey:e,defaultOptions:t})},t.getQueryDefaults=function(e){var t;return e?null==(t=this.queryDefaults.find((function(t){return partialMatchKey(e,t.queryKey)})))?void 0:t.defaultOptions:void 0},t.setMutationDefaults=function(e,t){var n=this.mutationDefaults.find((function(t){return hashQueryKey(e)===hashQueryKey(t.mutationKey)}));n?n.defaultOptions=t:this.mutationDefaults.push({mutationKey:e,defaultOptions:t})},t.getMutationDefaults=function(e){var t;return e?null==(t=this.mutationDefaults.find((function(t){return partialMatchKey(e,t.mutationKey)})))?void 0:t.defaultOptions:void 0},t.defaultQueryOptions=function(e){if(null==e?void 0:e._defaulted)return e;var t=_extends$1({},this.defaultOptions.queries,this.getQueryDefaults(null==e?void 0:e.queryKey),e,{_defaulted:!0});return!t.queryHash&&t.queryKey&&(t.queryHash=hashQueryKeyByOptions(t.queryKey,t)),t},t.defaultQueryObserverOptions=function(e){return this.defaultQueryOptions(e)},t.defaultMutationOptions=function(e){return(null==e?void 0:e._defaulted)?e:_extends$1({},this.defaultOptions.mutations,this.getMutationDefaults(null==e?void 0:e.mutationKey),e,{_defaulted:!0})},t.clear=function(){this.queryCache.clear(),this.mutationCache.clear()},e}(),QueryObserver=function(e){function t(t,n){var i;return(i=e.call(this)||this).client=t,i.options=n,i.trackedProps=[],i.selectError=null,i.bindMethods(),i.setOptions(n),i}_inheritsLoose(t,e);var n=t.prototype;return n.bindMethods=function(){this.remove=this.remove.bind(this),this.refetch=this.refetch.bind(this)},n.onSubscribe=function(){1===this.listeners.length&&(this.currentQuery.addObserver(this),shouldFetchOnMount(this.currentQuery,this.options)&&this.executeFetch(),this.updateTimers())},n.onUnsubscribe=function(){this.listeners.length||this.destroy()},n.shouldFetchOnReconnect=function(){return shouldFetchOn(this.currentQuery,this.options,this.options.refetchOnReconnect)},n.shouldFetchOnWindowFocus=function(){return shouldFetchOn(this.currentQuery,this.options,this.options.refetchOnWindowFocus)},n.destroy=function(){this.listeners=[],this.clearTimers(),this.currentQuery.removeObserver(this)},n.setOptions=function(e,t){var n=this.options,i=this.currentQuery;if(this.options=this.client.defaultQueryObserverOptions(e),void 0!==this.options.enabled&&"boolean"!=typeof this.options.enabled)throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=n.queryKey),this.updateQuery();var r=this.hasListeners();r&&shouldFetchOptionally(this.currentQuery,i,this.options,n)&&this.executeFetch(),this.updateResult(t),!r||this.currentQuery===i&&this.options.enabled===n.enabled&&this.options.staleTime===n.staleTime||this.updateStaleTimeout();var s=this.computeRefetchInterval();!r||this.currentQuery===i&&this.options.enabled===n.enabled&&s===this.currentRefetchInterval||this.updateRefetchInterval(s)},n.getOptimisticResult=function(e){var t=this.client.defaultQueryObserverOptions(e),n=this.client.getQueryCache().build(this.client,t);return this.createResult(n,t)},n.getCurrentResult=function(){return this.currentResult},n.trackResult=function(e,t){var n=this,i={},r=function(e){n.trackedProps.includes(e)||n.trackedProps.push(e)};return Object.keys(e).forEach((function(t){Object.defineProperty(i,t,{configurable:!1,enumerable:!0,get:function(){return r(t),e[t]}})})),(t.useErrorBoundary||t.suspense)&&r("error"),i},n.getNextResult=function(e){var t=this;return new Promise((function(n,i){var r=t.subscribe((function(t){t.isFetching||(r(),t.isError&&(null==e?void 0:e.throwOnError)?i(t.error):n(t))}))}))},n.getCurrentQuery=function(){return this.currentQuery},n.remove=function(){this.client.getQueryCache().remove(this.currentQuery)},n.refetch=function(e){return this.fetch(_extends$1({},e,{meta:{refetchPage:null==e?void 0:e.refetchPage}}))},n.fetchOptimistic=function(e){var t=this,n=this.client.defaultQueryObserverOptions(e),i=this.client.getQueryCache().build(this.client,n);return i.fetch().then((function(){return t.createResult(i,n)}))},n.fetch=function(e){var t=this;return this.executeFetch(e).then((function(){return t.updateResult(),t.currentResult}))},n.executeFetch=function(e){this.updateQuery();var t=this.currentQuery.fetch(this.options,e);return(null==e?void 0:e.throwOnError)||(t=t.catch(noop$1)),t},n.updateStaleTimeout=function(){var e=this;if(this.clearStaleTimeout(),!isServer&&!this.currentResult.isStale&&isValidTimeout(this.options.staleTime)){var t=timeUntilStale(this.currentResult.dataUpdatedAt,this.options.staleTime)+1;this.staleTimeoutId=setTimeout((function(){e.currentResult.isStale||e.updateResult()}),t)}},n.computeRefetchInterval=function(){var e;return"function"==typeof this.options.refetchInterval?this.options.refetchInterval(this.currentResult.data,this.currentQuery):null!=(e=this.options.refetchInterval)&&e},n.updateRefetchInterval=function(e){var t=this;this.clearRefetchInterval(),this.currentRefetchInterval=e,!isServer&&!1!==this.options.enabled&&isValidTimeout(this.currentRefetchInterval)&&0!==this.currentRefetchInterval&&(this.refetchIntervalId=setInterval((function(){(t.options.refetchIntervalInBackground||focusManager$1.isFocused())&&t.executeFetch()}),this.currentRefetchInterval))},n.updateTimers=function(){this.updateStaleTimeout(),this.updateRefetchInterval(this.computeRefetchInterval())},n.clearTimers=function(){this.clearStaleTimeout(),this.clearRefetchInterval()},n.clearStaleTimeout=function(){this.staleTimeoutId&&(clearTimeout(this.staleTimeoutId),this.staleTimeoutId=void 0)},n.clearRefetchInterval=function(){this.refetchIntervalId&&(clearInterval(this.refetchIntervalId),this.refetchIntervalId=void 0)},n.createResult=function(e,t){var n,i=this.currentQuery,r=this.options,s=this.currentResult,a=this.currentResultState,o=this.currentResultOptions,l=e!==i,c=l?e.state:this.currentQueryInitialState,d=l?this.currentResult:this.previousQueryResult,u=e.state,h=u.dataUpdatedAt,p=u.error,f=u.errorUpdatedAt,m=u.isFetching,g=u.status,O=!1,y=!1;if(t.optimisticResults){var v=this.hasListeners(),b=!v&&shouldFetchOnMount(e,t),_=v&&shouldFetchOptionally(e,i,t,r);(b||_)&&(m=!0,h||(g="loading"))}if(t.keepPreviousData&&!u.dataUpdateCount&&(null==d?void 0:d.isSuccess)&&"error"!==g)n=d.data,h=d.dataUpdatedAt,g=d.status,O=!0;else if(t.select&&void 0!==u.data)if(s&&u.data===(null==a?void 0:a.data)&&t.select===this.selectFn)n=this.selectResult;else try{this.selectFn=t.select,n=t.select(u.data),!1!==t.structuralSharing&&(n=replaceEqualDeep(null==s?void 0:s.data,n)),this.selectResult=n,this.selectError=null}catch(e){getLogger().error(e),this.selectError=e}else n=u.data;if(void 0!==t.placeholderData&&void 0===n&&("loading"===g||"idle"===g)){var S;if((null==s?void 0:s.isPlaceholderData)&&t.placeholderData===(null==o?void 0:o.placeholderData))S=s.data;else if(S="function"==typeof t.placeholderData?t.placeholderData():t.placeholderData,t.select&&void 0!==S)try{S=t.select(S),!1!==t.structuralSharing&&(S=replaceEqualDeep(null==s?void 0:s.data,S)),this.selectError=null}catch(e){getLogger().error(e),this.selectError=e}void 0!==S&&(g="success",n=S,y=!0)}return this.selectError&&(p=this.selectError,n=this.selectResult,f=Date.now(),g="error"),{status:g,isLoading:"loading"===g,isSuccess:"success"===g,isError:"error"===g,isIdle:"idle"===g,data:n,dataUpdatedAt:h,error:p,errorUpdatedAt:f,failureCount:u.fetchFailureCount,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>c.dataUpdateCount||u.errorUpdateCount>c.errorUpdateCount,isFetching:m,isRefetching:m&&"loading"!==g,isLoadingError:"error"===g&&0===u.dataUpdatedAt,isPlaceholderData:y,isPreviousData:O,isRefetchError:"error"===g&&0!==u.dataUpdatedAt,isStale:isStale(e,t),refetch:this.refetch,remove:this.remove}},n.shouldNotifyListeners=function(e,t){if(!t)return!0;var n=this.options,i=n.notifyOnChangeProps,r=n.notifyOnChangePropsExclusions;if(!i&&!r)return!0;if("tracked"===i&&!this.trackedProps.length)return!0;var s="tracked"===i?this.trackedProps:i;return Object.keys(e).some((function(n){var i=n,a=e[i]!==t[i],o=null==s?void 0:s.some((function(e){return e===n})),l=null==r?void 0:r.some((function(e){return e===n}));return a&&!l&&(!s||o)}))},n.updateResult=function(e){var t=this.currentResult;if(this.currentResult=this.createResult(this.currentQuery,this.options),this.currentResultState=this.currentQuery.state,this.currentResultOptions=this.options,!shallowEqualObjects(this.currentResult,t)){var n={cache:!0};!1!==(null==e?void 0:e.listeners)&&this.shouldNotifyListeners(this.currentResult,t)&&(n.listeners=!0),this.notify(_extends$1({},n,e))}},n.updateQuery=function(){var e=this.client.getQueryCache().build(this.client,this.options);if(e!==this.currentQuery){var t=this.currentQuery;this.currentQuery=e,this.currentQueryInitialState=e.state,this.previousQueryResult=this.currentResult,this.hasListeners()&&(null==t||t.removeObserver(this),e.addObserver(this))}},n.onQueryUpdate=function(e){var t={};"success"===e.type?t.onSuccess=!0:"error"!==e.type||isCancelledError(e.error)||(t.onError=!0),this.updateResult(t),this.hasListeners()&&this.updateTimers()},n.notify=function(e){var t=this;notifyManager.batch((function(){e.onSuccess?(null==t.options.onSuccess||t.options.onSuccess(t.currentResult.data),null==t.options.onSettled||t.options.onSettled(t.currentResult.data,null)):e.onError&&(null==t.options.onError||t.options.onError(t.currentResult.error),null==t.options.onSettled||t.options.onSettled(void 0,t.currentResult.error)),e.listeners&&t.listeners.forEach((function(e){e(t.currentResult)})),e.cache&&t.client.getQueryCache().notify({query:t.currentQuery,type:"observerResultsUpdated"})}))},t}(Subscribable);function shouldLoadOnMount(e,t){return!(!1===t.enabled||e.state.dataUpdatedAt||"error"===e.state.status&&!1===t.retryOnMount)}function shouldFetchOnMount(e,t){return shouldLoadOnMount(e,t)||e.state.dataUpdatedAt>0&&shouldFetchOn(e,t,t.refetchOnMount)}function shouldFetchOn(e,t,n){if(!1!==t.enabled){var i="function"==typeof n?n(e):n;return"always"===i||!1!==i&&isStale(e,t)}return!1}function shouldFetchOptionally(e,t,n,i){return!1!==n.enabled&&(e!==t||!1===i.enabled)&&(!n.suspense||"error"!==e.state.status)&&isStale(e,n)}function isStale(e,t){return e.isStaleByTime(t.staleTime)}var InfiniteQueryObserver=function(e){function t(t,n){return e.call(this,t,n)||this}_inheritsLoose(t,e);var n=t.prototype;return n.bindMethods=function(){e.prototype.bindMethods.call(this),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)},n.setOptions=function(t,n){e.prototype.setOptions.call(this,_extends$1({},t,{behavior:infiniteQueryBehavior()}),n)},n.getOptimisticResult=function(t){return t.behavior=infiniteQueryBehavior(),e.prototype.getOptimisticResult.call(this,t)},n.fetchNextPage=function(e){var t;return this.fetch({cancelRefetch:null==(t=null==e?void 0:e.cancelRefetch)||t,throwOnError:null==e?void 0:e.throwOnError,meta:{fetchMore:{direction:"forward",pageParam:null==e?void 0:e.pageParam}}})},n.fetchPreviousPage=function(e){var t;return this.fetch({cancelRefetch:null==(t=null==e?void 0:e.cancelRefetch)||t,throwOnError:null==e?void 0:e.throwOnError,meta:{fetchMore:{direction:"backward",pageParam:null==e?void 0:e.pageParam}}})},n.createResult=function(t,n){var i,r,s,a,o,l,c=t.state;return _extends$1({},e.prototype.createResult.call(this,t,n),{fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:hasNextPage(n,null==(i=c.data)?void 0:i.pages),hasPreviousPage:hasPreviousPage(n,null==(r=c.data)?void 0:r.pages),isFetchingNextPage:c.isFetching&&"forward"===(null==(s=c.fetchMeta)||null==(a=s.fetchMore)?void 0:a.direction),isFetchingPreviousPage:c.isFetching&&"backward"===(null==(o=c.fetchMeta)||null==(l=o.fetchMore)?void 0:l.direction)})},t}(QueryObserver),MutationObserver$1=function(e){function t(t,n){var i;return(i=e.call(this)||this).client=t,i.setOptions(n),i.bindMethods(),i.updateResult(),i}_inheritsLoose(t,e);var n=t.prototype;return n.bindMethods=function(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)},n.setOptions=function(e){this.options=this.client.defaultMutationOptions(e)},n.onUnsubscribe=function(){var e;this.listeners.length||(null==(e=this.currentMutation)||e.removeObserver(this))},n.onMutationUpdate=function(e){this.updateResult();var t={listeners:!0};"success"===e.type?t.onSuccess=!0:"error"===e.type&&(t.onError=!0),this.notify(t)},n.getCurrentResult=function(){return this.currentResult},n.reset=function(){this.currentMutation=void 0,this.updateResult(),this.notify({listeners:!0})},n.mutate=function(e,t){return this.mutateOptions=t,this.currentMutation&&this.currentMutation.removeObserver(this),this.currentMutation=this.client.getMutationCache().build(this.client,_extends$1({},this.options,{variables:void 0!==e?e:this.options.variables})),this.currentMutation.addObserver(this),this.currentMutation.execute()},n.updateResult=function(){var e=this.currentMutation?this.currentMutation.state:getDefaultState(),t=_extends$1({},e,{isLoading:"loading"===e.status,isSuccess:"success"===e.status,isError:"error"===e.status,isIdle:"idle"===e.status,mutate:this.mutate,reset:this.reset});this.currentResult=t},n.notify=function(e){var t=this;notifyManager.batch((function(){t.mutateOptions&&(e.onSuccess?(null==t.mutateOptions.onSuccess||t.mutateOptions.onSuccess(t.currentResult.data,t.currentResult.variables,t.currentResult.context),null==t.mutateOptions.onSettled||t.mutateOptions.onSettled(t.currentResult.data,null,t.currentResult.variables,t.currentResult.context)):e.onError&&(null==t.mutateOptions.onError||t.mutateOptions.onError(t.currentResult.error,t.currentResult.variables,t.currentResult.context),null==t.mutateOptions.onSettled||t.mutateOptions.onSettled(void 0,t.currentResult.error,t.currentResult.variables,t.currentResult.context))),e.listeners&&t.listeners.forEach((function(e){e(t.currentResult)}))}))},t}(Subscribable),unstable_batchedUpdates=ReactDOM__default.unstable_batchedUpdates;notifyManager.setBatchNotifyFunction(unstable_batchedUpdates);var logger=console;setLogger(logger);var defaultContext=React__default.createContext(void 0),QueryClientSharingContext=React__default.createContext(!1);function getQueryClientContext(e){return e&&"undefined"!=typeof window?(window.ReactQueryClientContext||(window.ReactQueryClientContext=defaultContext),window.ReactQueryClientContext):defaultContext}var useQueryClient=function(){var e=React__default.useContext(getQueryClientContext(React__default.useContext(QueryClientSharingContext)));if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},QueryClientProvider=function(e){var t=e.client,n=e.contextSharing,i=void 0!==n&&n,r=e.children;React__default.useEffect((function(){return t.mount(),function(){t.unmount()}}),[t]);var s=getQueryClientContext(i);return React__default.createElement(QueryClientSharingContext.Provider,{value:i},React__default.createElement(s.Provider,{value:t},r))};function createValue(){var e=!1;return{clearReset:function(){e=!1},reset:function(){e=!0},isReset:function(){return e}}}var QueryErrorResetBoundaryContext=React__default.createContext(createValue()),useQueryErrorResetBoundary=function(){return React__default.useContext(QueryErrorResetBoundaryContext)};function shouldThrowError(e,t,n){return"function"==typeof t?t.apply(void 0,n):"boolean"==typeof t?t:!!e}function useMutation(e,t,n){var i=React__default.useRef(!1),r=React__default.useState(0)[1],s=parseMutationArgs(e,t,n),a=useQueryClient(),o=React__default.useRef();o.current?o.current.setOptions(s):o.current=new MutationObserver$1(a,s);var l=o.current.getCurrentResult();React__default.useEffect((function(){i.current=!0;var e=o.current.subscribe(notifyManager.batchCalls((function(){i.current&&r((function(e){return e+1}))})));return function(){i.current=!1,e()}}),[]);var c=React__default.useCallback((function(e,t){o.current.mutate(e,t).catch(noop$1)}),[]);if(l.error&&shouldThrowError(void 0,o.current.options.useErrorBoundary,[l.error]))throw l.error;return _extends$1({},l,{mutate:c,mutateAsync:l.mutate})}function useBaseQuery(e,t){var n=React__default.useRef(!1),i=React__default.useState(0)[1],r=useQueryClient(),s=useQueryErrorResetBoundary(),a=r.defaultQueryObserverOptions(e);a.optimisticResults=!0,a.onError&&(a.onError=notifyManager.batchCalls(a.onError)),a.onSuccess&&(a.onSuccess=notifyManager.batchCalls(a.onSuccess)),a.onSettled&&(a.onSettled=notifyManager.batchCalls(a.onSettled)),a.suspense&&("number"!=typeof a.staleTime&&(a.staleTime=1e3),0===a.cacheTime&&(a.cacheTime=1)),(a.suspense||a.useErrorBoundary)&&(s.isReset()||(a.retryOnMount=!1));var o=React__default.useState((function(){return new t(r,a)}))[0],l=o.getOptimisticResult(a);if(React__default.useEffect((function(){n.current=!0,s.clearReset();var e=o.subscribe(notifyManager.batchCalls((function(){n.current&&i((function(e){return e+1}))})));return o.updateResult(),function(){n.current=!1,e()}}),[s,o]),React__default.useEffect((function(){o.setOptions(a,{listeners:!1})}),[a,o]),a.suspense&&l.isLoading)throw o.fetchOptimistic(a).then((function(e){var t=e.data;null==a.onSuccess||a.onSuccess(t),null==a.onSettled||a.onSettled(t,null)})).catch((function(e){s.clearReset(),null==a.onError||a.onError(e),null==a.onSettled||a.onSettled(void 0,e)}));if(l.isError&&!s.isReset()&&!l.isFetching&&shouldThrowError(a.suspense,a.useErrorBoundary,[l.error,o.getCurrentQuery()]))throw l.error;return"tracked"===a.notifyOnChangeProps&&(l=o.trackResult(l,a)),l}function useQuery(e,t,n){return useBaseQuery(parseQueryArgs(e,t,n),QueryObserver)}function useInfiniteQuery(e,t,n){return useBaseQuery(parseQueryArgs(e,t,n),InfiniteQueryObserver)}function useUser(e){if(!e)throw new Error("useUser must be used within an WeavyProvider");return useQuery("user",(async()=>{try{const t=await e.get("/api/user");return t.ok?await t.json():(console.error("Could not load Weavy user data..."),null)}catch(t){console.error(`Could not connect to the Weavy backend. Please make sure ${e.url} is up and running!`)}}))}const UserContext=createContext({user:{id:-1,uid:"",username:"anonymous",name:"Anonymous",email:"",display_name:"",presence:"",avatar_url:""}}),UserProvider=({children:e,client:t})=>{const{isLoading:n,data:i}=useUser(t);return React__default.createElement(React__default.Fragment,null,!n&&i&&React__default.createElement(UserContext.Provider,{value:{user:i}},e))};var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function getAugmentedNamespace(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var n=function e(){if(this instanceof e){var n=[null];return n.push.apply(n,arguments),new(Function.bind.apply(t,n))}return t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var i=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,i.get?i:{enumerable:!0,get:function(){return e[t]}})})),n}var dayjs_minExports={},dayjs_min={get exports(){return dayjs_minExports},set exports(e){dayjs_minExports=e}};dayjs_min.exports=function(){var e=1e3,t=6e4,n=36e5,i="millisecond",r="second",s="minute",a="hour",o="day",l="week",c="month",d="quarter",u="year",h="date",p="Invalid Date",f=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,m=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,g={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(e){var t=["th","st","nd","rd"],n=e%100;return"["+e+(t[(n-20)%10]||t[n]||t[0])+"]"}},O=function(e,t,n){var i=String(e);return!i||i.length>=t?e:""+Array(t+1-i.length).join(n)+e},y={s:O,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),i=Math.floor(n/60),r=n%60;return(t<=0?"+":"-")+O(i,2,"0")+":"+O(r,2,"0")},m:function e(t,n){if(t.date()<n.date())return-e(n,t);var i=12*(n.year()-t.year())+(n.month()-t.month()),r=t.clone().add(i,c),s=n-r<0,a=t.clone().add(i+(s?-1:1),c);return+(-(i+(n-r)/(s?r-a:a-r))||0)},a:function(e){return e<0?Math.ceil(e)||0:Math.floor(e)},p:function(e){return{M:c,y:u,w:l,d:o,D:h,h:a,m:s,s:r,ms:i,Q:d}[e]||String(e||"").toLowerCase().replace(/s$/,"")},u:function(e){return void 0===e}},v="en",b={};b[v]=g;var _=function(e){return e instanceof C},S=function e(t,n,i){var r;if(!t)return v;if("string"==typeof t){var s=t.toLowerCase();b[s]&&(r=s),n&&(b[s]=n,r=s);var a=t.split("-");if(!r&&a.length>1)return e(a[0])}else{var o=t.name;b[o]=t,r=o}return!i&&r&&(v=r),r||!i&&v},w=function(e,t){if(_(e))return e.clone();var n="object"==typeof t?t:{};return n.date=e,n.args=arguments,new C(n)},x=y;x.l=S,x.i=_,x.w=function(e,t){return w(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var C=function(){function g(e){this.$L=S(e.locale,null,!0),this.parse(e)}var O=g.prototype;return O.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(null===t)return new Date(NaN);if(x.u(t))return new Date;if(t instanceof Date)return new Date(t);if("string"==typeof t&&!/Z$/i.test(t)){var i=t.match(f);if(i){var r=i[2]-1||0,s=(i[7]||"0").substring(0,3);return n?new Date(Date.UTC(i[1],r,i[3]||1,i[4]||0,i[5]||0,i[6]||0,s)):new Date(i[1],r,i[3]||1,i[4]||0,i[5]||0,i[6]||0,s)}}return new Date(t)}(e),this.$x=e.x||{},this.init()},O.init=function(){var e=this.$d;this.$y=e.getFullYear(),this.$M=e.getMonth(),this.$D=e.getDate(),this.$W=e.getDay(),this.$H=e.getHours(),this.$m=e.getMinutes(),this.$s=e.getSeconds(),this.$ms=e.getMilliseconds()},O.$utils=function(){return x},O.isValid=function(){return!(this.$d.toString()===p)},O.isSame=function(e,t){var n=w(e);return this.startOf(t)<=n&&n<=this.endOf(t)},O.isAfter=function(e,t){return w(e)<this.startOf(t)},O.isBefore=function(e,t){return this.endOf(t)<w(e)},O.$g=function(e,t,n){return x.u(e)?this[t]:this.set(n,e)},O.unix=function(){return Math.floor(this.valueOf()/1e3)},O.valueOf=function(){return this.$d.getTime()},O.startOf=function(e,t){var n=this,i=!!x.u(t)||t,d=x.p(e),p=function(e,t){var r=x.w(n.$u?Date.UTC(n.$y,t,e):new Date(n.$y,t,e),n);return i?r:r.endOf(o)},f=function(e,t){return x.w(n.toDate()[e].apply(n.toDate("s"),(i?[0,0,0,0]:[23,59,59,999]).slice(t)),n)},m=this.$W,g=this.$M,O=this.$D,y="set"+(this.$u?"UTC":"");switch(d){case u:return i?p(1,0):p(31,11);case c:return i?p(1,g):p(0,g+1);case l:var v=this.$locale().weekStart||0,b=(m<v?m+7:m)-v;return p(i?O-b:O+(6-b),g);case o:case h:return f(y+"Hours",0);case a:return f(y+"Minutes",1);case s:return f(y+"Seconds",2);case r:return f(y+"Milliseconds",3);default:return this.clone()}},O.endOf=function(e){return this.startOf(e,!1)},O.$set=function(e,t){var n,l=x.p(e),d="set"+(this.$u?"UTC":""),p=(n={},n[o]=d+"Date",n[h]=d+"Date",n[c]=d+"Month",n[u]=d+"FullYear",n[a]=d+"Hours",n[s]=d+"Minutes",n[r]=d+"Seconds",n[i]=d+"Milliseconds",n)[l],f=l===o?this.$D+(t-this.$W):t;if(l===c||l===u){var m=this.clone().set(h,1);m.$d[p](f),m.init(),this.$d=m.set(h,Math.min(this.$D,m.daysInMonth())).$d}else p&&this.$d[p](f);return this.init(),this},O.set=function(e,t){return this.clone().$set(e,t)},O.get=function(e){return this[x.p(e)]()},O.add=function(i,d){var h,p=this;i=Number(i);var f=x.p(d),m=function(e){var t=w(p);return x.w(t.date(t.date()+Math.round(e*i)),p)};if(f===c)return this.set(c,this.$M+i);if(f===u)return this.set(u,this.$y+i);if(f===o)return m(1);if(f===l)return m(7);var g=(h={},h[s]=t,h[a]=n,h[r]=e,h)[f]||1,O=this.$d.getTime()+i*g;return x.w(O,this)},O.subtract=function(e,t){return this.add(-1*e,t)},O.format=function(e){var t=this,n=this.$locale();if(!this.isValid())return n.invalidDate||p;var i=e||"YYYY-MM-DDTHH:mm:ssZ",r=x.z(this),s=this.$H,a=this.$m,o=this.$M,l=n.weekdays,c=n.months,d=n.meridiem,u=function(e,n,r,s){return e&&(e[n]||e(t,i))||r[n].slice(0,s)},h=function(e){return x.s(s%12||12,e,"0")},f=d||function(e,t,n){var i=e<12?"AM":"PM";return n?i.toLowerCase():i};return i.replace(m,(function(e,i){return i||function(e){switch(e){case"YY":return String(t.$y).slice(-2);case"YYYY":return x.s(t.$y,4,"0");case"M":return o+1;case"MM":return x.s(o+1,2,"0");case"MMM":return u(n.monthsShort,o,c,3);case"MMMM":return u(c,o);case"D":return t.$D;case"DD":return x.s(t.$D,2,"0");case"d":return String(t.$W);case"dd":return u(n.weekdaysMin,t.$W,l,2);case"ddd":return u(n.weekdaysShort,t.$W,l,3);case"dddd":return l[t.$W];case"H":return String(s);case"HH":return x.s(s,2,"0");case"h":return h(1);case"hh":return h(2);case"a":return f(s,a,!0);case"A":return f(s,a,!1);case"m":return String(a);case"mm":return x.s(a,2,"0");case"s":return String(t.$s);case"ss":return x.s(t.$s,2,"0");case"SSS":return x.s(t.$ms,3,"0");case"Z":return r}return null}(e)||r.replace(":","")}))},O.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},O.diff=function(i,h,p){var f,m=this,g=x.p(h),O=w(i),y=(O.utcOffset()-this.utcOffset())*t,v=this-O,b=function(){return x.m(m,O)};switch(g){case u:f=b()/12;break;case c:f=b();break;case d:f=b()/3;break;case l:f=(v-y)/6048e5;break;case o:f=(v-y)/864e5;break;case a:f=v/n;break;case s:f=v/t;break;case r:f=v/e;break;default:f=v}return p?f:x.a(f)},O.daysInMonth=function(){return this.endOf(c).$D},O.$locale=function(){return b[this.$L]},O.locale=function(e,t){if(!e)return this.$L;var n=this.clone(),i=S(e,t,!0);return i&&(n.$L=i),n},O.clone=function(){return x.w(this.$d,this)},O.toDate=function(){return new Date(this.valueOf())},O.toJSON=function(){return this.isValid()?this.toISOString():null},O.toISOString=function(){return this.$d.toISOString()},O.toString=function(){return this.$d.toUTCString()},g}(),P=C.prototype;return w.prototype=P,[["$ms",i],["$s",r],["$m",s],["$H",a],["$W",o],["$M",c],["$y",u],["$D",h]].forEach((function(e){P[e[1]]=function(t){return this.$g(t,e[0],e[1])}})),w.extend=function(e,t){return e.$i||(e(t,C,w),e.$i=!0),w},w.locale=S,w.isDayjs=_,w.unix=function(e){return w(1e3*e)},w.en=b[v],w.Ls=b,w.p={},w}();var dayjs=dayjs_minExports,relativeTimeExports={},relativeTime$1={get exports(){return relativeTimeExports},set exports(e){relativeTimeExports=e}};relativeTime$1.exports=function(e,t,n){e=e||{};var i=t.prototype,r={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function s(e,t,n,r){return i.fromToBase(e,t,n,r)}n.en.relativeTime=r,i.fromToBase=function(t,i,s,a,o){for(var l,c,d,u=s.$locale().relativeTime||r,h=e.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],p=h.length,f=0;f<p;f+=1){var m=h[f];m.d&&(l=a?n(t).diff(s,m.d,!0):s.diff(t,m.d,!0));var g=(e.rounding||Math.round)(Math.abs(l));if(d=l>0,g<=m.r||!m.r){g<=1&&f>0&&(m=h[f-1]);var O=u[m.l];o&&(g=o(""+g)),c="string"==typeof O?O.replace("%d",g):O(g,i,m.l,d);break}}if(i)return c;var y=d?u.future:u.past;return"function"==typeof y?y(c):y.replace("%s",c)},i.to=function(e,t){return s(e,t,this,!0)},i.from=function(e,t){return s(e,t,this)};var a=function(e){return e.$u?n.utc():n()};i.toNow=function(e){return this.to(a(this),e)},i.fromNow=function(e){return this.from(a(this),e)}};var relativeTime=relativeTimeExports,utcExports={},utc$1={get exports(){return utcExports},set exports(e){utcExports=e}};utc$1.exports=function(){var e="minute",t=/[+-]\d\d(?::?\d\d)?/g,n=/([+-]|\d\d)/g;return function(i,r,s){var a=r.prototype;s.utc=function(e){return new r({date:e,utc:!0,args:arguments})},a.utc=function(t){var n=s(this.toDate(),{locale:this.$L,utc:!0});return t?n.add(this.utcOffset(),e):n},a.local=function(){return s(this.toDate(),{locale:this.$L,utc:!1})};var o=a.parse;a.parse=function(e){e.utc&&(this.$u=!0),this.$utils().u(e.$offset)||(this.$offset=e.$offset),o.call(this,e)};var l=a.init;a.init=function(){if(this.$u){var e=this.$d;this.$y=e.getUTCFullYear(),this.$M=e.getUTCMonth(),this.$D=e.getUTCDate(),this.$W=e.getUTCDay(),this.$H=e.getUTCHours(),this.$m=e.getUTCMinutes(),this.$s=e.getUTCSeconds(),this.$ms=e.getUTCMilliseconds()}else l.call(this)};var c=a.utcOffset;a.utcOffset=function(i,r){var s=this.$utils().u;if(s(i))return this.$u?0:s(this.$offset)?c.call(this):this.$offset;if("string"==typeof i&&(i=function(e){void 0===e&&(e="");var i=e.match(t);if(!i)return null;var r=(""+i[0]).match(n)||["-",0,0],s=r[0],a=60*+r[1]+ +r[2];return 0===a?0:"+"===s?a:-a}(i),null===i))return this;var a=Math.abs(i)<=16?60*i:i,o=this;if(r)return o.$offset=a,o.$u=0===i,o;if(0!==i){var l=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(o=this.local().add(a+l,e)).$offset=a,o.$x.$localOffset=l}else o=this.utc();return o};var d=a.format;a.format=function(e){var t=e||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return d.call(this,t)},a.valueOf=function(){var e=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*e},a.isUTC=function(){return!!this.$u},a.toISOString=function(){return this.toDate().toISOString()},a.toString=function(){return this.toDate().toUTCString()};var u=a.toDate;a.toDate=function(e){return"s"===e&&this.$offset?s(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():u.call(this)};var h=a.diff;a.diff=function(e,t,n){if(e&&this.$u===e.$u)return h.call(this,e,t,n);var i=this.local(),r=s(e).local();return h.call(i,r,t,n)}}}();var utc=utcExports,timezoneExports={},timezone$1={get exports(){return timezoneExports},set exports(e){timezoneExports=e}};timezone$1.exports=function(){var e={year:0,month:1,day:2,hour:3,minute:4,second:5},t={};return function(n,i,r){var s,a=function(e,n,i){void 0===i&&(i={});var r=new Date(e),s=function(e,n){void 0===n&&(n={});var i=n.timeZoneName||"short",r=e+"|"+i,s=t[r];return s||(s=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:i}),t[r]=s),s}(n,i);return s.formatToParts(r)},o=function(t,n){for(var i=a(t,n),s=[],o=0;o<i.length;o+=1){var l=i[o],c=l.type,d=l.value,u=e[c];u>=0&&(s[u]=parseInt(d,10))}var h=s[3],p=24===h?0:h,f=s[0]+"-"+s[1]+"-"+s[2]+" "+p+":"+s[4]+":"+s[5]+":000",m=+t;return(r.utc(f).valueOf()-(m-=m%1e3))/6e4},l=i.prototype;l.tz=function(e,t){void 0===e&&(e=s);var n=this.utcOffset(),i=this.toDate(),a=i.toLocaleString("en-US",{timeZone:e}),o=Math.round((i-new Date(a))/1e3/60),l=r(a).$set("millisecond",this.$ms).utcOffset(15*-Math.round(i.getTimezoneOffset()/15)-o,!0);if(t){var c=l.utcOffset();l=l.add(n-c,"minute")}return l.$x.$timezone=e,l},l.offsetName=function(e){var t=this.$x.$timezone||r.tz.guess(),n=a(this.valueOf(),t,{timeZoneName:e}).find((function(e){return"timezonename"===e.type.toLowerCase()}));return n&&n.value};var c=l.startOf;l.startOf=function(e,t){if(!this.$x||!this.$x.$timezone)return c.call(this,e,t);var n=r(this.format("YYYY-MM-DD HH:mm:ss:SSS"));return c.call(n,e,t).tz(this.$x.$timezone,!0)},r.tz=function(e,t,n){var i=n&&t,a=n||t||s,l=o(+r(),a);if("string"!=typeof e)return r(e).tz(a);var c=function(e,t,n){var i=e-60*t*1e3,r=o(i,n);if(t===r)return[i,t];var s=o(i-=60*(r-t)*1e3,n);return r===s?[i,r]:[e-60*Math.min(r,s)*1e3,Math.max(r,s)]}(r.utc(e,i).valueOf(),l,a),d=c[0],u=c[1],h=r(d).utcOffset(u);return h.$x.$timezone=a,h},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(e){s=e}}}();var timezone=timezoneExports,localizedFormatExports={},localizedFormat$1={get exports(){return localizedFormatExports},set exports(e){localizedFormatExports=e}},e;localizedFormat$1.exports=(e={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},function(t,n,i){var r=n.prototype,s=r.format;i.en.formats=e,r.format=function(t){void 0===t&&(t="YYYY-MM-DDTHH:mm:ssZ");var n=this.$locale().formats,i=function(t,n){return t.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,(function(t,i,r){var s=r&&r.toUpperCase();return i||n[r]||e[r]||n[s].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,(function(e,t,n){return t||n.slice(1)}))}))}(t,void 0===n?{}:n);return s.call(this,i)}});var localizedFormat=localizedFormatExports,libExports={},lib={get exports(){return libExports},set exports(e){libExports=e}},Modal$2={},propTypesExports$1={},propTypes={get exports(){return propTypesExports$1},set exports(e){propTypesExports$1=e}},reactIsExports={},reactIs={get exports(){return reactIsExports},set exports(e){reactIsExports=e}},reactIs_production_min={},hasRequiredReactIs_production_min;function requireReactIs_production_min(){if(hasRequiredReactIs_production_min)return reactIs_production_min;hasRequiredReactIs_production_min=1;var e="function"==typeof Symbol&&Symbol.for,t=e?Symbol.for("react.element"):60103,n=e?Symbol.for("react.portal"):60106,i=e?Symbol.for("react.fragment"):60107,r=e?Symbol.for("react.strict_mode"):60108,s=e?Symbol.for("react.profiler"):60114,a=e?Symbol.for("react.provider"):60109,o=e?Symbol.for("react.context"):60110,l=e?Symbol.for("react.async_mode"):60111,c=e?Symbol.for("react.concurrent_mode"):60111,d=e?Symbol.for("react.forward_ref"):60112,u=e?Symbol.for("react.suspense"):60113,h=e?Symbol.for("react.suspense_list"):60120,p=e?Symbol.for("react.memo"):60115,f=e?Symbol.for("react.lazy"):60116,m=e?Symbol.for("react.block"):60121,g=e?Symbol.for("react.fundamental"):60117,O=e?Symbol.for("react.responder"):60118,y=e?Symbol.for("react.scope"):60119;function v(e){if("object"==typeof e&&null!==e){var h=e.$$typeof;switch(h){case t:switch(e=e.type){case l:case c:case i:case s:case r:case u:return e;default:switch(e=e&&e.$$typeof){case o:case d:case f:case p:case a:return e;default:return h}}case n:return h}}}function b(e){return v(e)===c}return reactIs_production_min.AsyncMode=l,reactIs_production_min.ConcurrentMode=c,reactIs_production_min.ContextConsumer=o,reactIs_production_min.ContextProvider=a,reactIs_production_min.Element=t,reactIs_production_min.ForwardRef=d,reactIs_production_min.Fragment=i,reactIs_production_min.Lazy=f,reactIs_production_min.Memo=p,reactIs_production_min.Portal=n,reactIs_production_min.Profiler=s,reactIs_production_min.StrictMode=r,reactIs_production_min.Suspense=u,reactIs_production_min.isAsyncMode=function(e){return b(e)||v(e)===l},reactIs_production_min.isConcurrentMode=b,reactIs_production_min.isContextConsumer=function(e){return v(e)===o},reactIs_production_min.isContextProvider=function(e){return v(e)===a},reactIs_production_min.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===t},reactIs_production_min.isForwardRef=function(e){return v(e)===d},reactIs_production_min.isFragment=function(e){return v(e)===i},reactIs_production_min.isLazy=function(e){return v(e)===f},reactIs_production_min.isMemo=function(e){return v(e)===p},reactIs_production_min.isPortal=function(e){return v(e)===n},reactIs_production_min.isProfiler=function(e){return v(e)===s},reactIs_production_min.isStrictMode=function(e){return v(e)===r},reactIs_production_min.isSuspense=function(e){return v(e)===u},reactIs_production_min.isValidElementType=function(e){return"string"==typeof e||"function"==typeof e||e===i||e===c||e===s||e===r||e===u||e===h||"object"==typeof e&&null!==e&&(e.$$typeof===f||e.$$typeof===p||e.$$typeof===a||e.$$typeof===o||e.$$typeof===d||e.$$typeof===g||e.$$typeof===O||e.$$typeof===y||e.$$typeof===m)},reactIs_production_min.typeOf=v,reactIs_production_min}var reactIs_development={},hasRequiredReactIs_development,hasRequiredReactIs,objectAssign,hasRequiredObjectAssign,ReactPropTypesSecret_1,hasRequiredReactPropTypesSecret,has,hasRequiredHas,checkPropTypes_1,hasRequiredCheckPropTypes,factoryWithTypeCheckers,hasRequiredFactoryWithTypeCheckers,factoryWithThrowingShims,hasRequiredFactoryWithThrowingShims,hasRequiredPropTypes;
|
|
2
2
|
/** @license React v16.13.1
|
|
3
3
|
* react-is.development.js
|
|
4
4
|
*
|