{"version":3,"sources":["node_modules/@microsoft/signalr/dist/esm/Errors.js","node_modules/@microsoft/signalr/dist/esm/HttpClient.js","node_modules/@microsoft/signalr/dist/esm/ILogger.js","node_modules/@microsoft/signalr/dist/esm/Loggers.js","node_modules/@microsoft/signalr/dist/esm/Utils.js","node_modules/@microsoft/signalr/dist/esm/FetchHttpClient.js","node_modules/@microsoft/signalr/dist/esm/XhrHttpClient.js","node_modules/@microsoft/signalr/dist/esm/DefaultHttpClient.js","node_modules/@microsoft/signalr/dist/esm/TextMessageFormat.js","node_modules/@microsoft/signalr/dist/esm/HandshakeProtocol.js","node_modules/@microsoft/signalr/dist/esm/IHubProtocol.js","node_modules/@microsoft/signalr/dist/esm/Subject.js","node_modules/@microsoft/signalr/dist/esm/MessageBuffer.js","node_modules/@microsoft/signalr/dist/esm/HubConnection.js","node_modules/@microsoft/signalr/dist/esm/DefaultReconnectPolicy.js","node_modules/@microsoft/signalr/src/HeaderNames.ts","node_modules/@microsoft/signalr/dist/esm/AccessTokenHttpClient.js","node_modules/@microsoft/signalr/dist/esm/ITransport.js","node_modules/@microsoft/signalr/dist/esm/AbortController.js","node_modules/@microsoft/signalr/dist/esm/LongPollingTransport.js","node_modules/@microsoft/signalr/dist/esm/ServerSentEventsTransport.js","node_modules/@microsoft/signalr/dist/esm/WebSocketTransport.js","node_modules/@microsoft/signalr/dist/esm/HttpConnection.js","node_modules/@microsoft/signalr/dist/esm/JsonHubProtocol.js","node_modules/@microsoft/signalr/dist/esm/HubConnectionBuilder.js","src/app/_services/message-hub.service.ts"],"sourcesContent":["// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n/** Error thrown when an HTTP request fails. */\nexport class HttpError extends Error {\n /** Constructs a new instance of {@link @microsoft/signalr.HttpError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n * @param {number} statusCode The HTTP status code represented by this error.\r\n */\n constructor(errorMessage, statusCode) {\n const trueProto = new.target.prototype;\n super(`${errorMessage}: Status code '${statusCode}'`);\n this.statusCode = statusCode;\n // Workaround issue in Typescript compiler\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\n this.__proto__ = trueProto;\n }\n}\n/** Error thrown when a timeout elapses. */\nexport class TimeoutError extends Error {\n /** Constructs a new instance of {@link @microsoft/signalr.TimeoutError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n */\n constructor(errorMessage = \"A timeout occurred.\") {\n const trueProto = new.target.prototype;\n super(errorMessage);\n // Workaround issue in Typescript compiler\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\n this.__proto__ = trueProto;\n }\n}\n/** Error thrown when an action is aborted. */\nexport class AbortError extends Error {\n /** Constructs a new instance of {@link AbortError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n */\n constructor(errorMessage = \"An abort occurred.\") {\n const trueProto = new.target.prototype;\n super(errorMessage);\n // Workaround issue in Typescript compiler\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\n this.__proto__ = trueProto;\n }\n}\n/** Error thrown when the selected transport is unsupported by the browser. */\n/** @private */\nexport class UnsupportedTransportError extends Error {\n /** Constructs a new instance of {@link @microsoft/signalr.UnsupportedTransportError}.\r\n *\r\n * @param {string} message A descriptive error message.\r\n * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occurred on.\r\n */\n constructor(message, transport) {\n const trueProto = new.target.prototype;\n super(message);\n this.transport = transport;\n this.errorType = 'UnsupportedTransportError';\n // Workaround issue in Typescript compiler\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\n this.__proto__ = trueProto;\n }\n}\n/** Error thrown when the selected transport is disabled by the browser. */\n/** @private */\nexport class DisabledTransportError extends Error {\n /** Constructs a new instance of {@link @microsoft/signalr.DisabledTransportError}.\r\n *\r\n * @param {string} message A descriptive error message.\r\n * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occurred on.\r\n */\n constructor(message, transport) {\n const trueProto = new.target.prototype;\n super(message);\n this.transport = transport;\n this.errorType = 'DisabledTransportError';\n // Workaround issue in Typescript compiler\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\n this.__proto__ = trueProto;\n }\n}\n/** Error thrown when the selected transport cannot be started. */\n/** @private */\nexport class FailedToStartTransportError extends Error {\n /** Constructs a new instance of {@link @microsoft/signalr.FailedToStartTransportError}.\r\n *\r\n * @param {string} message A descriptive error message.\r\n * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occurred on.\r\n */\n constructor(message, transport) {\n const trueProto = new.target.prototype;\n super(message);\n this.transport = transport;\n this.errorType = 'FailedToStartTransportError';\n // Workaround issue in Typescript compiler\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\n this.__proto__ = trueProto;\n }\n}\n/** Error thrown when the negotiation with the server failed to complete. */\n/** @private */\nexport class FailedToNegotiateWithServerError extends Error {\n /** Constructs a new instance of {@link @microsoft/signalr.FailedToNegotiateWithServerError}.\r\n *\r\n * @param {string} message A descriptive error message.\r\n */\n constructor(message) {\n const trueProto = new.target.prototype;\n super(message);\n this.errorType = 'FailedToNegotiateWithServerError';\n // Workaround issue in Typescript compiler\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\n this.__proto__ = trueProto;\n }\n}\n/** Error thrown when multiple errors have occurred. */\n/** @private */\nexport class AggregateErrors extends Error {\n /** Constructs a new instance of {@link @microsoft/signalr.AggregateErrors}.\r\n *\r\n * @param {string} message A descriptive error message.\r\n * @param {Error[]} innerErrors The collection of errors this error is aggregating.\r\n */\n constructor(message, innerErrors) {\n const trueProto = new.target.prototype;\n super(message);\n this.innerErrors = innerErrors;\n // Workaround issue in Typescript compiler\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\n this.__proto__ = trueProto;\n }\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n/** Represents an HTTP response. */\nexport class HttpResponse {\n constructor(statusCode, statusText, content) {\n this.statusCode = statusCode;\n this.statusText = statusText;\n this.content = content;\n }\n}\n/** Abstraction over an HTTP client.\r\n *\r\n * This class provides an abstraction over an HTTP client so that a different implementation can be provided on different platforms.\r\n */\nexport class HttpClient {\n get(url, options) {\n return this.send({\n ...options,\n method: \"GET\",\n url\n });\n }\n post(url, options) {\n return this.send({\n ...options,\n method: \"POST\",\n url\n });\n }\n delete(url, options) {\n return this.send({\n ...options,\n method: \"DELETE\",\n url\n });\n }\n /** Gets all cookies that apply to the specified URL.\r\n *\r\n * @param url The URL that the cookies are valid for.\r\n * @returns {string} A string containing all the key-value cookie pairs for the specified URL.\r\n */\n // @ts-ignore\n getCookieString(url) {\n return \"\";\n }\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// These values are designed to match the ASP.NET Log Levels since that's the pattern we're emulating here.\n/** Indicates the severity of a log message.\r\n *\r\n * Log Levels are ordered in increasing severity. So `Debug` is more severe than `Trace`, etc.\r\n */\nexport var LogLevel = /*#__PURE__*/function (LogLevel) {\n /** Log level for very low severity diagnostic messages. */\n LogLevel[LogLevel[\"Trace\"] = 0] = \"Trace\";\n /** Log level for low severity diagnostic messages. */\n LogLevel[LogLevel[\"Debug\"] = 1] = \"Debug\";\n /** Log level for informational diagnostic messages. */\n LogLevel[LogLevel[\"Information\"] = 2] = \"Information\";\n /** Log level for diagnostic messages that indicate a non-fatal problem. */\n LogLevel[LogLevel[\"Warning\"] = 3] = \"Warning\";\n /** Log level for diagnostic messages that indicate a failure in the current operation. */\n LogLevel[LogLevel[\"Error\"] = 4] = \"Error\";\n /** Log level for diagnostic messages that indicate a failure that will terminate the entire application. */\n LogLevel[LogLevel[\"Critical\"] = 5] = \"Critical\";\n /** The highest possible log level. Used when configuring logging to indicate that no log messages should be emitted. */\n LogLevel[LogLevel[\"None\"] = 6] = \"None\";\n return LogLevel;\n}(LogLevel || {});\n\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n/** A logger that does nothing when log messages are sent to it. */\nexport class NullLogger {\n constructor() {}\n /** @inheritDoc */\n // eslint-disable-next-line\n log(_logLevel, _message) {}\n}\n/** The singleton instance of the {@link @microsoft/signalr.NullLogger}. */\nNullLogger.instance = new NullLogger();\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\nimport { LogLevel } from \"./ILogger\";\nimport { NullLogger } from \"./Loggers\";\n// Version token that will be replaced by the prepack command\n/** The version of the SignalR client. */\nexport const VERSION = \"8.0.7\";\n/** @private */\nexport class Arg {\n static isRequired(val, name) {\n if (val === null || val === undefined) {\n throw new Error(`The '${name}' argument is required.`);\n }\n }\n static isNotEmpty(val, name) {\n if (!val || val.match(/^\\s*$/)) {\n throw new Error(`The '${name}' argument should not be empty.`);\n }\n }\n static isIn(val, values, name) {\n // TypeScript enums have keys for **both** the name and the value of each enum member on the type itself.\n if (!(val in values)) {\n throw new Error(`Unknown ${name} value: ${val}.`);\n }\n }\n}\n/** @private */\nexport class Platform {\n // react-native has a window but no document so we should check both\n static get isBrowser() {\n return !Platform.isNode && typeof window === \"object\" && typeof window.document === \"object\";\n }\n // WebWorkers don't have a window object so the isBrowser check would fail\n static get isWebWorker() {\n return !Platform.isNode && typeof self === \"object\" && \"importScripts\" in self;\n }\n // react-native has a window but no document\n static get isReactNative() {\n return !Platform.isNode && typeof window === \"object\" && typeof window.document === \"undefined\";\n }\n // Node apps shouldn't have a window object, but WebWorkers don't either\n // so we need to check for both WebWorker and window\n static get isNode() {\n return typeof process !== \"undefined\" && process.release && process.release.name === \"node\";\n }\n}\n/** @private */\nexport function getDataDetail(data, includeContent) {\n let detail = \"\";\n if (isArrayBuffer(data)) {\n detail = `Binary data of length ${data.byteLength}`;\n if (includeContent) {\n detail += `. Content: '${formatArrayBuffer(data)}'`;\n }\n } else if (typeof data === \"string\") {\n detail = `String data of length ${data.length}`;\n if (includeContent) {\n detail += `. Content: '${data}'`;\n }\n }\n return detail;\n}\n/** @private */\nexport function formatArrayBuffer(data) {\n const view = new Uint8Array(data);\n // Uint8Array.map only supports returning another Uint8Array?\n let str = \"\";\n view.forEach(num => {\n const pad = num < 16 ? \"0\" : \"\";\n str += `0x${pad}${num.toString(16)} `;\n });\n // Trim of trailing space.\n return str.substr(0, str.length - 1);\n}\n// Also in signalr-protocol-msgpack/Utils.ts\n/** @private */\nexport function isArrayBuffer(val) {\n return val && typeof ArrayBuffer !== \"undefined\" && (val instanceof ArrayBuffer ||\n // Sometimes we get an ArrayBuffer that doesn't satisfy instanceof\n val.constructor && val.constructor.name === \"ArrayBuffer\");\n}\n/** @private */\nexport async function sendMessage(logger, transportName, httpClient, url, content, options) {\n const headers = {};\n const [name, value] = getUserAgentHeader();\n headers[name] = value;\n logger.log(LogLevel.Trace, `(${transportName} transport) sending data. ${getDataDetail(content, options.logMessageContent)}.`);\n const responseType = isArrayBuffer(content) ? \"arraybuffer\" : \"text\";\n const response = await httpClient.post(url, {\n content,\n headers: {\n ...headers,\n ...options.headers\n },\n responseType,\n timeout: options.timeout,\n withCredentials: options.withCredentials\n });\n logger.log(LogLevel.Trace, `(${transportName} transport) request complete. Response status: ${response.statusCode}.`);\n}\n/** @private */\nexport function createLogger(logger) {\n if (logger === undefined) {\n return new ConsoleLogger(LogLevel.Information);\n }\n if (logger === null) {\n return NullLogger.instance;\n }\n if (logger.log !== undefined) {\n return logger;\n }\n return new ConsoleLogger(logger);\n}\n/** @private */\nexport class SubjectSubscription {\n constructor(subject, observer) {\n this._subject = subject;\n this._observer = observer;\n }\n dispose() {\n const index = this._subject.observers.indexOf(this._observer);\n if (index > -1) {\n this._subject.observers.splice(index, 1);\n }\n if (this._subject.observers.length === 0 && this._subject.cancelCallback) {\n this._subject.cancelCallback().catch(_ => {});\n }\n }\n}\n/** @private */\nexport class ConsoleLogger {\n constructor(minimumLogLevel) {\n this._minLevel = minimumLogLevel;\n this.out = console;\n }\n log(logLevel, message) {\n if (logLevel >= this._minLevel) {\n const msg = `[${new Date().toISOString()}] ${LogLevel[logLevel]}: ${message}`;\n switch (logLevel) {\n case LogLevel.Critical:\n case LogLevel.Error:\n this.out.error(msg);\n break;\n case LogLevel.Warning:\n this.out.warn(msg);\n break;\n case LogLevel.Information:\n this.out.info(msg);\n break;\n default:\n // console.debug only goes to attached debuggers in Node, so we use console.log for Trace and Debug\n this.out.log(msg);\n break;\n }\n }\n }\n}\n/** @private */\nexport function getUserAgentHeader() {\n let userAgentHeaderName = \"X-SignalR-User-Agent\";\n if (Platform.isNode) {\n userAgentHeaderName = \"User-Agent\";\n }\n return [userAgentHeaderName, constructUserAgent(VERSION, getOsName(), getRuntime(), getRuntimeVersion())];\n}\n/** @private */\nexport function constructUserAgent(version, os, runtime, runtimeVersion) {\n // Microsoft SignalR/[Version] ([Detailed Version]; [Operating System]; [Runtime]; [Runtime Version])\n let userAgent = \"Microsoft SignalR/\";\n const majorAndMinor = version.split(\".\");\n userAgent += `${majorAndMinor[0]}.${majorAndMinor[1]}`;\n userAgent += ` (${version}; `;\n if (os && os !== \"\") {\n userAgent += `${os}; `;\n } else {\n userAgent += \"Unknown OS; \";\n }\n userAgent += `${runtime}`;\n if (runtimeVersion) {\n userAgent += `; ${runtimeVersion}`;\n } else {\n userAgent += \"; Unknown Runtime Version\";\n }\n userAgent += \")\";\n return userAgent;\n}\n// eslint-disable-next-line spaced-comment\n/*#__PURE__*/\nfunction getOsName() {\n if (Platform.isNode) {\n switch (process.platform) {\n case \"win32\":\n return \"Windows NT\";\n case \"darwin\":\n return \"macOS\";\n case \"linux\":\n return \"Linux\";\n default:\n return process.platform;\n }\n } else {\n return \"\";\n }\n}\n// eslint-disable-next-line spaced-comment\n/*#__PURE__*/\nfunction getRuntimeVersion() {\n if (Platform.isNode) {\n return process.versions.node;\n }\n return undefined;\n}\nfunction getRuntime() {\n if (Platform.isNode) {\n return \"NodeJS\";\n } else {\n return \"Browser\";\n }\n}\n/** @private */\nexport function getErrorString(e) {\n if (e.stack) {\n return e.stack;\n } else if (e.message) {\n return e.message;\n }\n return `${e}`;\n}\n/** @private */\nexport function getGlobalThis() {\n // globalThis is semi-new and not available in Node until v12\n if (typeof globalThis !== \"undefined\") {\n return globalThis;\n }\n if (typeof self !== \"undefined\") {\n return self;\n }\n if (typeof window !== \"undefined\") {\n return window;\n }\n if (typeof global !== \"undefined\") {\n return global;\n }\n throw new Error(\"could not find global\");\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\nimport { AbortError, HttpError, TimeoutError } from \"./Errors\";\nimport { HttpClient, HttpResponse } from \"./HttpClient\";\nimport { LogLevel } from \"./ILogger\";\nimport { Platform, getGlobalThis, isArrayBuffer } from \"./Utils\";\nexport class FetchHttpClient extends HttpClient {\n constructor(logger) {\n super();\n this._logger = logger;\n // Node added a fetch implementation to the global scope starting in v18.\n // We need to add a cookie jar in node to be able to share cookies with WebSocket\n if (typeof fetch === \"undefined\" || Platform.isNode) {\n // In order to ignore the dynamic require in webpack builds we need to do this magic\n // @ts-ignore: TS doesn't know about these names\n const requireFunc = typeof __webpack_require__ === \"function\" ? __non_webpack_require__ : require;\n // Cookies aren't automatically handled in Node so we need to add a CookieJar to preserve cookies across requests\n this._jar = new (requireFunc(\"tough-cookie\").CookieJar)();\n if (typeof fetch === \"undefined\") {\n this._fetchType = requireFunc(\"node-fetch\");\n } else {\n // Use fetch from Node if available\n this._fetchType = fetch;\n }\n // node-fetch doesn't have a nice API for getting and setting cookies\n // fetch-cookie will wrap a fetch implementation with a default CookieJar or a provided one\n this._fetchType = requireFunc(\"fetch-cookie\")(this._fetchType, this._jar);\n } else {\n this._fetchType = fetch.bind(getGlobalThis());\n }\n if (typeof AbortController === \"undefined\") {\n // In order to ignore the dynamic require in webpack builds we need to do this magic\n // @ts-ignore: TS doesn't know about these names\n const requireFunc = typeof __webpack_require__ === \"function\" ? __non_webpack_require__ : require;\n // Node needs EventListener methods on AbortController which our custom polyfill doesn't provide\n this._abortControllerType = requireFunc(\"abort-controller\");\n } else {\n this._abortControllerType = AbortController;\n }\n }\n /** @inheritDoc */\n async send(request) {\n // Check that abort was not signaled before calling send\n if (request.abortSignal && request.abortSignal.aborted) {\n throw new AbortError();\n }\n if (!request.method) {\n throw new Error(\"No method defined.\");\n }\n if (!request.url) {\n throw new Error(\"No url defined.\");\n }\n const abortController = new this._abortControllerType();\n let error;\n // Hook our abortSignal into the abort controller\n if (request.abortSignal) {\n request.abortSignal.onabort = () => {\n abortController.abort();\n error = new AbortError();\n };\n }\n // If a timeout has been passed in, setup a timeout to call abort\n // Type needs to be any to fit window.setTimeout and NodeJS.setTimeout\n let timeoutId = null;\n if (request.timeout) {\n const msTimeout = request.timeout;\n timeoutId = setTimeout(() => {\n abortController.abort();\n this._logger.log(LogLevel.Warning, `Timeout from HTTP request.`);\n error = new TimeoutError();\n }, msTimeout);\n }\n if (request.content === \"\") {\n request.content = undefined;\n }\n if (request.content) {\n // Explicitly setting the Content-Type header for React Native on Android platform.\n request.headers = request.headers || {};\n if (isArrayBuffer(request.content)) {\n request.headers[\"Content-Type\"] = \"application/octet-stream\";\n } else {\n request.headers[\"Content-Type\"] = \"text/plain;charset=UTF-8\";\n }\n }\n let response;\n try {\n response = await this._fetchType(request.url, {\n body: request.content,\n cache: \"no-cache\",\n credentials: request.withCredentials === true ? \"include\" : \"same-origin\",\n headers: {\n \"X-Requested-With\": \"XMLHttpRequest\",\n ...request.headers\n },\n method: request.method,\n mode: \"cors\",\n redirect: \"follow\",\n signal: abortController.signal\n });\n } catch (e) {\n if (error) {\n throw error;\n }\n this._logger.log(LogLevel.Warning, `Error from HTTP request. ${e}.`);\n throw e;\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n if (request.abortSignal) {\n request.abortSignal.onabort = null;\n }\n }\n if (!response.ok) {\n const errorMessage = await deserializeContent(response, \"text\");\n throw new HttpError(errorMessage || response.statusText, response.status);\n }\n const content = deserializeContent(response, request.responseType);\n const payload = await content;\n return new HttpResponse(response.status, response.statusText, payload);\n }\n getCookieString(url) {\n let cookies = \"\";\n if (Platform.isNode && this._jar) {\n // @ts-ignore: unused variable\n this._jar.getCookies(url, (e, c) => cookies = c.join(\"; \"));\n }\n return cookies;\n }\n}\nfunction deserializeContent(response, responseType) {\n let content;\n switch (responseType) {\n case \"arraybuffer\":\n content = response.arrayBuffer();\n break;\n case \"text\":\n content = response.text();\n break;\n case \"blob\":\n case \"document\":\n case \"json\":\n throw new Error(`${responseType} is not supported.`);\n default:\n content = response.text();\n break;\n }\n return content;\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\nimport { AbortError, HttpError, TimeoutError } from \"./Errors\";\nimport { HttpClient, HttpResponse } from \"./HttpClient\";\nimport { LogLevel } from \"./ILogger\";\nimport { isArrayBuffer } from \"./Utils\";\nexport class XhrHttpClient extends HttpClient {\n constructor(logger) {\n super();\n this._logger = logger;\n }\n /** @inheritDoc */\n send(request) {\n // Check that abort was not signaled before calling send\n if (request.abortSignal && request.abortSignal.aborted) {\n return Promise.reject(new AbortError());\n }\n if (!request.method) {\n return Promise.reject(new Error(\"No method defined.\"));\n }\n if (!request.url) {\n return Promise.reject(new Error(\"No url defined.\"));\n }\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(request.method, request.url, true);\n xhr.withCredentials = request.withCredentials === undefined ? true : request.withCredentials;\n xhr.setRequestHeader(\"X-Requested-With\", \"XMLHttpRequest\");\n if (request.content === \"\") {\n request.content = undefined;\n }\n if (request.content) {\n // Explicitly setting the Content-Type header for React Native on Android platform.\n if (isArrayBuffer(request.content)) {\n xhr.setRequestHeader(\"Content-Type\", \"application/octet-stream\");\n } else {\n xhr.setRequestHeader(\"Content-Type\", \"text/plain;charset=UTF-8\");\n }\n }\n const headers = request.headers;\n if (headers) {\n Object.keys(headers).forEach(header => {\n xhr.setRequestHeader(header, headers[header]);\n });\n }\n if (request.responseType) {\n xhr.responseType = request.responseType;\n }\n if (request.abortSignal) {\n request.abortSignal.onabort = () => {\n xhr.abort();\n reject(new AbortError());\n };\n }\n if (request.timeout) {\n xhr.timeout = request.timeout;\n }\n xhr.onload = () => {\n if (request.abortSignal) {\n request.abortSignal.onabort = null;\n }\n if (xhr.status >= 200 && xhr.status < 300) {\n resolve(new HttpResponse(xhr.status, xhr.statusText, xhr.response || xhr.responseText));\n } else {\n reject(new HttpError(xhr.response || xhr.responseText || xhr.statusText, xhr.status));\n }\n };\n xhr.onerror = () => {\n this._logger.log(LogLevel.Warning, `Error from HTTP request. ${xhr.status}: ${xhr.statusText}.`);\n reject(new HttpError(xhr.statusText, xhr.status));\n };\n xhr.ontimeout = () => {\n this._logger.log(LogLevel.Warning, `Timeout from HTTP request.`);\n reject(new TimeoutError());\n };\n xhr.send(request.content);\n });\n }\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\nimport { AbortError } from \"./Errors\";\nimport { FetchHttpClient } from \"./FetchHttpClient\";\nimport { HttpClient } from \"./HttpClient\";\nimport { Platform } from \"./Utils\";\nimport { XhrHttpClient } from \"./XhrHttpClient\";\n/** Default implementation of {@link @microsoft/signalr.HttpClient}. */\nexport class DefaultHttpClient extends HttpClient {\n /** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */\n constructor(logger) {\n super();\n if (typeof fetch !== \"undefined\" || Platform.isNode) {\n this._httpClient = new FetchHttpClient(logger);\n } else if (typeof XMLHttpRequest !== \"undefined\") {\n this._httpClient = new XhrHttpClient(logger);\n } else {\n throw new Error(\"No usable HttpClient found.\");\n }\n }\n /** @inheritDoc */\n send(request) {\n // Check that abort was not signaled before calling send\n if (request.abortSignal && request.abortSignal.aborted) {\n return Promise.reject(new AbortError());\n }\n if (!request.method) {\n return Promise.reject(new Error(\"No method defined.\"));\n }\n if (!request.url) {\n return Promise.reject(new Error(\"No url defined.\"));\n }\n return this._httpClient.send(request);\n }\n getCookieString(url) {\n return this._httpClient.getCookieString(url);\n }\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// Not exported from index\n/** @private */\nexport class TextMessageFormat {\n static write(output) {\n return `${output}${TextMessageFormat.RecordSeparator}`;\n }\n static parse(input) {\n if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) {\n throw new Error(\"Message is incomplete.\");\n }\n const messages = input.split(TextMessageFormat.RecordSeparator);\n messages.pop();\n return messages;\n }\n}\nTextMessageFormat.RecordSeparatorCode = 0x1e;\nTextMessageFormat.RecordSeparator = String.fromCharCode(TextMessageFormat.RecordSeparatorCode);\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\nimport { TextMessageFormat } from \"./TextMessageFormat\";\nimport { isArrayBuffer } from \"./Utils\";\n/** @private */\nexport class HandshakeProtocol {\n // Handshake request is always JSON\n writeHandshakeRequest(handshakeRequest) {\n return TextMessageFormat.write(JSON.stringify(handshakeRequest));\n }\n parseHandshakeResponse(data) {\n let messageData;\n let remainingData;\n if (isArrayBuffer(data)) {\n // Format is binary but still need to read JSON text from handshake response\n const binaryData = new Uint8Array(data);\n const separatorIndex = binaryData.indexOf(TextMessageFormat.RecordSeparatorCode);\n if (separatorIndex === -1) {\n throw new Error(\"Message is incomplete.\");\n }\n // content before separator is handshake response\n // optional content after is additional messages\n const responseLength = separatorIndex + 1;\n messageData = String.fromCharCode.apply(null, Array.prototype.slice.call(binaryData.slice(0, responseLength)));\n remainingData = binaryData.byteLength > responseLength ? binaryData.slice(responseLength).buffer : null;\n } else {\n const textData = data;\n const separatorIndex = textData.indexOf(TextMessageFormat.RecordSeparator);\n if (separatorIndex === -1) {\n throw new Error(\"Message is incomplete.\");\n }\n // content before separator is handshake response\n // optional content after is additional messages\n const responseLength = separatorIndex + 1;\n messageData = textData.substring(0, responseLength);\n remainingData = textData.length > responseLength ? textData.substring(responseLength) : null;\n }\n // At this point we should have just the single handshake message\n const messages = TextMessageFormat.parse(messageData);\n const response = JSON.parse(messages[0]);\n if (response.type) {\n throw new Error(\"Expected a handshake response from the server.\");\n }\n const responseMessage = response;\n // multiple messages could have arrived with handshake\n // return additional data to be parsed as usual, or null if all parsed\n return [remainingData, responseMessage];\n }\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n/** Defines the type of a Hub Message. */\nexport var MessageType = /*#__PURE__*/function (MessageType) {\n /** Indicates the message is an Invocation message and implements the {@link @microsoft/signalr.InvocationMessage} interface. */\n MessageType[MessageType[\"Invocation\"] = 1] = \"Invocation\";\n /** Indicates the message is a StreamItem message and implements the {@link @microsoft/signalr.StreamItemMessage} interface. */\n MessageType[MessageType[\"StreamItem\"] = 2] = \"StreamItem\";\n /** Indicates the message is a Completion message and implements the {@link @microsoft/signalr.CompletionMessage} interface. */\n MessageType[MessageType[\"Completion\"] = 3] = \"Completion\";\n /** Indicates the message is a Stream Invocation message and implements the {@link @microsoft/signalr.StreamInvocationMessage} interface. */\n MessageType[MessageType[\"StreamInvocation\"] = 4] = \"StreamInvocation\";\n /** Indicates the message is a Cancel Invocation message and implements the {@link @microsoft/signalr.CancelInvocationMessage} interface. */\n MessageType[MessageType[\"CancelInvocation\"] = 5] = \"CancelInvocation\";\n /** Indicates the message is a Ping message and implements the {@link @microsoft/signalr.PingMessage} interface. */\n MessageType[MessageType[\"Ping\"] = 6] = \"Ping\";\n /** Indicates the message is a Close message and implements the {@link @microsoft/signalr.CloseMessage} interface. */\n MessageType[MessageType[\"Close\"] = 7] = \"Close\";\n MessageType[MessageType[\"Ack\"] = 8] = \"Ack\";\n MessageType[MessageType[\"Sequence\"] = 9] = \"Sequence\";\n return MessageType;\n}(MessageType || {});\n\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\nimport { SubjectSubscription } from \"./Utils\";\n/** Stream implementation to stream items to the server. */\nexport class Subject {\n constructor() {\n this.observers = [];\n }\n next(item) {\n for (const observer of this.observers) {\n observer.next(item);\n }\n }\n error(err) {\n for (const observer of this.observers) {\n if (observer.error) {\n observer.error(err);\n }\n }\n }\n complete() {\n for (const observer of this.observers) {\n if (observer.complete) {\n observer.complete();\n }\n }\n }\n subscribe(observer) {\n this.observers.push(observer);\n return new SubjectSubscription(this, observer);\n }\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\nimport { MessageType } from \"./IHubProtocol\";\nimport { isArrayBuffer } from \"./Utils\";\n/** @private */\nexport class MessageBuffer {\n constructor(protocol, connection, bufferSize) {\n this._bufferSize = 100000;\n this._messages = [];\n this._totalMessageCount = 0;\n this._waitForSequenceMessage = false;\n // Message IDs start at 1 and always increment by 1\n this._nextReceivingSequenceId = 1;\n this._latestReceivedSequenceId = 0;\n this._bufferedByteCount = 0;\n this._reconnectInProgress = false;\n this._protocol = protocol;\n this._connection = connection;\n this._bufferSize = bufferSize;\n }\n async _send(message) {\n const serializedMessage = this._protocol.writeMessage(message);\n let backpressurePromise = Promise.resolve();\n // Only count invocation messages. Acks, pings, etc. don't need to be resent on reconnect\n if (this._isInvocationMessage(message)) {\n this._totalMessageCount++;\n let backpressurePromiseResolver = () => {};\n let backpressurePromiseRejector = () => {};\n if (isArrayBuffer(serializedMessage)) {\n this._bufferedByteCount += serializedMessage.byteLength;\n } else {\n this._bufferedByteCount += serializedMessage.length;\n }\n if (this._bufferedByteCount >= this._bufferSize) {\n backpressurePromise = new Promise((resolve, reject) => {\n backpressurePromiseResolver = resolve;\n backpressurePromiseRejector = reject;\n });\n }\n this._messages.push(new BufferedItem(serializedMessage, this._totalMessageCount, backpressurePromiseResolver, backpressurePromiseRejector));\n }\n try {\n // If this is set it means we are reconnecting or resending\n // We don't want to send on a disconnected connection\n // And we don't want to send if resend is running since that would mean sending\n // this message twice\n if (!this._reconnectInProgress) {\n await this._connection.send(serializedMessage);\n }\n } catch {\n this._disconnected();\n }\n await backpressurePromise;\n }\n _ack(ackMessage) {\n let newestAckedMessage = -1;\n // Find index of newest message being acked\n for (let index = 0; index < this._messages.length; index++) {\n const element = this._messages[index];\n if (element._id <= ackMessage.sequenceId) {\n newestAckedMessage = index;\n if (isArrayBuffer(element._message)) {\n this._bufferedByteCount -= element._message.byteLength;\n } else {\n this._bufferedByteCount -= element._message.length;\n }\n // resolve items that have already been sent and acked\n element._resolver();\n } else if (this._bufferedByteCount < this._bufferSize) {\n // resolve items that now fall under the buffer limit but haven't been acked\n element._resolver();\n } else {\n break;\n }\n }\n if (newestAckedMessage !== -1) {\n // We're removing everything including the message pointed to, so add 1\n this._messages = this._messages.slice(newestAckedMessage + 1);\n }\n }\n _shouldProcessMessage(message) {\n if (this._waitForSequenceMessage) {\n if (message.type !== MessageType.Sequence) {\n return false;\n } else {\n this._waitForSequenceMessage = false;\n return true;\n }\n }\n // No special processing for acks, pings, etc.\n if (!this._isInvocationMessage(message)) {\n return true;\n }\n const currentId = this._nextReceivingSequenceId;\n this._nextReceivingSequenceId++;\n if (currentId <= this._latestReceivedSequenceId) {\n if (currentId === this._latestReceivedSequenceId) {\n // Should only hit this if we just reconnected and the server is sending\n // Messages it has buffered, which would mean it hasn't seen an Ack for these messages\n this._ackTimer();\n }\n // Ignore, this is a duplicate message\n return false;\n }\n this._latestReceivedSequenceId = currentId;\n // Only start the timer for sending an Ack message when we have a message to ack. This also conveniently solves\n // timer throttling by not having a recursive timer, and by starting the timer via a network call (recv)\n this._ackTimer();\n return true;\n }\n _resetSequence(message) {\n if (message.sequenceId > this._nextReceivingSequenceId) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._connection.stop(new Error(\"Sequence ID greater than amount of messages we've received.\"));\n return;\n }\n this._nextReceivingSequenceId = message.sequenceId;\n }\n _disconnected() {\n this._reconnectInProgress = true;\n this._waitForSequenceMessage = true;\n }\n async _resend() {\n const sequenceId = this._messages.length !== 0 ? this._messages[0]._id : this._totalMessageCount + 1;\n await this._connection.send(this._protocol.writeMessage({\n type: MessageType.Sequence,\n sequenceId\n }));\n // Get a local variable to the _messages, just in case messages are acked while resending\n // Which would slice the _messages array (which creates a new copy)\n const messages = this._messages;\n for (const element of messages) {\n await this._connection.send(element._message);\n }\n this._reconnectInProgress = false;\n }\n _dispose(error) {\n error !== null && error !== void 0 ? error : error = new Error(\"Unable to reconnect to server.\");\n // Unblock backpressure if any\n for (const element of this._messages) {\n element._rejector(error);\n }\n }\n _isInvocationMessage(message) {\n // There is no way to check if something implements an interface.\n // So we individually check the messages in a switch statement.\n // To make sure we don't miss any message types we rely on the compiler\n // seeing the function returns a value and it will do the\n // exhaustive check for us on the switch statement, since we don't use 'case default'\n switch (message.type) {\n case MessageType.Invocation:\n case MessageType.StreamItem:\n case MessageType.Completion:\n case MessageType.StreamInvocation:\n case MessageType.CancelInvocation:\n return true;\n case MessageType.Close:\n case MessageType.Sequence:\n case MessageType.Ping:\n case MessageType.Ack:\n return false;\n }\n }\n _ackTimer() {\n if (this._ackTimerHandle === undefined) {\n this._ackTimerHandle = setTimeout(async () => {\n try {\n if (!this._reconnectInProgress) {\n await this._connection.send(this._protocol.writeMessage({\n type: MessageType.Ack,\n sequenceId: this._latestReceivedSequenceId\n }));\n }\n // Ignore errors, that means the connection is closed and we don't care about the Ack message anymore.\n } catch {}\n clearTimeout(this._ackTimerHandle);\n this._ackTimerHandle = undefined;\n // 1 second delay so we don't spam Ack messages if there are many messages being received at once.\n }, 1000);\n }\n }\n}\nclass BufferedItem {\n constructor(message, id, resolver, rejector) {\n this._message = message;\n this._id = id;\n this._resolver = resolver;\n this._rejector = rejector;\n }\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\nimport { HandshakeProtocol } from \"./HandshakeProtocol\";\nimport { AbortError } from \"./Errors\";\nimport { MessageType } from \"./IHubProtocol\";\nimport { LogLevel } from \"./ILogger\";\nimport { Subject } from \"./Subject\";\nimport { Arg, getErrorString, Platform } from \"./Utils\";\nimport { MessageBuffer } from \"./MessageBuffer\";\nconst DEFAULT_TIMEOUT_IN_MS = 30 * 1000;\nconst DEFAULT_PING_INTERVAL_IN_MS = 15 * 1000;\nconst DEFAULT_STATEFUL_RECONNECT_BUFFER_SIZE = 100000;\n/** Describes the current state of the {@link HubConnection} to the server. */\nexport var HubConnectionState = /*#__PURE__*/function (HubConnectionState) {\n /** The hub connection is disconnected. */\n HubConnectionState[\"Disconnected\"] = \"Disconnected\";\n /** The hub connection is connecting. */\n HubConnectionState[\"Connecting\"] = \"Connecting\";\n /** The hub connection is connected. */\n HubConnectionState[\"Connected\"] = \"Connected\";\n /** The hub connection is disconnecting. */\n HubConnectionState[\"Disconnecting\"] = \"Disconnecting\";\n /** The hub connection is reconnecting. */\n HubConnectionState[\"Reconnecting\"] = \"Reconnecting\";\n return HubConnectionState;\n}(HubConnectionState || {});\n/** Represents a connection to a SignalR Hub. */\nexport class HubConnection {\n /** @internal */\n // Using a public static factory method means we can have a private constructor and an _internal_\n // create method that can be used by HubConnectionBuilder. An \"internal\" constructor would just\n // be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a\n // public parameter-less constructor.\n static create(connection, logger, protocol, reconnectPolicy, serverTimeoutInMilliseconds, keepAliveIntervalInMilliseconds, statefulReconnectBufferSize) {\n return new HubConnection(connection, logger, protocol, reconnectPolicy, serverTimeoutInMilliseconds, keepAliveIntervalInMilliseconds, statefulReconnectBufferSize);\n }\n constructor(connection, logger, protocol, reconnectPolicy, serverTimeoutInMilliseconds, keepAliveIntervalInMilliseconds, statefulReconnectBufferSize) {\n this._nextKeepAlive = 0;\n this._freezeEventListener = () => {\n 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://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep\");\n };\n Arg.isRequired(connection, \"connection\");\n Arg.isRequired(logger, \"logger\");\n Arg.isRequired(protocol, \"protocol\");\n this.serverTimeoutInMilliseconds = serverTimeoutInMilliseconds !== null && serverTimeoutInMilliseconds !== void 0 ? serverTimeoutInMilliseconds : DEFAULT_TIMEOUT_IN_MS;\n this.keepAliveIntervalInMilliseconds = keepAliveIntervalInMilliseconds !== null && keepAliveIntervalInMilliseconds !== void 0 ? keepAliveIntervalInMilliseconds : DEFAULT_PING_INTERVAL_IN_MS;\n this._statefulReconnectBufferSize = statefulReconnectBufferSize !== null && statefulReconnectBufferSize !== void 0 ? statefulReconnectBufferSize : DEFAULT_STATEFUL_RECONNECT_BUFFER_SIZE;\n this._logger = logger;\n this._protocol = protocol;\n this.connection = connection;\n this._reconnectPolicy = reconnectPolicy;\n this._handshakeProtocol = new HandshakeProtocol();\n this.connection.onreceive = data => this._processIncomingData(data);\n this.connection.onclose = error => this._connectionClosed(error);\n this._callbacks = {};\n this._methods = {};\n this._closedCallbacks = [];\n this._reconnectingCallbacks = [];\n this._reconnectedCallbacks = [];\n this._invocationId = 0;\n this._receivedHandshakeResponse = false;\n this._connectionState = HubConnectionState.Disconnected;\n this._connectionStarted = false;\n this._cachedPingMessage = this._protocol.writeMessage({\n type: MessageType.Ping\n });\n }\n /** Indicates the state of the {@link HubConnection} to the server. */\n get state() {\n return this._connectionState;\n }\n /** Represents the connection id of the {@link HubConnection} on the server. The connection id will be null when the connection is either\r\n * in the disconnected state or if the negotiation step was skipped.\r\n */\n get connectionId() {\n return this.connection ? this.connection.connectionId || null : null;\n }\n /** Indicates the url of the {@link HubConnection} to the server. */\n get baseUrl() {\n return this.connection.baseUrl || \"\";\n }\n /**\r\n * Sets a new url for the HubConnection. Note that the url can only be changed when the connection is in either the Disconnected or\r\n * Reconnecting states.\r\n * @param {string} url The url to connect to.\r\n */\n set baseUrl(url) {\n if (this._connectionState !== HubConnectionState.Disconnected && this._connectionState !== HubConnectionState.Reconnecting) {\n throw new Error(\"The HubConnection must be in the Disconnected or Reconnecting state to change the url.\");\n }\n if (!url) {\n throw new Error(\"The HubConnection url must be a valid url.\");\n }\n this.connection.baseUrl = url;\n }\n /** Starts the connection.\r\n *\r\n * @returns {Promise} A Promise that resolves when the connection has been successfully established, or rejects with an error.\r\n */\n start() {\n this._startPromise = this._startWithStateTransitions();\n return this._startPromise;\n }\n async _startWithStateTransitions() {\n if (this._connectionState !== HubConnectionState.Disconnected) {\n return Promise.reject(new Error(\"Cannot start a HubConnection that is not in the 'Disconnected' state.\"));\n }\n this._connectionState = HubConnectionState.Connecting;\n this._logger.log(LogLevel.Debug, \"Starting HubConnection.\");\n try {\n await this._startInternal();\n if (Platform.isBrowser) {\n // Log when the browser freezes the tab so users know why their connection unexpectedly stopped working\n window.document.addEventListener(\"freeze\", this._freezeEventListener);\n }\n this._connectionState = HubConnectionState.Connected;\n this._connectionStarted = true;\n this._logger.log(LogLevel.Debug, \"HubConnection connected successfully.\");\n } catch (e) {\n this._connectionState = HubConnectionState.Disconnected;\n this._logger.log(LogLevel.Debug, `HubConnection failed to start successfully because of error '${e}'.`);\n return Promise.reject(e);\n }\n }\n async _startInternal() {\n this._stopDuringStartError = undefined;\n this._receivedHandshakeResponse = false;\n // Set up the promise before any connection is (re)started otherwise it could race with received messages\n const handshakePromise = new Promise((resolve, reject) => {\n this._handshakeResolver = resolve;\n this._handshakeRejecter = reject;\n });\n await this.connection.start(this._protocol.transferFormat);\n try {\n let version = this._protocol.version;\n if (!this.connection.features.reconnect) {\n // Stateful Reconnect starts with HubProtocol version 2, newer clients connecting to older servers will fail to connect due to\n // the handshake only supporting version 1, so we will try to send version 1 during the handshake to keep old servers working.\n version = 1;\n }\n const handshakeRequest = {\n protocol: this._protocol.name,\n version\n };\n this._logger.log(LogLevel.Debug, \"Sending handshake request.\");\n await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(handshakeRequest));\n this._logger.log(LogLevel.Information, `Using HubProtocol '${this._protocol.name}'.`);\n // defensively cleanup timeout in case we receive a message from the server before we finish start\n this._cleanupTimeout();\n this._resetTimeoutPeriod();\n this._resetKeepAliveInterval();\n await handshakePromise;\n // It's important to check the stopDuringStartError instead of just relying on the handshakePromise\n // being rejected on close, because this continuation can run after both the handshake completed successfully\n // and the connection was closed.\n if (this._stopDuringStartError) {\n // It's important to throw instead of returning a rejected promise, because we don't want to allow any state\n // transitions to occur between now and the calling code observing the exceptions. Returning a rejected promise\n // will cause the calling continuation to get scheduled to run later.\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw this._stopDuringStartError;\n }\n const useStatefulReconnect = this.connection.features.reconnect || false;\n if (useStatefulReconnect) {\n this._messageBuffer = new MessageBuffer(this._protocol, this.connection, this._statefulReconnectBufferSize);\n this.connection.features.disconnected = this._messageBuffer._disconnected.bind(this._messageBuffer);\n this.connection.features.resend = () => {\n if (this._messageBuffer) {\n return this._messageBuffer._resend();\n }\n };\n }\n if (!this.connection.features.inherentKeepAlive) {\n await this._sendMessage(this._cachedPingMessage);\n }\n } catch (e) {\n this._logger.log(LogLevel.Debug, `Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`);\n this._cleanupTimeout();\n this._cleanupPingTimer();\n // HttpConnection.stop() should not complete until after the onclose callback is invoked.\n // This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes.\n await this.connection.stop(e);\n throw e;\n }\n }\n /** Stops the connection.\r\n *\r\n * @returns {Promise} A Promise that resolves when the connection has been successfully terminated, or rejects with an error.\r\n */\n async stop() {\n // Capture the start promise before the connection might be restarted in an onclose callback.\n const startPromise = this._startPromise;\n this.connection.features.reconnect = false;\n this._stopPromise = this._stopInternal();\n await this._stopPromise;\n try {\n // Awaiting undefined continues immediately\n await startPromise;\n } catch (e) {\n // This exception is returned to the user as a rejected Promise from the start method.\n }\n }\n _stopInternal(error) {\n if (this._connectionState === HubConnectionState.Disconnected) {\n this._logger.log(LogLevel.Debug, `Call to HubConnection.stop(${error}) ignored because it is already in the disconnected state.`);\n return Promise.resolve();\n }\n if (this._connectionState === HubConnectionState.Disconnecting) {\n this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);\n return this._stopPromise;\n }\n const state = this._connectionState;\n this._connectionState = HubConnectionState.Disconnecting;\n this._logger.log(LogLevel.Debug, \"Stopping HubConnection.\");\n if (this._reconnectDelayHandle) {\n // We're in a reconnect delay which means the underlying connection is currently already stopped.\n // Just clear the handle to stop the reconnect loop (which no one is waiting on thankfully) and\n // fire the onclose callbacks.\n this._logger.log(LogLevel.Debug, \"Connection stopped during reconnect delay. Done reconnecting.\");\n clearTimeout(this._reconnectDelayHandle);\n this._reconnectDelayHandle = undefined;\n this._completeClose();\n return Promise.resolve();\n }\n if (state === HubConnectionState.Connected) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._sendCloseMessage();\n }\n this._cleanupTimeout();\n this._cleanupPingTimer();\n this._stopDuringStartError = error || new AbortError(\"The connection was stopped before the hub handshake could complete.\");\n // HttpConnection.stop() should not complete until after either HttpConnection.start() fails\n // or the onclose callback is invoked. The onclose callback will transition the HubConnection\n // to the disconnected state if need be before HttpConnection.stop() completes.\n return this.connection.stop(error);\n }\n async _sendCloseMessage() {\n try {\n await this._sendWithProtocol(this._createCloseMessage());\n } catch {\n // Ignore, this is a best effort attempt to let the server know the client closed gracefully.\n }\n }\n /** Invokes a streaming hub method on the server using the specified name and arguments.\r\n *\r\n * @typeparam T The type of the items returned by the server.\r\n * @param {string} methodName The name of the server method to invoke.\r\n * @param {any[]} args The arguments used to invoke the server method.\r\n * @returns {IStreamResult} An object that yields results from the server as they are received.\r\n */\n stream(methodName, ...args) {\n const [streams, streamIds] = this._replaceStreamingParams(args);\n const invocationDescriptor = this._createStreamInvocation(methodName, args, streamIds);\n // eslint-disable-next-line prefer-const\n let promiseQueue;\n const subject = new Subject();\n subject.cancelCallback = () => {\n const cancelInvocation = this._createCancelInvocation(invocationDescriptor.invocationId);\n delete this._callbacks[invocationDescriptor.invocationId];\n return promiseQueue.then(() => {\n return this._sendWithProtocol(cancelInvocation);\n });\n };\n this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => {\n if (error) {\n subject.error(error);\n return;\n } else if (invocationEvent) {\n // invocationEvent will not be null when an error is not passed to the callback\n if (invocationEvent.type === MessageType.Completion) {\n if (invocationEvent.error) {\n subject.error(new Error(invocationEvent.error));\n } else {\n subject.complete();\n }\n } else {\n subject.next(invocationEvent.item);\n }\n }\n };\n promiseQueue = this._sendWithProtocol(invocationDescriptor).catch(e => {\n subject.error(e);\n delete this._callbacks[invocationDescriptor.invocationId];\n });\n this._launchStreams(streams, promiseQueue);\n return subject;\n }\n _sendMessage(message) {\n this._resetKeepAliveInterval();\n return this.connection.send(message);\n }\n /**\r\n * Sends a js object to the server.\r\n * @param message The js object to serialize and send.\r\n */\n _sendWithProtocol(message) {\n if (this._messageBuffer) {\n return this._messageBuffer._send(message);\n } else {\n return this._sendMessage(this._protocol.writeMessage(message));\n }\n }\n /** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver.\r\n *\r\n * The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still\r\n * be processing the invocation.\r\n *\r\n * @param {string} methodName The name of the server method to invoke.\r\n * @param {any[]} args The arguments used to invoke the server method.\r\n * @returns {Promise} A Promise that resolves when the invocation has been successfully sent, or rejects with an error.\r\n */\n send(methodName, ...args) {\n const [streams, streamIds] = this._replaceStreamingParams(args);\n const sendPromise = this._sendWithProtocol(this._createInvocation(methodName, args, true, streamIds));\n this._launchStreams(streams, sendPromise);\n return sendPromise;\n }\n /** Invokes a hub method on the server using the specified name and arguments.\r\n *\r\n * The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise\r\n * resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of\r\n * resolving the Promise.\r\n *\r\n * @typeparam T The expected return type.\r\n * @param {string} methodName The name of the server method to invoke.\r\n * @param {any[]} args The arguments used to invoke the server method.\r\n * @returns {Promise} A Promise that resolves with the result of the server method (if any), or rejects with an error.\r\n */\n invoke(methodName, ...args) {\n const [streams, streamIds] = this._replaceStreamingParams(args);\n const invocationDescriptor = this._createInvocation(methodName, args, false, streamIds);\n const p = new Promise((resolve, reject) => {\n // invocationId will always have a value for a non-blocking invocation\n this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => {\n if (error) {\n reject(error);\n return;\n } else if (invocationEvent) {\n // invocationEvent will not be null when an error is not passed to the callback\n if (invocationEvent.type === MessageType.Completion) {\n if (invocationEvent.error) {\n reject(new Error(invocationEvent.error));\n } else {\n resolve(invocationEvent.result);\n }\n } else {\n reject(new Error(`Unexpected message type: ${invocationEvent.type}`));\n }\n }\n };\n const promiseQueue = this._sendWithProtocol(invocationDescriptor).catch(e => {\n reject(e);\n // invocationId will always have a value for a non-blocking invocation\n delete this._callbacks[invocationDescriptor.invocationId];\n });\n this._launchStreams(streams, promiseQueue);\n });\n return p;\n }\n on(methodName, newMethod) {\n if (!methodName || !newMethod) {\n return;\n }\n methodName = methodName.toLowerCase();\n if (!this._methods[methodName]) {\n this._methods[methodName] = [];\n }\n // Preventing adding the same handler multiple times.\n if (this._methods[methodName].indexOf(newMethod) !== -1) {\n return;\n }\n this._methods[methodName].push(newMethod);\n }\n off(methodName, method) {\n if (!methodName) {\n return;\n }\n methodName = methodName.toLowerCase();\n const handlers = this._methods[methodName];\n if (!handlers) {\n return;\n }\n if (method) {\n const removeIdx = handlers.indexOf(method);\n if (removeIdx !== -1) {\n handlers.splice(removeIdx, 1);\n if (handlers.length === 0) {\n delete this._methods[methodName];\n }\n }\n } else {\n delete this._methods[methodName];\n }\n }\n /** Registers a handler that will be invoked when the connection is closed.\r\n *\r\n * @param {Function} callback The handler that will be invoked when the connection is closed. Optionally receives a single argument containing the error that caused the connection to close (if any).\r\n */\n onclose(callback) {\n if (callback) {\n this._closedCallbacks.push(callback);\n }\n }\n /** Registers a handler that will be invoked when the connection starts reconnecting.\r\n *\r\n * @param {Function} callback The handler that will be invoked when the connection starts reconnecting. Optionally receives a single argument containing the error that caused the connection to start reconnecting (if any).\r\n */\n onreconnecting(callback) {\n if (callback) {\n this._reconnectingCallbacks.push(callback);\n }\n }\n /** Registers a handler that will be invoked when the connection successfully reconnects.\r\n *\r\n * @param {Function} callback The handler that will be invoked when the connection successfully reconnects.\r\n */\n onreconnected(callback) {\n if (callback) {\n this._reconnectedCallbacks.push(callback);\n }\n }\n _processIncomingData(data) {\n this._cleanupTimeout();\n if (!this._receivedHandshakeResponse) {\n data = this._processHandshakeResponse(data);\n this._receivedHandshakeResponse = true;\n }\n // Data may have all been read when processing handshake response\n if (data) {\n // Parse the messages\n const messages = this._protocol.parseMessages(data, this._logger);\n for (const message of messages) {\n if (this._messageBuffer && !this._messageBuffer._shouldProcessMessage(message)) {\n // Don't process the message, we are either waiting for a SequenceMessage or received a duplicate message\n continue;\n }\n switch (message.type) {\n case MessageType.Invocation:\n this._invokeClientMethod(message).catch(e => {\n this._logger.log(LogLevel.Error, `Invoke client method threw error: ${getErrorString(e)}`);\n });\n break;\n case MessageType.StreamItem:\n case MessageType.Completion:\n {\n const callback = this._callbacks[message.invocationId];\n if (callback) {\n if (message.type === MessageType.Completion) {\n delete this._callbacks[message.invocationId];\n }\n try {\n callback(message);\n } catch (e) {\n this._logger.log(LogLevel.Error, `Stream callback threw error: ${getErrorString(e)}`);\n }\n }\n break;\n }\n case MessageType.Ping:\n // Don't care about pings\n break;\n case MessageType.Close:\n {\n this._logger.log(LogLevel.Information, \"Close message received from server.\");\n const error = message.error ? new Error(\"Server returned an error on close: \" + message.error) : undefined;\n if (message.allowReconnect === true) {\n // It feels wrong not to await connection.stop() here, but processIncomingData is called as part of an onreceive callback which is not async,\n // this is already the behavior for serverTimeout(), and HttpConnection.Stop() should catch and log all possible exceptions.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.connection.stop(error);\n } else {\n // We cannot await stopInternal() here, but subsequent calls to stop() will await this if stopInternal() is still ongoing.\n this._stopPromise = this._stopInternal(error);\n }\n break;\n }\n case MessageType.Ack:\n if (this._messageBuffer) {\n this._messageBuffer._ack(message);\n }\n break;\n case MessageType.Sequence:\n if (this._messageBuffer) {\n this._messageBuffer._resetSequence(message);\n }\n break;\n default:\n this._logger.log(LogLevel.Warning, `Invalid message type: ${message.type}.`);\n break;\n }\n }\n }\n this._resetTimeoutPeriod();\n }\n _processHandshakeResponse(data) {\n let responseMessage;\n let remainingData;\n try {\n [remainingData, responseMessage] = this._handshakeProtocol.parseHandshakeResponse(data);\n } catch (e) {\n const message = \"Error parsing handshake response: \" + e;\n this._logger.log(LogLevel.Error, message);\n const error = new Error(message);\n this._handshakeRejecter(error);\n throw error;\n }\n if (responseMessage.error) {\n const message = \"Server returned handshake error: \" + responseMessage.error;\n this._logger.log(LogLevel.Error, message);\n const error = new Error(message);\n this._handshakeRejecter(error);\n throw error;\n } else {\n this._logger.log(LogLevel.Debug, \"Server handshake complete.\");\n }\n this._handshakeResolver();\n return remainingData;\n }\n _resetKeepAliveInterval() {\n if (this.connection.features.inherentKeepAlive) {\n return;\n }\n // Set the time we want the next keep alive to be sent\n // Timer will be setup on next message receive\n this._nextKeepAlive = new Date().getTime() + this.keepAliveIntervalInMilliseconds;\n this._cleanupPingTimer();\n }\n _resetTimeoutPeriod() {\n if (!this.connection.features || !this.connection.features.inherentKeepAlive) {\n // Set the timeout timer\n this._timeoutHandle = setTimeout(() => this.serverTimeout(), this.serverTimeoutInMilliseconds);\n // Set keepAlive timer if there isn't one\n if (this._pingServerHandle === undefined) {\n let nextPing = this._nextKeepAlive - new Date().getTime();\n if (nextPing < 0) {\n nextPing = 0;\n }\n // The timer needs to be set from a networking callback to avoid Chrome timer throttling from causing timers to run once a minute\n this._pingServerHandle = setTimeout(async () => {\n if (this._connectionState === HubConnectionState.Connected) {\n try {\n await this._sendMessage(this._cachedPingMessage);\n } catch {\n // We don't care about the error. It should be seen elsewhere in the client.\n // The connection is probably in a bad or closed state now, cleanup the timer so it stops triggering\n this._cleanupPingTimer();\n }\n }\n }, nextPing);\n }\n }\n }\n // eslint-disable-next-line @typescript-eslint/naming-convention\n serverTimeout() {\n // The server hasn't talked to us in a while. It doesn't like us anymore ... :(\n // Terminate the connection, but we don't need to wait on the promise. This could trigger reconnecting.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.connection.stop(new Error(\"Server timeout elapsed without receiving a message from the server.\"));\n }\n async _invokeClientMethod(invocationMessage) {\n const methodName = invocationMessage.target.toLowerCase();\n const methods = this._methods[methodName];\n if (!methods) {\n this._logger.log(LogLevel.Warning, `No client method with the name '${methodName}' found.`);\n // No handlers provided by client but the server is expecting a response still, so we send an error\n if (invocationMessage.invocationId) {\n this._logger.log(LogLevel.Warning, `No result given for '${methodName}' method and invocation ID '${invocationMessage.invocationId}'.`);\n await this._sendWithProtocol(this._createCompletionMessage(invocationMessage.invocationId, \"Client didn't provide a result.\", null));\n }\n return;\n }\n // Avoid issues with handlers removing themselves thus modifying the list while iterating through it\n const methodsCopy = methods.slice();\n // Server expects a response\n const expectsResponse = invocationMessage.invocationId ? true : false;\n // We preserve the last result or exception but still call all handlers\n let res;\n let exception;\n let completionMessage;\n for (const m of methodsCopy) {\n try {\n const prevRes = res;\n res = await m.apply(this, invocationMessage.arguments);\n if (expectsResponse && res && prevRes) {\n this._logger.log(LogLevel.Error, `Multiple results provided for '${methodName}'. Sending error to server.`);\n completionMessage = this._createCompletionMessage(invocationMessage.invocationId, `Client provided multiple results.`, null);\n }\n // Ignore exception if we got a result after, the exception will be logged\n exception = undefined;\n } catch (e) {\n exception = e;\n this._logger.log(LogLevel.Error, `A callback for the method '${methodName}' threw error '${e}'.`);\n }\n }\n if (completionMessage) {\n await this._sendWithProtocol(completionMessage);\n } else if (expectsResponse) {\n // If there is an exception that means either no result was given or a handler after a result threw\n if (exception) {\n completionMessage = this._createCompletionMessage(invocationMessage.invocationId, `${exception}`, null);\n } else if (res !== undefined) {\n completionMessage = this._createCompletionMessage(invocationMessage.invocationId, null, res);\n } else {\n this._logger.log(LogLevel.Warning, `No result given for '${methodName}' method and invocation ID '${invocationMessage.invocationId}'.`);\n // Client didn't provide a result or throw from a handler, server expects a response so we send an error\n completionMessage = this._createCompletionMessage(invocationMessage.invocationId, \"Client didn't provide a result.\", null);\n }\n await this._sendWithProtocol(completionMessage);\n } else {\n if (res) {\n this._logger.log(LogLevel.Error, `Result given for '${methodName}' method but server is not expecting a result.`);\n }\n }\n }\n _connectionClosed(error) {\n this._logger.log(LogLevel.Debug, `HubConnection.connectionClosed(${error}) called while in state ${this._connectionState}.`);\n // Triggering this.handshakeRejecter is insufficient because it could already be resolved without the continuation having run yet.\n this._stopDuringStartError = this._stopDuringStartError || error || new AbortError(\"The underlying connection was closed before the hub handshake could complete.\");\n // If the handshake is in progress, start will be waiting for the handshake promise, so we complete it.\n // If it has already completed, this should just noop.\n if (this._handshakeResolver) {\n this._handshakeResolver();\n }\n this._cancelCallbacksWithError(error || new Error(\"Invocation canceled due to the underlying connection being closed.\"));\n this._cleanupTimeout();\n this._cleanupPingTimer();\n if (this._connectionState === HubConnectionState.Disconnecting) {\n this._completeClose(error);\n } else if (this._connectionState === HubConnectionState.Connected && this._reconnectPolicy) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._reconnect(error);\n } else if (this._connectionState === HubConnectionState.Connected) {\n this._completeClose(error);\n }\n // If none of the above if conditions were true were called the HubConnection must be in either:\n // 1. The Connecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail it.\n // 2. The Reconnecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail the current reconnect attempt\n // and potentially continue the reconnect() loop.\n // 3. The Disconnected state in which case we're already done.\n }\n _completeClose(error) {\n if (this._connectionStarted) {\n this._connectionState = HubConnectionState.Disconnected;\n this._connectionStarted = false;\n if (this._messageBuffer) {\n this._messageBuffer._dispose(error !== null && error !== void 0 ? error : new Error(\"Connection closed.\"));\n this._messageBuffer = undefined;\n }\n if (Platform.isBrowser) {\n window.document.removeEventListener(\"freeze\", this._freezeEventListener);\n }\n try {\n this._closedCallbacks.forEach(c => c.apply(this, [error]));\n } catch (e) {\n this._logger.log(LogLevel.Error, `An onclose callback called with error '${error}' threw error '${e}'.`);\n }\n }\n }\n async _reconnect(error) {\n const reconnectStartTime = Date.now();\n let previousReconnectAttempts = 0;\n let retryError = error !== undefined ? error : new Error(\"Attempting to reconnect due to a unknown error.\");\n let nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts++, 0, retryError);\n if (nextRetryDelay === null) {\n this._logger.log(LogLevel.Debug, \"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt.\");\n this._completeClose(error);\n return;\n }\n this._connectionState = HubConnectionState.Reconnecting;\n if (error) {\n this._logger.log(LogLevel.Information, `Connection reconnecting because of error '${error}'.`);\n } else {\n this._logger.log(LogLevel.Information, \"Connection reconnecting.\");\n }\n if (this._reconnectingCallbacks.length !== 0) {\n try {\n this._reconnectingCallbacks.forEach(c => c.apply(this, [error]));\n } catch (e) {\n this._logger.log(LogLevel.Error, `An onreconnecting callback called with error '${error}' threw error '${e}'.`);\n }\n // Exit early if an onreconnecting callback called connection.stop().\n if (this._connectionState !== HubConnectionState.Reconnecting) {\n this._logger.log(LogLevel.Debug, \"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.\");\n return;\n }\n }\n while (nextRetryDelay !== null) {\n this._logger.log(LogLevel.Information, `Reconnect attempt number ${previousReconnectAttempts} will start in ${nextRetryDelay} ms.`);\n await new Promise(resolve => {\n this._reconnectDelayHandle = setTimeout(resolve, nextRetryDelay);\n });\n this._reconnectDelayHandle = undefined;\n if (this._connectionState !== HubConnectionState.Reconnecting) {\n this._logger.log(LogLevel.Debug, \"Connection left the reconnecting state during reconnect delay. Done reconnecting.\");\n return;\n }\n try {\n await this._startInternal();\n this._connectionState = HubConnectionState.Connected;\n this._logger.log(LogLevel.Information, \"HubConnection reconnected successfully.\");\n if (this._reconnectedCallbacks.length !== 0) {\n try {\n this._reconnectedCallbacks.forEach(c => c.apply(this, [this.connection.connectionId]));\n } catch (e) {\n this._logger.log(LogLevel.Error, `An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`);\n }\n }\n return;\n } catch (e) {\n this._logger.log(LogLevel.Information, `Reconnect attempt failed because of error '${e}'.`);\n if (this._connectionState !== HubConnectionState.Reconnecting) {\n this._logger.log(LogLevel.Debug, `Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`);\n // The TypeScript compiler thinks that connectionState must be Connected here. The TypeScript compiler is wrong.\n if (this._connectionState === HubConnectionState.Disconnecting) {\n this._completeClose();\n }\n return;\n }\n retryError = e instanceof Error ? e : new Error(e.toString());\n nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts++, Date.now() - reconnectStartTime, retryError);\n }\n }\n this._logger.log(LogLevel.Information, `Reconnect retries have been exhausted after ${Date.now() - reconnectStartTime} ms and ${previousReconnectAttempts} failed attempts. Connection disconnecting.`);\n this._completeClose();\n }\n _getNextRetryDelay(previousRetryCount, elapsedMilliseconds, retryReason) {\n try {\n return this._reconnectPolicy.nextRetryDelayInMilliseconds({\n elapsedMilliseconds,\n previousRetryCount,\n retryReason\n });\n } catch (e) {\n this._logger.log(LogLevel.Error, `IRetryPolicy.nextRetryDelayInMilliseconds(${previousRetryCount}, ${elapsedMilliseconds}) threw error '${e}'.`);\n return null;\n }\n }\n _cancelCallbacksWithError(error) {\n const callbacks = this._callbacks;\n this._callbacks = {};\n Object.keys(callbacks).forEach(key => {\n const callback = callbacks[key];\n try {\n callback(null, error);\n } catch (e) {\n this._logger.log(LogLevel.Error, `Stream 'error' callback called with '${error}' threw error: ${getErrorString(e)}`);\n }\n });\n }\n _cleanupPingTimer() {\n if (this._pingServerHandle) {\n clearTimeout(this._pingServerHandle);\n this._pingServerHandle = undefined;\n }\n }\n _cleanupTimeout() {\n if (this._timeoutHandle) {\n clearTimeout(this._timeoutHandle);\n }\n }\n _createInvocation(methodName, args, nonblocking, streamIds) {\n if (nonblocking) {\n if (streamIds.length !== 0) {\n return {\n arguments: args,\n streamIds,\n target: methodName,\n type: MessageType.Invocation\n };\n } else {\n return {\n arguments: args,\n target: methodName,\n type: MessageType.Invocation\n };\n }\n } else {\n const invocationId = this._invocationId;\n this._invocationId++;\n if (streamIds.length !== 0) {\n return {\n arguments: args,\n invocationId: invocationId.toString(),\n streamIds,\n target: methodName,\n type: MessageType.Invocation\n };\n } else {\n return {\n arguments: args,\n invocationId: invocationId.toString(),\n target: methodName,\n type: MessageType.Invocation\n };\n }\n }\n }\n _launchStreams(streams, promiseQueue) {\n if (streams.length === 0) {\n return;\n }\n // Synchronize stream data so they arrive in-order on the server\n if (!promiseQueue) {\n promiseQueue = Promise.resolve();\n }\n // We want to iterate over the keys, since the keys are the stream ids\n // eslint-disable-next-line guard-for-in\n for (const streamId in streams) {\n streams[streamId].subscribe({\n complete: () => {\n promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId)));\n },\n error: err => {\n let message;\n if (err instanceof Error) {\n message = err.message;\n } else if (err && err.toString) {\n message = err.toString();\n } else {\n message = \"Unknown error\";\n }\n promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId, message)));\n },\n next: item => {\n promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createStreamItemMessage(streamId, item)));\n }\n });\n }\n }\n _replaceStreamingParams(args) {\n const streams = [];\n const streamIds = [];\n for (let i = 0; i < args.length; i++) {\n const argument = args[i];\n if (this._isObservable(argument)) {\n const streamId = this._invocationId;\n this._invocationId++;\n // Store the stream for later use\n streams[streamId] = argument;\n streamIds.push(streamId.toString());\n // remove stream from args\n args.splice(i, 1);\n }\n }\n return [streams, streamIds];\n }\n _isObservable(arg) {\n // This allows other stream implementations to just work (like rxjs)\n return arg && arg.subscribe && typeof arg.subscribe === \"function\";\n }\n _createStreamInvocation(methodName, args, streamIds) {\n const invocationId = this._invocationId;\n this._invocationId++;\n if (streamIds.length !== 0) {\n return {\n arguments: args,\n invocationId: invocationId.toString(),\n streamIds,\n target: methodName,\n type: MessageType.StreamInvocation\n };\n } else {\n return {\n arguments: args,\n invocationId: invocationId.toString(),\n target: methodName,\n type: MessageType.StreamInvocation\n };\n }\n }\n _createCancelInvocation(id) {\n return {\n invocationId: id,\n type: MessageType.CancelInvocation\n };\n }\n _createStreamItemMessage(id, item) {\n return {\n invocationId: id,\n item,\n type: MessageType.StreamItem\n };\n }\n _createCompletionMessage(id, error, result) {\n if (error) {\n return {\n error,\n invocationId: id,\n type: MessageType.Completion\n };\n }\n return {\n invocationId: id,\n result,\n type: MessageType.Completion\n };\n }\n _createCloseMessage() {\n return {\n type: MessageType.Close\n };\n }\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// 0, 2, 10, 30 second delays before reconnect attempts.\nconst DEFAULT_RETRY_DELAYS_IN_MILLISECONDS = [0, 2000, 10000, 30000, null];\n/** @private */\nexport class DefaultReconnectPolicy {\n constructor(retryDelays) {\n this._retryDelays = retryDelays !== undefined ? [...retryDelays, null] : DEFAULT_RETRY_DELAYS_IN_MILLISECONDS;\n }\n nextRetryDelayInMilliseconds(retryContext) {\n return this._retryDelays[retryContext.previousRetryCount];\n }\n}\n","// Licensed to the .NET Foundation under one or more agreements.\r\n// The .NET Foundation licenses this file to you under the MIT license.\r\n\r\nexport abstract class HeaderNames {\r\n static readonly Authorization = \"Authorization\";\r\n static readonly Cookie = \"Cookie\";\r\n}\r\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\nimport { HeaderNames } from \"./HeaderNames\";\nimport { HttpClient } from \"./HttpClient\";\n/** @private */\nexport class AccessTokenHttpClient extends HttpClient {\n constructor(innerClient, accessTokenFactory) {\n super();\n this._innerClient = innerClient;\n this._accessTokenFactory = accessTokenFactory;\n }\n async send(request) {\n let allowRetry = true;\n if (this._accessTokenFactory && (!this._accessToken || request.url && request.url.indexOf(\"/negotiate?\") > 0)) {\n // don't retry if the request is a negotiate or if we just got a potentially new token from the access token factory\n allowRetry = false;\n this._accessToken = await this._accessTokenFactory();\n }\n this._setAuthorizationHeader(request);\n const response = await this._innerClient.send(request);\n if (allowRetry && response.statusCode === 401 && this._accessTokenFactory) {\n this._accessToken = await this._accessTokenFactory();\n this._setAuthorizationHeader(request);\n return await this._innerClient.send(request);\n }\n return response;\n }\n _setAuthorizationHeader(request) {\n if (!request.headers) {\n request.headers = {};\n }\n if (this._accessToken) {\n request.headers[HeaderNames.Authorization] = `Bearer ${this._accessToken}`;\n }\n // don't remove the header if there isn't an access token factory, the user manually added the header in this case\n else if (this._accessTokenFactory) {\n if (request.headers[HeaderNames.Authorization]) {\n delete request.headers[HeaderNames.Authorization];\n }\n }\n }\n getCookieString(url) {\n return this._innerClient.getCookieString(url);\n }\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// This will be treated as a bit flag in the future, so we keep it using power-of-two values.\n/** Specifies a specific HTTP transport type. */\nexport var HttpTransportType = /*#__PURE__*/function (HttpTransportType) {\n /** Specifies no transport preference. */\n HttpTransportType[HttpTransportType[\"None\"] = 0] = \"None\";\n /** Specifies the WebSockets transport. */\n HttpTransportType[HttpTransportType[\"WebSockets\"] = 1] = \"WebSockets\";\n /** Specifies the Server-Sent Events transport. */\n HttpTransportType[HttpTransportType[\"ServerSentEvents\"] = 2] = \"ServerSentEvents\";\n /** Specifies the Long Polling transport. */\n HttpTransportType[HttpTransportType[\"LongPolling\"] = 4] = \"LongPolling\";\n return HttpTransportType;\n}(HttpTransportType || {});\n/** Specifies the transfer format for a connection. */\nexport var TransferFormat = /*#__PURE__*/function (TransferFormat) {\n /** Specifies that only text data will be transmitted over the connection. */\n TransferFormat[TransferFormat[\"Text\"] = 1] = \"Text\";\n /** Specifies that binary data will be transmitted over the connection. */\n TransferFormat[TransferFormat[\"Binary\"] = 2] = \"Binary\";\n return TransferFormat;\n}(TransferFormat || {});\n\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController\n// We don't actually ever use the API being polyfilled, we always use the polyfill because\n// it's a very new API right now.\n// Not exported from index.\n/** @private */\nexport class AbortController {\n constructor() {\n this._isAborted = false;\n this.onabort = null;\n }\n abort() {\n if (!this._isAborted) {\n this._isAborted = true;\n if (this.onabort) {\n this.onabort();\n }\n }\n }\n get signal() {\n return this;\n }\n get aborted() {\n return this._isAborted;\n }\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\nimport { AbortController } from \"./AbortController\";\nimport { HttpError, TimeoutError } from \"./Errors\";\nimport { LogLevel } from \"./ILogger\";\nimport { TransferFormat } from \"./ITransport\";\nimport { Arg, getDataDetail, getUserAgentHeader, sendMessage } from \"./Utils\";\n// Not exported from 'index', this type is internal.\n/** @private */\nexport class LongPollingTransport {\n // This is an internal type, not exported from 'index' so this is really just internal.\n get pollAborted() {\n return this._pollAbort.aborted;\n }\n constructor(httpClient, logger, options) {\n this._httpClient = httpClient;\n this._logger = logger;\n this._pollAbort = new AbortController();\n this._options = options;\n this._running = false;\n this.onreceive = null;\n this.onclose = null;\n }\n async connect(url, transferFormat) {\n Arg.isRequired(url, \"url\");\n Arg.isRequired(transferFormat, \"transferFormat\");\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\n this._url = url;\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Connecting.\");\n // Allow binary format on Node and Browsers that support binary content (indicated by the presence of responseType property)\n if (transferFormat === TransferFormat.Binary && typeof XMLHttpRequest !== \"undefined\" && typeof new XMLHttpRequest().responseType !== \"string\") {\n throw new Error(\"Binary protocols over XmlHttpRequest not implementing advanced features are not supported.\");\n }\n const [name, value] = getUserAgentHeader();\n const headers = {\n [name]: value,\n ...this._options.headers\n };\n const pollOptions = {\n abortSignal: this._pollAbort.signal,\n headers,\n timeout: 100000,\n withCredentials: this._options.withCredentials\n };\n if (transferFormat === TransferFormat.Binary) {\n pollOptions.responseType = \"arraybuffer\";\n }\n // Make initial long polling request\n // Server uses first long polling request to finish initializing connection and it returns without data\n const pollUrl = `${url}&_=${Date.now()}`;\n this._logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`);\n const response = await this._httpClient.get(pollUrl, pollOptions);\n if (response.statusCode !== 200) {\n this._logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`);\n // Mark running as false so that the poll immediately ends and runs the close logic\n this._closeError = new HttpError(response.statusText || \"\", response.statusCode);\n this._running = false;\n } else {\n this._running = true;\n }\n this._receiving = this._poll(this._url, pollOptions);\n }\n async _poll(url, pollOptions) {\n try {\n while (this._running) {\n try {\n const pollUrl = `${url}&_=${Date.now()}`;\n this._logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`);\n const response = await this._httpClient.get(pollUrl, pollOptions);\n if (response.statusCode === 204) {\n this._logger.log(LogLevel.Information, \"(LongPolling transport) Poll terminated by server.\");\n this._running = false;\n } else if (response.statusCode !== 200) {\n this._logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`);\n // Unexpected status code\n this._closeError = new HttpError(response.statusText || \"\", response.statusCode);\n this._running = false;\n } else {\n // Process the response\n if (response.content) {\n this._logger.log(LogLevel.Trace, `(LongPolling transport) data received. ${getDataDetail(response.content, this._options.logMessageContent)}.`);\n if (this.onreceive) {\n this.onreceive(response.content);\n }\n } else {\n // This is another way timeout manifest.\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Poll timed out, reissuing.\");\n }\n }\n } catch (e) {\n if (!this._running) {\n // Log but disregard errors that occur after stopping\n this._logger.log(LogLevel.Trace, `(LongPolling transport) Poll errored after shutdown: ${e.message}`);\n } else {\n if (e instanceof TimeoutError) {\n // Ignore timeouts and reissue the poll.\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Poll timed out, reissuing.\");\n } else {\n // Close the connection with the error as the result.\n this._closeError = e;\n this._running = false;\n }\n }\n }\n }\n } finally {\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Polling complete.\");\n // We will reach here with pollAborted==false when the server returned a response causing the transport to stop.\n // If pollAborted==true then client initiated the stop and the stop method will raise the close event after DELETE is sent.\n if (!this.pollAborted) {\n this._raiseOnClose();\n }\n }\n }\n async send(data) {\n if (!this._running) {\n return Promise.reject(new Error(\"Cannot send until the transport is connected\"));\n }\n return sendMessage(this._logger, \"LongPolling\", this._httpClient, this._url, data, this._options);\n }\n async stop() {\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Stopping polling.\");\n // Tell receiving loop to stop, abort any current request, and then wait for it to finish\n this._running = false;\n this._pollAbort.abort();\n try {\n await this._receiving;\n // Send DELETE to clean up long polling on the server\n this._logger.log(LogLevel.Trace, `(LongPolling transport) sending DELETE request to ${this._url}.`);\n const headers = {};\n const [name, value] = getUserAgentHeader();\n headers[name] = value;\n const deleteOptions = {\n headers: {\n ...headers,\n ...this._options.headers\n },\n timeout: this._options.timeout,\n withCredentials: this._options.withCredentials\n };\n let error;\n try {\n await this._httpClient.delete(this._url, deleteOptions);\n } catch (err) {\n error = err;\n }\n if (error) {\n if (error instanceof HttpError) {\n if (error.statusCode === 404) {\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) A 404 response was returned from sending a DELETE request.\");\n } else {\n this._logger.log(LogLevel.Trace, `(LongPolling transport) Error sending a DELETE request: ${error}`);\n }\n }\n } else {\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) DELETE request accepted.\");\n }\n } finally {\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Stop finished.\");\n // Raise close event here instead of in polling\n // It needs to happen after the DELETE request is sent\n this._raiseOnClose();\n }\n }\n _raiseOnClose() {\n if (this.onclose) {\n let logMessage = \"(LongPolling transport) Firing onclose event.\";\n if (this._closeError) {\n logMessage += \" Error: \" + this._closeError;\n }\n this._logger.log(LogLevel.Trace, logMessage);\n this.onclose(this._closeError);\n }\n }\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\nimport { LogLevel } from \"./ILogger\";\nimport { TransferFormat } from \"./ITransport\";\nimport { Arg, getDataDetail, getUserAgentHeader, Platform, sendMessage } from \"./Utils\";\n/** @private */\nexport class ServerSentEventsTransport {\n constructor(httpClient, accessToken, logger, options) {\n this._httpClient = httpClient;\n this._accessToken = accessToken;\n this._logger = logger;\n this._options = options;\n this.onreceive = null;\n this.onclose = null;\n }\n async connect(url, transferFormat) {\n Arg.isRequired(url, \"url\");\n Arg.isRequired(transferFormat, \"transferFormat\");\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\n this._logger.log(LogLevel.Trace, \"(SSE transport) Connecting.\");\n // set url before accessTokenFactory because this._url is only for send and we set the auth header instead of the query string for send\n this._url = url;\n if (this._accessToken) {\n url += (url.indexOf(\"?\") < 0 ? \"?\" : \"&\") + `access_token=${encodeURIComponent(this._accessToken)}`;\n }\n return new Promise((resolve, reject) => {\n let opened = false;\n if (transferFormat !== TransferFormat.Text) {\n reject(new Error(\"The Server-Sent Events transport only supports the 'Text' transfer format\"));\n return;\n }\n let eventSource;\n if (Platform.isBrowser || Platform.isWebWorker) {\n eventSource = new this._options.EventSource(url, {\n withCredentials: this._options.withCredentials\n });\n } else {\n // Non-browser passes cookies via the dictionary\n const cookies = this._httpClient.getCookieString(url);\n const headers = {};\n headers.Cookie = cookies;\n const [name, value] = getUserAgentHeader();\n headers[name] = value;\n eventSource = new this._options.EventSource(url, {\n withCredentials: this._options.withCredentials,\n headers: {\n ...headers,\n ...this._options.headers\n }\n });\n }\n try {\n eventSource.onmessage = e => {\n if (this.onreceive) {\n try {\n this._logger.log(LogLevel.Trace, `(SSE transport) data received. ${getDataDetail(e.data, this._options.logMessageContent)}.`);\n this.onreceive(e.data);\n } catch (error) {\n this._close(error);\n return;\n }\n }\n };\n // @ts-ignore: not using event on purpose\n eventSource.onerror = e => {\n // EventSource doesn't give any useful information about server side closes.\n if (opened) {\n this._close();\n } else {\n reject(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.\"));\n }\n };\n eventSource.onopen = () => {\n this._logger.log(LogLevel.Information, `SSE connected to ${this._url}`);\n this._eventSource = eventSource;\n opened = true;\n resolve();\n };\n } catch (e) {\n reject(e);\n return;\n }\n });\n }\n async send(data) {\n if (!this._eventSource) {\n return Promise.reject(new Error(\"Cannot send until the transport is connected\"));\n }\n return sendMessage(this._logger, \"SSE\", this._httpClient, this._url, data, this._options);\n }\n stop() {\n this._close();\n return Promise.resolve();\n }\n _close(e) {\n if (this._eventSource) {\n this._eventSource.close();\n this._eventSource = undefined;\n if (this.onclose) {\n this.onclose(e);\n }\n }\n }\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\nimport { HeaderNames } from \"./HeaderNames\";\nimport { LogLevel } from \"./ILogger\";\nimport { TransferFormat } from \"./ITransport\";\nimport { Arg, getDataDetail, getUserAgentHeader, Platform } from \"./Utils\";\n/** @private */\nexport class WebSocketTransport {\n constructor(httpClient, accessTokenFactory, logger, logMessageContent, webSocketConstructor, headers) {\n this._logger = logger;\n this._accessTokenFactory = accessTokenFactory;\n this._logMessageContent = logMessageContent;\n this._webSocketConstructor = webSocketConstructor;\n this._httpClient = httpClient;\n this.onreceive = null;\n this.onclose = null;\n this._headers = headers;\n }\n async connect(url, transferFormat) {\n Arg.isRequired(url, \"url\");\n Arg.isRequired(transferFormat, \"transferFormat\");\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\n this._logger.log(LogLevel.Trace, \"(WebSockets transport) Connecting.\");\n let token;\n if (this._accessTokenFactory) {\n token = await this._accessTokenFactory();\n }\n return new Promise((resolve, reject) => {\n url = url.replace(/^http/, \"ws\");\n let webSocket;\n const cookies = this._httpClient.getCookieString(url);\n let opened = false;\n if (Platform.isNode || Platform.isReactNative) {\n const headers = {};\n const [name, value] = getUserAgentHeader();\n headers[name] = value;\n if (token) {\n headers[HeaderNames.Authorization] = `Bearer ${token}`;\n }\n if (cookies) {\n headers[HeaderNames.Cookie] = cookies;\n }\n // Only pass headers when in non-browser environments\n webSocket = new this._webSocketConstructor(url, undefined, {\n headers: {\n ...headers,\n ...this._headers\n }\n });\n } else {\n if (token) {\n url += (url.indexOf(\"?\") < 0 ? \"?\" : \"&\") + `access_token=${encodeURIComponent(token)}`;\n }\n }\n if (!webSocket) {\n // Chrome is not happy with passing 'undefined' as protocol\n webSocket = new this._webSocketConstructor(url);\n }\n if (transferFormat === TransferFormat.Binary) {\n webSocket.binaryType = \"arraybuffer\";\n }\n webSocket.onopen = _event => {\n this._logger.log(LogLevel.Information, `WebSocket connected to ${url}.`);\n this._webSocket = webSocket;\n opened = true;\n resolve();\n };\n webSocket.onerror = event => {\n let error = null;\n // ErrorEvent is a browser only type we need to check if the type exists before using it\n if (typeof ErrorEvent !== \"undefined\" && event instanceof ErrorEvent) {\n error = event.error;\n } else {\n error = \"There was an error with the transport\";\n }\n this._logger.log(LogLevel.Information, `(WebSockets transport) ${error}.`);\n };\n webSocket.onmessage = message => {\n this._logger.log(LogLevel.Trace, `(WebSockets transport) data received. ${getDataDetail(message.data, this._logMessageContent)}.`);\n if (this.onreceive) {\n try {\n this.onreceive(message.data);\n } catch (error) {\n this._close(error);\n return;\n }\n }\n };\n webSocket.onclose = event => {\n // Don't call close handler if connection was never established\n // We'll reject the connect call instead\n if (opened) {\n this._close(event);\n } else {\n let error = null;\n // ErrorEvent is a browser only type we need to check if the type exists before using it\n if (typeof ErrorEvent !== \"undefined\" && event instanceof ErrorEvent) {\n error = event.error;\n } else {\n 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.\";\n }\n reject(new Error(error));\n }\n };\n });\n }\n send(data) {\n if (this._webSocket && this._webSocket.readyState === this._webSocketConstructor.OPEN) {\n this._logger.log(LogLevel.Trace, `(WebSockets transport) sending data. ${getDataDetail(data, this._logMessageContent)}.`);\n this._webSocket.send(data);\n return Promise.resolve();\n }\n return Promise.reject(\"WebSocket is not in the OPEN state\");\n }\n stop() {\n if (this._webSocket) {\n // Manually invoke onclose callback inline so we know the HttpConnection was closed properly before returning\n // This also solves an issue where websocket.onclose could take 18+ seconds to trigger during network disconnects\n this._close(undefined);\n }\n return Promise.resolve();\n }\n _close(event) {\n // webSocket will be null if the transport did not start successfully\n if (this._webSocket) {\n // Clear websocket handlers because we are considering the socket closed now\n this._webSocket.onclose = () => {};\n this._webSocket.onmessage = () => {};\n this._webSocket.onerror = () => {};\n this._webSocket.close();\n this._webSocket = undefined;\n }\n this._logger.log(LogLevel.Trace, \"(WebSockets transport) socket closed.\");\n if (this.onclose) {\n if (this._isCloseEvent(event) && (event.wasClean === false || event.code !== 1000)) {\n this.onclose(new Error(`WebSocket closed with status code: ${event.code} (${event.reason || \"no reason given\"}).`));\n } else if (event instanceof Error) {\n this.onclose(event);\n } else {\n this.onclose();\n }\n }\n }\n _isCloseEvent(event) {\n return event && typeof event.wasClean === \"boolean\" && typeof event.code === \"number\";\n }\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\nimport { AccessTokenHttpClient } from \"./AccessTokenHttpClient\";\nimport { DefaultHttpClient } from \"./DefaultHttpClient\";\nimport { AggregateErrors, DisabledTransportError, FailedToNegotiateWithServerError, FailedToStartTransportError, HttpError, UnsupportedTransportError, AbortError } from \"./Errors\";\nimport { LogLevel } from \"./ILogger\";\nimport { HttpTransportType, TransferFormat } from \"./ITransport\";\nimport { LongPollingTransport } from \"./LongPollingTransport\";\nimport { ServerSentEventsTransport } from \"./ServerSentEventsTransport\";\nimport { Arg, createLogger, getUserAgentHeader, Platform } from \"./Utils\";\nimport { WebSocketTransport } from \"./WebSocketTransport\";\nconst MAX_REDIRECTS = 100;\n/** @private */\nexport class HttpConnection {\n constructor(url, options = {}) {\n this._stopPromiseResolver = () => {};\n this.features = {};\n this._negotiateVersion = 1;\n Arg.isRequired(url, \"url\");\n this._logger = createLogger(options.logger);\n this.baseUrl = this._resolveUrl(url);\n options = options || {};\n options.logMessageContent = options.logMessageContent === undefined ? false : options.logMessageContent;\n if (typeof options.withCredentials === \"boolean\" || options.withCredentials === undefined) {\n options.withCredentials = options.withCredentials === undefined ? true : options.withCredentials;\n } else {\n throw new Error(\"withCredentials option was not a 'boolean' or 'undefined' value\");\n }\n options.timeout = options.timeout === undefined ? 100 * 1000 : options.timeout;\n let webSocketModule = null;\n let eventSourceModule = null;\n if (Platform.isNode && typeof require !== \"undefined\") {\n // In order to ignore the dynamic require in webpack builds we need to do this magic\n // @ts-ignore: TS doesn't know about these names\n const requireFunc = typeof __webpack_require__ === \"function\" ? __non_webpack_require__ : require;\n webSocketModule = requireFunc(\"ws\");\n eventSourceModule = requireFunc(\"eventsource\");\n }\n if (!Platform.isNode && typeof WebSocket !== \"undefined\" && !options.WebSocket) {\n options.WebSocket = WebSocket;\n } else if (Platform.isNode && !options.WebSocket) {\n if (webSocketModule) {\n options.WebSocket = webSocketModule;\n }\n }\n if (!Platform.isNode && typeof EventSource !== \"undefined\" && !options.EventSource) {\n options.EventSource = EventSource;\n } else if (Platform.isNode && !options.EventSource) {\n if (typeof eventSourceModule !== \"undefined\") {\n options.EventSource = eventSourceModule;\n }\n }\n this._httpClient = new AccessTokenHttpClient(options.httpClient || new DefaultHttpClient(this._logger), options.accessTokenFactory);\n this._connectionState = \"Disconnected\" /* ConnectionState.Disconnected */;\n this._connectionStarted = false;\n this._options = options;\n this.onreceive = null;\n this.onclose = null;\n }\n async start(transferFormat) {\n transferFormat = transferFormat || TransferFormat.Binary;\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\n this._logger.log(LogLevel.Debug, `Starting connection with transfer format '${TransferFormat[transferFormat]}'.`);\n if (this._connectionState !== \"Disconnected\" /* ConnectionState.Disconnected */) {\n return Promise.reject(new Error(\"Cannot start an HttpConnection that is not in the 'Disconnected' state.\"));\n }\n this._connectionState = \"Connecting\" /* ConnectionState.Connecting */;\n this._startInternalPromise = this._startInternal(transferFormat);\n await this._startInternalPromise;\n // The TypeScript compiler thinks that connectionState must be Connecting here. The TypeScript compiler is wrong.\n if (this._connectionState === \"Disconnecting\" /* ConnectionState.Disconnecting */) {\n // stop() was called and transitioned the client into the Disconnecting state.\n const message = \"Failed to start the HttpConnection before stop() was called.\";\n this._logger.log(LogLevel.Error, message);\n // We cannot await stopPromise inside startInternal since stopInternal awaits the startInternalPromise.\n await this._stopPromise;\n return Promise.reject(new AbortError(message));\n } else if (this._connectionState !== \"Connected\" /* ConnectionState.Connected */) {\n // stop() was called and transitioned the client into the Disconnecting state.\n const message = \"HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!\";\n this._logger.log(LogLevel.Error, message);\n return Promise.reject(new AbortError(message));\n }\n this._connectionStarted = true;\n }\n send(data) {\n if (this._connectionState !== \"Connected\" /* ConnectionState.Connected */) {\n return Promise.reject(new Error(\"Cannot send data if the connection is not in the 'Connected' State.\"));\n }\n if (!this._sendQueue) {\n this._sendQueue = new TransportSendQueue(this.transport);\n }\n // Transport will not be null if state is connected\n return this._sendQueue.send(data);\n }\n async stop(error) {\n if (this._connectionState === \"Disconnected\" /* ConnectionState.Disconnected */) {\n this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnected state.`);\n return Promise.resolve();\n }\n if (this._connectionState === \"Disconnecting\" /* ConnectionState.Disconnecting */) {\n this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);\n return this._stopPromise;\n }\n this._connectionState = \"Disconnecting\" /* ConnectionState.Disconnecting */;\n this._stopPromise = new Promise(resolve => {\n // Don't complete stop() until stopConnection() completes.\n this._stopPromiseResolver = resolve;\n });\n // stopInternal should never throw so just observe it.\n await this._stopInternal(error);\n await this._stopPromise;\n }\n async _stopInternal(error) {\n // Set error as soon as possible otherwise there is a race between\n // the transport closing and providing an error and the error from a close message\n // We would prefer the close message error.\n this._stopError = error;\n try {\n await this._startInternalPromise;\n } catch (e) {\n // This exception is returned to the user as a rejected Promise from the start method.\n }\n // The transport's onclose will trigger stopConnection which will run our onclose event.\n // The transport should always be set if currently connected. If it wasn't set, it's likely because\n // stop was called during start() and start() failed.\n if (this.transport) {\n try {\n await this.transport.stop();\n } catch (e) {\n this._logger.log(LogLevel.Error, `HttpConnection.transport.stop() threw error '${e}'.`);\n this._stopConnection();\n }\n this.transport = undefined;\n } else {\n this._logger.log(LogLevel.Debug, \"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.\");\n }\n }\n async _startInternal(transferFormat) {\n // Store the original base url and the access token factory since they may change\n // as part of negotiating\n let url = this.baseUrl;\n this._accessTokenFactory = this._options.accessTokenFactory;\n this._httpClient._accessTokenFactory = this._accessTokenFactory;\n try {\n if (this._options.skipNegotiation) {\n if (this._options.transport === HttpTransportType.WebSockets) {\n // No need to add a connection ID in this case\n this.transport = this._constructTransport(HttpTransportType.WebSockets);\n // We should just call connect directly in this case.\n // No fallback or negotiate in this case.\n await this._startTransport(url, transferFormat);\n } else {\n throw new Error(\"Negotiation can only be skipped when using the WebSocket transport directly.\");\n }\n } else {\n let negotiateResponse = null;\n let redirects = 0;\n do {\n negotiateResponse = await this._getNegotiationResponse(url);\n // the user tries to stop the connection when it is being started\n if (this._connectionState === \"Disconnecting\" /* ConnectionState.Disconnecting */ || this._connectionState === \"Disconnected\" /* ConnectionState.Disconnected */) {\n throw new AbortError(\"The connection was stopped during negotiation.\");\n }\n if (negotiateResponse.error) {\n throw new Error(negotiateResponse.error);\n }\n if (negotiateResponse.ProtocolVersion) {\n 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.\");\n }\n if (negotiateResponse.url) {\n url = negotiateResponse.url;\n }\n if (negotiateResponse.accessToken) {\n // Replace the current access token factory with one that uses\n // the returned access token\n const accessToken = negotiateResponse.accessToken;\n this._accessTokenFactory = () => accessToken;\n // set the factory to undefined so the AccessTokenHttpClient won't retry with the same token, since we know it won't change until a connection restart\n this._httpClient._accessToken = accessToken;\n this._httpClient._accessTokenFactory = undefined;\n }\n redirects++;\n } while (negotiateResponse.url && redirects < MAX_REDIRECTS);\n if (redirects === MAX_REDIRECTS && negotiateResponse.url) {\n throw new Error(\"Negotiate redirection limit exceeded.\");\n }\n await this._createTransport(url, this._options.transport, negotiateResponse, transferFormat);\n }\n if (this.transport instanceof LongPollingTransport) {\n this.features.inherentKeepAlive = true;\n }\n if (this._connectionState === \"Connecting\" /* ConnectionState.Connecting */) {\n // Ensure the connection transitions to the connected state prior to completing this.startInternalPromise.\n // start() will handle the case when stop was called and startInternal exits still in the disconnecting state.\n this._logger.log(LogLevel.Debug, \"The HttpConnection connected successfully.\");\n this._connectionState = \"Connected\" /* ConnectionState.Connected */;\n }\n // stop() is waiting on us via this.startInternalPromise so keep this.transport around so it can clean up.\n // This is the only case startInternal can exit in neither the connected nor disconnected state because stopConnection()\n // will transition to the disconnected state. start() will wait for the transition using the stopPromise.\n } catch (e) {\n this._logger.log(LogLevel.Error, \"Failed to start the connection: \" + e);\n this._connectionState = \"Disconnected\" /* ConnectionState.Disconnected */;\n this.transport = undefined;\n // if start fails, any active calls to stop assume that start will complete the stop promise\n this._stopPromiseResolver();\n return Promise.reject(e);\n }\n }\n async _getNegotiationResponse(url) {\n const headers = {};\n const [name, value] = getUserAgentHeader();\n headers[name] = value;\n const negotiateUrl = this._resolveNegotiateUrl(url);\n this._logger.log(LogLevel.Debug, `Sending negotiation request: ${negotiateUrl}.`);\n try {\n const response = await this._httpClient.post(negotiateUrl, {\n content: \"\",\n headers: {\n ...headers,\n ...this._options.headers\n },\n timeout: this._options.timeout,\n withCredentials: this._options.withCredentials\n });\n if (response.statusCode !== 200) {\n return Promise.reject(new Error(`Unexpected status code returned from negotiate '${response.statusCode}'`));\n }\n const negotiateResponse = JSON.parse(response.content);\n if (!negotiateResponse.negotiateVersion || negotiateResponse.negotiateVersion < 1) {\n // Negotiate version 0 doesn't use connectionToken\n // So we set it equal to connectionId so all our logic can use connectionToken without being aware of the negotiate version\n negotiateResponse.connectionToken = negotiateResponse.connectionId;\n }\n if (negotiateResponse.useStatefulReconnect && this._options._useStatefulReconnect !== true) {\n return Promise.reject(new FailedToNegotiateWithServerError(\"Client didn't negotiate Stateful Reconnect but the server did.\"));\n }\n return negotiateResponse;\n } catch (e) {\n let errorMessage = \"Failed to complete negotiation with the server: \" + e;\n if (e instanceof HttpError) {\n if (e.statusCode === 404) {\n errorMessage = errorMessage + \" Either this is not a SignalR endpoint or there is a proxy blocking the connection.\";\n }\n }\n this._logger.log(LogLevel.Error, errorMessage);\n return Promise.reject(new FailedToNegotiateWithServerError(errorMessage));\n }\n }\n _createConnectUrl(url, connectionToken) {\n if (!connectionToken) {\n return url;\n }\n return url + (url.indexOf(\"?\") === -1 ? \"?\" : \"&\") + `id=${connectionToken}`;\n }\n async _createTransport(url, requestedTransport, negotiateResponse, requestedTransferFormat) {\n let connectUrl = this._createConnectUrl(url, negotiateResponse.connectionToken);\n if (this._isITransport(requestedTransport)) {\n this._logger.log(LogLevel.Debug, \"Connection was provided an instance of ITransport, using that directly.\");\n this.transport = requestedTransport;\n await this._startTransport(connectUrl, requestedTransferFormat);\n this.connectionId = negotiateResponse.connectionId;\n return;\n }\n const transportExceptions = [];\n const transports = negotiateResponse.availableTransports || [];\n let negotiate = negotiateResponse;\n for (const endpoint of transports) {\n const transportOrError = this._resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat, (negotiate === null || negotiate === void 0 ? void 0 : negotiate.useStatefulReconnect) === true);\n if (transportOrError instanceof Error) {\n // Store the error and continue, we don't want to cause a re-negotiate in these cases\n transportExceptions.push(`${endpoint.transport} failed:`);\n transportExceptions.push(transportOrError);\n } else if (this._isITransport(transportOrError)) {\n this.transport = transportOrError;\n if (!negotiate) {\n try {\n negotiate = await this._getNegotiationResponse(url);\n } catch (ex) {\n return Promise.reject(ex);\n }\n connectUrl = this._createConnectUrl(url, negotiate.connectionToken);\n }\n try {\n await this._startTransport(connectUrl, requestedTransferFormat);\n this.connectionId = negotiate.connectionId;\n return;\n } catch (ex) {\n this._logger.log(LogLevel.Error, `Failed to start the transport '${endpoint.transport}': ${ex}`);\n negotiate = undefined;\n transportExceptions.push(new FailedToStartTransportError(`${endpoint.transport} failed: ${ex}`, HttpTransportType[endpoint.transport]));\n if (this._connectionState !== \"Connecting\" /* ConnectionState.Connecting */) {\n const message = \"Failed to select transport before stop() was called.\";\n this._logger.log(LogLevel.Debug, message);\n return Promise.reject(new AbortError(message));\n }\n }\n }\n }\n if (transportExceptions.length > 0) {\n return Promise.reject(new AggregateErrors(`Unable to connect to the server with any of the available transports. ${transportExceptions.join(\" \")}`, transportExceptions));\n }\n return Promise.reject(new Error(\"None of the transports supported by the client are supported by the server.\"));\n }\n _constructTransport(transport) {\n switch (transport) {\n case HttpTransportType.WebSockets:\n if (!this._options.WebSocket) {\n throw new Error(\"'WebSocket' is not supported in your environment.\");\n }\n return new WebSocketTransport(this._httpClient, this._accessTokenFactory, this._logger, this._options.logMessageContent, this._options.WebSocket, this._options.headers || {});\n case HttpTransportType.ServerSentEvents:\n if (!this._options.EventSource) {\n throw new Error(\"'EventSource' is not supported in your environment.\");\n }\n return new ServerSentEventsTransport(this._httpClient, this._httpClient._accessToken, this._logger, this._options);\n case HttpTransportType.LongPolling:\n return new LongPollingTransport(this._httpClient, this._logger, this._options);\n default:\n throw new Error(`Unknown transport: ${transport}.`);\n }\n }\n _startTransport(url, transferFormat) {\n this.transport.onreceive = this.onreceive;\n if (this.features.reconnect) {\n this.transport.onclose = async e => {\n let callStop = false;\n if (this.features.reconnect) {\n try {\n this.features.disconnected();\n await this.transport.connect(url, transferFormat);\n await this.features.resend();\n } catch {\n callStop = true;\n }\n } else {\n this._stopConnection(e);\n return;\n }\n if (callStop) {\n this._stopConnection(e);\n }\n };\n } else {\n this.transport.onclose = e => this._stopConnection(e);\n }\n return this.transport.connect(url, transferFormat);\n }\n _resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat, useStatefulReconnect) {\n const transport = HttpTransportType[endpoint.transport];\n if (transport === null || transport === undefined) {\n this._logger.log(LogLevel.Debug, `Skipping transport '${endpoint.transport}' because it is not supported by this client.`);\n return new Error(`Skipping transport '${endpoint.transport}' because it is not supported by this client.`);\n } else {\n if (transportMatches(requestedTransport, transport)) {\n const transferFormats = endpoint.transferFormats.map(s => TransferFormat[s]);\n if (transferFormats.indexOf(requestedTransferFormat) >= 0) {\n if (transport === HttpTransportType.WebSockets && !this._options.WebSocket || transport === HttpTransportType.ServerSentEvents && !this._options.EventSource) {\n this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it is not supported in your environment.'`);\n return new UnsupportedTransportError(`'${HttpTransportType[transport]}' is not supported in your environment.`, transport);\n } else {\n this._logger.log(LogLevel.Debug, `Selecting transport '${HttpTransportType[transport]}'.`);\n try {\n this.features.reconnect = transport === HttpTransportType.WebSockets ? useStatefulReconnect : undefined;\n return this._constructTransport(transport);\n } catch (ex) {\n return ex;\n }\n }\n } else {\n this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it does not support the requested transfer format '${TransferFormat[requestedTransferFormat]}'.`);\n return new Error(`'${HttpTransportType[transport]}' does not support ${TransferFormat[requestedTransferFormat]}.`);\n }\n } else {\n this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it was disabled by the client.`);\n return new DisabledTransportError(`'${HttpTransportType[transport]}' is disabled by the client.`, transport);\n }\n }\n }\n _isITransport(transport) {\n return transport && typeof transport === \"object\" && \"connect\" in transport;\n }\n _stopConnection(error) {\n this._logger.log(LogLevel.Debug, `HttpConnection.stopConnection(${error}) called while in state ${this._connectionState}.`);\n this.transport = undefined;\n // If we have a stopError, it takes precedence over the error from the transport\n error = this._stopError || error;\n this._stopError = undefined;\n if (this._connectionState === \"Disconnected\" /* ConnectionState.Disconnected */) {\n this._logger.log(LogLevel.Debug, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is already in the disconnected state.`);\n return;\n }\n if (this._connectionState === \"Connecting\" /* ConnectionState.Connecting */) {\n this._logger.log(LogLevel.Warning, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is still in the connecting state.`);\n throw new Error(`HttpConnection.stopConnection(${error}) was called while the connection is still in the connecting state.`);\n }\n if (this._connectionState === \"Disconnecting\" /* ConnectionState.Disconnecting */) {\n // A call to stop() induced this call to stopConnection and needs to be completed.\n // Any stop() awaiters will be scheduled to continue after the onclose callback fires.\n this._stopPromiseResolver();\n }\n if (error) {\n this._logger.log(LogLevel.Error, `Connection disconnected with error '${error}'.`);\n } else {\n this._logger.log(LogLevel.Information, \"Connection disconnected.\");\n }\n if (this._sendQueue) {\n this._sendQueue.stop().catch(e => {\n this._logger.log(LogLevel.Error, `TransportSendQueue.stop() threw error '${e}'.`);\n });\n this._sendQueue = undefined;\n }\n this.connectionId = undefined;\n this._connectionState = \"Disconnected\" /* ConnectionState.Disconnected */;\n if (this._connectionStarted) {\n this._connectionStarted = false;\n try {\n if (this.onclose) {\n this.onclose(error);\n }\n } catch (e) {\n this._logger.log(LogLevel.Error, `HttpConnection.onclose(${error}) threw error '${e}'.`);\n }\n }\n }\n _resolveUrl(url) {\n // startsWith is not supported in IE\n if (url.lastIndexOf(\"https://\", 0) === 0 || url.lastIndexOf(\"http://\", 0) === 0) {\n return url;\n }\n if (!Platform.isBrowser) {\n throw new Error(`Cannot resolve '${url}'.`);\n }\n // Setting the url to the href propery of an anchor tag handles normalization\n // for us. There are 3 main cases.\n // 1. Relative path normalization e.g \"b\" -> \"http://localhost:5000/a/b\"\n // 2. Absolute path normalization e.g \"/a/b\" -> \"http://localhost:5000/a/b\"\n // 3. Networkpath reference normalization e.g \"//localhost:5000/a/b\" -> \"http://localhost:5000/a/b\"\n const aTag = window.document.createElement(\"a\");\n aTag.href = url;\n this._logger.log(LogLevel.Information, `Normalizing '${url}' to '${aTag.href}'.`);\n return aTag.href;\n }\n _resolveNegotiateUrl(url) {\n const negotiateUrl = new URL(url);\n if (negotiateUrl.pathname.endsWith('/')) {\n negotiateUrl.pathname += \"negotiate\";\n } else {\n negotiateUrl.pathname += \"/negotiate\";\n }\n const searchParams = new URLSearchParams(negotiateUrl.searchParams);\n if (!searchParams.has(\"negotiateVersion\")) {\n searchParams.append(\"negotiateVersion\", this._negotiateVersion.toString());\n }\n if (searchParams.has(\"useStatefulReconnect\")) {\n if (searchParams.get(\"useStatefulReconnect\") === \"true\") {\n this._options._useStatefulReconnect = true;\n }\n } else if (this._options._useStatefulReconnect === true) {\n searchParams.append(\"useStatefulReconnect\", \"true\");\n }\n negotiateUrl.search = searchParams.toString();\n return negotiateUrl.toString();\n }\n}\nfunction transportMatches(requestedTransport, actualTransport) {\n return !requestedTransport || (actualTransport & requestedTransport) !== 0;\n}\n/** @private */\nexport class TransportSendQueue {\n constructor(_transport) {\n this._transport = _transport;\n this._buffer = [];\n this._executing = true;\n this._sendBufferedData = new PromiseSource();\n this._transportResult = new PromiseSource();\n this._sendLoopPromise = this._sendLoop();\n }\n send(data) {\n this._bufferData(data);\n if (!this._transportResult) {\n this._transportResult = new PromiseSource();\n }\n return this._transportResult.promise;\n }\n stop() {\n this._executing = false;\n this._sendBufferedData.resolve();\n return this._sendLoopPromise;\n }\n _bufferData(data) {\n if (this._buffer.length && typeof this._buffer[0] !== typeof data) {\n throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof data}`);\n }\n this._buffer.push(data);\n this._sendBufferedData.resolve();\n }\n async _sendLoop() {\n while (true) {\n await this._sendBufferedData.promise;\n if (!this._executing) {\n if (this._transportResult) {\n this._transportResult.reject(\"Connection stopped.\");\n }\n break;\n }\n this._sendBufferedData = new PromiseSource();\n const transportResult = this._transportResult;\n this._transportResult = undefined;\n const data = typeof this._buffer[0] === \"string\" ? this._buffer.join(\"\") : TransportSendQueue._concatBuffers(this._buffer);\n this._buffer.length = 0;\n try {\n await this._transport.send(data);\n transportResult.resolve();\n } catch (error) {\n transportResult.reject(error);\n }\n }\n }\n static _concatBuffers(arrayBuffers) {\n const totalLength = arrayBuffers.map(b => b.byteLength).reduce((a, b) => a + b);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const item of arrayBuffers) {\n result.set(new Uint8Array(item), offset);\n offset += item.byteLength;\n }\n return result.buffer;\n }\n}\nclass PromiseSource {\n constructor() {\n this.promise = new Promise((resolve, reject) => [this._resolver, this._rejecter] = [resolve, reject]);\n }\n resolve() {\n this._resolver();\n }\n reject(reason) {\n this._rejecter(reason);\n }\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\nimport { MessageType } from \"./IHubProtocol\";\nimport { LogLevel } from \"./ILogger\";\nimport { TransferFormat } from \"./ITransport\";\nimport { NullLogger } from \"./Loggers\";\nimport { TextMessageFormat } from \"./TextMessageFormat\";\nconst JSON_HUB_PROTOCOL_NAME = \"json\";\n/** Implements the JSON Hub Protocol. */\nexport class JsonHubProtocol {\n constructor() {\n /** @inheritDoc */\n this.name = JSON_HUB_PROTOCOL_NAME;\n /** @inheritDoc */\n this.version = 2;\n /** @inheritDoc */\n this.transferFormat = TransferFormat.Text;\n }\n /** Creates an array of {@link @microsoft/signalr.HubMessage} objects from the specified serialized representation.\r\n *\r\n * @param {string} input A string containing the serialized representation.\r\n * @param {ILogger} logger A logger that will be used to log messages that occur during parsing.\r\n */\n parseMessages(input, logger) {\n // The interface does allow \"ArrayBuffer\" to be passed in, but this implementation does not. So let's throw a useful error.\n if (typeof input !== \"string\") {\n throw new Error(\"Invalid input for JSON hub protocol. Expected a string.\");\n }\n if (!input) {\n return [];\n }\n if (logger === null) {\n logger = NullLogger.instance;\n }\n // Parse the messages\n const messages = TextMessageFormat.parse(input);\n const hubMessages = [];\n for (const message of messages) {\n const parsedMessage = JSON.parse(message);\n if (typeof parsedMessage.type !== \"number\") {\n throw new Error(\"Invalid payload.\");\n }\n switch (parsedMessage.type) {\n case MessageType.Invocation:\n this._isInvocationMessage(parsedMessage);\n break;\n case MessageType.StreamItem:\n this._isStreamItemMessage(parsedMessage);\n break;\n case MessageType.Completion:\n this._isCompletionMessage(parsedMessage);\n break;\n case MessageType.Ping:\n // Single value, no need to validate\n break;\n case MessageType.Close:\n // All optional values, no need to validate\n break;\n case MessageType.Ack:\n this._isAckMessage(parsedMessage);\n break;\n case MessageType.Sequence:\n this._isSequenceMessage(parsedMessage);\n break;\n default:\n // Future protocol changes can add message types, old clients can ignore them\n logger.log(LogLevel.Information, \"Unknown message type '\" + parsedMessage.type + \"' ignored.\");\n continue;\n }\n hubMessages.push(parsedMessage);\n }\n return hubMessages;\n }\n /** Writes the specified {@link @microsoft/signalr.HubMessage} to a string and returns it.\r\n *\r\n * @param {HubMessage} message The message to write.\r\n * @returns {string} A string containing the serialized representation of the message.\r\n */\n writeMessage(message) {\n return TextMessageFormat.write(JSON.stringify(message));\n }\n _isInvocationMessage(message) {\n this._assertNotEmptyString(message.target, \"Invalid payload for Invocation message.\");\n if (message.invocationId !== undefined) {\n this._assertNotEmptyString(message.invocationId, \"Invalid payload for Invocation message.\");\n }\n }\n _isStreamItemMessage(message) {\n this._assertNotEmptyString(message.invocationId, \"Invalid payload for StreamItem message.\");\n if (message.item === undefined) {\n throw new Error(\"Invalid payload for StreamItem message.\");\n }\n }\n _isCompletionMessage(message) {\n if (message.result && message.error) {\n throw new Error(\"Invalid payload for Completion message.\");\n }\n if (!message.result && message.error) {\n this._assertNotEmptyString(message.error, \"Invalid payload for Completion message.\");\n }\n this._assertNotEmptyString(message.invocationId, \"Invalid payload for Completion message.\");\n }\n _isAckMessage(message) {\n if (typeof message.sequenceId !== 'number') {\n throw new Error(\"Invalid SequenceId for Ack message.\");\n }\n }\n _isSequenceMessage(message) {\n if (typeof message.sequenceId !== 'number') {\n throw new Error(\"Invalid SequenceId for Sequence message.\");\n }\n }\n _assertNotEmptyString(value, errorMessage) {\n if (typeof value !== \"string\" || value === \"\") {\n throw new Error(errorMessage);\n }\n }\n}\n","// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\nimport { DefaultReconnectPolicy } from \"./DefaultReconnectPolicy\";\nimport { HttpConnection } from \"./HttpConnection\";\nimport { HubConnection } from \"./HubConnection\";\nimport { LogLevel } from \"./ILogger\";\nimport { JsonHubProtocol } from \"./JsonHubProtocol\";\nimport { NullLogger } from \"./Loggers\";\nimport { Arg, ConsoleLogger } from \"./Utils\";\nconst LogLevelNameMapping = {\n trace: LogLevel.Trace,\n debug: LogLevel.Debug,\n info: LogLevel.Information,\n information: LogLevel.Information,\n warn: LogLevel.Warning,\n warning: LogLevel.Warning,\n error: LogLevel.Error,\n critical: LogLevel.Critical,\n none: LogLevel.None\n};\nfunction parseLogLevel(name) {\n // Case-insensitive matching via lower-casing\n // Yes, I know case-folding is a complicated problem in Unicode, but we only support\n // the ASCII strings defined in LogLevelNameMapping anyway, so it's fine -anurse.\n const mapping = LogLevelNameMapping[name.toLowerCase()];\n if (typeof mapping !== \"undefined\") {\n return mapping;\n } else {\n throw new Error(`Unknown log level: ${name}`);\n }\n}\n/** A builder for configuring {@link @microsoft/signalr.HubConnection} instances. */\nexport class HubConnectionBuilder {\n configureLogging(logging) {\n Arg.isRequired(logging, \"logging\");\n if (isLogger(logging)) {\n this.logger = logging;\n } else if (typeof logging === \"string\") {\n const logLevel = parseLogLevel(logging);\n this.logger = new ConsoleLogger(logLevel);\n } else {\n this.logger = new ConsoleLogger(logging);\n }\n return this;\n }\n withUrl(url, transportTypeOrOptions) {\n Arg.isRequired(url, \"url\");\n Arg.isNotEmpty(url, \"url\");\n this.url = url;\n // Flow-typing knows where it's at. Since HttpTransportType is a number and IHttpConnectionOptions is guaranteed\n // to be an object, we know (as does TypeScript) this comparison is all we need to figure out which overload was called.\n if (typeof transportTypeOrOptions === \"object\") {\n this.httpConnectionOptions = {\n ...this.httpConnectionOptions,\n ...transportTypeOrOptions\n };\n } else {\n this.httpConnectionOptions = {\n ...this.httpConnectionOptions,\n transport: transportTypeOrOptions\n };\n }\n return this;\n }\n /** Configures the {@link @microsoft/signalr.HubConnection} to use the specified Hub Protocol.\r\n *\r\n * @param {IHubProtocol} protocol The {@link @microsoft/signalr.IHubProtocol} implementation to use.\r\n */\n withHubProtocol(protocol) {\n Arg.isRequired(protocol, \"protocol\");\n this.protocol = protocol;\n return this;\n }\n withAutomaticReconnect(retryDelaysOrReconnectPolicy) {\n if (this.reconnectPolicy) {\n throw new Error(\"A reconnectPolicy has already been set.\");\n }\n if (!retryDelaysOrReconnectPolicy) {\n this.reconnectPolicy = new DefaultReconnectPolicy();\n } else if (Array.isArray(retryDelaysOrReconnectPolicy)) {\n this.reconnectPolicy = new DefaultReconnectPolicy(retryDelaysOrReconnectPolicy);\n } else {\n this.reconnectPolicy = retryDelaysOrReconnectPolicy;\n }\n return this;\n }\n /** Configures {@link @microsoft/signalr.HubConnection.serverTimeoutInMilliseconds} for the {@link @microsoft/signalr.HubConnection}.\r\n *\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\n withServerTimeout(milliseconds) {\n Arg.isRequired(milliseconds, \"milliseconds\");\n this._serverTimeoutInMilliseconds = milliseconds;\n return this;\n }\n /** Configures {@link @microsoft/signalr.HubConnection.keepAliveIntervalInMilliseconds} for the {@link @microsoft/signalr.HubConnection}.\r\n *\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\n withKeepAliveInterval(milliseconds) {\n Arg.isRequired(milliseconds, \"milliseconds\");\n this._keepAliveIntervalInMilliseconds = milliseconds;\n return this;\n }\n /** Enables and configures options for the Stateful Reconnect feature.\r\n *\r\n * @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.\r\n */\n withStatefulReconnect(options) {\n if (this.httpConnectionOptions === undefined) {\n this.httpConnectionOptions = {};\n }\n this.httpConnectionOptions._useStatefulReconnect = true;\n this._statefulReconnectBufferSize = options === null || options === void 0 ? void 0 : options.bufferSize;\n return this;\n }\n /** Creates a {@link @microsoft/signalr.HubConnection} from the configuration options specified in this builder.\r\n *\r\n * @returns {HubConnection} The configured {@link @microsoft/signalr.HubConnection}.\r\n */\n build() {\n // If httpConnectionOptions has a logger, use it. Otherwise, override it with the one\n // provided to configureLogger\n const httpConnectionOptions = this.httpConnectionOptions || {};\n // If it's 'null', the user **explicitly** asked for null, don't mess with it.\n if (httpConnectionOptions.logger === undefined) {\n // If our logger is undefined or null, that's OK, the HttpConnection constructor will handle it.\n httpConnectionOptions.logger = this.logger;\n }\n // Now create the connection\n if (!this.url) {\n throw new Error(\"The 'HubConnectionBuilder.withUrl' method must be called before building the connection.\");\n }\n const connection = new HttpConnection(this.url, httpConnectionOptions);\n return HubConnection.create(connection, this.logger || NullLogger.instance, this.protocol || new JsonHubProtocol(), this.reconnectPolicy, this._serverTimeoutInMilliseconds, this._keepAliveIntervalInMilliseconds, this._statefulReconnectBufferSize);\n }\n}\nfunction isLogger(logger) {\n return logger.log !== undefined;\n}\n","import { Injectable } from '@angular/core';\r\nimport { HubConnection, HubConnectionBuilder } from '@microsoft/signalr';\r\nimport { BehaviorSubject, ReplaySubject } from 'rxjs';\r\nimport { environment } from 'src/environments/environment';\r\nimport { LibraryModifiedEvent } from '../_models/events/library-modified-event';\r\nimport { NotificationProgressEvent } from '../_models/events/notification-progress-event';\r\nimport { ThemeProgressEvent } from '../_models/events/theme-progress-event';\r\nimport { UserUpdateEvent } from '../_models/events/user-update-event';\r\nimport { User } from '../_models/user';\r\nimport {DashboardUpdateEvent} from \"../_models/events/dashboard-update-event\";\r\nimport {SideNavUpdateEvent} from \"../_models/events/sidenav-update-event\";\r\nimport {SiteThemeUpdatedEvent} from \"../_models/events/site-theme-updated-event\";\r\n\r\nexport enum EVENTS {\r\n UpdateAvailable = 'UpdateAvailable',\r\n ScanSeries = 'ScanSeries',\r\n SeriesAdded = 'SeriesAdded',\r\n SeriesRemoved = 'SeriesRemoved',\r\n VolumeRemoved = 'VolumeRemoved',\r\n ChapterRemoved = 'ChapterRemoved',\r\n ScanLibraryProgress = 'ScanLibraryProgress',\r\n OnlineUsers = 'OnlineUsers',\r\n /**\r\n * When a Collection has been updated\r\n */\r\n CollectionUpdated = 'CollectionUpdated',\r\n /**\r\n * A generic error that occurs during operations on the server\r\n */\r\n Error = 'Error',\r\n BackupDatabaseProgress = 'BackupDatabaseProgress',\r\n /**\r\n * A subtype of NotificationProgress that represents maintenance cleanup on server-owned resources\r\n */\r\n CleanupProgress = 'CleanupProgress',\r\n /**\r\n * A subtype of NotificationProgress that represnts a user downloading a file or group of files.\r\n * Note: In v0.5.5, this is being replaced by an inbrowser experience. The message is changed and this will be moved to dashboard view once built\r\n */\r\n DownloadProgress = 'DownloadProgress',\r\n /**\r\n * A generic progress event\r\n */\r\n NotificationProgress = 'NotificationProgress',\r\n /**\r\n * A subtype of NotificationProgress that represents the underlying file being processed during a scan\r\n */\r\n FileScanProgress = 'FileScanProgress',\r\n /**\r\n * A subtype of NotificationProgress that represents a single series being processed (into the DB)\r\n */\r\n ScanProgress = 'ScanProgress',\r\n /**\r\n * A custom user site theme is added or removed during a scan\r\n */\r\n SiteThemeProgress = 'SiteThemeProgress',\r\n /**\r\n * A cover is updated\r\n */\r\n CoverUpdate = 'CoverUpdate',\r\n /**\r\n * A subtype of NotificationProgress that represents a file being processed for cover image extraction\r\n */\r\n CoverUpdateProgress = 'CoverUpdateProgress',\r\n /**\r\n * A library is created or removed from the instance\r\n */\r\n LibraryModified = 'LibraryModified',\r\n /**\r\n * A user updates an entities read progress\r\n */\r\n UserProgressUpdate = 'UserProgressUpdate',\r\n /**\r\n * A user updates account or preferences\r\n */\r\n UserUpdate = 'UserUpdate',\r\n /**\r\n * When bulk bookmarks are being converted\r\n */\r\n ConvertBookmarksProgress = 'ConvertBookmarksProgress',\r\n /**\r\n * When files are being scanned to calculate word count\r\n */\r\n WordCountAnalyzerProgress = 'WordCountAnalyzerProgress',\r\n /**\r\n * When the user needs to be informed, but it's not a big deal\r\n */\r\n Info = 'Info',\r\n /**\r\n * A user is sending files to their device\r\n */\r\n SendingToDevice = 'SendingToDevice',\r\n /**\r\n * A scrobbling token has expired\r\n */\r\n ScrobblingKeyExpired = 'ScrobblingKeyExpired',\r\n /**\r\n * User's dashboard needs to be re-rendered\r\n */\r\n DashboardUpdate = 'DashboardUpdate',\r\n /**\r\n * User's sidenav needs to be re-rendered\r\n */\r\n SideNavUpdate = 'SideNavUpdate',\r\n /**\r\n * A Theme was updated and UI should refresh to get the latest version\r\n */\r\n SiteThemeUpdated = 'SiteThemeUpdated',\r\n /**\r\n * A Progress event when a smart collection is synchronizing\r\n */\r\n SmartCollectionSync = 'SmartCollectionSync'\r\n}\r\n\r\nexport interface Message {\r\n event: EVENTS;\r\n payload: T;\r\n}\r\n\r\n\r\n@Injectable({\r\n providedIn: 'root'\r\n})\r\nexport class MessageHubService {\r\n hubUrl = environment.hubUrl;\r\n private hubConnection!: HubConnection;\r\n\r\n private messagesSource = new ReplaySubject>(1);\r\n private onlineUsersSource = new BehaviorSubject([]); // UserNames\r\n\r\n /**\r\n * Any events that come from the backend\r\n */\r\n public messages$ = this.messagesSource.asObservable();\r\n /**\r\n * Users that are online\r\n */\r\n public onlineUsers$ = this.onlineUsersSource.asObservable();\r\n\r\n constructor() {}\r\n\r\n /**\r\n * Tests that an event is of the type passed\r\n * @param event\r\n * @param eventType\r\n * @returns\r\n */\r\n public isEventType(event: Message, eventType: EVENTS) {\r\n if (event.event == EVENTS.NotificationProgress) {\r\n const notification = event.payload as NotificationProgressEvent;\r\n return notification.eventType.toLowerCase() == eventType.toLowerCase();\r\n }\r\n return event.event === eventType;\r\n }\r\n\r\n createHubConnection(user: User) {\r\n this.hubConnection = new HubConnectionBuilder()\r\n .withUrl(this.hubUrl + 'messages', {\r\n accessTokenFactory: () => user.token\r\n })\r\n .withAutomaticReconnect()\r\n //.withStatefulReconnect() // Requires signalr@8.0\r\n .build();\r\n\r\n this.hubConnection\r\n .start()\r\n .catch(err => console.error(err));\r\n\r\n this.hubConnection.on(EVENTS.OnlineUsers, (usernames: string[]) => {\r\n this.onlineUsersSource.next(usernames);\r\n });\r\n\r\n this.hubConnection.on(EVENTS.ScanSeries, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.ScanSeries,\r\n payload: resp.body\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.ScanLibraryProgress, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.ScanLibraryProgress,\r\n payload: resp.body\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.ConvertBookmarksProgress, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.ConvertBookmarksProgress,\r\n payload: resp.body\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.WordCountAnalyzerProgress, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.WordCountAnalyzerProgress,\r\n payload: resp.body\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.LibraryModified, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.LibraryModified,\r\n payload: resp.body as LibraryModifiedEvent\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.SmartCollectionSync, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.NotificationProgress,\r\n payload: resp.body\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.SiteThemeUpdated, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.SiteThemeUpdated,\r\n payload: resp.body as SiteThemeUpdatedEvent\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.DashboardUpdate, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.DashboardUpdate,\r\n payload: resp.body as DashboardUpdateEvent\r\n });\r\n });\r\n this.hubConnection.on(EVENTS.SideNavUpdate, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.SideNavUpdate,\r\n payload: resp.body as SideNavUpdateEvent\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.NotificationProgress, (resp: NotificationProgressEvent) => {\r\n this.messagesSource.next({\r\n event: EVENTS.NotificationProgress,\r\n payload: resp\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.SiteThemeProgress, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.SiteThemeProgress,\r\n payload: resp.body as ThemeProgressEvent\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.CollectionUpdated, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.CollectionUpdated,\r\n payload: resp.body\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.UserProgressUpdate, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.UserProgressUpdate,\r\n payload: resp.body\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.UserUpdate, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.UserUpdate,\r\n payload: resp.body as UserUpdateEvent\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.Error, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.Error,\r\n payload: resp.body\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.Info, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.Info,\r\n payload: resp.body\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.SeriesAdded, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.SeriesAdded,\r\n payload: resp.body\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.SeriesRemoved, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.SeriesRemoved,\r\n payload: resp.body\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.ChapterRemoved, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.ChapterRemoved,\r\n payload: resp.body\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.VolumeRemoved, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.VolumeRemoved,\r\n payload: resp.body\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.CoverUpdate, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.CoverUpdate,\r\n payload: resp.body\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.UpdateAvailable, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.UpdateAvailable,\r\n payload: resp.body\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.SendingToDevice, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.SendingToDevice,\r\n payload: resp.body\r\n });\r\n });\r\n\r\n this.hubConnection.on(EVENTS.ScrobblingKeyExpired, resp => {\r\n this.messagesSource.next({\r\n event: EVENTS.ScrobblingKeyExpired,\r\n payload: resp.body\r\n });\r\n });\r\n }\r\n\r\n stopHubConnection() {\r\n if (this.hubConnection) {\r\n this.hubConnection.stop().catch(err => console.error(err));\r\n }\r\n }\r\n\r\n sendMessage(methodName: string, body?: any) {\r\n return this.hubConnection.invoke(methodName, body);\r\n }\r\n\r\n}\r\n"],"mappings":"0HAGO,IAAMA,EAAN,cAAwB,KAAM,CAMnC,YAAYC,EAAcC,EAAY,CACpC,IAAMC,EAAY,WAAW,UAC7B,MAAM,GAAGF,CAAY,kBAAkBC,CAAU,GAAG,EACpD,KAAK,WAAaA,EAGlB,KAAK,UAAYC,CACnB,CACF,EAEaC,EAAN,cAA2B,KAAM,CAKtC,YAAYH,EAAe,sBAAuB,CAChD,IAAME,EAAY,WAAW,UAC7B,MAAMF,CAAY,EAGlB,KAAK,UAAYE,CACnB,CACF,EAEaE,EAAN,cAAyB,KAAM,CAKpC,YAAYJ,EAAe,qBAAsB,CAC/C,IAAME,EAAY,WAAW,UAC7B,MAAMF,CAAY,EAGlB,KAAK,UAAYE,CACnB,CACF,EAGaG,EAAN,cAAwC,KAAM,CAMnD,YAAYC,EAASC,EAAW,CAC9B,IAAML,EAAY,WAAW,UAC7B,MAAMI,CAAO,EACb,KAAK,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QAASqB,EAAKC,KACf,CACH,CAAC,CACH,CAEAuB,mBAAiB,CACX,KAAKzC,eACP,KAAKA,cAAc0C,KAAI,EAAGlC,MAAMC,GAAOC,QAAQC,MAAMF,CAAG,CAAC,CAE7D,CAEAkC,YAAYC,EAAoB1B,EAAU,CACxC,OAAO,KAAKlB,cAAc6C,OAAOD,EAAY1B,CAAI,CACnD,iDAjOWrC,EAAiB,CAAA,kCAAjBA,EAAiBiE,QAAjBjE,EAAiBkE,UAAAC,WAFhB,MAAM,CAAA,CAAA,SAEPnE,CAAiB,GAAA","names":["HttpError","errorMessage","statusCode","trueProto","TimeoutError","AbortError","UnsupportedTransportError","message","transport","DisabledTransportError","FailedToStartTransportError","FailedToNegotiateWithServerError","AggregateErrors","innerErrors","HttpResponse","statusCode","statusText","content","HttpClient","url","options","__spreadProps","__spreadValues","LogLevel","NullLogger","_logLevel","_message","VERSION","Arg","val","name","values","Platform","_Platform","getDataDetail","data","includeContent","detail","isArrayBuffer","formatArrayBuffer","view","str","num","pad","sendMessage","logger","transportName","httpClient","url","content","options","__async","headers","value","getUserAgentHeader","LogLevel","responseType","response","__spreadValues","createLogger","ConsoleLogger","NullLogger","SubjectSubscription","subject","observer","index","_","minimumLogLevel","logLevel","message","msg","userAgentHeaderName","constructUserAgent","getOsName","getRuntime","getRuntimeVersion","version","os","runtime","runtimeVersion","userAgent","majorAndMinor","getErrorString","e","getGlobalThis","FetchHttpClient","HttpClient","logger","Platform","requireFunc","__require","getGlobalThis","request","__async","AbortError","abortController","error","timeoutId","msTimeout","LogLevel","TimeoutError","isArrayBuffer","response","__spreadValues","e","errorMessage","deserializeContent","HttpError","payload","HttpResponse","url","cookies","c","responseType","content","XhrHttpClient","HttpClient","logger","request","AbortError","resolve","reject","xhr","isArrayBuffer","headers","header","HttpResponse","HttpError","LogLevel","TimeoutError","DefaultHttpClient","HttpClient","logger","Platform","FetchHttpClient","XhrHttpClient","request","AbortError","url","TextMessageFormat","_TextMessageFormat","output","input","messages","HandshakeProtocol","handshakeRequest","TextMessageFormat","data","messageData","remainingData","isArrayBuffer","binaryData","separatorIndex","responseLength","textData","messages","response","MessageType","Subject","item","observer","err","SubjectSubscription","MessageBuffer","protocol","connection","bufferSize","message","__async","serializedMessage","backpressurePromise","backpressurePromiseResolver","backpressurePromiseRejector","isArrayBuffer","resolve","reject","BufferedItem","ackMessage","newestAckedMessage","index","element","MessageType","currentId","sequenceId","messages","error","id","resolver","rejector","DEFAULT_TIMEOUT_IN_MS","DEFAULT_PING_INTERVAL_IN_MS","DEFAULT_STATEFUL_RECONNECT_BUFFER_SIZE","HubConnectionState","HubConnection","_HubConnection","connection","logger","protocol","reconnectPolicy","serverTimeoutInMilliseconds","keepAliveIntervalInMilliseconds","statefulReconnectBufferSize","LogLevel","Arg","HandshakeProtocol","data","error","MessageType","url","__async","Platform","handshakePromise","resolve","reject","version","handshakeRequest","MessageBuffer","e","startPromise","state","AbortError","methodName","args","streams","streamIds","invocationDescriptor","promiseQueue","subject","Subject","cancelInvocation","invocationEvent","message","sendPromise","newMethod","method","handlers","removeIdx","callback","messages","getErrorString","responseMessage","remainingData","nextPing","invocationMessage","methods","methodsCopy","expectsResponse","res","exception","completionMessage","m","prevRes","c","reconnectStartTime","previousReconnectAttempts","retryError","nextRetryDelay","previousRetryCount","elapsedMilliseconds","retryReason","callbacks","key","nonblocking","invocationId","streamId","err","item","i","argument","arg","id","result","DEFAULT_RETRY_DELAYS_IN_MILLISECONDS","DefaultReconnectPolicy","retryDelays","retryContext","HeaderNames","AccessTokenHttpClient","HttpClient","innerClient","accessTokenFactory","request","__async","allowRetry","response","HeaderNames","url","HttpTransportType","TransferFormat","AbortController","LongPollingTransport","httpClient","logger","options","AbortController","url","transferFormat","__async","Arg","TransferFormat","LogLevel","name","value","getUserAgentHeader","headers","__spreadValues","pollOptions","pollUrl","response","HttpError","getDataDetail","e","TimeoutError","data","sendMessage","deleteOptions","error","err","logMessage","ServerSentEventsTransport","httpClient","accessToken","logger","options","url","transferFormat","__async","Arg","TransferFormat","LogLevel","resolve","reject","opened","eventSource","Platform","cookies","headers","name","value","getUserAgentHeader","__spreadValues","e","getDataDetail","error","data","sendMessage","WebSocketTransport","httpClient","accessTokenFactory","logger","logMessageContent","webSocketConstructor","headers","url","transferFormat","__async","Arg","TransferFormat","LogLevel","token","resolve","reject","webSocket","cookies","opened","Platform","name","value","getUserAgentHeader","HeaderNames","__spreadValues","_event","event","error","message","getDataDetail","data","MAX_REDIRECTS","HttpConnection","url","options","Arg","createLogger","webSocketModule","eventSourceModule","Platform","__require","requireFunc","AccessTokenHttpClient","DefaultHttpClient","transferFormat","__async","TransferFormat","LogLevel","message","AbortError","data","TransportSendQueue","error","resolve","e","HttpTransportType","negotiateResponse","redirects","accessToken","LongPollingTransport","headers","name","value","getUserAgentHeader","negotiateUrl","response","__spreadValues","FailedToNegotiateWithServerError","errorMessage","HttpError","connectionToken","requestedTransport","requestedTransferFormat","connectUrl","transportExceptions","transports","negotiate","endpoint","transportOrError","ex","FailedToStartTransportError","AggregateErrors","transport","WebSocketTransport","ServerSentEventsTransport","callStop","useStatefulReconnect","transportMatches","s","UnsupportedTransportError","DisabledTransportError","aTag","searchParams","actualTransport","_TransportSendQueue","_transport","PromiseSource","transportResult","arrayBuffers","totalLength","b","a","result","offset","item","reject","reason","JSON_HUB_PROTOCOL_NAME","JsonHubProtocol","TransferFormat","input","logger","NullLogger","messages","TextMessageFormat","hubMessages","message","parsedMessage","MessageType","LogLevel","value","errorMessage","LogLevelNameMapping","LogLevel","parseLogLevel","name","mapping","HubConnectionBuilder","logging","Arg","isLogger","logLevel","ConsoleLogger","url","transportTypeOrOptions","__spreadValues","__spreadProps","protocol","retryDelaysOrReconnectPolicy","DefaultReconnectPolicy","milliseconds","options","httpConnectionOptions","connection","HttpConnection","HubConnection","NullLogger","JsonHubProtocol","logger","EVENTS","MessageHubService","constructor","hubUrl","environment","messagesSource","ReplaySubject","onlineUsersSource","BehaviorSubject","messages$","asObservable","onlineUsers$","isEventType","event","eventType","NotificationProgress","payload","toLowerCase","createHubConnection","user","hubConnection","HubConnectionBuilder","withUrl","accessTokenFactory","token","withAutomaticReconnect","build","start","catch","err","console","error","on","OnlineUsers","usernames","next","ScanSeries","resp","body","ScanLibraryProgress","ConvertBookmarksProgress","WordCountAnalyzerProgress","LibraryModified","SmartCollectionSync","SiteThemeUpdated","DashboardUpdate","SideNavUpdate","SiteThemeProgress","CollectionUpdated","UserProgressUpdate","UserUpdate","Error","Info","SeriesAdded","SeriesRemoved","ChapterRemoved","VolumeRemoved","CoverUpdate","UpdateAvailable","SendingToDevice","ScrobblingKeyExpired","stopHubConnection","stop","sendMessage","methodName","invoke","factory","ɵfac","providedIn"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]}