{"version":3,"file":"wr.min.js","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/dist/esm/HeaderNames.js","../../../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","../../../node_modules/bouncer-waitingroom/dist/Events.js","../../../node_modules/bouncer-waitingroom/dist/Models.js","../../../node_modules/bouncer-waitingroom/dist/Helpers.js","../../../node_modules/bouncer-waitingroom/dist/WaitingRoomConnection.js","../../../src/WaitingRoomHandler.ts","../../../src/wr.ts"],"sourcesContent":["// 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/** Error thrown when an HTTP request fails. */\r\nexport class HttpError extends Error {\r\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 */\r\n constructor(errorMessage, statusCode) {\r\n const trueProto = new.target.prototype;\r\n super(`${errorMessage}: Status code '${statusCode}'`);\r\n this.statusCode = statusCode;\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n/** Error thrown when a timeout elapses. */\r\nexport class TimeoutError extends Error {\r\n /** Constructs a new instance of {@link @microsoft/signalr.TimeoutError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n */\r\n constructor(errorMessage = \"A timeout occurred.\") {\r\n const trueProto = new.target.prototype;\r\n super(errorMessage);\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n/** Error thrown when an action is aborted. */\r\nexport class AbortError extends Error {\r\n /** Constructs a new instance of {@link AbortError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n */\r\n constructor(errorMessage = \"An abort occurred.\") {\r\n const trueProto = new.target.prototype;\r\n super(errorMessage);\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n/** Error thrown when the selected transport is unsupported by the browser. */\r\n/** @private */\r\nexport class UnsupportedTransportError extends Error {\r\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 */\r\n constructor(message, transport) {\r\n const trueProto = new.target.prototype;\r\n super(message);\r\n this.transport = transport;\r\n this.errorType = 'UnsupportedTransportError';\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n/** Error thrown when the selected transport is disabled by the browser. */\r\n/** @private */\r\nexport class DisabledTransportError extends Error {\r\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 */\r\n constructor(message, transport) {\r\n const trueProto = new.target.prototype;\r\n super(message);\r\n this.transport = transport;\r\n this.errorType = 'DisabledTransportError';\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n/** Error thrown when the selected transport cannot be started. */\r\n/** @private */\r\nexport class FailedToStartTransportError extends Error {\r\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 */\r\n constructor(message, transport) {\r\n const trueProto = new.target.prototype;\r\n super(message);\r\n this.transport = transport;\r\n this.errorType = 'FailedToStartTransportError';\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n/** Error thrown when the negotiation with the server failed to complete. */\r\n/** @private */\r\nexport class FailedToNegotiateWithServerError extends Error {\r\n /** Constructs a new instance of {@link @microsoft/signalr.FailedToNegotiateWithServerError}.\r\n *\r\n * @param {string} message A descriptive error message.\r\n */\r\n constructor(message) {\r\n const trueProto = new.target.prototype;\r\n super(message);\r\n this.errorType = 'FailedToNegotiateWithServerError';\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n/** Error thrown when multiple errors have occurred. */\r\n/** @private */\r\nexport class AggregateErrors extends Error {\r\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 */\r\n constructor(message, innerErrors) {\r\n const trueProto = new.target.prototype;\r\n super(message);\r\n this.innerErrors = innerErrors;\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n//# sourceMappingURL=Errors.js.map","// 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/** Represents an HTTP response. */\r\nexport class HttpResponse {\r\n constructor(statusCode, statusText, content) {\r\n this.statusCode = statusCode;\r\n this.statusText = statusText;\r\n this.content = content;\r\n }\r\n}\r\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 */\r\nexport class HttpClient {\r\n get(url, options) {\r\n return this.send({\r\n ...options,\r\n method: \"GET\",\r\n url,\r\n });\r\n }\r\n post(url, options) {\r\n return this.send({\r\n ...options,\r\n method: \"POST\",\r\n url,\r\n });\r\n }\r\n delete(url, options) {\r\n return this.send({\r\n ...options,\r\n method: \"DELETE\",\r\n url,\r\n });\r\n }\r\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 */\r\n // @ts-ignore\r\n getCookieString(url) {\r\n return \"\";\r\n }\r\n}\r\n//# sourceMappingURL=HttpClient.js.map","// 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// These values are designed to match the ASP.NET Log Levels since that's the pattern we're emulating here.\r\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 */\r\nexport var LogLevel;\r\n(function (LogLevel) {\r\n /** Log level for very low severity diagnostic messages. */\r\n LogLevel[LogLevel[\"Trace\"] = 0] = \"Trace\";\r\n /** Log level for low severity diagnostic messages. */\r\n LogLevel[LogLevel[\"Debug\"] = 1] = \"Debug\";\r\n /** Log level for informational diagnostic messages. */\r\n LogLevel[LogLevel[\"Information\"] = 2] = \"Information\";\r\n /** Log level for diagnostic messages that indicate a non-fatal problem. */\r\n LogLevel[LogLevel[\"Warning\"] = 3] = \"Warning\";\r\n /** Log level for diagnostic messages that indicate a failure in the current operation. */\r\n LogLevel[LogLevel[\"Error\"] = 4] = \"Error\";\r\n /** Log level for diagnostic messages that indicate a failure that will terminate the entire application. */\r\n LogLevel[LogLevel[\"Critical\"] = 5] = \"Critical\";\r\n /** The highest possible log level. Used when configuring logging to indicate that no log messages should be emitted. */\r\n LogLevel[LogLevel[\"None\"] = 6] = \"None\";\r\n})(LogLevel || (LogLevel = {}));\r\n//# sourceMappingURL=ILogger.js.map","// 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/** A logger that does nothing when log messages are sent to it. */\r\nexport class NullLogger {\r\n constructor() { }\r\n /** @inheritDoc */\r\n // eslint-disable-next-line\r\n log(_logLevel, _message) {\r\n }\r\n}\r\n/** The singleton instance of the {@link @microsoft/signalr.NullLogger}. */\r\nNullLogger.instance = new NullLogger();\r\n//# sourceMappingURL=Loggers.js.map","// 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\nimport { LogLevel } from \"./ILogger\";\r\nimport { NullLogger } from \"./Loggers\";\r\n// Version token that will be replaced by the prepack command\r\n/** The version of the SignalR client. */\r\nexport const VERSION = \"8.0.7\";\r\n/** @private */\r\nexport class Arg {\r\n static isRequired(val, name) {\r\n if (val === null || val === undefined) {\r\n throw new Error(`The '${name}' argument is required.`);\r\n }\r\n }\r\n static isNotEmpty(val, name) {\r\n if (!val || val.match(/^\\s*$/)) {\r\n throw new Error(`The '${name}' argument should not be empty.`);\r\n }\r\n }\r\n static isIn(val, values, name) {\r\n // TypeScript enums have keys for **both** the name and the value of each enum member on the type itself.\r\n if (!(val in values)) {\r\n throw new Error(`Unknown ${name} value: ${val}.`);\r\n }\r\n }\r\n}\r\n/** @private */\r\nexport class Platform {\r\n // react-native has a window but no document so we should check both\r\n static get isBrowser() {\r\n return !Platform.isNode && typeof window === \"object\" && typeof window.document === \"object\";\r\n }\r\n // WebWorkers don't have a window object so the isBrowser check would fail\r\n static get isWebWorker() {\r\n return !Platform.isNode && typeof self === \"object\" && \"importScripts\" in self;\r\n }\r\n // react-native has a window but no document\r\n static get isReactNative() {\r\n return !Platform.isNode && typeof window === \"object\" && typeof window.document === \"undefined\";\r\n }\r\n // Node apps shouldn't have a window object, but WebWorkers don't either\r\n // so we need to check for both WebWorker and window\r\n static get isNode() {\r\n return typeof process !== \"undefined\" && process.release && process.release.name === \"node\";\r\n }\r\n}\r\n/** @private */\r\nexport function getDataDetail(data, includeContent) {\r\n let detail = \"\";\r\n if (isArrayBuffer(data)) {\r\n detail = `Binary data of length ${data.byteLength}`;\r\n if (includeContent) {\r\n detail += `. Content: '${formatArrayBuffer(data)}'`;\r\n }\r\n }\r\n else if (typeof data === \"string\") {\r\n detail = `String data of length ${data.length}`;\r\n if (includeContent) {\r\n detail += `. Content: '${data}'`;\r\n }\r\n }\r\n return detail;\r\n}\r\n/** @private */\r\nexport function formatArrayBuffer(data) {\r\n const view = new Uint8Array(data);\r\n // Uint8Array.map only supports returning another Uint8Array?\r\n let str = \"\";\r\n view.forEach((num) => {\r\n const pad = num < 16 ? \"0\" : \"\";\r\n str += `0x${pad}${num.toString(16)} `;\r\n });\r\n // Trim of trailing space.\r\n return str.substr(0, str.length - 1);\r\n}\r\n// Also in signalr-protocol-msgpack/Utils.ts\r\n/** @private */\r\nexport function isArrayBuffer(val) {\r\n return val && typeof ArrayBuffer !== \"undefined\" &&\r\n (val instanceof ArrayBuffer ||\r\n // Sometimes we get an ArrayBuffer that doesn't satisfy instanceof\r\n (val.constructor && val.constructor.name === \"ArrayBuffer\"));\r\n}\r\n/** @private */\r\nexport async function sendMessage(logger, transportName, httpClient, url, content, options) {\r\n const headers = {};\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n logger.log(LogLevel.Trace, `(${transportName} transport) sending data. ${getDataDetail(content, options.logMessageContent)}.`);\r\n const responseType = isArrayBuffer(content) ? \"arraybuffer\" : \"text\";\r\n const response = await httpClient.post(url, {\r\n content,\r\n headers: { ...headers, ...options.headers },\r\n responseType,\r\n timeout: options.timeout,\r\n withCredentials: options.withCredentials,\r\n });\r\n logger.log(LogLevel.Trace, `(${transportName} transport) request complete. Response status: ${response.statusCode}.`);\r\n}\r\n/** @private */\r\nexport function createLogger(logger) {\r\n if (logger === undefined) {\r\n return new ConsoleLogger(LogLevel.Information);\r\n }\r\n if (logger === null) {\r\n return NullLogger.instance;\r\n }\r\n if (logger.log !== undefined) {\r\n return logger;\r\n }\r\n return new ConsoleLogger(logger);\r\n}\r\n/** @private */\r\nexport class SubjectSubscription {\r\n constructor(subject, observer) {\r\n this._subject = subject;\r\n this._observer = observer;\r\n }\r\n dispose() {\r\n const index = this._subject.observers.indexOf(this._observer);\r\n if (index > -1) {\r\n this._subject.observers.splice(index, 1);\r\n }\r\n if (this._subject.observers.length === 0 && this._subject.cancelCallback) {\r\n this._subject.cancelCallback().catch((_) => { });\r\n }\r\n }\r\n}\r\n/** @private */\r\nexport class ConsoleLogger {\r\n constructor(minimumLogLevel) {\r\n this._minLevel = minimumLogLevel;\r\n this.out = console;\r\n }\r\n log(logLevel, message) {\r\n if (logLevel >= this._minLevel) {\r\n const msg = `[${new Date().toISOString()}] ${LogLevel[logLevel]}: ${message}`;\r\n switch (logLevel) {\r\n case LogLevel.Critical:\r\n case LogLevel.Error:\r\n this.out.error(msg);\r\n break;\r\n case LogLevel.Warning:\r\n this.out.warn(msg);\r\n break;\r\n case LogLevel.Information:\r\n this.out.info(msg);\r\n break;\r\n default:\r\n // console.debug only goes to attached debuggers in Node, so we use console.log for Trace and Debug\r\n this.out.log(msg);\r\n break;\r\n }\r\n }\r\n }\r\n}\r\n/** @private */\r\nexport function getUserAgentHeader() {\r\n let userAgentHeaderName = \"X-SignalR-User-Agent\";\r\n if (Platform.isNode) {\r\n userAgentHeaderName = \"User-Agent\";\r\n }\r\n return [userAgentHeaderName, constructUserAgent(VERSION, getOsName(), getRuntime(), getRuntimeVersion())];\r\n}\r\n/** @private */\r\nexport function constructUserAgent(version, os, runtime, runtimeVersion) {\r\n // Microsoft SignalR/[Version] ([Detailed Version]; [Operating System]; [Runtime]; [Runtime Version])\r\n let userAgent = \"Microsoft SignalR/\";\r\n const majorAndMinor = version.split(\".\");\r\n userAgent += `${majorAndMinor[0]}.${majorAndMinor[1]}`;\r\n userAgent += ` (${version}; `;\r\n if (os && os !== \"\") {\r\n userAgent += `${os}; `;\r\n }\r\n else {\r\n userAgent += \"Unknown OS; \";\r\n }\r\n userAgent += `${runtime}`;\r\n if (runtimeVersion) {\r\n userAgent += `; ${runtimeVersion}`;\r\n }\r\n else {\r\n userAgent += \"; Unknown Runtime Version\";\r\n }\r\n userAgent += \")\";\r\n return userAgent;\r\n}\r\n// eslint-disable-next-line spaced-comment\r\n/*#__PURE__*/ function getOsName() {\r\n if (Platform.isNode) {\r\n switch (process.platform) {\r\n case \"win32\":\r\n return \"Windows NT\";\r\n case \"darwin\":\r\n return \"macOS\";\r\n case \"linux\":\r\n return \"Linux\";\r\n default:\r\n return process.platform;\r\n }\r\n }\r\n else {\r\n return \"\";\r\n }\r\n}\r\n// eslint-disable-next-line spaced-comment\r\n/*#__PURE__*/ function getRuntimeVersion() {\r\n if (Platform.isNode) {\r\n return process.versions.node;\r\n }\r\n return undefined;\r\n}\r\nfunction getRuntime() {\r\n if (Platform.isNode) {\r\n return \"NodeJS\";\r\n }\r\n else {\r\n return \"Browser\";\r\n }\r\n}\r\n/** @private */\r\nexport function getErrorString(e) {\r\n if (e.stack) {\r\n return e.stack;\r\n }\r\n else if (e.message) {\r\n return e.message;\r\n }\r\n return `${e}`;\r\n}\r\n/** @private */\r\nexport function getGlobalThis() {\r\n // globalThis is semi-new and not available in Node until v12\r\n if (typeof globalThis !== \"undefined\") {\r\n return globalThis;\r\n }\r\n if (typeof self !== \"undefined\") {\r\n return self;\r\n }\r\n if (typeof window !== \"undefined\") {\r\n return window;\r\n }\r\n if (typeof global !== \"undefined\") {\r\n return global;\r\n }\r\n throw new Error(\"could not find global\");\r\n}\r\n//# sourceMappingURL=Utils.js.map","// 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\nimport { AbortError, HttpError, TimeoutError } from \"./Errors\";\r\nimport { HttpClient, HttpResponse } from \"./HttpClient\";\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { Platform, getGlobalThis, isArrayBuffer } from \"./Utils\";\r\nexport class FetchHttpClient extends HttpClient {\r\n constructor(logger) {\r\n super();\r\n this._logger = logger;\r\n // Node added a fetch implementation to the global scope starting in v18.\r\n // We need to add a cookie jar in node to be able to share cookies with WebSocket\r\n if (typeof fetch === \"undefined\" || Platform.isNode) {\r\n // In order to ignore the dynamic require in webpack builds we need to do this magic\r\n // @ts-ignore: TS doesn't know about these names\r\n const requireFunc = typeof __webpack_require__ === \"function\" ? __non_webpack_require__ : require;\r\n // Cookies aren't automatically handled in Node so we need to add a CookieJar to preserve cookies across requests\r\n this._jar = new (requireFunc(\"tough-cookie\")).CookieJar();\r\n if (typeof fetch === \"undefined\") {\r\n this._fetchType = requireFunc(\"node-fetch\");\r\n }\r\n else {\r\n // Use fetch from Node if available\r\n this._fetchType = fetch;\r\n }\r\n // node-fetch doesn't have a nice API for getting and setting cookies\r\n // fetch-cookie will wrap a fetch implementation with a default CookieJar or a provided one\r\n this._fetchType = requireFunc(\"fetch-cookie\")(this._fetchType, this._jar);\r\n }\r\n else {\r\n this._fetchType = fetch.bind(getGlobalThis());\r\n }\r\n if (typeof AbortController === \"undefined\") {\r\n // In order to ignore the dynamic require in webpack builds we need to do this magic\r\n // @ts-ignore: TS doesn't know about these names\r\n const requireFunc = typeof __webpack_require__ === \"function\" ? __non_webpack_require__ : require;\r\n // Node needs EventListener methods on AbortController which our custom polyfill doesn't provide\r\n this._abortControllerType = requireFunc(\"abort-controller\");\r\n }\r\n else {\r\n this._abortControllerType = AbortController;\r\n }\r\n }\r\n /** @inheritDoc */\r\n async send(request) {\r\n // Check that abort was not signaled before calling send\r\n if (request.abortSignal && request.abortSignal.aborted) {\r\n throw new AbortError();\r\n }\r\n if (!request.method) {\r\n throw new Error(\"No method defined.\");\r\n }\r\n if (!request.url) {\r\n throw new Error(\"No url defined.\");\r\n }\r\n const abortController = new this._abortControllerType();\r\n let error;\r\n // Hook our abortSignal into the abort controller\r\n if (request.abortSignal) {\r\n request.abortSignal.onabort = () => {\r\n abortController.abort();\r\n error = new AbortError();\r\n };\r\n }\r\n // If a timeout has been passed in, setup a timeout to call abort\r\n // Type needs to be any to fit window.setTimeout and NodeJS.setTimeout\r\n let timeoutId = null;\r\n if (request.timeout) {\r\n const msTimeout = request.timeout;\r\n timeoutId = setTimeout(() => {\r\n abortController.abort();\r\n this._logger.log(LogLevel.Warning, `Timeout from HTTP request.`);\r\n error = new TimeoutError();\r\n }, msTimeout);\r\n }\r\n if (request.content === \"\") {\r\n request.content = undefined;\r\n }\r\n if (request.content) {\r\n // Explicitly setting the Content-Type header for React Native on Android platform.\r\n request.headers = request.headers || {};\r\n if (isArrayBuffer(request.content)) {\r\n request.headers[\"Content-Type\"] = \"application/octet-stream\";\r\n }\r\n else {\r\n request.headers[\"Content-Type\"] = \"text/plain;charset=UTF-8\";\r\n }\r\n }\r\n let response;\r\n try {\r\n response = await this._fetchType(request.url, {\r\n body: request.content,\r\n cache: \"no-cache\",\r\n credentials: request.withCredentials === true ? \"include\" : \"same-origin\",\r\n headers: {\r\n \"X-Requested-With\": \"XMLHttpRequest\",\r\n ...request.headers,\r\n },\r\n method: request.method,\r\n mode: \"cors\",\r\n redirect: \"follow\",\r\n signal: abortController.signal,\r\n });\r\n }\r\n catch (e) {\r\n if (error) {\r\n throw error;\r\n }\r\n this._logger.log(LogLevel.Warning, `Error from HTTP request. ${e}.`);\r\n throw e;\r\n }\r\n finally {\r\n if (timeoutId) {\r\n clearTimeout(timeoutId);\r\n }\r\n if (request.abortSignal) {\r\n request.abortSignal.onabort = null;\r\n }\r\n }\r\n if (!response.ok) {\r\n const errorMessage = await deserializeContent(response, \"text\");\r\n throw new HttpError(errorMessage || response.statusText, response.status);\r\n }\r\n const content = deserializeContent(response, request.responseType);\r\n const payload = await content;\r\n return new HttpResponse(response.status, response.statusText, payload);\r\n }\r\n getCookieString(url) {\r\n let cookies = \"\";\r\n if (Platform.isNode && this._jar) {\r\n // @ts-ignore: unused variable\r\n this._jar.getCookies(url, (e, c) => cookies = c.join(\"; \"));\r\n }\r\n return cookies;\r\n }\r\n}\r\nfunction deserializeContent(response, responseType) {\r\n let content;\r\n switch (responseType) {\r\n case \"arraybuffer\":\r\n content = response.arrayBuffer();\r\n break;\r\n case \"text\":\r\n content = response.text();\r\n break;\r\n case \"blob\":\r\n case \"document\":\r\n case \"json\":\r\n throw new Error(`${responseType} is not supported.`);\r\n default:\r\n content = response.text();\r\n break;\r\n }\r\n return content;\r\n}\r\n//# sourceMappingURL=FetchHttpClient.js.map","// 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\nimport { AbortError, HttpError, TimeoutError } from \"./Errors\";\r\nimport { HttpClient, HttpResponse } from \"./HttpClient\";\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { isArrayBuffer } from \"./Utils\";\r\nexport class XhrHttpClient extends HttpClient {\r\n constructor(logger) {\r\n super();\r\n this._logger = logger;\r\n }\r\n /** @inheritDoc */\r\n send(request) {\r\n // Check that abort was not signaled before calling send\r\n if (request.abortSignal && request.abortSignal.aborted) {\r\n return Promise.reject(new AbortError());\r\n }\r\n if (!request.method) {\r\n return Promise.reject(new Error(\"No method defined.\"));\r\n }\r\n if (!request.url) {\r\n return Promise.reject(new Error(\"No url defined.\"));\r\n }\r\n return new Promise((resolve, reject) => {\r\n const xhr = new XMLHttpRequest();\r\n xhr.open(request.method, request.url, true);\r\n xhr.withCredentials = request.withCredentials === undefined ? true : request.withCredentials;\r\n xhr.setRequestHeader(\"X-Requested-With\", \"XMLHttpRequest\");\r\n if (request.content === \"\") {\r\n request.content = undefined;\r\n }\r\n if (request.content) {\r\n // Explicitly setting the Content-Type header for React Native on Android platform.\r\n if (isArrayBuffer(request.content)) {\r\n xhr.setRequestHeader(\"Content-Type\", \"application/octet-stream\");\r\n }\r\n else {\r\n xhr.setRequestHeader(\"Content-Type\", \"text/plain;charset=UTF-8\");\r\n }\r\n }\r\n const headers = request.headers;\r\n if (headers) {\r\n Object.keys(headers)\r\n .forEach((header) => {\r\n xhr.setRequestHeader(header, headers[header]);\r\n });\r\n }\r\n if (request.responseType) {\r\n xhr.responseType = request.responseType;\r\n }\r\n if (request.abortSignal) {\r\n request.abortSignal.onabort = () => {\r\n xhr.abort();\r\n reject(new AbortError());\r\n };\r\n }\r\n if (request.timeout) {\r\n xhr.timeout = request.timeout;\r\n }\r\n xhr.onload = () => {\r\n if (request.abortSignal) {\r\n request.abortSignal.onabort = null;\r\n }\r\n if (xhr.status >= 200 && xhr.status < 300) {\r\n resolve(new HttpResponse(xhr.status, xhr.statusText, xhr.response || xhr.responseText));\r\n }\r\n else {\r\n reject(new HttpError(xhr.response || xhr.responseText || xhr.statusText, xhr.status));\r\n }\r\n };\r\n xhr.onerror = () => {\r\n this._logger.log(LogLevel.Warning, `Error from HTTP request. ${xhr.status}: ${xhr.statusText}.`);\r\n reject(new HttpError(xhr.statusText, xhr.status));\r\n };\r\n xhr.ontimeout = () => {\r\n this._logger.log(LogLevel.Warning, `Timeout from HTTP request.`);\r\n reject(new TimeoutError());\r\n };\r\n xhr.send(request.content);\r\n });\r\n }\r\n}\r\n//# sourceMappingURL=XhrHttpClient.js.map","// 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\nimport { AbortError } from \"./Errors\";\r\nimport { FetchHttpClient } from \"./FetchHttpClient\";\r\nimport { HttpClient } from \"./HttpClient\";\r\nimport { Platform } from \"./Utils\";\r\nimport { XhrHttpClient } from \"./XhrHttpClient\";\r\n/** Default implementation of {@link @microsoft/signalr.HttpClient}. */\r\nexport class DefaultHttpClient extends HttpClient {\r\n /** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */\r\n constructor(logger) {\r\n super();\r\n if (typeof fetch !== \"undefined\" || Platform.isNode) {\r\n this._httpClient = new FetchHttpClient(logger);\r\n }\r\n else if (typeof XMLHttpRequest !== \"undefined\") {\r\n this._httpClient = new XhrHttpClient(logger);\r\n }\r\n else {\r\n throw new Error(\"No usable HttpClient found.\");\r\n }\r\n }\r\n /** @inheritDoc */\r\n send(request) {\r\n // Check that abort was not signaled before calling send\r\n if (request.abortSignal && request.abortSignal.aborted) {\r\n return Promise.reject(new AbortError());\r\n }\r\n if (!request.method) {\r\n return Promise.reject(new Error(\"No method defined.\"));\r\n }\r\n if (!request.url) {\r\n return Promise.reject(new Error(\"No url defined.\"));\r\n }\r\n return this._httpClient.send(request);\r\n }\r\n getCookieString(url) {\r\n return this._httpClient.getCookieString(url);\r\n }\r\n}\r\n//# sourceMappingURL=DefaultHttpClient.js.map","// 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// Not exported from index\r\n/** @private */\r\nexport class TextMessageFormat {\r\n static write(output) {\r\n return `${output}${TextMessageFormat.RecordSeparator}`;\r\n }\r\n static parse(input) {\r\n if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) {\r\n throw new Error(\"Message is incomplete.\");\r\n }\r\n const messages = input.split(TextMessageFormat.RecordSeparator);\r\n messages.pop();\r\n return messages;\r\n }\r\n}\r\nTextMessageFormat.RecordSeparatorCode = 0x1e;\r\nTextMessageFormat.RecordSeparator = String.fromCharCode(TextMessageFormat.RecordSeparatorCode);\r\n//# sourceMappingURL=TextMessageFormat.js.map","// 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\nimport { TextMessageFormat } from \"./TextMessageFormat\";\r\nimport { isArrayBuffer } from \"./Utils\";\r\n/** @private */\r\nexport class HandshakeProtocol {\r\n // Handshake request is always JSON\r\n writeHandshakeRequest(handshakeRequest) {\r\n return TextMessageFormat.write(JSON.stringify(handshakeRequest));\r\n }\r\n parseHandshakeResponse(data) {\r\n let messageData;\r\n let remainingData;\r\n if (isArrayBuffer(data)) {\r\n // Format is binary but still need to read JSON text from handshake response\r\n const binaryData = new Uint8Array(data);\r\n const separatorIndex = binaryData.indexOf(TextMessageFormat.RecordSeparatorCode);\r\n if (separatorIndex === -1) {\r\n throw new Error(\"Message is incomplete.\");\r\n }\r\n // content before separator is handshake response\r\n // optional content after is additional messages\r\n const responseLength = separatorIndex + 1;\r\n messageData = String.fromCharCode.apply(null, Array.prototype.slice.call(binaryData.slice(0, responseLength)));\r\n remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null;\r\n }\r\n else {\r\n const textData = data;\r\n const separatorIndex = textData.indexOf(TextMessageFormat.RecordSeparator);\r\n if (separatorIndex === -1) {\r\n throw new Error(\"Message is incomplete.\");\r\n }\r\n // content before separator is handshake response\r\n // optional content after is additional messages\r\n const responseLength = separatorIndex + 1;\r\n messageData = textData.substring(0, responseLength);\r\n remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null;\r\n }\r\n // At this point we should have just the single handshake message\r\n const messages = TextMessageFormat.parse(messageData);\r\n const response = JSON.parse(messages[0]);\r\n if (response.type) {\r\n throw new Error(\"Expected a handshake response from the server.\");\r\n }\r\n const responseMessage = response;\r\n // multiple messages could have arrived with handshake\r\n // return additional data to be parsed as usual, or null if all parsed\r\n return [remainingData, responseMessage];\r\n }\r\n}\r\n//# sourceMappingURL=HandshakeProtocol.js.map","// 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/** Defines the type of a Hub Message. */\r\nexport var MessageType;\r\n(function (MessageType) {\r\n /** Indicates the message is an Invocation message and implements the {@link @microsoft/signalr.InvocationMessage} interface. */\r\n MessageType[MessageType[\"Invocation\"] = 1] = \"Invocation\";\r\n /** Indicates the message is a StreamItem message and implements the {@link @microsoft/signalr.StreamItemMessage} interface. */\r\n MessageType[MessageType[\"StreamItem\"] = 2] = \"StreamItem\";\r\n /** Indicates the message is a Completion message and implements the {@link @microsoft/signalr.CompletionMessage} interface. */\r\n MessageType[MessageType[\"Completion\"] = 3] = \"Completion\";\r\n /** Indicates the message is a Stream Invocation message and implements the {@link @microsoft/signalr.StreamInvocationMessage} interface. */\r\n MessageType[MessageType[\"StreamInvocation\"] = 4] = \"StreamInvocation\";\r\n /** Indicates the message is a Cancel Invocation message and implements the {@link @microsoft/signalr.CancelInvocationMessage} interface. */\r\n MessageType[MessageType[\"CancelInvocation\"] = 5] = \"CancelInvocation\";\r\n /** Indicates the message is a Ping message and implements the {@link @microsoft/signalr.PingMessage} interface. */\r\n MessageType[MessageType[\"Ping\"] = 6] = \"Ping\";\r\n /** Indicates the message is a Close message and implements the {@link @microsoft/signalr.CloseMessage} interface. */\r\n MessageType[MessageType[\"Close\"] = 7] = \"Close\";\r\n MessageType[MessageType[\"Ack\"] = 8] = \"Ack\";\r\n MessageType[MessageType[\"Sequence\"] = 9] = \"Sequence\";\r\n})(MessageType || (MessageType = {}));\r\n//# sourceMappingURL=IHubProtocol.js.map","// 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\nimport { SubjectSubscription } from \"./Utils\";\r\n/** Stream implementation to stream items to the server. */\r\nexport class Subject {\r\n constructor() {\r\n this.observers = [];\r\n }\r\n next(item) {\r\n for (const observer of this.observers) {\r\n observer.next(item);\r\n }\r\n }\r\n error(err) {\r\n for (const observer of this.observers) {\r\n if (observer.error) {\r\n observer.error(err);\r\n }\r\n }\r\n }\r\n complete() {\r\n for (const observer of this.observers) {\r\n if (observer.complete) {\r\n observer.complete();\r\n }\r\n }\r\n }\r\n subscribe(observer) {\r\n this.observers.push(observer);\r\n return new SubjectSubscription(this, observer);\r\n }\r\n}\r\n//# sourceMappingURL=Subject.js.map","// 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\nimport { MessageType } from \"./IHubProtocol\";\r\nimport { isArrayBuffer } from \"./Utils\";\r\n/** @private */\r\nexport class MessageBuffer {\r\n constructor(protocol, connection, bufferSize) {\r\n this._bufferSize = 100000;\r\n this._messages = [];\r\n this._totalMessageCount = 0;\r\n this._waitForSequenceMessage = false;\r\n // Message IDs start at 1 and always increment by 1\r\n this._nextReceivingSequenceId = 1;\r\n this._latestReceivedSequenceId = 0;\r\n this._bufferedByteCount = 0;\r\n this._reconnectInProgress = false;\r\n this._protocol = protocol;\r\n this._connection = connection;\r\n this._bufferSize = bufferSize;\r\n }\r\n async _send(message) {\r\n const serializedMessage = this._protocol.writeMessage(message);\r\n let backpressurePromise = Promise.resolve();\r\n // Only count invocation messages. Acks, pings, etc. don't need to be resent on reconnect\r\n if (this._isInvocationMessage(message)) {\r\n this._totalMessageCount++;\r\n let backpressurePromiseResolver = () => { };\r\n let backpressurePromiseRejector = () => { };\r\n if (isArrayBuffer(serializedMessage)) {\r\n this._bufferedByteCount += serializedMessage.byteLength;\r\n }\r\n else {\r\n this._bufferedByteCount += serializedMessage.length;\r\n }\r\n if (this._bufferedByteCount >= this._bufferSize) {\r\n backpressurePromise = new Promise((resolve, reject) => {\r\n backpressurePromiseResolver = resolve;\r\n backpressurePromiseRejector = reject;\r\n });\r\n }\r\n this._messages.push(new BufferedItem(serializedMessage, this._totalMessageCount, backpressurePromiseResolver, backpressurePromiseRejector));\r\n }\r\n try {\r\n // If this is set it means we are reconnecting or resending\r\n // We don't want to send on a disconnected connection\r\n // And we don't want to send if resend is running since that would mean sending\r\n // this message twice\r\n if (!this._reconnectInProgress) {\r\n await this._connection.send(serializedMessage);\r\n }\r\n }\r\n catch {\r\n this._disconnected();\r\n }\r\n await backpressurePromise;\r\n }\r\n _ack(ackMessage) {\r\n let newestAckedMessage = -1;\r\n // Find index of newest message being acked\r\n for (let index = 0; index < this._messages.length; index++) {\r\n const element = this._messages[index];\r\n if (element._id <= ackMessage.sequenceId) {\r\n newestAckedMessage = index;\r\n if (isArrayBuffer(element._message)) {\r\n this._bufferedByteCount -= element._message.byteLength;\r\n }\r\n else {\r\n this._bufferedByteCount -= element._message.length;\r\n }\r\n // resolve items that have already been sent and acked\r\n element._resolver();\r\n }\r\n else if (this._bufferedByteCount < this._bufferSize) {\r\n // resolve items that now fall under the buffer limit but haven't been acked\r\n element._resolver();\r\n }\r\n else {\r\n break;\r\n }\r\n }\r\n if (newestAckedMessage !== -1) {\r\n // We're removing everything including the message pointed to, so add 1\r\n this._messages = this._messages.slice(newestAckedMessage + 1);\r\n }\r\n }\r\n _shouldProcessMessage(message) {\r\n if (this._waitForSequenceMessage) {\r\n if (message.type !== MessageType.Sequence) {\r\n return false;\r\n }\r\n else {\r\n this._waitForSequenceMessage = false;\r\n return true;\r\n }\r\n }\r\n // No special processing for acks, pings, etc.\r\n if (!this._isInvocationMessage(message)) {\r\n return true;\r\n }\r\n const currentId = this._nextReceivingSequenceId;\r\n this._nextReceivingSequenceId++;\r\n if (currentId <= this._latestReceivedSequenceId) {\r\n if (currentId === this._latestReceivedSequenceId) {\r\n // Should only hit this if we just reconnected and the server is sending\r\n // Messages it has buffered, which would mean it hasn't seen an Ack for these messages\r\n this._ackTimer();\r\n }\r\n // Ignore, this is a duplicate message\r\n return false;\r\n }\r\n this._latestReceivedSequenceId = currentId;\r\n // Only start the timer for sending an Ack message when we have a message to ack. This also conveniently solves\r\n // timer throttling by not having a recursive timer, and by starting the timer via a network call (recv)\r\n this._ackTimer();\r\n return true;\r\n }\r\n _resetSequence(message) {\r\n if (message.sequenceId > this._nextReceivingSequenceId) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this._connection.stop(new Error(\"Sequence ID greater than amount of messages we've received.\"));\r\n return;\r\n }\r\n this._nextReceivingSequenceId = message.sequenceId;\r\n }\r\n _disconnected() {\r\n this._reconnectInProgress = true;\r\n this._waitForSequenceMessage = true;\r\n }\r\n async _resend() {\r\n const sequenceId = this._messages.length !== 0\r\n ? this._messages[0]._id\r\n : this._totalMessageCount + 1;\r\n await this._connection.send(this._protocol.writeMessage({ type: MessageType.Sequence, sequenceId }));\r\n // Get a local variable to the _messages, just in case messages are acked while resending\r\n // Which would slice the _messages array (which creates a new copy)\r\n const messages = this._messages;\r\n for (const element of messages) {\r\n await this._connection.send(element._message);\r\n }\r\n this._reconnectInProgress = false;\r\n }\r\n _dispose(error) {\r\n error !== null && error !== void 0 ? error : (error = new Error(\"Unable to reconnect to server.\"));\r\n // Unblock backpressure if any\r\n for (const element of this._messages) {\r\n element._rejector(error);\r\n }\r\n }\r\n _isInvocationMessage(message) {\r\n // There is no way to check if something implements an interface.\r\n // So we individually check the messages in a switch statement.\r\n // To make sure we don't miss any message types we rely on the compiler\r\n // seeing the function returns a value and it will do the\r\n // exhaustive check for us on the switch statement, since we don't use 'case default'\r\n switch (message.type) {\r\n case MessageType.Invocation:\r\n case MessageType.StreamItem:\r\n case MessageType.Completion:\r\n case MessageType.StreamInvocation:\r\n case MessageType.CancelInvocation:\r\n return true;\r\n case MessageType.Close:\r\n case MessageType.Sequence:\r\n case MessageType.Ping:\r\n case MessageType.Ack:\r\n return false;\r\n }\r\n }\r\n _ackTimer() {\r\n if (this._ackTimerHandle === undefined) {\r\n this._ackTimerHandle = setTimeout(async () => {\r\n try {\r\n if (!this._reconnectInProgress) {\r\n await this._connection.send(this._protocol.writeMessage({ type: MessageType.Ack, sequenceId: this._latestReceivedSequenceId }));\r\n }\r\n // Ignore errors, that means the connection is closed and we don't care about the Ack message anymore.\r\n }\r\n catch { }\r\n clearTimeout(this._ackTimerHandle);\r\n this._ackTimerHandle = undefined;\r\n // 1 second delay so we don't spam Ack messages if there are many messages being received at once.\r\n }, 1000);\r\n }\r\n }\r\n}\r\nclass BufferedItem {\r\n constructor(message, id, resolver, rejector) {\r\n this._message = message;\r\n this._id = id;\r\n this._resolver = resolver;\r\n this._rejector = rejector;\r\n }\r\n}\r\n//# sourceMappingURL=MessageBuffer.js.map","// 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\nimport { HandshakeProtocol } from \"./HandshakeProtocol\";\r\nimport { AbortError } from \"./Errors\";\r\nimport { MessageType } from \"./IHubProtocol\";\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { Subject } from \"./Subject\";\r\nimport { Arg, getErrorString, Platform } from \"./Utils\";\r\nimport { MessageBuffer } from \"./MessageBuffer\";\r\nconst DEFAULT_TIMEOUT_IN_MS = 30 * 1000;\r\nconst DEFAULT_PING_INTERVAL_IN_MS = 15 * 1000;\r\nconst DEFAULT_STATEFUL_RECONNECT_BUFFER_SIZE = 100000;\r\n/** Describes the current state of the {@link HubConnection} to the server. */\r\nexport var HubConnectionState;\r\n(function (HubConnectionState) {\r\n /** The hub connection is disconnected. */\r\n HubConnectionState[\"Disconnected\"] = \"Disconnected\";\r\n /** The hub connection is connecting. */\r\n HubConnectionState[\"Connecting\"] = \"Connecting\";\r\n /** The hub connection is connected. */\r\n HubConnectionState[\"Connected\"] = \"Connected\";\r\n /** The hub connection is disconnecting. */\r\n HubConnectionState[\"Disconnecting\"] = \"Disconnecting\";\r\n /** The hub connection is reconnecting. */\r\n HubConnectionState[\"Reconnecting\"] = \"Reconnecting\";\r\n})(HubConnectionState || (HubConnectionState = {}));\r\n/** Represents a connection to a SignalR Hub. */\r\nexport class HubConnection {\r\n /** @internal */\r\n // Using a public static factory method means we can have a private constructor and an _internal_\r\n // create method that can be used by HubConnectionBuilder. An \"internal\" constructor would just\r\n // be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a\r\n // public parameter-less constructor.\r\n static create(connection, logger, protocol, reconnectPolicy, serverTimeoutInMilliseconds, keepAliveIntervalInMilliseconds, statefulReconnectBufferSize) {\r\n return new HubConnection(connection, logger, protocol, reconnectPolicy, serverTimeoutInMilliseconds, keepAliveIntervalInMilliseconds, statefulReconnectBufferSize);\r\n }\r\n constructor(connection, logger, protocol, reconnectPolicy, serverTimeoutInMilliseconds, keepAliveIntervalInMilliseconds, statefulReconnectBufferSize) {\r\n this._nextKeepAlive = 0;\r\n this._freezeEventListener = () => {\r\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\");\r\n };\r\n Arg.isRequired(connection, \"connection\");\r\n Arg.isRequired(logger, \"logger\");\r\n Arg.isRequired(protocol, \"protocol\");\r\n this.serverTimeoutInMilliseconds = serverTimeoutInMilliseconds !== null && serverTimeoutInMilliseconds !== void 0 ? serverTimeoutInMilliseconds : DEFAULT_TIMEOUT_IN_MS;\r\n this.keepAliveIntervalInMilliseconds = keepAliveIntervalInMilliseconds !== null && keepAliveIntervalInMilliseconds !== void 0 ? keepAliveIntervalInMilliseconds : DEFAULT_PING_INTERVAL_IN_MS;\r\n this._statefulReconnectBufferSize = statefulReconnectBufferSize !== null && statefulReconnectBufferSize !== void 0 ? statefulReconnectBufferSize : DEFAULT_STATEFUL_RECONNECT_BUFFER_SIZE;\r\n this._logger = logger;\r\n this._protocol = protocol;\r\n this.connection = connection;\r\n this._reconnectPolicy = reconnectPolicy;\r\n this._handshakeProtocol = new HandshakeProtocol();\r\n this.connection.onreceive = (data) => this._processIncomingData(data);\r\n this.connection.onclose = (error) => this._connectionClosed(error);\r\n this._callbacks = {};\r\n this._methods = {};\r\n this._closedCallbacks = [];\r\n this._reconnectingCallbacks = [];\r\n this._reconnectedCallbacks = [];\r\n this._invocationId = 0;\r\n this._receivedHandshakeResponse = false;\r\n this._connectionState = HubConnectionState.Disconnected;\r\n this._connectionStarted = false;\r\n this._cachedPingMessage = this._protocol.writeMessage({ type: MessageType.Ping });\r\n }\r\n /** Indicates the state of the {@link HubConnection} to the server. */\r\n get state() {\r\n return this._connectionState;\r\n }\r\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 */\r\n get connectionId() {\r\n return this.connection ? (this.connection.connectionId || null) : null;\r\n }\r\n /** Indicates the url of the {@link HubConnection} to the server. */\r\n get baseUrl() {\r\n return this.connection.baseUrl || \"\";\r\n }\r\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 */\r\n set baseUrl(url) {\r\n if (this._connectionState !== HubConnectionState.Disconnected && this._connectionState !== HubConnectionState.Reconnecting) {\r\n throw new Error(\"The HubConnection must be in the Disconnected or Reconnecting state to change the url.\");\r\n }\r\n if (!url) {\r\n throw new Error(\"The HubConnection url must be a valid url.\");\r\n }\r\n this.connection.baseUrl = url;\r\n }\r\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 */\r\n start() {\r\n this._startPromise = this._startWithStateTransitions();\r\n return this._startPromise;\r\n }\r\n async _startWithStateTransitions() {\r\n if (this._connectionState !== HubConnectionState.Disconnected) {\r\n return Promise.reject(new Error(\"Cannot start a HubConnection that is not in the 'Disconnected' state.\"));\r\n }\r\n this._connectionState = HubConnectionState.Connecting;\r\n this._logger.log(LogLevel.Debug, \"Starting HubConnection.\");\r\n try {\r\n await this._startInternal();\r\n if (Platform.isBrowser) {\r\n // Log when the browser freezes the tab so users know why their connection unexpectedly stopped working\r\n window.document.addEventListener(\"freeze\", this._freezeEventListener);\r\n }\r\n this._connectionState = HubConnectionState.Connected;\r\n this._connectionStarted = true;\r\n this._logger.log(LogLevel.Debug, \"HubConnection connected successfully.\");\r\n }\r\n catch (e) {\r\n this._connectionState = HubConnectionState.Disconnected;\r\n this._logger.log(LogLevel.Debug, `HubConnection failed to start successfully because of error '${e}'.`);\r\n return Promise.reject(e);\r\n }\r\n }\r\n async _startInternal() {\r\n this._stopDuringStartError = undefined;\r\n this._receivedHandshakeResponse = false;\r\n // Set up the promise before any connection is (re)started otherwise it could race with received messages\r\n const handshakePromise = new Promise((resolve, reject) => {\r\n this._handshakeResolver = resolve;\r\n this._handshakeRejecter = reject;\r\n });\r\n await this.connection.start(this._protocol.transferFormat);\r\n try {\r\n let version = this._protocol.version;\r\n if (!this.connection.features.reconnect) {\r\n // Stateful Reconnect starts with HubProtocol version 2, newer clients connecting to older servers will fail to connect due to\r\n // the handshake only supporting version 1, so we will try to send version 1 during the handshake to keep old servers working.\r\n version = 1;\r\n }\r\n const handshakeRequest = {\r\n protocol: this._protocol.name,\r\n version,\r\n };\r\n this._logger.log(LogLevel.Debug, \"Sending handshake request.\");\r\n await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(handshakeRequest));\r\n this._logger.log(LogLevel.Information, `Using HubProtocol '${this._protocol.name}'.`);\r\n // defensively cleanup timeout in case we receive a message from the server before we finish start\r\n this._cleanupTimeout();\r\n this._resetTimeoutPeriod();\r\n this._resetKeepAliveInterval();\r\n await handshakePromise;\r\n // It's important to check the stopDuringStartError instead of just relying on the handshakePromise\r\n // being rejected on close, because this continuation can run after both the handshake completed successfully\r\n // and the connection was closed.\r\n if (this._stopDuringStartError) {\r\n // It's important to throw instead of returning a rejected promise, because we don't want to allow any state\r\n // transitions to occur between now and the calling code observing the exceptions. Returning a rejected promise\r\n // will cause the calling continuation to get scheduled to run later.\r\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\r\n throw this._stopDuringStartError;\r\n }\r\n const useStatefulReconnect = this.connection.features.reconnect || false;\r\n if (useStatefulReconnect) {\r\n this._messageBuffer = new MessageBuffer(this._protocol, this.connection, this._statefulReconnectBufferSize);\r\n this.connection.features.disconnected = this._messageBuffer._disconnected.bind(this._messageBuffer);\r\n this.connection.features.resend = () => {\r\n if (this._messageBuffer) {\r\n return this._messageBuffer._resend();\r\n }\r\n };\r\n }\r\n if (!this.connection.features.inherentKeepAlive) {\r\n await this._sendMessage(this._cachedPingMessage);\r\n }\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Debug, `Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`);\r\n this._cleanupTimeout();\r\n this._cleanupPingTimer();\r\n // HttpConnection.stop() should not complete until after the onclose callback is invoked.\r\n // This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes.\r\n await this.connection.stop(e);\r\n throw e;\r\n }\r\n }\r\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 */\r\n async stop() {\r\n // Capture the start promise before the connection might be restarted in an onclose callback.\r\n const startPromise = this._startPromise;\r\n this.connection.features.reconnect = false;\r\n this._stopPromise = this._stopInternal();\r\n await this._stopPromise;\r\n try {\r\n // Awaiting undefined continues immediately\r\n await startPromise;\r\n }\r\n catch (e) {\r\n // This exception is returned to the user as a rejected Promise from the start method.\r\n }\r\n }\r\n _stopInternal(error) {\r\n if (this._connectionState === HubConnectionState.Disconnected) {\r\n this._logger.log(LogLevel.Debug, `Call to HubConnection.stop(${error}) ignored because it is already in the disconnected state.`);\r\n return Promise.resolve();\r\n }\r\n if (this._connectionState === HubConnectionState.Disconnecting) {\r\n this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);\r\n return this._stopPromise;\r\n }\r\n const state = this._connectionState;\r\n this._connectionState = HubConnectionState.Disconnecting;\r\n this._logger.log(LogLevel.Debug, \"Stopping HubConnection.\");\r\n if (this._reconnectDelayHandle) {\r\n // We're in a reconnect delay which means the underlying connection is currently already stopped.\r\n // Just clear the handle to stop the reconnect loop (which no one is waiting on thankfully) and\r\n // fire the onclose callbacks.\r\n this._logger.log(LogLevel.Debug, \"Connection stopped during reconnect delay. Done reconnecting.\");\r\n clearTimeout(this._reconnectDelayHandle);\r\n this._reconnectDelayHandle = undefined;\r\n this._completeClose();\r\n return Promise.resolve();\r\n }\r\n if (state === HubConnectionState.Connected) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this._sendCloseMessage();\r\n }\r\n this._cleanupTimeout();\r\n this._cleanupPingTimer();\r\n this._stopDuringStartError = error || new AbortError(\"The connection was stopped before the hub handshake could complete.\");\r\n // HttpConnection.stop() should not complete until after either HttpConnection.start() fails\r\n // or the onclose callback is invoked. The onclose callback will transition the HubConnection\r\n // to the disconnected state if need be before HttpConnection.stop() completes.\r\n return this.connection.stop(error);\r\n }\r\n async _sendCloseMessage() {\r\n try {\r\n await this._sendWithProtocol(this._createCloseMessage());\r\n }\r\n catch {\r\n // Ignore, this is a best effort attempt to let the server know the client closed gracefully.\r\n }\r\n }\r\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 */\r\n stream(methodName, ...args) {\r\n const [streams, streamIds] = this._replaceStreamingParams(args);\r\n const invocationDescriptor = this._createStreamInvocation(methodName, args, streamIds);\r\n // eslint-disable-next-line prefer-const\r\n let promiseQueue;\r\n const subject = new Subject();\r\n subject.cancelCallback = () => {\r\n const cancelInvocation = this._createCancelInvocation(invocationDescriptor.invocationId);\r\n delete this._callbacks[invocationDescriptor.invocationId];\r\n return promiseQueue.then(() => {\r\n return this._sendWithProtocol(cancelInvocation);\r\n });\r\n };\r\n this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => {\r\n if (error) {\r\n subject.error(error);\r\n return;\r\n }\r\n else if (invocationEvent) {\r\n // invocationEvent will not be null when an error is not passed to the callback\r\n if (invocationEvent.type === MessageType.Completion) {\r\n if (invocationEvent.error) {\r\n subject.error(new Error(invocationEvent.error));\r\n }\r\n else {\r\n subject.complete();\r\n }\r\n }\r\n else {\r\n subject.next((invocationEvent.item));\r\n }\r\n }\r\n };\r\n promiseQueue = this._sendWithProtocol(invocationDescriptor)\r\n .catch((e) => {\r\n subject.error(e);\r\n delete this._callbacks[invocationDescriptor.invocationId];\r\n });\r\n this._launchStreams(streams, promiseQueue);\r\n return subject;\r\n }\r\n _sendMessage(message) {\r\n this._resetKeepAliveInterval();\r\n return this.connection.send(message);\r\n }\r\n /**\r\n * Sends a js object to the server.\r\n * @param message The js object to serialize and send.\r\n */\r\n _sendWithProtocol(message) {\r\n if (this._messageBuffer) {\r\n return this._messageBuffer._send(message);\r\n }\r\n else {\r\n return this._sendMessage(this._protocol.writeMessage(message));\r\n }\r\n }\r\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 */\r\n send(methodName, ...args) {\r\n const [streams, streamIds] = this._replaceStreamingParams(args);\r\n const sendPromise = this._sendWithProtocol(this._createInvocation(methodName, args, true, streamIds));\r\n this._launchStreams(streams, sendPromise);\r\n return sendPromise;\r\n }\r\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 */\r\n invoke(methodName, ...args) {\r\n const [streams, streamIds] = this._replaceStreamingParams(args);\r\n const invocationDescriptor = this._createInvocation(methodName, args, false, streamIds);\r\n const p = new Promise((resolve, reject) => {\r\n // invocationId will always have a value for a non-blocking invocation\r\n this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => {\r\n if (error) {\r\n reject(error);\r\n return;\r\n }\r\n else if (invocationEvent) {\r\n // invocationEvent will not be null when an error is not passed to the callback\r\n if (invocationEvent.type === MessageType.Completion) {\r\n if (invocationEvent.error) {\r\n reject(new Error(invocationEvent.error));\r\n }\r\n else {\r\n resolve(invocationEvent.result);\r\n }\r\n }\r\n else {\r\n reject(new Error(`Unexpected message type: ${invocationEvent.type}`));\r\n }\r\n }\r\n };\r\n const promiseQueue = this._sendWithProtocol(invocationDescriptor)\r\n .catch((e) => {\r\n reject(e);\r\n // invocationId will always have a value for a non-blocking invocation\r\n delete this._callbacks[invocationDescriptor.invocationId];\r\n });\r\n this._launchStreams(streams, promiseQueue);\r\n });\r\n return p;\r\n }\r\n on(methodName, newMethod) {\r\n if (!methodName || !newMethod) {\r\n return;\r\n }\r\n methodName = methodName.toLowerCase();\r\n if (!this._methods[methodName]) {\r\n this._methods[methodName] = [];\r\n }\r\n // Preventing adding the same handler multiple times.\r\n if (this._methods[methodName].indexOf(newMethod) !== -1) {\r\n return;\r\n }\r\n this._methods[methodName].push(newMethod);\r\n }\r\n off(methodName, method) {\r\n if (!methodName) {\r\n return;\r\n }\r\n methodName = methodName.toLowerCase();\r\n const handlers = this._methods[methodName];\r\n if (!handlers) {\r\n return;\r\n }\r\n if (method) {\r\n const removeIdx = handlers.indexOf(method);\r\n if (removeIdx !== -1) {\r\n handlers.splice(removeIdx, 1);\r\n if (handlers.length === 0) {\r\n delete this._methods[methodName];\r\n }\r\n }\r\n }\r\n else {\r\n delete this._methods[methodName];\r\n }\r\n }\r\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 */\r\n onclose(callback) {\r\n if (callback) {\r\n this._closedCallbacks.push(callback);\r\n }\r\n }\r\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 */\r\n onreconnecting(callback) {\r\n if (callback) {\r\n this._reconnectingCallbacks.push(callback);\r\n }\r\n }\r\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 */\r\n onreconnected(callback) {\r\n if (callback) {\r\n this._reconnectedCallbacks.push(callback);\r\n }\r\n }\r\n _processIncomingData(data) {\r\n this._cleanupTimeout();\r\n if (!this._receivedHandshakeResponse) {\r\n data = this._processHandshakeResponse(data);\r\n this._receivedHandshakeResponse = true;\r\n }\r\n // Data may have all been read when processing handshake response\r\n if (data) {\r\n // Parse the messages\r\n const messages = this._protocol.parseMessages(data, this._logger);\r\n for (const message of messages) {\r\n if (this._messageBuffer && !this._messageBuffer._shouldProcessMessage(message)) {\r\n // Don't process the message, we are either waiting for a SequenceMessage or received a duplicate message\r\n continue;\r\n }\r\n switch (message.type) {\r\n case MessageType.Invocation:\r\n this._invokeClientMethod(message)\r\n .catch((e) => {\r\n this._logger.log(LogLevel.Error, `Invoke client method threw error: ${getErrorString(e)}`);\r\n });\r\n break;\r\n case MessageType.StreamItem:\r\n case MessageType.Completion: {\r\n const callback = this._callbacks[message.invocationId];\r\n if (callback) {\r\n if (message.type === MessageType.Completion) {\r\n delete this._callbacks[message.invocationId];\r\n }\r\n try {\r\n callback(message);\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `Stream callback threw error: ${getErrorString(e)}`);\r\n }\r\n }\r\n break;\r\n }\r\n case MessageType.Ping:\r\n // Don't care about pings\r\n break;\r\n case MessageType.Close: {\r\n this._logger.log(LogLevel.Information, \"Close message received from server.\");\r\n const error = message.error ? new Error(\"Server returned an error on close: \" + message.error) : undefined;\r\n if (message.allowReconnect === true) {\r\n // It feels wrong not to await connection.stop() here, but processIncomingData is called as part of an onreceive callback which is not async,\r\n // this is already the behavior for serverTimeout(), and HttpConnection.Stop() should catch and log all possible exceptions.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.connection.stop(error);\r\n }\r\n else {\r\n // We cannot await stopInternal() here, but subsequent calls to stop() will await this if stopInternal() is still ongoing.\r\n this._stopPromise = this._stopInternal(error);\r\n }\r\n break;\r\n }\r\n case MessageType.Ack:\r\n if (this._messageBuffer) {\r\n this._messageBuffer._ack(message);\r\n }\r\n break;\r\n case MessageType.Sequence:\r\n if (this._messageBuffer) {\r\n this._messageBuffer._resetSequence(message);\r\n }\r\n break;\r\n default:\r\n this._logger.log(LogLevel.Warning, `Invalid message type: ${message.type}.`);\r\n break;\r\n }\r\n }\r\n }\r\n this._resetTimeoutPeriod();\r\n }\r\n _processHandshakeResponse(data) {\r\n let responseMessage;\r\n let remainingData;\r\n try {\r\n [remainingData, responseMessage] = this._handshakeProtocol.parseHandshakeResponse(data);\r\n }\r\n catch (e) {\r\n const message = \"Error parsing handshake response: \" + e;\r\n this._logger.log(LogLevel.Error, message);\r\n const error = new Error(message);\r\n this._handshakeRejecter(error);\r\n throw error;\r\n }\r\n if (responseMessage.error) {\r\n const message = \"Server returned handshake error: \" + responseMessage.error;\r\n this._logger.log(LogLevel.Error, message);\r\n const error = new Error(message);\r\n this._handshakeRejecter(error);\r\n throw error;\r\n }\r\n else {\r\n this._logger.log(LogLevel.Debug, \"Server handshake complete.\");\r\n }\r\n this._handshakeResolver();\r\n return remainingData;\r\n }\r\n _resetKeepAliveInterval() {\r\n if (this.connection.features.inherentKeepAlive) {\r\n return;\r\n }\r\n // Set the time we want the next keep alive to be sent\r\n // Timer will be setup on next message receive\r\n this._nextKeepAlive = new Date().getTime() + this.keepAliveIntervalInMilliseconds;\r\n this._cleanupPingTimer();\r\n }\r\n _resetTimeoutPeriod() {\r\n if (!this.connection.features || !this.connection.features.inherentKeepAlive) {\r\n // Set the timeout timer\r\n this._timeoutHandle = setTimeout(() => this.serverTimeout(), this.serverTimeoutInMilliseconds);\r\n // Set keepAlive timer if there isn't one\r\n if (this._pingServerHandle === undefined) {\r\n let nextPing = this._nextKeepAlive - new Date().getTime();\r\n if (nextPing < 0) {\r\n nextPing = 0;\r\n }\r\n // The timer needs to be set from a networking callback to avoid Chrome timer throttling from causing timers to run once a minute\r\n this._pingServerHandle = setTimeout(async () => {\r\n if (this._connectionState === HubConnectionState.Connected) {\r\n try {\r\n await this._sendMessage(this._cachedPingMessage);\r\n }\r\n catch {\r\n // We don't care about the error. It should be seen elsewhere in the client.\r\n // The connection is probably in a bad or closed state now, cleanup the timer so it stops triggering\r\n this._cleanupPingTimer();\r\n }\r\n }\r\n }, nextPing);\r\n }\r\n }\r\n }\r\n // eslint-disable-next-line @typescript-eslint/naming-convention\r\n serverTimeout() {\r\n // The server hasn't talked to us in a while. It doesn't like us anymore ... :(\r\n // Terminate the connection, but we don't need to wait on the promise. This could trigger reconnecting.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.connection.stop(new Error(\"Server timeout elapsed without receiving a message from the server.\"));\r\n }\r\n async _invokeClientMethod(invocationMessage) {\r\n const methodName = invocationMessage.target.toLowerCase();\r\n const methods = this._methods[methodName];\r\n if (!methods) {\r\n this._logger.log(LogLevel.Warning, `No client method with the name '${methodName}' found.`);\r\n // No handlers provided by client but the server is expecting a response still, so we send an error\r\n if (invocationMessage.invocationId) {\r\n this._logger.log(LogLevel.Warning, `No result given for '${methodName}' method and invocation ID '${invocationMessage.invocationId}'.`);\r\n await this._sendWithProtocol(this._createCompletionMessage(invocationMessage.invocationId, \"Client didn't provide a result.\", null));\r\n }\r\n return;\r\n }\r\n // Avoid issues with handlers removing themselves thus modifying the list while iterating through it\r\n const methodsCopy = methods.slice();\r\n // Server expects a response\r\n const expectsResponse = invocationMessage.invocationId ? true : false;\r\n // We preserve the last result or exception but still call all handlers\r\n let res;\r\n let exception;\r\n let completionMessage;\r\n for (const m of methodsCopy) {\r\n try {\r\n const prevRes = res;\r\n res = await m.apply(this, invocationMessage.arguments);\r\n if (expectsResponse && res && prevRes) {\r\n this._logger.log(LogLevel.Error, `Multiple results provided for '${methodName}'. Sending error to server.`);\r\n completionMessage = this._createCompletionMessage(invocationMessage.invocationId, `Client provided multiple results.`, null);\r\n }\r\n // Ignore exception if we got a result after, the exception will be logged\r\n exception = undefined;\r\n }\r\n catch (e) {\r\n exception = e;\r\n this._logger.log(LogLevel.Error, `A callback for the method '${methodName}' threw error '${e}'.`);\r\n }\r\n }\r\n if (completionMessage) {\r\n await this._sendWithProtocol(completionMessage);\r\n }\r\n else if (expectsResponse) {\r\n // If there is an exception that means either no result was given or a handler after a result threw\r\n if (exception) {\r\n completionMessage = this._createCompletionMessage(invocationMessage.invocationId, `${exception}`, null);\r\n }\r\n else if (res !== undefined) {\r\n completionMessage = this._createCompletionMessage(invocationMessage.invocationId, null, res);\r\n }\r\n else {\r\n this._logger.log(LogLevel.Warning, `No result given for '${methodName}' method and invocation ID '${invocationMessage.invocationId}'.`);\r\n // Client didn't provide a result or throw from a handler, server expects a response so we send an error\r\n completionMessage = this._createCompletionMessage(invocationMessage.invocationId, \"Client didn't provide a result.\", null);\r\n }\r\n await this._sendWithProtocol(completionMessage);\r\n }\r\n else {\r\n if (res) {\r\n this._logger.log(LogLevel.Error, `Result given for '${methodName}' method but server is not expecting a result.`);\r\n }\r\n }\r\n }\r\n _connectionClosed(error) {\r\n this._logger.log(LogLevel.Debug, `HubConnection.connectionClosed(${error}) called while in state ${this._connectionState}.`);\r\n // Triggering this.handshakeRejecter is insufficient because it could already be resolved without the continuation having run yet.\r\n this._stopDuringStartError = this._stopDuringStartError || error || new AbortError(\"The underlying connection was closed before the hub handshake could complete.\");\r\n // If the handshake is in progress, start will be waiting for the handshake promise, so we complete it.\r\n // If it has already completed, this should just noop.\r\n if (this._handshakeResolver) {\r\n this._handshakeResolver();\r\n }\r\n this._cancelCallbacksWithError(error || new Error(\"Invocation canceled due to the underlying connection being closed.\"));\r\n this._cleanupTimeout();\r\n this._cleanupPingTimer();\r\n if (this._connectionState === HubConnectionState.Disconnecting) {\r\n this._completeClose(error);\r\n }\r\n else if (this._connectionState === HubConnectionState.Connected && this._reconnectPolicy) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this._reconnect(error);\r\n }\r\n else if (this._connectionState === HubConnectionState.Connected) {\r\n this._completeClose(error);\r\n }\r\n // If none of the above if conditions were true were called the HubConnection must be in either:\r\n // 1. The Connecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail it.\r\n // 2. The Reconnecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail the current reconnect attempt\r\n // and potentially continue the reconnect() loop.\r\n // 3. The Disconnected state in which case we're already done.\r\n }\r\n _completeClose(error) {\r\n if (this._connectionStarted) {\r\n this._connectionState = HubConnectionState.Disconnected;\r\n this._connectionStarted = false;\r\n if (this._messageBuffer) {\r\n this._messageBuffer._dispose(error !== null && error !== void 0 ? error : new Error(\"Connection closed.\"));\r\n this._messageBuffer = undefined;\r\n }\r\n if (Platform.isBrowser) {\r\n window.document.removeEventListener(\"freeze\", this._freezeEventListener);\r\n }\r\n try {\r\n this._closedCallbacks.forEach((c) => c.apply(this, [error]));\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `An onclose callback called with error '${error}' threw error '${e}'.`);\r\n }\r\n }\r\n }\r\n async _reconnect(error) {\r\n const reconnectStartTime = Date.now();\r\n let previousReconnectAttempts = 0;\r\n let retryError = error !== undefined ? error : new Error(\"Attempting to reconnect due to a unknown error.\");\r\n let nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts++, 0, retryError);\r\n if (nextRetryDelay === null) {\r\n this._logger.log(LogLevel.Debug, \"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt.\");\r\n this._completeClose(error);\r\n return;\r\n }\r\n this._connectionState = HubConnectionState.Reconnecting;\r\n if (error) {\r\n this._logger.log(LogLevel.Information, `Connection reconnecting because of error '${error}'.`);\r\n }\r\n else {\r\n this._logger.log(LogLevel.Information, \"Connection reconnecting.\");\r\n }\r\n if (this._reconnectingCallbacks.length !== 0) {\r\n try {\r\n this._reconnectingCallbacks.forEach((c) => c.apply(this, [error]));\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `An onreconnecting callback called with error '${error}' threw error '${e}'.`);\r\n }\r\n // Exit early if an onreconnecting callback called connection.stop().\r\n if (this._connectionState !== HubConnectionState.Reconnecting) {\r\n this._logger.log(LogLevel.Debug, \"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.\");\r\n return;\r\n }\r\n }\r\n while (nextRetryDelay !== null) {\r\n this._logger.log(LogLevel.Information, `Reconnect attempt number ${previousReconnectAttempts} will start in ${nextRetryDelay} ms.`);\r\n await new Promise((resolve) => {\r\n this._reconnectDelayHandle = setTimeout(resolve, nextRetryDelay);\r\n });\r\n this._reconnectDelayHandle = undefined;\r\n if (this._connectionState !== HubConnectionState.Reconnecting) {\r\n this._logger.log(LogLevel.Debug, \"Connection left the reconnecting state during reconnect delay. Done reconnecting.\");\r\n return;\r\n }\r\n try {\r\n await this._startInternal();\r\n this._connectionState = HubConnectionState.Connected;\r\n this._logger.log(LogLevel.Information, \"HubConnection reconnected successfully.\");\r\n if (this._reconnectedCallbacks.length !== 0) {\r\n try {\r\n this._reconnectedCallbacks.forEach((c) => c.apply(this, [this.connection.connectionId]));\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`);\r\n }\r\n }\r\n return;\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Information, `Reconnect attempt failed because of error '${e}'.`);\r\n if (this._connectionState !== HubConnectionState.Reconnecting) {\r\n this._logger.log(LogLevel.Debug, `Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`);\r\n // The TypeScript compiler thinks that connectionState must be Connected here. The TypeScript compiler is wrong.\r\n if (this._connectionState === HubConnectionState.Disconnecting) {\r\n this._completeClose();\r\n }\r\n return;\r\n }\r\n retryError = e instanceof Error ? e : new Error(e.toString());\r\n nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts++, Date.now() - reconnectStartTime, retryError);\r\n }\r\n }\r\n this._logger.log(LogLevel.Information, `Reconnect retries have been exhausted after ${Date.now() - reconnectStartTime} ms and ${previousReconnectAttempts} failed attempts. Connection disconnecting.`);\r\n this._completeClose();\r\n }\r\n _getNextRetryDelay(previousRetryCount, elapsedMilliseconds, retryReason) {\r\n try {\r\n return this._reconnectPolicy.nextRetryDelayInMilliseconds({\r\n elapsedMilliseconds,\r\n previousRetryCount,\r\n retryReason,\r\n });\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `IRetryPolicy.nextRetryDelayInMilliseconds(${previousRetryCount}, ${elapsedMilliseconds}) threw error '${e}'.`);\r\n return null;\r\n }\r\n }\r\n _cancelCallbacksWithError(error) {\r\n const callbacks = this._callbacks;\r\n this._callbacks = {};\r\n Object.keys(callbacks)\r\n .forEach((key) => {\r\n const callback = callbacks[key];\r\n try {\r\n callback(null, error);\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `Stream 'error' callback called with '${error}' threw error: ${getErrorString(e)}`);\r\n }\r\n });\r\n }\r\n _cleanupPingTimer() {\r\n if (this._pingServerHandle) {\r\n clearTimeout(this._pingServerHandle);\r\n this._pingServerHandle = undefined;\r\n }\r\n }\r\n _cleanupTimeout() {\r\n if (this._timeoutHandle) {\r\n clearTimeout(this._timeoutHandle);\r\n }\r\n }\r\n _createInvocation(methodName, args, nonblocking, streamIds) {\r\n if (nonblocking) {\r\n if (streamIds.length !== 0) {\r\n return {\r\n arguments: args,\r\n streamIds,\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n }\r\n else {\r\n return {\r\n arguments: args,\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n }\r\n }\r\n else {\r\n const invocationId = this._invocationId;\r\n this._invocationId++;\r\n if (streamIds.length !== 0) {\r\n return {\r\n arguments: args,\r\n invocationId: invocationId.toString(),\r\n streamIds,\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n }\r\n else {\r\n return {\r\n arguments: args,\r\n invocationId: invocationId.toString(),\r\n target: methodName,\r\n type: MessageType.Invocation,\r\n };\r\n }\r\n }\r\n }\r\n _launchStreams(streams, promiseQueue) {\r\n if (streams.length === 0) {\r\n return;\r\n }\r\n // Synchronize stream data so they arrive in-order on the server\r\n if (!promiseQueue) {\r\n promiseQueue = Promise.resolve();\r\n }\r\n // We want to iterate over the keys, since the keys are the stream ids\r\n // eslint-disable-next-line guard-for-in\r\n for (const streamId in streams) {\r\n streams[streamId].subscribe({\r\n complete: () => {\r\n promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId)));\r\n },\r\n error: (err) => {\r\n let message;\r\n if (err instanceof Error) {\r\n message = err.message;\r\n }\r\n else if (err && err.toString) {\r\n message = err.toString();\r\n }\r\n else {\r\n message = \"Unknown error\";\r\n }\r\n promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId, message)));\r\n },\r\n next: (item) => {\r\n promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createStreamItemMessage(streamId, item)));\r\n },\r\n });\r\n }\r\n }\r\n _replaceStreamingParams(args) {\r\n const streams = [];\r\n const streamIds = [];\r\n for (let i = 0; i < args.length; i++) {\r\n const argument = args[i];\r\n if (this._isObservable(argument)) {\r\n const streamId = this._invocationId;\r\n this._invocationId++;\r\n // Store the stream for later use\r\n streams[streamId] = argument;\r\n streamIds.push(streamId.toString());\r\n // remove stream from args\r\n args.splice(i, 1);\r\n }\r\n }\r\n return [streams, streamIds];\r\n }\r\n _isObservable(arg) {\r\n // This allows other stream implementations to just work (like rxjs)\r\n return arg && arg.subscribe && typeof arg.subscribe === \"function\";\r\n }\r\n _createStreamInvocation(methodName, args, streamIds) {\r\n const invocationId = this._invocationId;\r\n this._invocationId++;\r\n if (streamIds.length !== 0) {\r\n return {\r\n arguments: args,\r\n invocationId: invocationId.toString(),\r\n streamIds,\r\n target: methodName,\r\n type: MessageType.StreamInvocation,\r\n };\r\n }\r\n else {\r\n return {\r\n arguments: args,\r\n invocationId: invocationId.toString(),\r\n target: methodName,\r\n type: MessageType.StreamInvocation,\r\n };\r\n }\r\n }\r\n _createCancelInvocation(id) {\r\n return {\r\n invocationId: id,\r\n type: MessageType.CancelInvocation,\r\n };\r\n }\r\n _createStreamItemMessage(id, item) {\r\n return {\r\n invocationId: id,\r\n item,\r\n type: MessageType.StreamItem,\r\n };\r\n }\r\n _createCompletionMessage(id, error, result) {\r\n if (error) {\r\n return {\r\n error,\r\n invocationId: id,\r\n type: MessageType.Completion,\r\n };\r\n }\r\n return {\r\n invocationId: id,\r\n result,\r\n type: MessageType.Completion,\r\n };\r\n }\r\n _createCloseMessage() {\r\n return { type: MessageType.Close };\r\n }\r\n}\r\n//# sourceMappingURL=HubConnection.js.map","// 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// 0, 2, 10, 30 second delays before reconnect attempts.\r\nconst DEFAULT_RETRY_DELAYS_IN_MILLISECONDS = [0, 2000, 10000, 30000, null];\r\n/** @private */\r\nexport class DefaultReconnectPolicy {\r\n constructor(retryDelays) {\r\n this._retryDelays = retryDelays !== undefined ? [...retryDelays, null] : DEFAULT_RETRY_DELAYS_IN_MILLISECONDS;\r\n }\r\n nextRetryDelayInMilliseconds(retryContext) {\r\n return this._retryDelays[retryContext.previousRetryCount];\r\n }\r\n}\r\n//# sourceMappingURL=DefaultReconnectPolicy.js.map","// 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\nexport class HeaderNames {\r\n}\r\nHeaderNames.Authorization = \"Authorization\";\r\nHeaderNames.Cookie = \"Cookie\";\r\n//# sourceMappingURL=HeaderNames.js.map","// 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\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport { HttpClient } from \"./HttpClient\";\r\n/** @private */\r\nexport class AccessTokenHttpClient extends HttpClient {\r\n constructor(innerClient, accessTokenFactory) {\r\n super();\r\n this._innerClient = innerClient;\r\n this._accessTokenFactory = accessTokenFactory;\r\n }\r\n async send(request) {\r\n let allowRetry = true;\r\n if (this._accessTokenFactory && (!this._accessToken || (request.url && request.url.indexOf(\"/negotiate?\") > 0))) {\r\n // don't retry if the request is a negotiate or if we just got a potentially new token from the access token factory\r\n allowRetry = false;\r\n this._accessToken = await this._accessTokenFactory();\r\n }\r\n this._setAuthorizationHeader(request);\r\n const response = await this._innerClient.send(request);\r\n if (allowRetry && response.statusCode === 401 && this._accessTokenFactory) {\r\n this._accessToken = await this._accessTokenFactory();\r\n this._setAuthorizationHeader(request);\r\n return await this._innerClient.send(request);\r\n }\r\n return response;\r\n }\r\n _setAuthorizationHeader(request) {\r\n if (!request.headers) {\r\n request.headers = {};\r\n }\r\n if (this._accessToken) {\r\n request.headers[HeaderNames.Authorization] = `Bearer ${this._accessToken}`;\r\n }\r\n // don't remove the header if there isn't an access token factory, the user manually added the header in this case\r\n else if (this._accessTokenFactory) {\r\n if (request.headers[HeaderNames.Authorization]) {\r\n delete request.headers[HeaderNames.Authorization];\r\n }\r\n }\r\n }\r\n getCookieString(url) {\r\n return this._innerClient.getCookieString(url);\r\n }\r\n}\r\n//# sourceMappingURL=AccessTokenHttpClient.js.map","// 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// This will be treated as a bit flag in the future, so we keep it using power-of-two values.\r\n/** Specifies a specific HTTP transport type. */\r\nexport var HttpTransportType;\r\n(function (HttpTransportType) {\r\n /** Specifies no transport preference. */\r\n HttpTransportType[HttpTransportType[\"None\"] = 0] = \"None\";\r\n /** Specifies the WebSockets transport. */\r\n HttpTransportType[HttpTransportType[\"WebSockets\"] = 1] = \"WebSockets\";\r\n /** Specifies the Server-Sent Events transport. */\r\n HttpTransportType[HttpTransportType[\"ServerSentEvents\"] = 2] = \"ServerSentEvents\";\r\n /** Specifies the Long Polling transport. */\r\n HttpTransportType[HttpTransportType[\"LongPolling\"] = 4] = \"LongPolling\";\r\n})(HttpTransportType || (HttpTransportType = {}));\r\n/** Specifies the transfer format for a connection. */\r\nexport var TransferFormat;\r\n(function (TransferFormat) {\r\n /** Specifies that only text data will be transmitted over the connection. */\r\n TransferFormat[TransferFormat[\"Text\"] = 1] = \"Text\";\r\n /** Specifies that binary data will be transmitted over the connection. */\r\n TransferFormat[TransferFormat[\"Binary\"] = 2] = \"Binary\";\r\n})(TransferFormat || (TransferFormat = {}));\r\n//# sourceMappingURL=ITransport.js.map","// 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// Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController\r\n// We don't actually ever use the API being polyfilled, we always use the polyfill because\r\n// it's a very new API right now.\r\n// Not exported from index.\r\n/** @private */\r\nexport class AbortController {\r\n constructor() {\r\n this._isAborted = false;\r\n this.onabort = null;\r\n }\r\n abort() {\r\n if (!this._isAborted) {\r\n this._isAborted = true;\r\n if (this.onabort) {\r\n this.onabort();\r\n }\r\n }\r\n }\r\n get signal() {\r\n return this;\r\n }\r\n get aborted() {\r\n return this._isAborted;\r\n }\r\n}\r\n//# sourceMappingURL=AbortController.js.map","// 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\nimport { AbortController } from \"./AbortController\";\r\nimport { HttpError, TimeoutError } from \"./Errors\";\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { TransferFormat } from \"./ITransport\";\r\nimport { Arg, getDataDetail, getUserAgentHeader, sendMessage } from \"./Utils\";\r\n// Not exported from 'index', this type is internal.\r\n/** @private */\r\nexport class LongPollingTransport {\r\n // This is an internal type, not exported from 'index' so this is really just internal.\r\n get pollAborted() {\r\n return this._pollAbort.aborted;\r\n }\r\n constructor(httpClient, logger, options) {\r\n this._httpClient = httpClient;\r\n this._logger = logger;\r\n this._pollAbort = new AbortController();\r\n this._options = options;\r\n this._running = false;\r\n this.onreceive = null;\r\n this.onclose = null;\r\n }\r\n async connect(url, transferFormat) {\r\n Arg.isRequired(url, \"url\");\r\n Arg.isRequired(transferFormat, \"transferFormat\");\r\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\r\n this._url = url;\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Connecting.\");\r\n // Allow binary format on Node and Browsers that support binary content (indicated by the presence of responseType property)\r\n if (transferFormat === TransferFormat.Binary &&\r\n (typeof XMLHttpRequest !== \"undefined\" && typeof new XMLHttpRequest().responseType !== \"string\")) {\r\n throw new Error(\"Binary protocols over XmlHttpRequest not implementing advanced features are not supported.\");\r\n }\r\n const [name, value] = getUserAgentHeader();\r\n const headers = { [name]: value, ...this._options.headers };\r\n const pollOptions = {\r\n abortSignal: this._pollAbort.signal,\r\n headers,\r\n timeout: 100000,\r\n withCredentials: this._options.withCredentials,\r\n };\r\n if (transferFormat === TransferFormat.Binary) {\r\n pollOptions.responseType = \"arraybuffer\";\r\n }\r\n // Make initial long polling request\r\n // Server uses first long polling request to finish initializing connection and it returns without data\r\n const pollUrl = `${url}&_=${Date.now()}`;\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`);\r\n const response = await this._httpClient.get(pollUrl, pollOptions);\r\n if (response.statusCode !== 200) {\r\n this._logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`);\r\n // Mark running as false so that the poll immediately ends and runs the close logic\r\n this._closeError = new HttpError(response.statusText || \"\", response.statusCode);\r\n this._running = false;\r\n }\r\n else {\r\n this._running = true;\r\n }\r\n this._receiving = this._poll(this._url, pollOptions);\r\n }\r\n async _poll(url, pollOptions) {\r\n try {\r\n while (this._running) {\r\n try {\r\n const pollUrl = `${url}&_=${Date.now()}`;\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`);\r\n const response = await this._httpClient.get(pollUrl, pollOptions);\r\n if (response.statusCode === 204) {\r\n this._logger.log(LogLevel.Information, \"(LongPolling transport) Poll terminated by server.\");\r\n this._running = false;\r\n }\r\n else if (response.statusCode !== 200) {\r\n this._logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`);\r\n // Unexpected status code\r\n this._closeError = new HttpError(response.statusText || \"\", response.statusCode);\r\n this._running = false;\r\n }\r\n else {\r\n // Process the response\r\n if (response.content) {\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) data received. ${getDataDetail(response.content, this._options.logMessageContent)}.`);\r\n if (this.onreceive) {\r\n this.onreceive(response.content);\r\n }\r\n }\r\n else {\r\n // This is another way timeout manifest.\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Poll timed out, reissuing.\");\r\n }\r\n }\r\n }\r\n catch (e) {\r\n if (!this._running) {\r\n // Log but disregard errors that occur after stopping\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) Poll errored after shutdown: ${e.message}`);\r\n }\r\n else {\r\n if (e instanceof TimeoutError) {\r\n // Ignore timeouts and reissue the poll.\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Poll timed out, reissuing.\");\r\n }\r\n else {\r\n // Close the connection with the error as the result.\r\n this._closeError = e;\r\n this._running = false;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n finally {\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Polling complete.\");\r\n // We will reach here with pollAborted==false when the server returned a response causing the transport to stop.\r\n // If pollAborted==true then client initiated the stop and the stop method will raise the close event after DELETE is sent.\r\n if (!this.pollAborted) {\r\n this._raiseOnClose();\r\n }\r\n }\r\n }\r\n async send(data) {\r\n if (!this._running) {\r\n return Promise.reject(new Error(\"Cannot send until the transport is connected\"));\r\n }\r\n return sendMessage(this._logger, \"LongPolling\", this._httpClient, this._url, data, this._options);\r\n }\r\n async stop() {\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Stopping polling.\");\r\n // Tell receiving loop to stop, abort any current request, and then wait for it to finish\r\n this._running = false;\r\n this._pollAbort.abort();\r\n try {\r\n await this._receiving;\r\n // Send DELETE to clean up long polling on the server\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) sending DELETE request to ${this._url}.`);\r\n const headers = {};\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n const deleteOptions = {\r\n headers: { ...headers, ...this._options.headers },\r\n timeout: this._options.timeout,\r\n withCredentials: this._options.withCredentials,\r\n };\r\n let error;\r\n try {\r\n await this._httpClient.delete(this._url, deleteOptions);\r\n }\r\n catch (err) {\r\n error = err;\r\n }\r\n if (error) {\r\n if (error instanceof HttpError) {\r\n if (error.statusCode === 404) {\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) A 404 response was returned from sending a DELETE request.\");\r\n }\r\n else {\r\n this._logger.log(LogLevel.Trace, `(LongPolling transport) Error sending a DELETE request: ${error}`);\r\n }\r\n }\r\n }\r\n else {\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) DELETE request accepted.\");\r\n }\r\n }\r\n finally {\r\n this._logger.log(LogLevel.Trace, \"(LongPolling transport) Stop finished.\");\r\n // Raise close event here instead of in polling\r\n // It needs to happen after the DELETE request is sent\r\n this._raiseOnClose();\r\n }\r\n }\r\n _raiseOnClose() {\r\n if (this.onclose) {\r\n let logMessage = \"(LongPolling transport) Firing onclose event.\";\r\n if (this._closeError) {\r\n logMessage += \" Error: \" + this._closeError;\r\n }\r\n this._logger.log(LogLevel.Trace, logMessage);\r\n this.onclose(this._closeError);\r\n }\r\n }\r\n}\r\n//# sourceMappingURL=LongPollingTransport.js.map","// 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\nimport { LogLevel } from \"./ILogger\";\r\nimport { TransferFormat } from \"./ITransport\";\r\nimport { Arg, getDataDetail, getUserAgentHeader, Platform, sendMessage } from \"./Utils\";\r\n/** @private */\r\nexport class ServerSentEventsTransport {\r\n constructor(httpClient, accessToken, logger, options) {\r\n this._httpClient = httpClient;\r\n this._accessToken = accessToken;\r\n this._logger = logger;\r\n this._options = options;\r\n this.onreceive = null;\r\n this.onclose = null;\r\n }\r\n async connect(url, transferFormat) {\r\n Arg.isRequired(url, \"url\");\r\n Arg.isRequired(transferFormat, \"transferFormat\");\r\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\r\n this._logger.log(LogLevel.Trace, \"(SSE transport) Connecting.\");\r\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\r\n this._url = url;\r\n if (this._accessToken) {\r\n url += (url.indexOf(\"?\") < 0 ? \"?\" : \"&\") + `access_token=${encodeURIComponent(this._accessToken)}`;\r\n }\r\n return new Promise((resolve, reject) => {\r\n let opened = false;\r\n if (transferFormat !== TransferFormat.Text) {\r\n reject(new Error(\"The Server-Sent Events transport only supports the 'Text' transfer format\"));\r\n return;\r\n }\r\n let eventSource;\r\n if (Platform.isBrowser || Platform.isWebWorker) {\r\n eventSource = new this._options.EventSource(url, { withCredentials: this._options.withCredentials });\r\n }\r\n else {\r\n // Non-browser passes cookies via the dictionary\r\n const cookies = this._httpClient.getCookieString(url);\r\n const headers = {};\r\n headers.Cookie = cookies;\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n eventSource = new this._options.EventSource(url, { withCredentials: this._options.withCredentials, headers: { ...headers, ...this._options.headers } });\r\n }\r\n try {\r\n eventSource.onmessage = (e) => {\r\n if (this.onreceive) {\r\n try {\r\n this._logger.log(LogLevel.Trace, `(SSE transport) data received. ${getDataDetail(e.data, this._options.logMessageContent)}.`);\r\n this.onreceive(e.data);\r\n }\r\n catch (error) {\r\n this._close(error);\r\n return;\r\n }\r\n }\r\n };\r\n // @ts-ignore: not using event on purpose\r\n eventSource.onerror = (e) => {\r\n // EventSource doesn't give any useful information about server side closes.\r\n if (opened) {\r\n this._close();\r\n }\r\n else {\r\n reject(new Error(\"EventSource failed to connect. The connection could not be found on the server,\"\r\n + \" either the connection ID is not present on the server, or a proxy is refusing/buffering the connection.\"\r\n + \" If you have multiple servers check that sticky sessions are enabled.\"));\r\n }\r\n };\r\n eventSource.onopen = () => {\r\n this._logger.log(LogLevel.Information, `SSE connected to ${this._url}`);\r\n this._eventSource = eventSource;\r\n opened = true;\r\n resolve();\r\n };\r\n }\r\n catch (e) {\r\n reject(e);\r\n return;\r\n }\r\n });\r\n }\r\n async send(data) {\r\n if (!this._eventSource) {\r\n return Promise.reject(new Error(\"Cannot send until the transport is connected\"));\r\n }\r\n return sendMessage(this._logger, \"SSE\", this._httpClient, this._url, data, this._options);\r\n }\r\n stop() {\r\n this._close();\r\n return Promise.resolve();\r\n }\r\n _close(e) {\r\n if (this._eventSource) {\r\n this._eventSource.close();\r\n this._eventSource = undefined;\r\n if (this.onclose) {\r\n this.onclose(e);\r\n }\r\n }\r\n }\r\n}\r\n//# sourceMappingURL=ServerSentEventsTransport.js.map","// 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\nimport { HeaderNames } from \"./HeaderNames\";\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { TransferFormat } from \"./ITransport\";\r\nimport { Arg, getDataDetail, getUserAgentHeader, Platform } from \"./Utils\";\r\n/** @private */\r\nexport class WebSocketTransport {\r\n constructor(httpClient, accessTokenFactory, logger, logMessageContent, webSocketConstructor, headers) {\r\n this._logger = logger;\r\n this._accessTokenFactory = accessTokenFactory;\r\n this._logMessageContent = logMessageContent;\r\n this._webSocketConstructor = webSocketConstructor;\r\n this._httpClient = httpClient;\r\n this.onreceive = null;\r\n this.onclose = null;\r\n this._headers = headers;\r\n }\r\n async connect(url, transferFormat) {\r\n Arg.isRequired(url, \"url\");\r\n Arg.isRequired(transferFormat, \"transferFormat\");\r\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\r\n this._logger.log(LogLevel.Trace, \"(WebSockets transport) Connecting.\");\r\n let token;\r\n if (this._accessTokenFactory) {\r\n token = await this._accessTokenFactory();\r\n }\r\n return new Promise((resolve, reject) => {\r\n url = url.replace(/^http/, \"ws\");\r\n let webSocket;\r\n const cookies = this._httpClient.getCookieString(url);\r\n let opened = false;\r\n if (Platform.isNode || Platform.isReactNative) {\r\n const headers = {};\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n if (token) {\r\n headers[HeaderNames.Authorization] = `Bearer ${token}`;\r\n }\r\n if (cookies) {\r\n headers[HeaderNames.Cookie] = cookies;\r\n }\r\n // Only pass headers when in non-browser environments\r\n webSocket = new this._webSocketConstructor(url, undefined, {\r\n headers: { ...headers, ...this._headers },\r\n });\r\n }\r\n else {\r\n if (token) {\r\n url += (url.indexOf(\"?\") < 0 ? \"?\" : \"&\") + `access_token=${encodeURIComponent(token)}`;\r\n }\r\n }\r\n if (!webSocket) {\r\n // Chrome is not happy with passing 'undefined' as protocol\r\n webSocket = new this._webSocketConstructor(url);\r\n }\r\n if (transferFormat === TransferFormat.Binary) {\r\n webSocket.binaryType = \"arraybuffer\";\r\n }\r\n webSocket.onopen = (_event) => {\r\n this._logger.log(LogLevel.Information, `WebSocket connected to ${url}.`);\r\n this._webSocket = webSocket;\r\n opened = true;\r\n resolve();\r\n };\r\n webSocket.onerror = (event) => {\r\n let error = null;\r\n // ErrorEvent is a browser only type we need to check if the type exists before using it\r\n if (typeof ErrorEvent !== \"undefined\" && event instanceof ErrorEvent) {\r\n error = event.error;\r\n }\r\n else {\r\n error = \"There was an error with the transport\";\r\n }\r\n this._logger.log(LogLevel.Information, `(WebSockets transport) ${error}.`);\r\n };\r\n webSocket.onmessage = (message) => {\r\n this._logger.log(LogLevel.Trace, `(WebSockets transport) data received. ${getDataDetail(message.data, this._logMessageContent)}.`);\r\n if (this.onreceive) {\r\n try {\r\n this.onreceive(message.data);\r\n }\r\n catch (error) {\r\n this._close(error);\r\n return;\r\n }\r\n }\r\n };\r\n webSocket.onclose = (event) => {\r\n // Don't call close handler if connection was never established\r\n // We'll reject the connect call instead\r\n if (opened) {\r\n this._close(event);\r\n }\r\n else {\r\n let error = null;\r\n // ErrorEvent is a browser only type we need to check if the type exists before using it\r\n if (typeof ErrorEvent !== \"undefined\" && event instanceof ErrorEvent) {\r\n error = event.error;\r\n }\r\n else {\r\n error = \"WebSocket failed to connect. The connection could not be found on the server,\"\r\n + \" either the endpoint may not be a SignalR endpoint,\"\r\n + \" the connection ID is not present on the server, or there is a proxy blocking WebSockets.\"\r\n + \" If you have multiple servers check that sticky sessions are enabled.\";\r\n }\r\n reject(new Error(error));\r\n }\r\n };\r\n });\r\n }\r\n send(data) {\r\n if (this._webSocket && this._webSocket.readyState === this._webSocketConstructor.OPEN) {\r\n this._logger.log(LogLevel.Trace, `(WebSockets transport) sending data. ${getDataDetail(data, this._logMessageContent)}.`);\r\n this._webSocket.send(data);\r\n return Promise.resolve();\r\n }\r\n return Promise.reject(\"WebSocket is not in the OPEN state\");\r\n }\r\n stop() {\r\n if (this._webSocket) {\r\n // Manually invoke onclose callback inline so we know the HttpConnection was closed properly before returning\r\n // This also solves an issue where websocket.onclose could take 18+ seconds to trigger during network disconnects\r\n this._close(undefined);\r\n }\r\n return Promise.resolve();\r\n }\r\n _close(event) {\r\n // webSocket will be null if the transport did not start successfully\r\n if (this._webSocket) {\r\n // Clear websocket handlers because we are considering the socket closed now\r\n this._webSocket.onclose = () => { };\r\n this._webSocket.onmessage = () => { };\r\n this._webSocket.onerror = () => { };\r\n this._webSocket.close();\r\n this._webSocket = undefined;\r\n }\r\n this._logger.log(LogLevel.Trace, \"(WebSockets transport) socket closed.\");\r\n if (this.onclose) {\r\n if (this._isCloseEvent(event) && (event.wasClean === false || event.code !== 1000)) {\r\n this.onclose(new Error(`WebSocket closed with status code: ${event.code} (${event.reason || \"no reason given\"}).`));\r\n }\r\n else if (event instanceof Error) {\r\n this.onclose(event);\r\n }\r\n else {\r\n this.onclose();\r\n }\r\n }\r\n }\r\n _isCloseEvent(event) {\r\n return event && typeof event.wasClean === \"boolean\" && typeof event.code === \"number\";\r\n }\r\n}\r\n//# sourceMappingURL=WebSocketTransport.js.map","// 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\nimport { AccessTokenHttpClient } from \"./AccessTokenHttpClient\";\r\nimport { DefaultHttpClient } from \"./DefaultHttpClient\";\r\nimport { AggregateErrors, DisabledTransportError, FailedToNegotiateWithServerError, FailedToStartTransportError, HttpError, UnsupportedTransportError, AbortError } from \"./Errors\";\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { HttpTransportType, TransferFormat } from \"./ITransport\";\r\nimport { LongPollingTransport } from \"./LongPollingTransport\";\r\nimport { ServerSentEventsTransport } from \"./ServerSentEventsTransport\";\r\nimport { Arg, createLogger, getUserAgentHeader, Platform } from \"./Utils\";\r\nimport { WebSocketTransport } from \"./WebSocketTransport\";\r\nconst MAX_REDIRECTS = 100;\r\n/** @private */\r\nexport class HttpConnection {\r\n constructor(url, options = {}) {\r\n this._stopPromiseResolver = () => { };\r\n this.features = {};\r\n this._negotiateVersion = 1;\r\n Arg.isRequired(url, \"url\");\r\n this._logger = createLogger(options.logger);\r\n this.baseUrl = this._resolveUrl(url);\r\n options = options || {};\r\n options.logMessageContent = options.logMessageContent === undefined ? false : options.logMessageContent;\r\n if (typeof options.withCredentials === \"boolean\" || options.withCredentials === undefined) {\r\n options.withCredentials = options.withCredentials === undefined ? true : options.withCredentials;\r\n }\r\n else {\r\n throw new Error(\"withCredentials option was not a 'boolean' or 'undefined' value\");\r\n }\r\n options.timeout = options.timeout === undefined ? 100 * 1000 : options.timeout;\r\n let webSocketModule = null;\r\n let eventSourceModule = null;\r\n if (Platform.isNode && typeof require !== \"undefined\") {\r\n // In order to ignore the dynamic require in webpack builds we need to do this magic\r\n // @ts-ignore: TS doesn't know about these names\r\n const requireFunc = typeof __webpack_require__ === \"function\" ? __non_webpack_require__ : require;\r\n webSocketModule = requireFunc(\"ws\");\r\n eventSourceModule = requireFunc(\"eventsource\");\r\n }\r\n if (!Platform.isNode && typeof WebSocket !== \"undefined\" && !options.WebSocket) {\r\n options.WebSocket = WebSocket;\r\n }\r\n else if (Platform.isNode && !options.WebSocket) {\r\n if (webSocketModule) {\r\n options.WebSocket = webSocketModule;\r\n }\r\n }\r\n if (!Platform.isNode && typeof EventSource !== \"undefined\" && !options.EventSource) {\r\n options.EventSource = EventSource;\r\n }\r\n else if (Platform.isNode && !options.EventSource) {\r\n if (typeof eventSourceModule !== \"undefined\") {\r\n options.EventSource = eventSourceModule;\r\n }\r\n }\r\n this._httpClient = new AccessTokenHttpClient(options.httpClient || new DefaultHttpClient(this._logger), options.accessTokenFactory);\r\n this._connectionState = \"Disconnected\" /* ConnectionState.Disconnected */;\r\n this._connectionStarted = false;\r\n this._options = options;\r\n this.onreceive = null;\r\n this.onclose = null;\r\n }\r\n async start(transferFormat) {\r\n transferFormat = transferFormat || TransferFormat.Binary;\r\n Arg.isIn(transferFormat, TransferFormat, \"transferFormat\");\r\n this._logger.log(LogLevel.Debug, `Starting connection with transfer format '${TransferFormat[transferFormat]}'.`);\r\n if (this._connectionState !== \"Disconnected\" /* ConnectionState.Disconnected */) {\r\n return Promise.reject(new Error(\"Cannot start an HttpConnection that is not in the 'Disconnected' state.\"));\r\n }\r\n this._connectionState = \"Connecting\" /* ConnectionState.Connecting */;\r\n this._startInternalPromise = this._startInternal(transferFormat);\r\n await this._startInternalPromise;\r\n // The TypeScript compiler thinks that connectionState must be Connecting here. The TypeScript compiler is wrong.\r\n if (this._connectionState === \"Disconnecting\" /* ConnectionState.Disconnecting */) {\r\n // stop() was called and transitioned the client into the Disconnecting state.\r\n const message = \"Failed to start the HttpConnection before stop() was called.\";\r\n this._logger.log(LogLevel.Error, message);\r\n // We cannot await stopPromise inside startInternal since stopInternal awaits the startInternalPromise.\r\n await this._stopPromise;\r\n return Promise.reject(new AbortError(message));\r\n }\r\n else if (this._connectionState !== \"Connected\" /* ConnectionState.Connected */) {\r\n // stop() was called and transitioned the client into the Disconnecting state.\r\n const message = \"HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!\";\r\n this._logger.log(LogLevel.Error, message);\r\n return Promise.reject(new AbortError(message));\r\n }\r\n this._connectionStarted = true;\r\n }\r\n send(data) {\r\n if (this._connectionState !== \"Connected\" /* ConnectionState.Connected */) {\r\n return Promise.reject(new Error(\"Cannot send data if the connection is not in the 'Connected' State.\"));\r\n }\r\n if (!this._sendQueue) {\r\n this._sendQueue = new TransportSendQueue(this.transport);\r\n }\r\n // Transport will not be null if state is connected\r\n return this._sendQueue.send(data);\r\n }\r\n async stop(error) {\r\n if (this._connectionState === \"Disconnected\" /* ConnectionState.Disconnected */) {\r\n this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnected state.`);\r\n return Promise.resolve();\r\n }\r\n if (this._connectionState === \"Disconnecting\" /* ConnectionState.Disconnecting */) {\r\n this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);\r\n return this._stopPromise;\r\n }\r\n this._connectionState = \"Disconnecting\" /* ConnectionState.Disconnecting */;\r\n this._stopPromise = new Promise((resolve) => {\r\n // Don't complete stop() until stopConnection() completes.\r\n this._stopPromiseResolver = resolve;\r\n });\r\n // stopInternal should never throw so just observe it.\r\n await this._stopInternal(error);\r\n await this._stopPromise;\r\n }\r\n async _stopInternal(error) {\r\n // Set error as soon as possible otherwise there is a race between\r\n // the transport closing and providing an error and the error from a close message\r\n // We would prefer the close message error.\r\n this._stopError = error;\r\n try {\r\n await this._startInternalPromise;\r\n }\r\n catch (e) {\r\n // This exception is returned to the user as a rejected Promise from the start method.\r\n }\r\n // The transport's onclose will trigger stopConnection which will run our onclose event.\r\n // The transport should always be set if currently connected. If it wasn't set, it's likely because\r\n // stop was called during start() and start() failed.\r\n if (this.transport) {\r\n try {\r\n await this.transport.stop();\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `HttpConnection.transport.stop() threw error '${e}'.`);\r\n this._stopConnection();\r\n }\r\n this.transport = undefined;\r\n }\r\n else {\r\n this._logger.log(LogLevel.Debug, \"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.\");\r\n }\r\n }\r\n async _startInternal(transferFormat) {\r\n // Store the original base url and the access token factory since they may change\r\n // as part of negotiating\r\n let url = this.baseUrl;\r\n this._accessTokenFactory = this._options.accessTokenFactory;\r\n this._httpClient._accessTokenFactory = this._accessTokenFactory;\r\n try {\r\n if (this._options.skipNegotiation) {\r\n if (this._options.transport === HttpTransportType.WebSockets) {\r\n // No need to add a connection ID in this case\r\n this.transport = this._constructTransport(HttpTransportType.WebSockets);\r\n // We should just call connect directly in this case.\r\n // No fallback or negotiate in this case.\r\n await this._startTransport(url, transferFormat);\r\n }\r\n else {\r\n throw new Error(\"Negotiation can only be skipped when using the WebSocket transport directly.\");\r\n }\r\n }\r\n else {\r\n let negotiateResponse = null;\r\n let redirects = 0;\r\n do {\r\n negotiateResponse = await this._getNegotiationResponse(url);\r\n // the user tries to stop the connection when it is being started\r\n if (this._connectionState === \"Disconnecting\" /* ConnectionState.Disconnecting */ || this._connectionState === \"Disconnected\" /* ConnectionState.Disconnected */) {\r\n throw new AbortError(\"The connection was stopped during negotiation.\");\r\n }\r\n if (negotiateResponse.error) {\r\n throw new Error(negotiateResponse.error);\r\n }\r\n if (negotiateResponse.ProtocolVersion) {\r\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.\");\r\n }\r\n if (negotiateResponse.url) {\r\n url = negotiateResponse.url;\r\n }\r\n if (negotiateResponse.accessToken) {\r\n // Replace the current access token factory with one that uses\r\n // the returned access token\r\n const accessToken = negotiateResponse.accessToken;\r\n this._accessTokenFactory = () => accessToken;\r\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\r\n this._httpClient._accessToken = accessToken;\r\n this._httpClient._accessTokenFactory = undefined;\r\n }\r\n redirects++;\r\n } while (negotiateResponse.url && redirects < MAX_REDIRECTS);\r\n if (redirects === MAX_REDIRECTS && negotiateResponse.url) {\r\n throw new Error(\"Negotiate redirection limit exceeded.\");\r\n }\r\n await this._createTransport(url, this._options.transport, negotiateResponse, transferFormat);\r\n }\r\n if (this.transport instanceof LongPollingTransport) {\r\n this.features.inherentKeepAlive = true;\r\n }\r\n if (this._connectionState === \"Connecting\" /* ConnectionState.Connecting */) {\r\n // Ensure the connection transitions to the connected state prior to completing this.startInternalPromise.\r\n // start() will handle the case when stop was called and startInternal exits still in the disconnecting state.\r\n this._logger.log(LogLevel.Debug, \"The HttpConnection connected successfully.\");\r\n this._connectionState = \"Connected\" /* ConnectionState.Connected */;\r\n }\r\n // stop() is waiting on us via this.startInternalPromise so keep this.transport around so it can clean up.\r\n // This is the only case startInternal can exit in neither the connected nor disconnected state because stopConnection()\r\n // will transition to the disconnected state. start() will wait for the transition using the stopPromise.\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, \"Failed to start the connection: \" + e);\r\n this._connectionState = \"Disconnected\" /* ConnectionState.Disconnected */;\r\n this.transport = undefined;\r\n // if start fails, any active calls to stop assume that start will complete the stop promise\r\n this._stopPromiseResolver();\r\n return Promise.reject(e);\r\n }\r\n }\r\n async _getNegotiationResponse(url) {\r\n const headers = {};\r\n const [name, value] = getUserAgentHeader();\r\n headers[name] = value;\r\n const negotiateUrl = this._resolveNegotiateUrl(url);\r\n this._logger.log(LogLevel.Debug, `Sending negotiation request: ${negotiateUrl}.`);\r\n try {\r\n const response = await this._httpClient.post(negotiateUrl, {\r\n content: \"\",\r\n headers: { ...headers, ...this._options.headers },\r\n timeout: this._options.timeout,\r\n withCredentials: this._options.withCredentials,\r\n });\r\n if (response.statusCode !== 200) {\r\n return Promise.reject(new Error(`Unexpected status code returned from negotiate '${response.statusCode}'`));\r\n }\r\n const negotiateResponse = JSON.parse(response.content);\r\n if (!negotiateResponse.negotiateVersion || negotiateResponse.negotiateVersion < 1) {\r\n // Negotiate version 0 doesn't use connectionToken\r\n // So we set it equal to connectionId so all our logic can use connectionToken without being aware of the negotiate version\r\n negotiateResponse.connectionToken = negotiateResponse.connectionId;\r\n }\r\n if (negotiateResponse.useStatefulReconnect && this._options._useStatefulReconnect !== true) {\r\n return Promise.reject(new FailedToNegotiateWithServerError(\"Client didn't negotiate Stateful Reconnect but the server did.\"));\r\n }\r\n return negotiateResponse;\r\n }\r\n catch (e) {\r\n let errorMessage = \"Failed to complete negotiation with the server: \" + e;\r\n if (e instanceof HttpError) {\r\n if (e.statusCode === 404) {\r\n errorMessage = errorMessage + \" Either this is not a SignalR endpoint or there is a proxy blocking the connection.\";\r\n }\r\n }\r\n this._logger.log(LogLevel.Error, errorMessage);\r\n return Promise.reject(new FailedToNegotiateWithServerError(errorMessage));\r\n }\r\n }\r\n _createConnectUrl(url, connectionToken) {\r\n if (!connectionToken) {\r\n return url;\r\n }\r\n return url + (url.indexOf(\"?\") === -1 ? \"?\" : \"&\") + `id=${connectionToken}`;\r\n }\r\n async _createTransport(url, requestedTransport, negotiateResponse, requestedTransferFormat) {\r\n let connectUrl = this._createConnectUrl(url, negotiateResponse.connectionToken);\r\n if (this._isITransport(requestedTransport)) {\r\n this._logger.log(LogLevel.Debug, \"Connection was provided an instance of ITransport, using that directly.\");\r\n this.transport = requestedTransport;\r\n await this._startTransport(connectUrl, requestedTransferFormat);\r\n this.connectionId = negotiateResponse.connectionId;\r\n return;\r\n }\r\n const transportExceptions = [];\r\n const transports = negotiateResponse.availableTransports || [];\r\n let negotiate = negotiateResponse;\r\n for (const endpoint of transports) {\r\n const transportOrError = this._resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat, (negotiate === null || negotiate === void 0 ? void 0 : negotiate.useStatefulReconnect) === true);\r\n if (transportOrError instanceof Error) {\r\n // Store the error and continue, we don't want to cause a re-negotiate in these cases\r\n transportExceptions.push(`${endpoint.transport} failed:`);\r\n transportExceptions.push(transportOrError);\r\n }\r\n else if (this._isITransport(transportOrError)) {\r\n this.transport = transportOrError;\r\n if (!negotiate) {\r\n try {\r\n negotiate = await this._getNegotiationResponse(url);\r\n }\r\n catch (ex) {\r\n return Promise.reject(ex);\r\n }\r\n connectUrl = this._createConnectUrl(url, negotiate.connectionToken);\r\n }\r\n try {\r\n await this._startTransport(connectUrl, requestedTransferFormat);\r\n this.connectionId = negotiate.connectionId;\r\n return;\r\n }\r\n catch (ex) {\r\n this._logger.log(LogLevel.Error, `Failed to start the transport '${endpoint.transport}': ${ex}`);\r\n negotiate = undefined;\r\n transportExceptions.push(new FailedToStartTransportError(`${endpoint.transport} failed: ${ex}`, HttpTransportType[endpoint.transport]));\r\n if (this._connectionState !== \"Connecting\" /* ConnectionState.Connecting */) {\r\n const message = \"Failed to select transport before stop() was called.\";\r\n this._logger.log(LogLevel.Debug, message);\r\n return Promise.reject(new AbortError(message));\r\n }\r\n }\r\n }\r\n }\r\n if (transportExceptions.length > 0) {\r\n return Promise.reject(new AggregateErrors(`Unable to connect to the server with any of the available transports. ${transportExceptions.join(\" \")}`, transportExceptions));\r\n }\r\n return Promise.reject(new Error(\"None of the transports supported by the client are supported by the server.\"));\r\n }\r\n _constructTransport(transport) {\r\n switch (transport) {\r\n case HttpTransportType.WebSockets:\r\n if (!this._options.WebSocket) {\r\n throw new Error(\"'WebSocket' is not supported in your environment.\");\r\n }\r\n return new WebSocketTransport(this._httpClient, this._accessTokenFactory, this._logger, this._options.logMessageContent, this._options.WebSocket, this._options.headers || {});\r\n case HttpTransportType.ServerSentEvents:\r\n if (!this._options.EventSource) {\r\n throw new Error(\"'EventSource' is not supported in your environment.\");\r\n }\r\n return new ServerSentEventsTransport(this._httpClient, this._httpClient._accessToken, this._logger, this._options);\r\n case HttpTransportType.LongPolling:\r\n return new LongPollingTransport(this._httpClient, this._logger, this._options);\r\n default:\r\n throw new Error(`Unknown transport: ${transport}.`);\r\n }\r\n }\r\n _startTransport(url, transferFormat) {\r\n this.transport.onreceive = this.onreceive;\r\n if (this.features.reconnect) {\r\n this.transport.onclose = async (e) => {\r\n let callStop = false;\r\n if (this.features.reconnect) {\r\n try {\r\n this.features.disconnected();\r\n await this.transport.connect(url, transferFormat);\r\n await this.features.resend();\r\n }\r\n catch {\r\n callStop = true;\r\n }\r\n }\r\n else {\r\n this._stopConnection(e);\r\n return;\r\n }\r\n if (callStop) {\r\n this._stopConnection(e);\r\n }\r\n };\r\n }\r\n else {\r\n this.transport.onclose = (e) => this._stopConnection(e);\r\n }\r\n return this.transport.connect(url, transferFormat);\r\n }\r\n _resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat, useStatefulReconnect) {\r\n const transport = HttpTransportType[endpoint.transport];\r\n if (transport === null || transport === undefined) {\r\n this._logger.log(LogLevel.Debug, `Skipping transport '${endpoint.transport}' because it is not supported by this client.`);\r\n return new Error(`Skipping transport '${endpoint.transport}' because it is not supported by this client.`);\r\n }\r\n else {\r\n if (transportMatches(requestedTransport, transport)) {\r\n const transferFormats = endpoint.transferFormats.map((s) => TransferFormat[s]);\r\n if (transferFormats.indexOf(requestedTransferFormat) >= 0) {\r\n if ((transport === HttpTransportType.WebSockets && !this._options.WebSocket) ||\r\n (transport === HttpTransportType.ServerSentEvents && !this._options.EventSource)) {\r\n this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it is not supported in your environment.'`);\r\n return new UnsupportedTransportError(`'${HttpTransportType[transport]}' is not supported in your environment.`, transport);\r\n }\r\n else {\r\n this._logger.log(LogLevel.Debug, `Selecting transport '${HttpTransportType[transport]}'.`);\r\n try {\r\n this.features.reconnect = transport === HttpTransportType.WebSockets ? useStatefulReconnect : undefined;\r\n return this._constructTransport(transport);\r\n }\r\n catch (ex) {\r\n return ex;\r\n }\r\n }\r\n }\r\n else {\r\n this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it does not support the requested transfer format '${TransferFormat[requestedTransferFormat]}'.`);\r\n return new Error(`'${HttpTransportType[transport]}' does not support ${TransferFormat[requestedTransferFormat]}.`);\r\n }\r\n }\r\n else {\r\n this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it was disabled by the client.`);\r\n return new DisabledTransportError(`'${HttpTransportType[transport]}' is disabled by the client.`, transport);\r\n }\r\n }\r\n }\r\n _isITransport(transport) {\r\n return transport && typeof (transport) === \"object\" && \"connect\" in transport;\r\n }\r\n _stopConnection(error) {\r\n this._logger.log(LogLevel.Debug, `HttpConnection.stopConnection(${error}) called while in state ${this._connectionState}.`);\r\n this.transport = undefined;\r\n // If we have a stopError, it takes precedence over the error from the transport\r\n error = this._stopError || error;\r\n this._stopError = undefined;\r\n if (this._connectionState === \"Disconnected\" /* ConnectionState.Disconnected */) {\r\n this._logger.log(LogLevel.Debug, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is already in the disconnected state.`);\r\n return;\r\n }\r\n if (this._connectionState === \"Connecting\" /* ConnectionState.Connecting */) {\r\n this._logger.log(LogLevel.Warning, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is still in the connecting state.`);\r\n throw new Error(`HttpConnection.stopConnection(${error}) was called while the connection is still in the connecting state.`);\r\n }\r\n if (this._connectionState === \"Disconnecting\" /* ConnectionState.Disconnecting */) {\r\n // A call to stop() induced this call to stopConnection and needs to be completed.\r\n // Any stop() awaiters will be scheduled to continue after the onclose callback fires.\r\n this._stopPromiseResolver();\r\n }\r\n if (error) {\r\n this._logger.log(LogLevel.Error, `Connection disconnected with error '${error}'.`);\r\n }\r\n else {\r\n this._logger.log(LogLevel.Information, \"Connection disconnected.\");\r\n }\r\n if (this._sendQueue) {\r\n this._sendQueue.stop().catch((e) => {\r\n this._logger.log(LogLevel.Error, `TransportSendQueue.stop() threw error '${e}'.`);\r\n });\r\n this._sendQueue = undefined;\r\n }\r\n this.connectionId = undefined;\r\n this._connectionState = \"Disconnected\" /* ConnectionState.Disconnected */;\r\n if (this._connectionStarted) {\r\n this._connectionStarted = false;\r\n try {\r\n if (this.onclose) {\r\n this.onclose(error);\r\n }\r\n }\r\n catch (e) {\r\n this._logger.log(LogLevel.Error, `HttpConnection.onclose(${error}) threw error '${e}'.`);\r\n }\r\n }\r\n }\r\n _resolveUrl(url) {\r\n // startsWith is not supported in IE\r\n if (url.lastIndexOf(\"https://\", 0) === 0 || url.lastIndexOf(\"http://\", 0) === 0) {\r\n return url;\r\n }\r\n if (!Platform.isBrowser) {\r\n throw new Error(`Cannot resolve '${url}'.`);\r\n }\r\n // Setting the url to the href propery of an anchor tag handles normalization\r\n // for us. There are 3 main cases.\r\n // 1. Relative path normalization e.g \"b\" -> \"http://localhost:5000/a/b\"\r\n // 2. Absolute path normalization e.g \"/a/b\" -> \"http://localhost:5000/a/b\"\r\n // 3. Networkpath reference normalization e.g \"//localhost:5000/a/b\" -> \"http://localhost:5000/a/b\"\r\n const aTag = window.document.createElement(\"a\");\r\n aTag.href = url;\r\n this._logger.log(LogLevel.Information, `Normalizing '${url}' to '${aTag.href}'.`);\r\n return aTag.href;\r\n }\r\n _resolveNegotiateUrl(url) {\r\n const negotiateUrl = new URL(url);\r\n if (negotiateUrl.pathname.endsWith('/')) {\r\n negotiateUrl.pathname += \"negotiate\";\r\n }\r\n else {\r\n negotiateUrl.pathname += \"/negotiate\";\r\n }\r\n const searchParams = new URLSearchParams(negotiateUrl.searchParams);\r\n if (!searchParams.has(\"negotiateVersion\")) {\r\n searchParams.append(\"negotiateVersion\", this._negotiateVersion.toString());\r\n }\r\n if (searchParams.has(\"useStatefulReconnect\")) {\r\n if (searchParams.get(\"useStatefulReconnect\") === \"true\") {\r\n this._options._useStatefulReconnect = true;\r\n }\r\n }\r\n else if (this._options._useStatefulReconnect === true) {\r\n searchParams.append(\"useStatefulReconnect\", \"true\");\r\n }\r\n negotiateUrl.search = searchParams.toString();\r\n return negotiateUrl.toString();\r\n }\r\n}\r\nfunction transportMatches(requestedTransport, actualTransport) {\r\n return !requestedTransport || ((actualTransport & requestedTransport) !== 0);\r\n}\r\n/** @private */\r\nexport class TransportSendQueue {\r\n constructor(_transport) {\r\n this._transport = _transport;\r\n this._buffer = [];\r\n this._executing = true;\r\n this._sendBufferedData = new PromiseSource();\r\n this._transportResult = new PromiseSource();\r\n this._sendLoopPromise = this._sendLoop();\r\n }\r\n send(data) {\r\n this._bufferData(data);\r\n if (!this._transportResult) {\r\n this._transportResult = new PromiseSource();\r\n }\r\n return this._transportResult.promise;\r\n }\r\n stop() {\r\n this._executing = false;\r\n this._sendBufferedData.resolve();\r\n return this._sendLoopPromise;\r\n }\r\n _bufferData(data) {\r\n if (this._buffer.length && typeof (this._buffer[0]) !== typeof (data)) {\r\n throw new Error(`Expected data to be of type ${typeof (this._buffer)} but was of type ${typeof (data)}`);\r\n }\r\n this._buffer.push(data);\r\n this._sendBufferedData.resolve();\r\n }\r\n async _sendLoop() {\r\n while (true) {\r\n await this._sendBufferedData.promise;\r\n if (!this._executing) {\r\n if (this._transportResult) {\r\n this._transportResult.reject(\"Connection stopped.\");\r\n }\r\n break;\r\n }\r\n this._sendBufferedData = new PromiseSource();\r\n const transportResult = this._transportResult;\r\n this._transportResult = undefined;\r\n const data = typeof (this._buffer[0]) === \"string\" ?\r\n this._buffer.join(\"\") :\r\n TransportSendQueue._concatBuffers(this._buffer);\r\n this._buffer.length = 0;\r\n try {\r\n await this._transport.send(data);\r\n transportResult.resolve();\r\n }\r\n catch (error) {\r\n transportResult.reject(error);\r\n }\r\n }\r\n }\r\n static _concatBuffers(arrayBuffers) {\r\n const totalLength = arrayBuffers.map((b) => b.byteLength).reduce((a, b) => a + b);\r\n const result = new Uint8Array(totalLength);\r\n let offset = 0;\r\n for (const item of arrayBuffers) {\r\n result.set(new Uint8Array(item), offset);\r\n offset += item.byteLength;\r\n }\r\n return result.buffer;\r\n }\r\n}\r\nclass PromiseSource {\r\n constructor() {\r\n this.promise = new Promise((resolve, reject) => [this._resolver, this._rejecter] = [resolve, reject]);\r\n }\r\n resolve() {\r\n this._resolver();\r\n }\r\n reject(reason) {\r\n this._rejecter(reason);\r\n }\r\n}\r\n//# sourceMappingURL=HttpConnection.js.map","// 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\nimport { MessageType } from \"./IHubProtocol\";\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { TransferFormat } from \"./ITransport\";\r\nimport { NullLogger } from \"./Loggers\";\r\nimport { TextMessageFormat } from \"./TextMessageFormat\";\r\nconst JSON_HUB_PROTOCOL_NAME = \"json\";\r\n/** Implements the JSON Hub Protocol. */\r\nexport class JsonHubProtocol {\r\n constructor() {\r\n /** @inheritDoc */\r\n this.name = JSON_HUB_PROTOCOL_NAME;\r\n /** @inheritDoc */\r\n this.version = 2;\r\n /** @inheritDoc */\r\n this.transferFormat = TransferFormat.Text;\r\n }\r\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 */\r\n parseMessages(input, logger) {\r\n // The interface does allow \"ArrayBuffer\" to be passed in, but this implementation does not. So let's throw a useful error.\r\n if (typeof input !== \"string\") {\r\n throw new Error(\"Invalid input for JSON hub protocol. Expected a string.\");\r\n }\r\n if (!input) {\r\n return [];\r\n }\r\n if (logger === null) {\r\n logger = NullLogger.instance;\r\n }\r\n // Parse the messages\r\n const messages = TextMessageFormat.parse(input);\r\n const hubMessages = [];\r\n for (const message of messages) {\r\n const parsedMessage = JSON.parse(message);\r\n if (typeof parsedMessage.type !== \"number\") {\r\n throw new Error(\"Invalid payload.\");\r\n }\r\n switch (parsedMessage.type) {\r\n case MessageType.Invocation:\r\n this._isInvocationMessage(parsedMessage);\r\n break;\r\n case MessageType.StreamItem:\r\n this._isStreamItemMessage(parsedMessage);\r\n break;\r\n case MessageType.Completion:\r\n this._isCompletionMessage(parsedMessage);\r\n break;\r\n case MessageType.Ping:\r\n // Single value, no need to validate\r\n break;\r\n case MessageType.Close:\r\n // All optional values, no need to validate\r\n break;\r\n case MessageType.Ack:\r\n this._isAckMessage(parsedMessage);\r\n break;\r\n case MessageType.Sequence:\r\n this._isSequenceMessage(parsedMessage);\r\n break;\r\n default:\r\n // Future protocol changes can add message types, old clients can ignore them\r\n logger.log(LogLevel.Information, \"Unknown message type '\" + parsedMessage.type + \"' ignored.\");\r\n continue;\r\n }\r\n hubMessages.push(parsedMessage);\r\n }\r\n return hubMessages;\r\n }\r\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 */\r\n writeMessage(message) {\r\n return TextMessageFormat.write(JSON.stringify(message));\r\n }\r\n _isInvocationMessage(message) {\r\n this._assertNotEmptyString(message.target, \"Invalid payload for Invocation message.\");\r\n if (message.invocationId !== undefined) {\r\n this._assertNotEmptyString(message.invocationId, \"Invalid payload for Invocation message.\");\r\n }\r\n }\r\n _isStreamItemMessage(message) {\r\n this._assertNotEmptyString(message.invocationId, \"Invalid payload for StreamItem message.\");\r\n if (message.item === undefined) {\r\n throw new Error(\"Invalid payload for StreamItem message.\");\r\n }\r\n }\r\n _isCompletionMessage(message) {\r\n if (message.result && message.error) {\r\n throw new Error(\"Invalid payload for Completion message.\");\r\n }\r\n if (!message.result && message.error) {\r\n this._assertNotEmptyString(message.error, \"Invalid payload for Completion message.\");\r\n }\r\n this._assertNotEmptyString(message.invocationId, \"Invalid payload for Completion message.\");\r\n }\r\n _isAckMessage(message) {\r\n if (typeof message.sequenceId !== 'number') {\r\n throw new Error(\"Invalid SequenceId for Ack message.\");\r\n }\r\n }\r\n _isSequenceMessage(message) {\r\n if (typeof message.sequenceId !== 'number') {\r\n throw new Error(\"Invalid SequenceId for Sequence message.\");\r\n }\r\n }\r\n _assertNotEmptyString(value, errorMessage) {\r\n if (typeof value !== \"string\" || value === \"\") {\r\n throw new Error(errorMessage);\r\n }\r\n }\r\n}\r\n//# sourceMappingURL=JsonHubProtocol.js.map","// 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\nimport { DefaultReconnectPolicy } from \"./DefaultReconnectPolicy\";\r\nimport { HttpConnection } from \"./HttpConnection\";\r\nimport { HubConnection } from \"./HubConnection\";\r\nimport { LogLevel } from \"./ILogger\";\r\nimport { JsonHubProtocol } from \"./JsonHubProtocol\";\r\nimport { NullLogger } from \"./Loggers\";\r\nimport { Arg, ConsoleLogger } from \"./Utils\";\r\nconst LogLevelNameMapping = {\r\n trace: LogLevel.Trace,\r\n debug: LogLevel.Debug,\r\n info: LogLevel.Information,\r\n information: LogLevel.Information,\r\n warn: LogLevel.Warning,\r\n warning: LogLevel.Warning,\r\n error: LogLevel.Error,\r\n critical: LogLevel.Critical,\r\n none: LogLevel.None,\r\n};\r\nfunction parseLogLevel(name) {\r\n // Case-insensitive matching via lower-casing\r\n // Yes, I know case-folding is a complicated problem in Unicode, but we only support\r\n // the ASCII strings defined in LogLevelNameMapping anyway, so it's fine -anurse.\r\n const mapping = LogLevelNameMapping[name.toLowerCase()];\r\n if (typeof mapping !== \"undefined\") {\r\n return mapping;\r\n }\r\n else {\r\n throw new Error(`Unknown log level: ${name}`);\r\n }\r\n}\r\n/** A builder for configuring {@link @microsoft/signalr.HubConnection} instances. */\r\nexport class HubConnectionBuilder {\r\n configureLogging(logging) {\r\n Arg.isRequired(logging, \"logging\");\r\n if (isLogger(logging)) {\r\n this.logger = logging;\r\n }\r\n else if (typeof logging === \"string\") {\r\n const logLevel = parseLogLevel(logging);\r\n this.logger = new ConsoleLogger(logLevel);\r\n }\r\n else {\r\n this.logger = new ConsoleLogger(logging);\r\n }\r\n return this;\r\n }\r\n withUrl(url, transportTypeOrOptions) {\r\n Arg.isRequired(url, \"url\");\r\n Arg.isNotEmpty(url, \"url\");\r\n this.url = url;\r\n // Flow-typing knows where it's at. Since HttpTransportType is a number and IHttpConnectionOptions is guaranteed\r\n // to be an object, we know (as does TypeScript) this comparison is all we need to figure out which overload was called.\r\n if (typeof transportTypeOrOptions === \"object\") {\r\n this.httpConnectionOptions = { ...this.httpConnectionOptions, ...transportTypeOrOptions };\r\n }\r\n else {\r\n this.httpConnectionOptions = {\r\n ...this.httpConnectionOptions,\r\n transport: transportTypeOrOptions,\r\n };\r\n }\r\n return this;\r\n }\r\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 */\r\n withHubProtocol(protocol) {\r\n Arg.isRequired(protocol, \"protocol\");\r\n this.protocol = protocol;\r\n return this;\r\n }\r\n withAutomaticReconnect(retryDelaysOrReconnectPolicy) {\r\n if (this.reconnectPolicy) {\r\n throw new Error(\"A reconnectPolicy has already been set.\");\r\n }\r\n if (!retryDelaysOrReconnectPolicy) {\r\n this.reconnectPolicy = new DefaultReconnectPolicy();\r\n }\r\n else if (Array.isArray(retryDelaysOrReconnectPolicy)) {\r\n this.reconnectPolicy = new DefaultReconnectPolicy(retryDelaysOrReconnectPolicy);\r\n }\r\n else {\r\n this.reconnectPolicy = retryDelaysOrReconnectPolicy;\r\n }\r\n return this;\r\n }\r\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 */\r\n withServerTimeout(milliseconds) {\r\n Arg.isRequired(milliseconds, \"milliseconds\");\r\n this._serverTimeoutInMilliseconds = milliseconds;\r\n return this;\r\n }\r\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 */\r\n withKeepAliveInterval(milliseconds) {\r\n Arg.isRequired(milliseconds, \"milliseconds\");\r\n this._keepAliveIntervalInMilliseconds = milliseconds;\r\n return this;\r\n }\r\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 */\r\n withStatefulReconnect(options) {\r\n if (this.httpConnectionOptions === undefined) {\r\n this.httpConnectionOptions = {};\r\n }\r\n this.httpConnectionOptions._useStatefulReconnect = true;\r\n this._statefulReconnectBufferSize = options === null || options === void 0 ? void 0 : options.bufferSize;\r\n return this;\r\n }\r\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 */\r\n build() {\r\n // If httpConnectionOptions has a logger, use it. Otherwise, override it with the one\r\n // provided to configureLogger\r\n const httpConnectionOptions = this.httpConnectionOptions || {};\r\n // If it's 'null', the user **explicitly** asked for null, don't mess with it.\r\n if (httpConnectionOptions.logger === undefined) {\r\n // If our logger is undefined or null, that's OK, the HttpConnection constructor will handle it.\r\n httpConnectionOptions.logger = this.logger;\r\n }\r\n // Now create the connection\r\n if (!this.url) {\r\n throw new Error(\"The 'HubConnectionBuilder.withUrl' method must be called before building the connection.\");\r\n }\r\n const connection = new HttpConnection(this.url, httpConnectionOptions);\r\n return HubConnection.create(connection, this.logger || NullLogger.instance, this.protocol || new JsonHubProtocol(), this.reconnectPolicy, this._serverTimeoutInMilliseconds, this._keepAliveIntervalInMilliseconds, this._statefulReconnectBufferSize);\r\n }\r\n}\r\nfunction isLogger(logger) {\r\n return logger.log !== undefined;\r\n}\r\n//# sourceMappingURL=HubConnectionBuilder.js.map","export const QUEUE_POSITION_UPDATED_KEY = \"bouncer:queuePositionUpdated\";\nexport const NOTICES_UPDATED_KEY = \"bouncer:noticesUpdated\";\nexport const STATE_UPDATED_KEY = \"bouncer:stateUpdated\";\nexport const CONNECTION_CLOSED_KEY = \"bouncer:connectionClosed\";\nexport class QueuePositionUpdatedEvent extends CustomEvent {\n constructor(data) {\n super(QUEUE_POSITION_UPDATED_KEY, {\n detail: data,\n bubbles: false,\n cancelable: false\n });\n }\n}\nexport class NoticesUpdatedEvent extends CustomEvent {\n constructor(data) {\n super(NOTICES_UPDATED_KEY, {\n detail: data,\n bubbles: false,\n cancelable: false\n });\n }\n}\nexport class StateUpdatedEvent extends CustomEvent {\n constructor(data) {\n super(STATE_UPDATED_KEY, {\n detail: data,\n bubbles: false,\n cancelable: false\n });\n }\n}\nexport class ConnectionClosedEvent extends CustomEvent {\n constructor(data) {\n super(CONNECTION_CLOSED_KEY, {\n detail: data,\n bubbles: false,\n cancelable: false\n });\n }\n}\n","export class ConnectionError {\n error;\n constructor(error) {\n this.error = error;\n }\n}\nexport class Notice {\n id;\n message;\n constructor(id, message) {\n this.id = id;\n this.message = message;\n }\n}\nexport class Queue {\n waitingRoomNumber;\n currentTicket;\n admittedTicket;\n admittedTicketOnActivation;\n isPrequeue;\n admittedTicketOnLoad;\n constructor(waitingRoomNumber, currentTicket, admittedTicket, admittedTicketOnActivation, isPrequeue) {\n this.waitingRoomNumber = waitingRoomNumber;\n this.currentTicket = currentTicket;\n this.admittedTicket = admittedTicket;\n this.admittedTicketOnActivation = admittedTicketOnActivation;\n this.isPrequeue = isPrequeue;\n this.admittedTicketOnLoad = admittedTicket;\n }\n getPosition(ticketNumber) {\n return ticketNumber - this.admittedTicket;\n }\n getAdmittedTicketNormalized() {\n return this.normalize(this.admittedTicket);\n }\n normalize(n) {\n return n - this.admittedTicketOnActivation;\n }\n getQueuePosition(ticketNumber, positionOnLoad) {\n if (ticketNumber === null) {\n this.isPrequeue = true;\n return null;\n }\n this.isPrequeue = false;\n const position = this.getPosition(ticketNumber);\n const calculatedProgress = (position * 100) / positionOnLoad;\n const progress = this.normalize(ticketNumber) == 0\n ? 100\n : 100 - calculatedProgress;\n return new QueuePosition(ticketNumber, position, progress);\n }\n}\nexport class QueuePosition {\n ticketNumber;\n position;\n progress;\n constructor(ticketNumber, position, progress) {\n this.ticketNumber = ticketNumber;\n this.position = position;\n this.progress = progress;\n }\n}\nexport class State {\n ticketExpiryMinutes;\n admissionStartTime;\n constructor(ticketExpiryMinutes, admissionStartTime) {\n this.ticketExpiryMinutes = ticketExpiryMinutes;\n this.admissionStartTime = admissionStartTime;\n }\n}\nexport class Ticket {\n id;\n number;\n prequeueNumber;\n constructor(id, number, prequeueNumber) {\n this.id = id;\n this.number = number;\n this.prequeueNumber = prequeueNumber;\n }\n}\n","export class Helpers {\n static async sleep(ms) {\n return new Promise(resolve => {\n setTimeout(() => {\n resolve();\n }, ms);\n });\n }\n static async sha256(input) {\n const encoder = new TextEncoder();\n const data = encoder.encode(input);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n return hashHex;\n }\n}\n","import { HubConnectionBuilder } from \"@microsoft/signalr\";\nimport { ConnectionClosedEvent, StateUpdatedEvent, QueuePositionUpdatedEvent, NoticesUpdatedEvent } from \"./Events\";\nimport { Ticket, Queue, State, Notice, ConnectionError } from \"./Models\";\nimport { Helpers } from \"./Helpers\";\nexport class WaitingRoomConnection {\n ticket = new Ticket(\"\", null, null);\n queue = new Queue(0, 0, 0, 0, false);\n state = new State(0, new Date(Date.now()));\n notices = new Array();\n positionOnLoad = 0;\n autoRefresh = false;\n connection;\n constructor() {\n this.connection = new HubConnectionBuilder()\n // .configureLogging(signalR.LogLevel.Trace)\n // with default value 0, two requests (page load and signalr reconnect) with the same ticket id cookie are being sent to the server\n // the ticket can either be expired or all tickets have been dropped\n // thus creating two separate tickets\n .withAutomaticReconnect([1000, 2000, 10000, 30000])\n .withUrl(\"/bouncer/hubs/waiting-room\")\n .build();\n this.handleQueueUpdated();\n this.handleStateUpdated();\n this.handleNoticesUpdated();\n this.handlePrequeueCalculated();\n this.handleWaitingRoomUpdated();\n this.handleReloadWaitingClients();\n this.handleOnClose();\n }\n async startConnection() {\n try {\n // Start SignalR connection\n await this.connection.start();\n // Load initial data\n let data = await this.connection.invoke(\"getWaitingRoomData\");\n console.log(\"signalr connection established and loaded initial data\", data);\n // Only send validation if required\n const numbersUnset = data.ticket.number === null && data.ticket.prequeueNumber === null;\n if (!data.ticket.isValidated && numbersUnset) {\n let validation = await Helpers.sha256(data.ticket.id);\n const result = await fetch(\"bouncer/validation\", {\n method: \"POST\",\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(validation)\n });\n if (result.ok) {\n data = await this.connection.invoke(\"getWaitingRoomData\");\n console.log(\"validated sucessfully, reloading waitingroom data\");\n }\n else {\n const body = await result.text();\n console.log(result.status, body);\n }\n }\n console.log(\"applying loaded data\", data);\n this.autoRefresh = data.autoRefreshOnceThresholdIsMet;\n this.ticket = new Ticket(data.ticket.id, data.ticket.number, data.ticket.prequeueNumber);\n this.queue = new Queue(data.queue.waitingRoomNumber, data.queue.currentTicketNumber, data.queue.admittingTicketThreshold, data.queue.ticketNumberOnWaitingRoomActivation, data.queue.isPrequeue);\n this.state = new State(data.state.ticketExpiryMinutes, new Date(data.state.admissionStartTime));\n if (this.ticket.number !== null) {\n this.positionOnLoad = this.queue.getPosition(this.ticket.number);\n }\n this.notices = [];\n data.notices.forEach(notice => this.notices.push(notice));\n // Dispatch updates as events\n this.dispatchNoticesUpdatedEvent();\n this.dispatchStateUpdatedEvent();\n this.dispatchQueueUpdatedEvent();\n }\n catch (err) {\n console.error(err);\n Helpers.sleep(3000).then(() => {\n this.startConnection();\n });\n }\n }\n getQueuePosition() {\n return this.queue.getQueuePosition(this.ticket.number, this.positionOnLoad);\n }\n dispatchQueueUpdatedEvent() {\n const queuePosition = this.getQueuePosition();\n this.dispatchEvent(new QueuePositionUpdatedEvent(queuePosition));\n if (queuePosition !== null && queuePosition.position <= 0) {\n console.info(\"this ticket is admitted - stopping signalr connection \");\n this.connection.stop();\n if (this.autoRefresh) {\n console.info(\"auto refresh to shop\");\n location.reload();\n }\n }\n }\n dispatchStateUpdatedEvent() {\n this.dispatchEvent(new StateUpdatedEvent(this.state));\n }\n dispatchNoticesUpdatedEvent() {\n this.dispatchEvent(new NoticesUpdatedEvent(this.notices));\n }\n dispatchEvent(event) {\n document.dispatchEvent(event);\n }\n handleReloadWaitingClients() {\n const reloadWaitingClientsKey = \"reload_waiting_clients\";\n this.connection.on(reloadWaitingClientsKey, (timeoutMilliseconds) => {\n const totalDelayMilliseconds = 1000 + Math.random() * timeoutMilliseconds;\n console.debug(`force reload from server has been requested. waiting for ${totalDelayMilliseconds}ms before refreshing`);\n Helpers.sleep(totalDelayMilliseconds).then(() => {\n console.debug(`force reloading page after waiting ${totalDelayMilliseconds}ms`);\n location.reload();\n return;\n });\n });\n }\n handleWaitingRoomUpdated() {\n const waitingRoomUpdatedKey = \"waiting_room_updated\";\n this.connection.on(waitingRoomUpdatedKey, async () => {\n // Stop SignalR connection\n this.connection.stop();\n // Waiting a random amount of time (1-11 seconds) to spread the load for the server\n await Helpers.sleep(1000 + Math.random() * 5000);\n // Connect to SignalR Hub and load current data after delay\n await this.startConnection();\n });\n }\n handlePrequeueCalculated() {\n const prequeueCalculatedKey = \"prequeue_calculated\";\n this.connection.on(prequeueCalculatedKey, async () => {\n console.log(\"prequeue is: \", this.ticket.prequeueNumber);\n if (this.ticket.prequeueNumber == null) {\n console.log(\"jetzt haben wir den salat weil wir den neuen warteraum verpasst haben\");\n location.reload();\n return;\n }\n const newTicketNumber = await this.connection.invoke(\"getTicketNumberForPrequeueNumber\", this.ticket.prequeueNumber);\n console.debug(`received ticket number ${newTicketNumber} for prequeue number ${this.ticket.prequeueNumber}`);\n this.ticket.number = newTicketNumber;\n this.queue.isPrequeue = false;\n // Load admitted ticket so the position and progress can be calucated correctly\n let queue = await this.connection.invoke(\"getQueue\");\n this.queue.admittedTicket = queue.admittingTicketThreshold;\n this.positionOnLoad = this.queue.getPosition(this.ticket.number);\n this.dispatchQueueUpdatedEvent();\n });\n }\n handleNoticesUpdated() {\n const noticesUpdatedKey = \"notices_updated\";\n this.connection.on(noticesUpdatedKey, (updatedNotices) => {\n this.notices = [];\n updatedNotices.forEach(x => this.notices.push(new Notice(x.id, x.message)));\n this.dispatchNoticesUpdatedEvent();\n });\n }\n handleStateUpdated() {\n const stateUpdatedKey = \"state_updated\";\n this.connection.on(stateUpdatedKey, (state) => {\n this.state.ticketExpiryMinutes = state.ticketExpiryMinutes;\n this.state.admissionStartTime = new Date(state.admissionStartTime);\n this.dispatchStateUpdatedEvent();\n });\n }\n handleQueueUpdated() {\n const queueUpdatedKey = \"queue_updated\";\n this.connection.on(queueUpdatedKey, (admittingTicketThreshold) => {\n this.queue.admittedTicket = admittingTicketThreshold;\n this.dispatchQueueUpdatedEvent();\n });\n }\n handleOnClose() {\n this.connection.onclose((error) => {\n if (error === undefined) {\n console.debug(\"closed signalr connection without errors\");\n this.dispatchEvent(new ConnectionClosedEvent(null));\n return;\n }\n console.warn(`disconnected from SignalR WaitingRoom Hub due to error \"${error}\".`);\n this.dispatchEvent(new ConnectionClosedEvent(new ConnectionError(error)));\n });\n }\n}\n","import { Notice, QueuePosition } from \"bouncer-waitingroom\";\n\nexport class WaitingRoomHandler {\n // progress bar\n private progressBarElement: HTMLDivElement;\n private progressStripeElement: HTMLDivElement;\n private progressStripe2Element: HTMLDivElement;\n private queueProgressBarValueElement: HTMLSpanElement;\n\n // postion info\n private positionInfoElement: HTMLParagraphElement;\n\n // notices\n private noticeListElement: HTMLUListElement;\n\n // views\n private waitingContent: HTMLDivElement;\n private enterContent: HTMLDivElement;\n\n\n constructor() {\n this.progressBarElement = document.querySelector(\"#progress-bar\") as HTMLDivElement;\n this.progressStripeElement = document.querySelector(\"#progress-stripe\") as HTMLDivElement;\n this.progressStripe2Element = document.querySelector(\"#progress-stripe-2\") as HTMLDivElement;\n this.queueProgressBarValueElement = document.querySelector(\"#queue-progress-bar-value\") as HTMLSpanElement;\n\n this.positionInfoElement = document.querySelector(\"#position-info\") as HTMLParagraphElement;\n\n this.noticeListElement = document.querySelector(\"#notice-list\") as HTMLUListElement;\n\n this.waitingContent = document.querySelector(\"#waiting\") as HTMLDivElement;\n this.enterContent = document.querySelector(\"#enter\") as HTMLDivElement;\n\n this.registerHandlers();\n }\n\n\n private registerHandlers(): void {\n document.addEventListener(\"bouncer:queuePositionUpdated\", (e) => this.updateQueuePosition(e.detail));\n document.addEventListener(\"bouncer:noticesUpdated\", (e) => this.updateNotices(e.detail));\n\n //document.addEventListener(\"bouncer:stateUpdated\", (e) => console.log(\"handling event stateUpdated\", e));\n //document.addEventListener(\"bouncer:connectionClosed\", (e) => console.log(\"handling event connectionClosed\", e));\n }\n\n private updateQueuePosition(queuePosition: QueuePosition | null): void {\n this.updateProgressText(queuePosition);\n this.updateProgressBar(queuePosition);\n }\n\n private updateProgressBar(queuePosition: QueuePosition | null): void {\n let progress = 0;\n\n if (queuePosition !== null) {\n progress = queuePosition.progress;\n }\n\n const queueProgressRoundedPercentage = `${Math.round(progress)}%`;\n const queueProgressPercentage = `${progress}%`;\n\n this.progressBarElement.style.width = queueProgressPercentage;\n this.progressStripeElement.style.left = queueProgressPercentage;\n this.progressStripe2Element.style.left = queueProgressPercentage;\n this.queueProgressBarValueElement.innerText = queueProgressRoundedPercentage;\n }\n\n private updateProgressText(queuePosition: QueuePosition | null): void {\n if (queuePosition === null) {\n console.info(\"prequeue positionInfoElement text applied\")\n\n this.positionInfoElement.innerText = \"Du bist im Vorwarteraum. Deine Position wird Dir gleich angezeigt!\"\n\n return;\n }\n\n if (queuePosition.position === 1) {\n console.info(\"one ticket ahead positionInfoElement text applied\")\n\n this.positionInfoElement.innerText = \"Ein Fan ist vor Dir!\"\n\n return;\n }\n\n if (queuePosition.position <= 0) {\n console.info(\"its this tickets turn positionInfoElement text applied\")\n\n this.positionInfoElement.innerText = \"Du bist der N�chste!\"\n\n this.waitingContent.style.display = \"none\";\n this.enterContent.style.display = \"block\";\n\n return;\n }\n\n this.positionInfoElement.innerText = `${queuePosition.position} Fans sind vor Dir!`;\n }\n\n private updateNotices(notices: Array): void {\n let updatedNoticeList = \"\";\n notices.forEach(n => updatedNoticeList += `
  • ${n.message}
  • `);\n\n this.noticeListElement.innerHTML = updatedNoticeList;\n }\n}\n","import { WaitingRoomConnection } from \"bouncer-waitingroom\";\nimport { WaitingRoomHandler } from \"./WaitingRoomHandler\";\n\ndocument.addEventListener(\"DOMContentLoaded\", async function () {\n const wrc = new WaitingRoomConnection();\n new WaitingRoomHandler();\n\n await wrc.startConnection();\n});\n"],"names":["HttpError","Error","constructor","errorMessage","statusCode","trueProto","prototype","super","this","__proto__","TimeoutError","AbortError","UnsupportedTransportError","message","transport","errorType","DisabledTransportError","FailedToStartTransportError","FailedToNegotiateWithServerError","AggregateErrors","innerErrors","HttpResponse","statusText","content","HttpClient","get","url","options","send","method","post","getCookieString","LogLevel","NullLogger","log","_logLevel","_message","instance","VERSION","Arg","isRequired","val","name","isNotEmpty","match","isIn","values","Platform","isBrowser","isNode","window","document","isWebWorker","self","isReactNative","process","release","getDataDetail","data","includeContent","detail","isArrayBuffer","byteLength","view","Uint8Array","str","forEach","num","toString","substr","length","formatArrayBuffer","ArrayBuffer","async","sendMessage","logger","transportName","httpClient","headers","value","getUserAgentHeader","Trace","logMessageContent","responseType","response","timeout","withCredentials","SubjectSubscription","subject","observer","_subject","_observer","dispose","index","observers","indexOf","splice","cancelCallback","catch","_","ConsoleLogger","minimumLogLevel","_minLevel","out","console","logLevel","msg","Date","toISOString","Critical","error","Warning","warn","Information","info","userAgentHeaderName","constructUserAgent","getOsName","getRuntime","getRuntimeVersion","version","os","runtime","runtimeVersion","userAgent","majorAndMinor","split","platform","versions","node","getErrorString","e","stack","FetchHttpClient","_logger","fetch","requireFunc","__webpack_require__","__non_webpack_require__","require","_jar","CookieJar","_fetchType","bind","globalThis","global","getGlobalThis","AbortController","_abortControllerType","request","abortSignal","aborted","abortController","onabort","abort","timeoutId","msTimeout","setTimeout","undefined","body","cache","credentials","mode","redirect","signal","clearTimeout","ok","deserializeContent","status","payload","cookies","getCookies","c","join","arrayBuffer","text","XhrHttpClient","Promise","reject","resolve","xhr","XMLHttpRequest","open","setRequestHeader","Object","keys","header","onload","responseText","onerror","ontimeout","DefaultHttpClient","_httpClient","TextMessageFormat","write","output","RecordSeparator","parse","input","messages","pop","RecordSeparatorCode","String","fromCharCode","HandshakeProtocol","writeHandshakeRequest","handshakeRequest","JSON","stringify","parseHandshakeResponse","messageData","remainingData","binaryData","separatorIndex","responseLength","apply","Array","slice","call","buffer","textData","substring","type","MessageType","Subject","next","item","err","complete","subscribe","push","MessageBuffer","protocol","connection","bufferSize","_bufferSize","_messages","_totalMessageCount","_waitForSequenceMessage","_nextReceivingSequenceId","_latestReceivedSequenceId","_bufferedByteCount","_reconnectInProgress","_protocol","_connection","_send","serializedMessage","writeMessage","backpressurePromise","_isInvocationMessage","backpressurePromiseResolver","backpressurePromiseRejector","BufferedItem","_disconnected","_ack","ackMessage","newestAckedMessage","element","_id","sequenceId","_resolver","_shouldProcessMessage","Sequence","currentId","_ackTimer","_resetSequence","stop","_resend","_dispose","_rejector","Invocation","StreamItem","Completion","StreamInvocation","CancelInvocation","Close","Ping","Ack","_ackTimerHandle","id","resolver","rejector","HubConnectionState","HubConnection","create","reconnectPolicy","serverTimeoutInMilliseconds","keepAliveIntervalInMilliseconds","statefulReconnectBufferSize","_nextKeepAlive","_freezeEventListener","_statefulReconnectBufferSize","_reconnectPolicy","_handshakeProtocol","onreceive","_processIncomingData","onclose","_connectionClosed","_callbacks","_methods","_closedCallbacks","_reconnectingCallbacks","_reconnectedCallbacks","_invocationId","_receivedHandshakeResponse","_connectionState","Disconnected","_connectionStarted","_cachedPingMessage","state","connectionId","baseUrl","Reconnecting","start","_startPromise","_startWithStateTransitions","Connecting","Debug","_startInternal","addEventListener","Connected","_stopDuringStartError","handshakePromise","_handshakeResolver","_handshakeRejecter","transferFormat","features","reconnect","_sendMessage","_cleanupTimeout","_resetTimeoutPeriod","_resetKeepAliveInterval","_messageBuffer","disconnected","resend","inherentKeepAlive","_cleanupPingTimer","startPromise","_stopPromise","_stopInternal","Disconnecting","_reconnectDelayHandle","_completeClose","_sendCloseMessage","_sendWithProtocol","_createCloseMessage","stream","methodName","args","streams","streamIds","_replaceStreamingParams","invocationDescriptor","_createStreamInvocation","promiseQueue","cancelInvocation","_createCancelInvocation","invocationId","then","invocationEvent","_launchStreams","sendPromise","_createInvocation","invoke","result","on","newMethod","toLowerCase","off","handlers","removeIdx","callback","onreconnecting","onreconnected","_processHandshakeResponse","parseMessages","_invokeClientMethod","allowReconnect","responseMessage","getTime","_timeoutHandle","serverTimeout","_pingServerHandle","nextPing","invocationMessage","target","methods","_createCompletionMessage","methodsCopy","expectsResponse","res","exception","completionMessage","m","prevRes","arguments","_cancelCallbacksWithError","_reconnect","removeEventListener","reconnectStartTime","now","previousReconnectAttempts","retryError","nextRetryDelay","_getNextRetryDelay","previousRetryCount","elapsedMilliseconds","retryReason","nextRetryDelayInMilliseconds","callbacks","key","nonblocking","streamId","_createStreamItemMessage","i","argument","_isObservable","arg","DEFAULT_RETRY_DELAYS_IN_MILLISECONDS","DefaultReconnectPolicy","retryDelays","_retryDelays","retryContext","HeaderNames","Authorization","Cookie","AccessTokenHttpClient","innerClient","accessTokenFactory","_innerClient","_accessTokenFactory","allowRetry","_accessToken","_setAuthorizationHeader","HttpTransportType","TransferFormat","AbortController$1","_isAborted","LongPollingTransport","pollAborted","_pollAbort","_options","_running","connect","_url","Binary","pollOptions","pollUrl","_closeError","_receiving","_poll","_raiseOnClose","deleteOptions","delete","logMessage","ServerSentEventsTransport","accessToken","encodeURIComponent","eventSource","opened","Text","EventSource","onmessage","_close","onopen","_eventSource","close","WebSocketTransport","webSocketConstructor","_logMessageContent","_webSocketConstructor","_headers","token","webSocket","replace","binaryType","_event","_webSocket","event","ErrorEvent","readyState","OPEN","_isCloseEvent","wasClean","code","reason","HttpConnection","_stopPromiseResolver","_negotiateVersion","_resolveUrl","webSocketModule","eventSourceModule","WebSocket","_startInternalPromise","_sendQueue","TransportSendQueue","_stopError","_stopConnection","skipNegotiation","WebSockets","_constructTransport","_startTransport","negotiateResponse","redirects","_getNegotiationResponse","ProtocolVersion","_createTransport","negotiateUrl","_resolveNegotiateUrl","negotiateVersion","connectionToken","useStatefulReconnect","_useStatefulReconnect","_createConnectUrl","requestedTransport","requestedTransferFormat","connectUrl","_isITransport","transportExceptions","transports","availableTransports","negotiate","endpoint","transportOrError","_resolveTransportOrError","ex","ServerSentEvents","LongPolling","callStop","actualTransport","transportMatches","transferFormats","map","s","lastIndexOf","aTag","createElement","href","URL","pathname","endsWith","searchParams","URLSearchParams","has","append","search","_transport","_buffer","_executing","_sendBufferedData","PromiseSource","_transportResult","_sendLoopPromise","_sendLoop","_bufferData","promise","transportResult","_concatBuffers","arrayBuffers","totalLength","b","reduce","a","offset","set","_rejecter","JsonHubProtocol","hubMessages","parsedMessage","_isStreamItemMessage","_isCompletionMessage","_isAckMessage","_isSequenceMessage","_assertNotEmptyString","LogLevelNameMapping","trace","debug","information","warning","critical","none","None","HubConnectionBuilder","configureLogging","logging","mapping","parseLogLevel","withUrl","transportTypeOrOptions","httpConnectionOptions","withHubProtocol","withAutomaticReconnect","retryDelaysOrReconnectPolicy","isArray","withServerTimeout","milliseconds","_serverTimeoutInMilliseconds","withKeepAliveInterval","_keepAliveIntervalInMilliseconds","withStatefulReconnect","build","QueuePositionUpdatedEvent","CustomEvent","bubbles","cancelable","NoticesUpdatedEvent","StateUpdatedEvent","ConnectionClosedEvent","ConnectionError","Notice","Queue","waitingRoomNumber","currentTicket","admittedTicket","admittedTicketOnActivation","isPrequeue","admittedTicketOnLoad","getPosition","ticketNumber","getAdmittedTicketNormalized","normalize","n","getQueuePosition","positionOnLoad","position","calculatedProgress","progress","QueuePosition","State","ticketExpiryMinutes","admissionStartTime","Ticket","number","prequeueNumber","Helpers","sleep","ms","sha256","TextEncoder","encode","hashBuffer","crypto","subtle","digest","from","padStart","WaitingRoomConnection","ticket","queue","notices","autoRefresh","handleQueueUpdated","handleStateUpdated","handleNoticesUpdated","handlePrequeueCalculated","handleWaitingRoomUpdated","handleReloadWaitingClients","handleOnClose","startConnection","numbersUnset","isValidated","validation","autoRefreshOnceThresholdIsMet","currentTicketNumber","admittingTicketThreshold","ticketNumberOnWaitingRoomActivation","notice","dispatchNoticesUpdatedEvent","dispatchStateUpdatedEvent","dispatchQueueUpdatedEvent","queuePosition","dispatchEvent","location","reload","timeoutMilliseconds","totalDelayMilliseconds","Math","random","newTicketNumber","updatedNotices","x","WaitingRoomHandler","progressBarElement","progressStripeElement","progressStripe2Element","queueProgressBarValueElement","positionInfoElement","noticeListElement","waitingContent","enterContent","querySelector","registerHandlers","updateQueuePosition","updateNotices","updateProgressText","updateProgressBar","queueProgressRoundedPercentage","round","queueProgressPercentage","style","width","left","innerText","display","updatedNoticeList","innerHTML","wrc"],"mappings":"AAGO,MAAMA,UAAkBC,MAM3B,WAAAC,CAAYC,EAAcC,GACtB,MAAMC,aAAuBC,UAC7BC,MAAM,GAAGJ,mBAA8BC,MACvCI,KAAKJ,WAAaA,EAGlBI,KAAKC,UAAYJ,CACpB,EAGE,MAAMK,UAAqBT,MAK9B,WAAAC,CAAYC,EAAe,uBACvB,MAAME,aAAuBC,UAC7BC,MAAMJ,GAGNK,KAAKC,UAAYJ,CACpB,EAGE,MAAMM,UAAmBV,MAK5B,WAAAC,CAAYC,EAAe,sBACvB,MAAME,aAAuBC,UAC7BC,MAAMJ,GAGNK,KAAKC,UAAYJ,CACpB,EAIE,MAAMO,UAAkCX,MAM3C,WAAAC,CAAYW,EAASC,GACjB,MAAMT,aAAuBC,UAC7BC,MAAMM,GACNL,KAAKM,UAAYA,EACjBN,KAAKO,UAAY,4BAGjBP,KAAKC,UAAYJ,CACpB,EAIE,MAAMW,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