@therms/rpc-client
Advanced tools
Comparing version 2.10.0 to 2.10.1
@@ -0,1 +1,8 @@ | ||
## [2.10.1](https://bitbucket.org/thermsio/rpc-client-ts/compare/v2.10.0...v2.10.1) (2022-08-29) | ||
### Bug Fixes | ||
* force bump version ([bfdde82](https://bitbucket.org/thermsio/rpc-client-ts/commits/bfdde82dd646bd499ad47f9d84da2ee996a7560c)) | ||
# [2.10.0](http://bitbucket.org/thermsio/rpc-client-ts/compare/v2.9.1...v2.10.0) (2022-08-02) | ||
@@ -2,0 +9,0 @@ |
@@ -1,3 +0,875 @@ | ||
export { RPCClient } from './RPCClient.js'; | ||
export { CallResponseDTO as RPCResponse } from './CallResponseDTO.js'; | ||
import stringify from 'fast-json-stable-stringify'; | ||
import { cloneDeep, merge } from 'lodash-es'; | ||
import LRU from 'lru-cache'; | ||
/****************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
Permission to use, copy, modify, and/or distribute this software for any | ||
purpose with or without fee is hereby granted. | ||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | ||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY | ||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | ||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM | ||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR | ||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | ||
PERFORMANCE OF THIS SOFTWARE. | ||
***************************************************************************** */ | ||
function __awaiter(thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
} | ||
const DEFAULT_REQUEST_SCOPE = 'global'; | ||
const DEFAULT_REQUEST_VERSION = '1'; | ||
class CallRequestDTO { | ||
constructor(call) { | ||
const { args, correlationId, identity, procedure, scope, version } = call; | ||
this.args = args; | ||
if (correlationId && typeof correlationId !== 'string') | ||
throw new Error('correlationId must be a string'); | ||
this.correlationId = correlationId || Math.random().toString(); | ||
if (identity) { | ||
if (typeof identity !== 'object') | ||
throw new Error('identity must be an object'); | ||
if (identity.authorization && typeof identity.authorization !== 'string') | ||
throw new Error('identity.authorization must be a string'); | ||
if (identity.deviceName && typeof identity.deviceName !== 'string') | ||
throw new Error('identity.deviceName must be a string'); | ||
if (identity.metadata && typeof identity.metadata !== 'object') | ||
throw new Error('identity.metadata must be a object'); | ||
this.identity = identity; | ||
} | ||
if (procedure && typeof procedure !== 'string') | ||
throw new Error('procedure must be string'); | ||
this.procedure = procedure; | ||
if (scope && typeof scope !== 'string') | ||
throw new Error('scope must be string'); | ||
this.scope = scope; | ||
if (version && typeof version !== 'string') | ||
throw new Error('version must be string'); | ||
this.version = version; | ||
} | ||
} | ||
class CallRequestError extends Error { | ||
} | ||
class CallRequestTransportError extends Error { | ||
} | ||
class ManagerCallRequestTimeoutError extends Error { | ||
} | ||
function isPlainObject(value) { | ||
if (Object.prototype.toString.call(value) !== '[object Object]') { | ||
return false; | ||
} | ||
const prototype = Object.getPrototypeOf(value); | ||
return prototype === null || prototype === Object.prototype; | ||
} | ||
function sortKeys(object, options = {}) { | ||
if (!isPlainObject(object) && !Array.isArray(object)) { | ||
throw new TypeError('Expected a plain object or array'); | ||
} | ||
const { deep, compare } = options; | ||
const seenInput = []; | ||
const seenOutput = []; | ||
const deepSortArray = (array) => { | ||
const seenIndex = seenInput.indexOf(array); | ||
if (seenIndex !== -1) { | ||
return seenOutput[seenIndex]; | ||
} | ||
const result = []; | ||
seenInput.push(array); | ||
seenOutput.push(result); | ||
result.push(...array.map((item) => { | ||
if (Array.isArray(item)) { | ||
return deepSortArray(item); | ||
} | ||
if (isPlainObject(item)) { | ||
return _sortKeys(item); | ||
} | ||
return item; | ||
})); | ||
return result; | ||
}; | ||
const _sortKeys = (object) => { | ||
const seenIndex = seenInput.indexOf(object); | ||
if (seenIndex !== -1) { | ||
return seenOutput[seenIndex]; | ||
} | ||
const result = {}; | ||
const keys = Object.keys(object).sort(compare); | ||
seenInput.push(object); | ||
seenOutput.push(result); | ||
for (const key of keys) { | ||
const value = object[key]; | ||
let newValue; | ||
if (deep && Array.isArray(value)) { | ||
newValue = deepSortArray(value); | ||
} | ||
else { | ||
newValue = deep && isPlainObject(value) ? _sortKeys(value) : value; | ||
} | ||
Object.defineProperty(result, key, Object.assign(Object.assign({}, Object.getOwnPropertyDescriptor(object, key)), { value: newValue })); | ||
} | ||
return result; | ||
}; | ||
if (Array.isArray(object)) { | ||
return deep ? deepSortArray(object) : object.slice(); | ||
} | ||
return _sortKeys(object); | ||
} | ||
const makeCallRequestKey = (request) => { | ||
if (!request.args) | ||
return `${request.scope}${request.procedure}${request.version}`; | ||
return `${request.scope}${request.procedure}${request.version}${stringify(sortKeys(request.args || {}, { deep: true }))}`; | ||
}; | ||
let lsDebug = null; | ||
try { | ||
lsDebug = localStorage.getItem('debug') || ''; | ||
} | ||
catch (e) { | ||
if (typeof window !== 'undefined' && typeof localStorage !== 'undefined') { | ||
console.warn('Error checking window.debug'); | ||
} | ||
} | ||
const GetDebugLogger = (prefix) => { | ||
if (lsDebug) { | ||
if (new RegExp(lsDebug).test(prefix)) { | ||
return (...args) => console.log(prefix, ...args); | ||
} | ||
} | ||
return (() => undefined); | ||
}; | ||
const debug$3 = GetDebugLogger('rpc:ClientManager'); | ||
class ClientManager { | ||
constructor(options) { | ||
this.options = options; | ||
this.inflightCallsByKey = {}; | ||
this.interceptors = { | ||
request: [], | ||
response: [], | ||
}; | ||
this.addResponseInterceptor = (interceptor) => { | ||
if (typeof interceptor !== 'function') | ||
throw new Error('cannot add interceptor that is not a function'); | ||
this.interceptors.response.push(interceptor); | ||
}; | ||
this.addRequestInterceptor = (interceptor) => { | ||
if (typeof interceptor !== 'function') | ||
throw new Error('cannot add interceptor that is not a function'); | ||
this.interceptors.request.push(interceptor); | ||
}; | ||
this.clearCache = (request) => { | ||
debug$3('clearCache'); | ||
if (!this.cache) | ||
return; | ||
if (request) { | ||
this.cache.setCachedResponse(request, undefined); | ||
} | ||
else { | ||
this.cache.clearCache(); | ||
} | ||
}; | ||
this.getCachedResponse = (request) => { | ||
var _a; | ||
debug$3('getCachedResponse', request); | ||
return (_a = this === null || this === void 0 ? void 0 : this.cache) === null || _a === void 0 ? void 0 : _a.getCachedResponse(request); | ||
}; | ||
this.getInFlightCallCount = () => { | ||
debug$3('getInFlightCallCount'); | ||
return Object.keys(this.inflightCallsByKey).length; | ||
}; | ||
this.manageClientRequest = (originalRequest) => __awaiter(this, void 0, void 0, function* () { | ||
debug$3('manageClientRequest', originalRequest); | ||
const request = yield this.interceptRequestMutator(originalRequest); | ||
const key = makeCallRequestKey(request); | ||
if (this.inflightCallsByKey.hasOwnProperty(key)) { | ||
debug$3('manageClientRequest using an existing in-flight call', key); | ||
return this.inflightCallsByKey[key].then((res) => { | ||
const response = cloneDeep(res); | ||
if (originalRequest.correlationId) { | ||
response.correlationId = originalRequest.correlationId; | ||
} | ||
return response; | ||
}); | ||
} | ||
const requestPromiseWrapper = () => __awaiter(this, void 0, void 0, function* () { | ||
const transportResponse = yield this.sendRequestWithTransport(request); | ||
const response = yield this.interceptResponseMutator(transportResponse, request); | ||
if (this.cache && response) { | ||
this.cache.setCachedResponse(request, response); | ||
} | ||
return response; | ||
}); | ||
const requestPromise = requestPromiseWrapper() | ||
.then((response) => { | ||
delete this.inflightCallsByKey[key]; | ||
return response; | ||
}) | ||
.catch((err) => { | ||
delete this.inflightCallsByKey[key]; | ||
throw err; | ||
}); | ||
this.inflightCallsByKey[key] = requestPromise; | ||
return yield requestPromise; | ||
}); | ||
this.setIdentity = (identity) => { | ||
debug$3('setIdentity', identity); | ||
this.transports.forEach((transport) => transport.setIdentity(identity)); | ||
}; | ||
this.interceptRequestMutator = (originalRequest) => __awaiter(this, void 0, void 0, function* () { | ||
let request = originalRequest; | ||
if (this.interceptors.request.length) { | ||
debug$3('interceptRequestMutator(), original request:', originalRequest); | ||
for (const interceptor of this.interceptors.request) { | ||
request = yield interceptor(request); | ||
} | ||
} | ||
return request; | ||
}); | ||
this.interceptResponseMutator = (originalResponse, request) => __awaiter(this, void 0, void 0, function* () { | ||
let response = originalResponse; | ||
if (this.interceptors.response.length) { | ||
debug$3('interceptResponseMutator', request, originalResponse); | ||
for (const interceptor of this.interceptors.response) { | ||
try { | ||
response = yield interceptor(response, request); | ||
} | ||
catch (e) { | ||
debug$3('caught response interceptor, request:', request, 'original response:', originalResponse, 'mutated response:', response); | ||
throw e; | ||
} | ||
} | ||
} | ||
return response; | ||
}); | ||
this.sendRequestWithTransport = (request) => __awaiter(this, void 0, void 0, function* () { | ||
debug$3('sendRequestWithTransport', request); | ||
let response; | ||
let transportsIndex = 0; | ||
while (!response && this.transports[transportsIndex]) { | ||
const transport = this.transports[transportsIndex]; | ||
if (!transport.isConnected()) { | ||
transportsIndex++; | ||
continue; | ||
} | ||
debug$3(`sendRequestWithTransport trying ${this.transports[transportsIndex].name}`, request); | ||
try { | ||
let timeout; | ||
const deadlinePromise = new Promise((_, reject) => { | ||
timeout = setTimeout(() => { | ||
reject(new ManagerCallRequestTimeoutError(`Procedure ${request.procedure}`)); | ||
}, this.options.deadlineMs); | ||
}); | ||
response = yield Promise.race([ | ||
deadlinePromise, | ||
transport.sendRequest(request), | ||
]).then((response) => { | ||
clearTimeout(timeout); | ||
return response; | ||
}); | ||
} | ||
catch (e) { | ||
if (e instanceof ManagerCallRequestTimeoutError || | ||
e instanceof CallRequestTransportError) { | ||
debug$3(`sending request with ${this.transports[transportsIndex].name} failed, trying next transport`); | ||
transportsIndex++; | ||
} | ||
else { | ||
throw e; | ||
} | ||
} | ||
} | ||
if (!response && !this.transports[transportsIndex]) { | ||
throw new CallRequestError(`Procedure ${request.procedure} did not get a response from any transports`); | ||
} | ||
else if (!response) { | ||
throw new CallRequestError(`Procedure ${request.procedure} did not get a response from the remote`); | ||
} | ||
return response; | ||
}); | ||
this.cache = options.cache; | ||
if (options.requestInterceptor) { | ||
this.interceptors.request.push(options.requestInterceptor); | ||
} | ||
if (options.responseInterceptor) { | ||
this.interceptors.response.push(options.responseInterceptor); | ||
} | ||
this.transports = options.transports; | ||
} | ||
} | ||
class BrowserCache { | ||
constructor(cacheOptions) { | ||
this.cacheOptions = cacheOptions; | ||
} | ||
clearCache() { | ||
} | ||
getCachedResponse(request) { | ||
return undefined; | ||
} | ||
setCachedResponse(request, response) { | ||
} | ||
} | ||
BrowserCache.DEFAULT_CACHE_MAX_AGE_MS = 1000 * 60 * 5; | ||
BrowserCache.DEFAULT_CACHE_MAX_SIZE = 100; | ||
const debug$2 = GetDebugLogger('rpc:InMemoryCache'); | ||
class InMemoryCache { | ||
constructor(cacheOptions) { | ||
this.clearCache = () => { | ||
var _a; | ||
debug$2('clearCache'); | ||
(_a = this.cachedResponseByParams) === null || _a === void 0 ? void 0 : _a.clear(); | ||
}; | ||
this.getCachedResponse = (request) => { | ||
var _a; | ||
debug$2('getCachedResponse, key: ', request); | ||
let cachedResponse = (_a = this.cachedResponseByParams) === null || _a === void 0 ? void 0 : _a.get(makeCallRequestKey(request)); | ||
if (typeof cachedResponse === 'string') { | ||
cachedResponse = JSON.parse(cachedResponse); | ||
} | ||
return cachedResponse; | ||
}; | ||
this.setCachedResponse = (request, response) => { | ||
var _a, _b; | ||
debug$2('setCachedResponse', request, response); | ||
const requestKey = makeCallRequestKey(request); | ||
if (!response) { | ||
return (_a = this.cachedResponseByParams) === null || _a === void 0 ? void 0 : _a.del(requestKey); | ||
} | ||
const cachedResponse = Object.assign({}, response); | ||
delete cachedResponse.correlationId; | ||
(_b = this.cachedResponseByParams) === null || _b === void 0 ? void 0 : _b.set(requestKey, cachedResponse ? JSON.stringify(cachedResponse) : undefined); | ||
}; | ||
this.cachedResponseByParams = new LRU({ | ||
max: (cacheOptions === null || cacheOptions === void 0 ? void 0 : cacheOptions.cacheMaxSize) || InMemoryCache.DEFAULT_CACHE_MAX_SIZE, | ||
ttl: (cacheOptions === null || cacheOptions === void 0 ? void 0 : cacheOptions.cacheMaxAgeMs) || InMemoryCache.DEFAULT_CACHE_MAX_AGE_MS, | ||
}); | ||
} | ||
} | ||
InMemoryCache.DEFAULT_CACHE_MAX_AGE_MS = 1000 * 60 * 5; | ||
InMemoryCache.DEFAULT_CACHE_MAX_SIZE = 100; | ||
class CallResponseDTO { | ||
constructor(response) { | ||
const { code, correlationId, data, message, success } = response; | ||
if (typeof code !== 'number') | ||
throw new Error('code must be a number'); | ||
this.code = code; | ||
if (correlationId && typeof correlationId !== 'string') | ||
throw new Error('correlationId must be a string'); | ||
this.correlationId = correlationId; | ||
this.data = data; | ||
if (message && typeof message !== 'string') | ||
throw new Error('message must be a string'); | ||
this.message = message; | ||
if (typeof success !== 'boolean') | ||
throw new Error('success must be a boolean'); | ||
this.success = success; | ||
} | ||
} | ||
const debug$1 = GetDebugLogger('rpc:HTTPTransport'); | ||
class HTTPTransport { | ||
constructor(options) { | ||
this.options = options; | ||
this.networkIsConnected = false; | ||
this.name = 'HttpTransport'; | ||
this.isConnected = () => { | ||
var _a; | ||
if (typeof window !== 'undefined') { | ||
return !!((_a = window === null || window === void 0 ? void 0 : window.navigator) === null || _a === void 0 ? void 0 : _a.onLine); | ||
} | ||
return this.networkIsConnected; | ||
}; | ||
this.sendRequest = (call) => __awaiter(this, void 0, void 0, function* () { | ||
debug$1('sendRequest', call); | ||
const body = JSON.stringify(Object.assign({ identity: this.identity }, call)); | ||
const res = yield (window === null || window === void 0 ? void 0 : window.fetch(this.host, { | ||
body, | ||
cache: 'default', | ||
credentials: 'omit', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
method: 'POST', | ||
mode: 'cors', | ||
redirect: 'follow', | ||
referrerPolicy: 'origin', | ||
})); | ||
const string = yield res.text(); | ||
if (!string) | ||
throw new Error('No response received from remote'); | ||
const response = JSON.parse(string); | ||
return new CallResponseDTO(response); | ||
}); | ||
this.setIdentity = (identity) => { | ||
debug$1('setIdentity', identity); | ||
this.identity = identity; | ||
}; | ||
this.host = options.host; | ||
} | ||
} | ||
const DEFAULT_TIMEOUT = 30000; | ||
class PromiseWrapper { | ||
constructor(timeout) { | ||
this.reject = (rejectReturnValue) => { | ||
if (this.rejectPromise) { | ||
this.rejectPromise(rejectReturnValue); | ||
} | ||
}; | ||
this.resolve = (resolveReturnValue) => { | ||
if (this.resolvePromise) { | ||
this.resolvePromise(resolveReturnValue); | ||
} | ||
}; | ||
this.promise = new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { | ||
const timer = setTimeout(() => { | ||
reject(new Error('PromiseWraper timeout')); | ||
}, timeout || DEFAULT_TIMEOUT); | ||
this.rejectPromise = (arg) => { | ||
clearTimeout(timer); | ||
reject(arg); | ||
}; | ||
this.resolvePromise = (arg) => { | ||
clearTimeout(timer); | ||
resolve(arg); | ||
}; | ||
})); | ||
} | ||
} | ||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); | ||
const debug = GetDebugLogger('rpc:WebSocketTransport'); | ||
class WebSocketTransport { | ||
constructor(options) { | ||
this.options = options; | ||
this.connectedToRemote = false; | ||
this.isWaitingForIdentityConfirmation = false; | ||
this.pendingPromisesForResponse = {}; | ||
this.serverMessageHandlers = []; | ||
this.websocketId = undefined; | ||
this.name = 'WebSocketTransport'; | ||
this.isConnected = () => { | ||
return this.connectedToRemote && !!this.websocket; | ||
}; | ||
this.sendClientMessageToServer = (msg) => { | ||
var _a; | ||
let strMsg = msg; | ||
try { | ||
strMsg = JSON.stringify({ clientMessage: msg }); | ||
} | ||
catch (err) { | ||
console.warn('WebSocketTransport.sendClientMessage() unable to stringify "msg"', msg); | ||
} | ||
(_a = this.websocket) === null || _a === void 0 ? void 0 : _a.send(strMsg); | ||
}; | ||
this.sendRequest = (call) => __awaiter(this, void 0, void 0, function* () { | ||
debug('sendRequest', call); | ||
while (this.isWaitingForIdentityConfirmation) { | ||
debug('waiting for identity confirmation'); | ||
yield sleep(100); | ||
} | ||
return this.sendCall(call); | ||
}); | ||
this.setIdentity = (identity) => __awaiter(this, void 0, void 0, function* () { | ||
debug('setIdentity', identity); | ||
if (!identity) { | ||
this.identity = undefined; | ||
yield this.resetConnection(); | ||
return; | ||
} | ||
else { | ||
this.identity = identity; | ||
} | ||
if (!this.connectedToRemote) { | ||
debug('setIdentity is not connected to remote'); | ||
return; | ||
} | ||
else if (this.isWaitingForIdentityConfirmation) { | ||
debug('setIdentity returning early because "this.isWaitingForIdentityConfirmation=true"'); | ||
return; | ||
} | ||
this.isWaitingForIdentityConfirmation = true; | ||
this.sendCall({ identity }) | ||
.then(() => { | ||
debug('setIdentity with remote complete'); | ||
}) | ||
.catch((e) => { | ||
debug('setIdentity with remote error', e); | ||
}) | ||
.finally(() => { | ||
this.isWaitingForIdentityConfirmation = false; | ||
}); | ||
}); | ||
this.subscribeToServerMessages = (handler) => { | ||
this.serverMessageHandlers.push(handler); | ||
}; | ||
this.unsubscribeFromServerMessages = (handler) => { | ||
this.serverMessageHandlers = this.serverMessageHandlers.filter((_handler) => _handler !== handler); | ||
}; | ||
this.connect = () => { | ||
debug('connect', this.host); | ||
if (this.websocket) { | ||
debug('connect() returning early, websocket already exists'); | ||
return; | ||
} | ||
this.websocketId = Math.random(); | ||
this.websocket = new WebSocket(this.host); | ||
const ws = this.websocket; | ||
ws.onopen = () => { | ||
console.info(`[${new Date().toLocaleTimeString()}] WebSocket connected`); | ||
this.setConnectedToRemote(true); | ||
}; | ||
ws.onmessage = (msg) => { | ||
this.handleWebSocketMsg(msg); | ||
}; | ||
ws.onclose = (e) => { | ||
if (this.connectedToRemote) { | ||
console.info(`[${new Date().toLocaleTimeString()}] WebSocket closed`, e.reason); | ||
} | ||
else { | ||
debug('WebSocket closed, it was not connected to the remote'); | ||
} | ||
this.setConnectedToRemote(false); | ||
this.isWaitingForIdentityConfirmation = false; | ||
this.websocket = undefined; | ||
this.websocketId = undefined; | ||
Object.entries(this.pendingPromisesForResponse).forEach(([correlationId, promiseWrapper]) => { | ||
promiseWrapper.reject(new CallRequestTransportError('Websocket disconnected')); | ||
}); | ||
if (!e.wasClean) { | ||
setTimeout(() => { | ||
this.connect(); | ||
}, 1000); | ||
} | ||
}; | ||
ws.onerror = (err) => { | ||
if (this.connectedToRemote) { | ||
console.error('WebSocket encountered error: ', err); | ||
} | ||
else { | ||
debug('WebSocket errored, it was not connected to the remote'); | ||
} | ||
ws.close(); | ||
}; | ||
}; | ||
this.disconnect = (reason) => { | ||
var _a; | ||
debug('disconnect'); | ||
this.setConnectedToRemote(false); | ||
this.isWaitingForIdentityConfirmation = false; | ||
(_a = this.websocket) === null || _a === void 0 ? void 0 : _a.close(1000, reason); | ||
this.websocket = undefined; | ||
this.websocketId = undefined; | ||
}; | ||
this.handleServerMessage = (msg) => { | ||
this.serverMessageHandlers.forEach((handler) => { | ||
try { | ||
handler(msg.serverMessage); | ||
} | ||
catch (err) { | ||
console.warn(`WebSocketTransport.handleServerMessage() a serverMessageHandler errored when calling`, msg, 'handler func:', handler); | ||
console.error(err); | ||
} | ||
}); | ||
}; | ||
this.handleWebSocketMsg = (msg) => { | ||
debug('handleWebSocketMsg', msg); | ||
let json; | ||
try { | ||
json = JSON.parse(msg.data); | ||
} | ||
catch (e) { | ||
console.error('error parsing WS msg', e); | ||
} | ||
if ('serverMessage' in json) { | ||
this.handleServerMessage(json); | ||
return; | ||
} | ||
const callResponseDTO = new CallResponseDTO(json); | ||
if (!callResponseDTO.correlationId) { | ||
console.error('RPCClient WebSocketTransport received unexpected msg from the server, not correlationId found in response.', json); | ||
return; | ||
} | ||
const pendingRequestPromise = this.pendingPromisesForResponse[callResponseDTO.correlationId]; | ||
if (pendingRequestPromise) { | ||
pendingRequestPromise.resolve(callResponseDTO); | ||
} | ||
else { | ||
console.warn("rcvd WS msg/response that doesn't match any pending RPC's", json); | ||
} | ||
}; | ||
this.resetConnection = () => __awaiter(this, void 0, void 0, function* () { | ||
debug('resetConnection'); | ||
this.disconnect('WebSocketTransport#resetConnection'); | ||
yield sleep(100); | ||
this.connect(); | ||
}); | ||
this.sendCall = (call) => __awaiter(this, void 0, void 0, function* () { | ||
var _a; | ||
debug('sendCall', call); | ||
const correlationId = Math.random().toString(); | ||
call.correlationId = call.correlationId || correlationId; | ||
let promiseWrapper = new PromiseWrapper(WebSocketTransport.DEFAULT_TIMEOUT_MS); | ||
(_a = this.websocket) === null || _a === void 0 ? void 0 : _a.send(JSON.stringify(call)); | ||
this.pendingPromisesForResponse[call.correlationId] = promiseWrapper; | ||
return yield promiseWrapper.promise.finally(() => { | ||
delete this.pendingPromisesForResponse[call.correlationId]; | ||
}); | ||
}); | ||
this.setConnectedToRemote = (connected) => { | ||
debug(`setConnectedToRemote: ${connected}`); | ||
this.connectedToRemote = connected; | ||
if (this.options.onConnectionStatusChange) { | ||
this.options.onConnectionStatusChange(connected); | ||
} | ||
if (connected && this.identity) { | ||
this.setIdentity(this.identity); | ||
} | ||
}; | ||
debug('new WebSocketTransport()'); | ||
this.host = options.host; | ||
this.connect(); | ||
} | ||
} | ||
WebSocketTransport.DEFAULT_TIMEOUT_MS = 10000; | ||
const parseRequestShorthand = (requestString) => { | ||
const parsed = requestString.split('::'); | ||
return { | ||
procedure: parsed[1], | ||
scope: parsed[0] || DEFAULT_REQUEST_SCOPE, | ||
version: parsed[2] || DEFAULT_REQUEST_VERSION, | ||
}; | ||
}; | ||
class Vent { | ||
constructor() { | ||
this.events = {}; | ||
this.publish = (topic, data) => __awaiter(this, void 0, void 0, function* () { | ||
const handlers = this.events[topic]; | ||
if (!handlers) | ||
return; | ||
handlers.forEach(function (handler) { | ||
handler.call(handler, data); | ||
}); | ||
}); | ||
this.subscribe = (topic, handler) => { | ||
if (!this.events[topic]) { | ||
this.events[topic] = []; | ||
} | ||
this.events[topic].push(handler); | ||
}; | ||
this.unsubscribe = (topic, handler) => { | ||
if (!this.events[topic]) | ||
return; | ||
let handlerIdx = this.events[topic].indexOf(handler); | ||
this.events[topic].splice(handlerIdx); | ||
}; | ||
} | ||
} | ||
const ERRORS = { | ||
HTTP_HOST_OR_TRANSPORT_REQUIRED: `http host or tansport is required`, | ||
INTERCEPTOR_MUSTBE_FUNC: `interceptors must be a function`, | ||
}; | ||
class RPCClient { | ||
constructor(options) { | ||
var _a, _b, _c, _d, _e, _f; | ||
this.options = options; | ||
this.webSocketConnectionChangeListeners = []; | ||
this.vent = new Vent(); | ||
this.onWebSocketConnectionStatusChange = (connected) => { | ||
if (this.options.onWebSocketConnectionStatusChange) { | ||
this.options.onWebSocketConnectionStatusChange(connected); | ||
} | ||
this.webSocketConnectionChangeListeners.forEach((cb) => cb(connected)); | ||
}; | ||
this.call = (request, args) => __awaiter(this, void 0, void 0, function* () { | ||
if (!request) | ||
throw new Error('RPCClient.call(request) requires a "request" param'); | ||
let req; | ||
if (typeof request === 'string') | ||
req = parseRequestShorthand(request); | ||
else | ||
req = request; | ||
if (args) { | ||
req.args = args; | ||
} | ||
const requestDTO = new CallRequestDTO(req); | ||
if (!requestDTO.procedure && !requestDTO.identity) { | ||
throw new TypeError('RPCClient#call requires a "identity" or "procedure" prop and received neither'); | ||
} | ||
if (!requestDTO.identity) | ||
requestDTO.identity = {}; | ||
requestDTO.identity = merge(Object.assign({}, this.identity), requestDTO.identity); | ||
const callResponse = yield this.callManager.manageClientRequest(requestDTO); | ||
if (!callResponse.success) { | ||
throw callResponse; | ||
} | ||
const callRequestKey = makeCallRequestKey(req); | ||
this.vent.publish(callRequestKey, callResponse === null || callResponse === void 0 ? void 0 : callResponse.data); | ||
return callResponse; | ||
}); | ||
this.clearCache = (request) => { | ||
this.callManager.clearCache(request); | ||
}; | ||
this.getCallCache = (request, args) => { | ||
let req; | ||
if (typeof request === 'string') | ||
req = parseRequestShorthand(request); | ||
else | ||
req = request; | ||
if (args) { | ||
req.args = args; | ||
} | ||
const cachedResponse = this.callManager.getCachedResponse(req); | ||
if (cachedResponse) | ||
return cachedResponse; | ||
return undefined; | ||
}; | ||
this.getIdentity = () => this.identity ? cloneDeep(this.identity) : this.identity; | ||
this.getInFlightCallCount = () => { | ||
return this.callManager.getInFlightCallCount(); | ||
}; | ||
this.getWebSocketConnected = () => { | ||
var _a; | ||
return !!((_a = this === null || this === void 0 ? void 0 : this.webSocketTransport) === null || _a === void 0 ? void 0 : _a.isConnected()); | ||
}; | ||
this.makeProcedure = (request) => { | ||
const self = this; | ||
let req; | ||
if (typeof request === 'string') | ||
req = parseRequestShorthand(request); | ||
else | ||
req = request; | ||
return function curriedProcedure(args) { | ||
return self.call(Object.assign(Object.assign({}, req), { args })); | ||
}; | ||
}; | ||
this.registerResponseInterceptor = (responseInterceptor) => { | ||
this.callManager.addResponseInterceptor(responseInterceptor); | ||
}; | ||
this.registerRequestInterceptor = (requestInterceptor) => { | ||
this.callManager.addRequestInterceptor(requestInterceptor); | ||
}; | ||
this.registerWebSocketConnectionStatusChangeListener = (cb) => { | ||
this.webSocketConnectionChangeListeners.push(cb); | ||
}; | ||
this.sendClientMessageToServer = (msg) => { | ||
if (!this.webSocketTransport) { | ||
console.warn('RPCClient.sendClientMessageToServer() unable to send because RPCClient has no websocket configuration'); | ||
return; | ||
} | ||
if (this.webSocketTransport.isConnected()) { | ||
this.webSocketTransport.sendClientMessageToServer(msg); | ||
} | ||
else { | ||
console.info('RPCClient.sendClientMessageToServer() cannot send because the websocket is not connected'); | ||
} | ||
}; | ||
this.setIdentity = (identity) => { | ||
let newIdentity = cloneDeep(identity); | ||
this.identity = identity; | ||
this.callManager.setIdentity(newIdentity); | ||
}; | ||
this.setIdentityMetadata = (metadata) => { | ||
var _a; | ||
(_a = this.identity) !== null && _a !== void 0 ? _a : (this.identity = {}); | ||
const newIdentity = cloneDeep(this.identity); | ||
newIdentity.metadata = metadata; | ||
this.identity.metadata = metadata; | ||
this.callManager.setIdentity(newIdentity); | ||
}; | ||
if (!((_a = options === null || options === void 0 ? void 0 : options.hosts) === null || _a === void 0 ? void 0 : _a.http) && !((_b = options === null || options === void 0 ? void 0 : options.transports) === null || _b === void 0 ? void 0 : _b.http)) { | ||
throw new Error(ERRORS.HTTP_HOST_OR_TRANSPORT_REQUIRED); | ||
} | ||
if (options.requestInterceptor && | ||
typeof options.requestInterceptor !== 'function') { | ||
throw new Error(ERRORS.INTERCEPTOR_MUSTBE_FUNC); | ||
} | ||
if (options.responseInterceptor && | ||
typeof options.responseInterceptor !== 'function') { | ||
throw new Error(ERRORS.INTERCEPTOR_MUSTBE_FUNC); | ||
} | ||
let cache; | ||
const cacheOptions = { cacheMaxAgeMs: options === null || options === void 0 ? void 0 : options.cacheMaxAgeMs }; | ||
if (options.cacheType == 'browser') { | ||
cache = new BrowserCache(cacheOptions); | ||
} | ||
else { | ||
cache = new InMemoryCache(cacheOptions); | ||
} | ||
const transports = []; | ||
if ((_c = options.transports) === null || _c === void 0 ? void 0 : _c.websocket) { | ||
transports.push(options.transports.websocket); | ||
} | ||
else if ((_d = options === null || options === void 0 ? void 0 : options.hosts) === null || _d === void 0 ? void 0 : _d.websocket) { | ||
this.webSocketTransport = new WebSocketTransport({ | ||
host: options.hosts.websocket, | ||
onConnectionStatusChange: this.onWebSocketConnectionStatusChange, | ||
}); | ||
transports.push(this.webSocketTransport); | ||
} | ||
if ((_e = options.transports) === null || _e === void 0 ? void 0 : _e.http) { | ||
transports.push(options.transports.http); | ||
} | ||
else if ((_f = options === null || options === void 0 ? void 0 : options.hosts) === null || _f === void 0 ? void 0 : _f.http) { | ||
this.httpTransport = new HTTPTransport({ host: options.hosts.http }); | ||
transports.push(this.httpTransport); | ||
} | ||
this.callManager = new ClientManager({ | ||
cache, | ||
deadlineMs: options.deadlineMs || RPCClient.DEFAULT_DEADLINE_MS, | ||
requestInterceptor: options.requestInterceptor, | ||
responseInterceptor: options.responseInterceptor, | ||
transports, | ||
}); | ||
} | ||
subscribe(filter, handler) { | ||
const request = typeof filter.request === 'string' | ||
? parseRequestShorthand(filter.request) | ||
: filter.request; | ||
const callRequestKey = makeCallRequestKey(Object.assign(Object.assign({}, request), { args: filter.args })); | ||
this.vent.subscribe(callRequestKey, handler); | ||
} | ||
unsubscribe(filter, handler) { | ||
const request = typeof filter.request === 'string' | ||
? parseRequestShorthand(filter.request) | ||
: filter.request; | ||
const callRequestKey = makeCallRequestKey(Object.assign(Object.assign({}, request), { args: filter.args })); | ||
this.vent.unsubscribe(callRequestKey, handler); | ||
} | ||
subscribeToServerMessages(handler) { | ||
if (!this.webSocketTransport) { | ||
console.warn('RPCClient.subscribeToServerMessages() cannot subscribe because RPCClient has no websocket configuration'); | ||
return; | ||
} | ||
this.webSocketTransport.subscribeToServerMessages(handler); | ||
} | ||
unsubscribeFromServerMessages(handler) { | ||
var _a; | ||
(_a = this.webSocketTransport) === null || _a === void 0 ? void 0 : _a.unsubscribeFromServerMessages(handler); | ||
} | ||
} | ||
RPCClient.DEFAULT_DEADLINE_MS = 10000; | ||
export { RPCClient, CallResponseDTO as RPCResponse }; | ||
//# sourceMappingURL=index.js.map |
@@ -1,2 +0,2 @@ | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).RPCClient={})}(this,(function(t){"use strict";function e(t,e,i,s){return new(i||(i=Promise))((function(n,r){function o(t){try{c(s.next(t))}catch(t){r(t)}}function a(t){try{c(s.throw(t))}catch(t){r(t)}}function c(t){var e;t.done?n(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,a)}c((s=s.apply(t,e||[])).next())}))}class i{constructor(t){const{args:e,correlationId:i,identity:s,procedure:n,scope:r,version:o}=t;if(this.args=e,i&&"string"!=typeof i)throw new Error("correlationId must be a string");if(this.correlationId=i||Math.random().toString(),s){if("object"!=typeof s)throw new Error("identity must be an object");if(s.authorization&&"string"!=typeof s.authorization)throw new Error("identity.authorization must be a string");if(s.deviceName&&"string"!=typeof s.deviceName)throw new Error("identity.deviceName must be a string");if(s.metadata&&"object"!=typeof s.metadata)throw new Error("identity.metadata must be a object");this.identity=s}if(n&&"string"!=typeof n)throw new Error("procedure must be string");if(this.procedure=n,r&&"string"!=typeof r)throw new Error("scope must be string");if(this.scope=r,o&&"string"!=typeof o)throw new Error("version must be string");this.version=o}}class s extends Error{}class n extends Error{}class r extends Error{}function o(t){if("[object Object]"!==Object.prototype.toString.call(t))return!1;const e=Object.getPrototypeOf(t);return null===e||e===Object.prototype}const a=t=>t.args?`${t.scope}${t.procedure}${t.version}${function(t,e){e||(e={}),"function"==typeof e&&(e={cmp:e});var i,s="boolean"==typeof e.cycles&&e.cycles,n=e.cmp&&(i=e.cmp,function(t){return function(e,s){var n={key:e,value:t[e]},r={key:s,value:t[s]};return i(n,r)}}),r=[];return function t(e){if(e&&e.toJSON&&"function"==typeof e.toJSON&&(e=e.toJSON()),void 0!==e){if("number"==typeof e)return isFinite(e)?""+e:"null";if("object"!=typeof e)return JSON.stringify(e);var i,o;if(Array.isArray(e)){for(o="[",i=0;i<e.length;i++)i&&(o+=","),o+=t(e[i])||"null";return o+"]"}if(null===e)return"null";if(-1!==r.indexOf(e)){if(s)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var a=r.push(e)-1,c=Object.keys(e).sort(n&&n(e));for(o="",i=0;i<c.length;i++){var h=c[i],l=t(e[h]);l&&(o&&(o+=","),o+=JSON.stringify(h)+":"+l)}return r.splice(a,1),"{"+o+"}"}}(t)}(function(t,e={}){if(!o(t)&&!Array.isArray(t))throw new TypeError("Expected a plain object or array");const{deep:i,compare:s}=e,n=[],r=[],a=t=>{const e=n.indexOf(t);if(-1!==e)return r[e];const i=[];return n.push(t),r.push(i),i.push(...t.map((t=>Array.isArray(t)?a(t):o(t)?c(t):t))),i},c=t=>{const e=n.indexOf(t);if(-1!==e)return r[e];const h={},l=Object.keys(t).sort(s);n.push(t),r.push(h);for(const e of l){const s=t[e];let n;n=i&&Array.isArray(s)?a(s):i&&o(s)?c(s):s,Object.defineProperty(h,e,Object.assign(Object.assign({},Object.getOwnPropertyDescriptor(t,e)),{value:n}))}return h};return Array.isArray(t)?i?a(t):t.slice():c(t)}(t.args||{},{deep:!0}))}`:`${t.scope}${t.procedure}${t.version}`;var c="object"==typeof global&&global&&global.Object===Object&&global,h="object"==typeof self&&self&&self.Object===Object&&self,l=c||h||Function("return this")(),u=l.Symbol,d=Object.prototype,p=d.hasOwnProperty,f=d.toString,y=u?u.toStringTag:void 0;var v=Object.prototype.toString;var g=u?u.toStringTag:void 0;function b(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":g&&g in Object(t)?function(t){var e=p.call(t,y),i=t[y];try{t[y]=void 0;var s=!0}catch(t){}var n=f.call(t);return s&&(e?t[y]=i:delete t[y]),n}(t):function(t){return v.call(t)}(t)}function w(t){return null!=t&&"object"==typeof t}var m=Array.isArray;function _(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}function S(t){return t}function j(t){if(!_(t))return!1;var e=b(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var C,T=l["__core-js_shared__"],O=(C=/[^.]+$/.exec(T&&T.keys&&T.keys.IE_PROTO||""))?"Symbol(src)_1."+C:"";var A=Function.prototype.toString;function k(t){if(null!=t){try{return A.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var I=/^\[object .+?Constructor\]$/,M=Function.prototype,E=Object.prototype,R=M.toString,x=E.hasOwnProperty,z=RegExp("^"+R.call(x).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function L(t){return!(!_(t)||(e=t,O&&O in e))&&(j(t)?z:I).test(k(t));var e}function F(t,e){var i=function(t,e){return null==t?void 0:t[e]}(t,e);return L(i)?i:void 0}var P=F(l,"WeakMap"),D=Object.create,W=function(){function t(){}return function(e){if(!_(e))return{};if(D)return D(e);t.prototype=e;var i=new t;return t.prototype=void 0,i}}();function U(t,e,i){switch(i.length){case 0:return t.call(e);case 1:return t.call(e,i[0]);case 2:return t.call(e,i[0],i[1]);case 3:return t.call(e,i[0],i[1],i[2])}return t.apply(e,i)}function q(t,e){var i=-1,s=t.length;for(e||(e=Array(s));++i<s;)e[i]=t[i];return e}var N=Date.now;var B,$,H,G=function(){try{var t=F(Object,"defineProperty");return t({},"",{}),t}catch(t){}}(),J=G,V=J?function(t,e){return J(t,"toString",{configurable:!0,enumerable:!1,value:(i=e,function(){return i}),writable:!0});var i}:S,K=(B=V,$=0,H=0,function(){var t=N(),e=16-(t-H);if(H=t,e>0){if(++$>=800)return arguments[0]}else $=0;return B.apply(void 0,arguments)}),X=K;var Z=/^(?:0|[1-9]\d*)$/;function Q(t,e){var i=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==i||"symbol"!=i&&Z.test(t))&&t>-1&&t%1==0&&t<e}function Y(t,e,i){"__proto__"==e&&J?J(t,e,{configurable:!0,enumerable:!0,value:i,writable:!0}):t[e]=i}function tt(t,e){return t===e||t!=t&&e!=e}var et=Object.prototype.hasOwnProperty;function it(t,e,i){var s=t[e];et.call(t,e)&&tt(s,i)&&(void 0!==i||e in t)||Y(t,e,i)}function st(t,e,i,s){var n=!i;i||(i={});for(var r=-1,o=e.length;++r<o;){var a=e[r],c=s?s(i[a],t[a],a,i,t):void 0;void 0===c&&(c=t[a]),n?Y(i,a,c):it(i,a,c)}return i}var nt=Math.max;function rt(t,e){return X(function(t,e,i){return e=nt(void 0===e?t.length-1:e,0),function(){for(var s=arguments,n=-1,r=nt(s.length-e,0),o=Array(r);++n<r;)o[n]=s[e+n];n=-1;for(var a=Array(e+1);++n<e;)a[n]=s[n];return a[e]=i(o),U(t,this,a)}}(t,e,S),t+"")}function ot(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=9007199254740991}function at(t){return null!=t&&ot(t.length)&&!j(t)}var ct=Object.prototype;function ht(t){var e=t&&t.constructor;return t===("function"==typeof e&&e.prototype||ct)}function lt(t){return w(t)&&"[object Arguments]"==b(t)}var ut=Object.prototype,dt=ut.hasOwnProperty,pt=ut.propertyIsEnumerable,ft=lt(function(){return arguments}())?lt:function(t){return w(t)&&dt.call(t,"callee")&&!pt.call(t,"callee")},yt=ft;var vt="object"==typeof t&&t&&!t.nodeType&&t,gt=vt&&"object"==typeof module&&module&&!module.nodeType&&module,bt=gt&>.exports===vt?l.Buffer:void 0,wt=(bt?bt.isBuffer:void 0)||function(){return!1},mt={};function _t(t){return function(e){return t(e)}}mt["[object Float32Array]"]=mt["[object Float64Array]"]=mt["[object Int8Array]"]=mt["[object Int16Array]"]=mt["[object Int32Array]"]=mt["[object Uint8Array]"]=mt["[object Uint8ClampedArray]"]=mt["[object Uint16Array]"]=mt["[object Uint32Array]"]=!0,mt["[object Arguments]"]=mt["[object Array]"]=mt["[object ArrayBuffer]"]=mt["[object Boolean]"]=mt["[object DataView]"]=mt["[object Date]"]=mt["[object Error]"]=mt["[object Function]"]=mt["[object Map]"]=mt["[object Number]"]=mt["[object Object]"]=mt["[object RegExp]"]=mt["[object Set]"]=mt["[object String]"]=mt["[object WeakMap]"]=!1;var St="object"==typeof t&&t&&!t.nodeType&&t,jt=St&&"object"==typeof module&&module&&!module.nodeType&&module,Ct=jt&&jt.exports===St&&c.process,Tt=function(){try{var t=jt&&jt.require&&jt.require("util").types;return t||Ct&&Ct.binding&&Ct.binding("util")}catch(t){}}(),Ot=Tt&&Tt.isTypedArray,At=Ot?_t(Ot):function(t){return w(t)&&ot(t.length)&&!!mt[b(t)]},kt=Object.prototype.hasOwnProperty;function It(t,e){var i=m(t),s=!i&&yt(t),n=!i&&!s&&wt(t),r=!i&&!s&&!n&&At(t),o=i||s||n||r,a=o?function(t,e){for(var i=-1,s=Array(t);++i<t;)s[i]=e(i);return s}(t.length,String):[],c=a.length;for(var h in t)!e&&!kt.call(t,h)||o&&("length"==h||n&&("offset"==h||"parent"==h)||r&&("buffer"==h||"byteLength"==h||"byteOffset"==h)||Q(h,c))||a.push(h);return a}function Mt(t,e){return function(i){return t(e(i))}}var Et=Mt(Object.keys,Object),Rt=Object.prototype.hasOwnProperty;function xt(t){return at(t)?It(t):function(t){if(!ht(t))return Et(t);var e=[];for(var i in Object(t))Rt.call(t,i)&&"constructor"!=i&&e.push(i);return e}(t)}var zt=Object.prototype.hasOwnProperty;function Lt(t){if(!_(t))return function(t){var e=[];if(null!=t)for(var i in Object(t))e.push(i);return e}(t);var e=ht(t),i=[];for(var s in t)("constructor"!=s||!e&&zt.call(t,s))&&i.push(s);return i}function Ft(t){return at(t)?It(t,!0):Lt(t)}var Pt=F(Object,"create");var Dt=Object.prototype.hasOwnProperty;var Wt=Object.prototype.hasOwnProperty;function Ut(t){var e=-1,i=null==t?0:t.length;for(this.clear();++e<i;){var s=t[e];this.set(s[0],s[1])}}function qt(t,e){for(var i=t.length;i--;)if(tt(t[i][0],e))return i;return-1}Ut.prototype.clear=function(){this.__data__=Pt?Pt(null):{},this.size=0},Ut.prototype.delete=function(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e},Ut.prototype.get=function(t){var e=this.__data__;if(Pt){var i=e[t];return"__lodash_hash_undefined__"===i?void 0:i}return Dt.call(e,t)?e[t]:void 0},Ut.prototype.has=function(t){var e=this.__data__;return Pt?void 0!==e[t]:Wt.call(e,t)},Ut.prototype.set=function(t,e){var i=this.__data__;return this.size+=this.has(t)?0:1,i[t]=Pt&&void 0===e?"__lodash_hash_undefined__":e,this};var Nt=Array.prototype.splice;function Bt(t){var e=-1,i=null==t?0:t.length;for(this.clear();++e<i;){var s=t[e];this.set(s[0],s[1])}}Bt.prototype.clear=function(){this.__data__=[],this.size=0},Bt.prototype.delete=function(t){var e=this.__data__,i=qt(e,t);return!(i<0)&&(i==e.length-1?e.pop():Nt.call(e,i,1),--this.size,!0)},Bt.prototype.get=function(t){var e=this.__data__,i=qt(e,t);return i<0?void 0:e[i][1]},Bt.prototype.has=function(t){return qt(this.__data__,t)>-1},Bt.prototype.set=function(t,e){var i=this.__data__,s=qt(i,t);return s<0?(++this.size,i.push([t,e])):i[s][1]=e,this};var $t=F(l,"Map");function Ht(t,e){var i,s,n=t.__data__;return("string"==(s=typeof(i=e))||"number"==s||"symbol"==s||"boolean"==s?"__proto__"!==i:null===i)?n["string"==typeof e?"string":"hash"]:n.map}function Gt(t){var e=-1,i=null==t?0:t.length;for(this.clear();++e<i;){var s=t[e];this.set(s[0],s[1])}}function Jt(t,e){for(var i=-1,s=e.length,n=t.length;++i<s;)t[n+i]=e[i];return t}Gt.prototype.clear=function(){this.size=0,this.__data__={hash:new Ut,map:new($t||Bt),string:new Ut}},Gt.prototype.delete=function(t){var e=Ht(this,t).delete(t);return this.size-=e?1:0,e},Gt.prototype.get=function(t){return Ht(this,t).get(t)},Gt.prototype.has=function(t){return Ht(this,t).has(t)},Gt.prototype.set=function(t,e){var i=Ht(this,t),s=i.size;return i.set(t,e),this.size+=i.size==s?0:1,this};var Vt=Mt(Object.getPrototypeOf,Object),Kt=Function.prototype,Xt=Object.prototype,Zt=Kt.toString,Qt=Xt.hasOwnProperty,Yt=Zt.call(Object);function te(t){var e=this.__data__=new Bt(t);this.size=e.size}te.prototype.clear=function(){this.__data__=new Bt,this.size=0},te.prototype.delete=function(t){var e=this.__data__,i=e.delete(t);return this.size=e.size,i},te.prototype.get=function(t){return this.__data__.get(t)},te.prototype.has=function(t){return this.__data__.has(t)},te.prototype.set=function(t,e){var i=this.__data__;if(i instanceof Bt){var s=i.__data__;if(!$t||s.length<199)return s.push([t,e]),this.size=++i.size,this;i=this.__data__=new Gt(s)}return i.set(t,e),this.size=i.size,this};var ee="object"==typeof t&&t&&!t.nodeType&&t,ie=ee&&"object"==typeof module&&module&&!module.nodeType&&module,se=ie&&ie.exports===ee?l.Buffer:void 0,ne=se?se.allocUnsafe:void 0;function re(t,e){if(e)return t.slice();var i=t.length,s=ne?ne(i):new t.constructor(i);return t.copy(s),s}function oe(){return[]}var ae=Object.prototype.propertyIsEnumerable,ce=Object.getOwnPropertySymbols,he=ce?function(t){return null==t?[]:(t=Object(t),function(t,e){for(var i=-1,s=null==t?0:t.length,n=0,r=[];++i<s;){var o=t[i];e(o,i,t)&&(r[n++]=o)}return r}(ce(t),(function(e){return ae.call(t,e)})))}:oe;var le=Object.getOwnPropertySymbols?function(t){for(var e=[];t;)Jt(e,he(t)),t=Vt(t);return e}:oe;function ue(t,e,i){var s=e(t);return m(t)?s:Jt(s,i(t))}function de(t){return ue(t,xt,he)}function pe(t){return ue(t,Ft,le)}var fe=F(l,"DataView"),ye=F(l,"Promise"),ve=F(l,"Set"),ge="[object Map]",be="[object Promise]",we="[object Set]",me="[object WeakMap]",_e="[object DataView]",Se=k(fe),je=k($t),Ce=k(ye),Te=k(ve),Oe=k(P),Ae=b;(fe&&Ae(new fe(new ArrayBuffer(1)))!=_e||$t&&Ae(new $t)!=ge||ye&&Ae(ye.resolve())!=be||ve&&Ae(new ve)!=we||P&&Ae(new P)!=me)&&(Ae=function(t){var e=b(t),i="[object Object]"==e?t.constructor:void 0,s=i?k(i):"";if(s)switch(s){case Se:return _e;case je:return ge;case Ce:return be;case Te:return we;case Oe:return me}return e});var ke=Ae,Ie=Object.prototype.hasOwnProperty;var Me=l.Uint8Array;function Ee(t){var e=new t.constructor(t.byteLength);return new Me(e).set(new Me(t)),e}var Re=/\w*$/;var xe=u?u.prototype:void 0,ze=xe?xe.valueOf:void 0;function Le(t,e){var i=e?Ee(t.buffer):t.buffer;return new t.constructor(i,t.byteOffset,t.length)}function Fe(t,e,i){var s,n,r,o=t.constructor;switch(e){case"[object ArrayBuffer]":return Ee(t);case"[object Boolean]":case"[object Date]":return new o(+t);case"[object DataView]":return function(t,e){var i=e?Ee(t.buffer):t.buffer;return new t.constructor(i,t.byteOffset,t.byteLength)}(t,i);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return Le(t,i);case"[object Map]":case"[object Set]":return new o;case"[object Number]":case"[object String]":return new o(t);case"[object RegExp]":return(r=new(n=t).constructor(n.source,Re.exec(n))).lastIndex=n.lastIndex,r;case"[object Symbol]":return s=t,ze?Object(ze.call(s)):{}}}function Pe(t){return"function"!=typeof t.constructor||ht(t)?{}:W(Vt(t))}var De=Tt&&Tt.isMap,We=De?_t(De):function(t){return w(t)&&"[object Map]"==ke(t)};var Ue=Tt&&Tt.isSet,qe=Ue?_t(Ue):function(t){return w(t)&&"[object Set]"==ke(t)},Ne="[object Arguments]",Be="[object Function]",$e="[object Object]",He={};function Ge(t,e,i,s,n,r){var o,a=1&e,c=2&e,h=4&e;if(i&&(o=n?i(t,s,n,r):i(t)),void 0!==o)return o;if(!_(t))return t;var l=m(t);if(l){if(o=function(t){var e=t.length,i=new t.constructor(e);return e&&"string"==typeof t[0]&&Ie.call(t,"index")&&(i.index=t.index,i.input=t.input),i}(t),!a)return q(t,o)}else{var u=ke(t),d=u==Be||"[object GeneratorFunction]"==u;if(wt(t))return re(t,a);if(u==$e||u==Ne||d&&!n){if(o=c||d?{}:Pe(t),!a)return c?function(t,e){return st(t,le(t),e)}(t,function(t,e){return t&&st(e,Ft(e),t)}(o,t)):function(t,e){return st(t,he(t),e)}(t,function(t,e){return t&&st(e,xt(e),t)}(o,t))}else{if(!He[u])return n?t:{};o=Fe(t,u,a)}}r||(r=new te);var p=r.get(t);if(p)return p;r.set(t,o),qe(t)?t.forEach((function(s){o.add(Ge(s,e,i,s,t,r))})):We(t)&&t.forEach((function(s,n){o.set(n,Ge(s,e,i,n,t,r))}));var f=l?void 0:(h?c?pe:de:c?Ft:xt)(t);return function(t,e){for(var i=-1,s=null==t?0:t.length;++i<s&&!1!==e(t[i],i,t););}(f||t,(function(s,n){f&&(s=t[n=s]),it(o,n,Ge(s,e,i,n,t,r))})),o}He[Ne]=He["[object Array]"]=He["[object ArrayBuffer]"]=He["[object DataView]"]=He["[object Boolean]"]=He["[object Date]"]=He["[object Float32Array]"]=He["[object Float64Array]"]=He["[object Int8Array]"]=He["[object Int16Array]"]=He["[object Int32Array]"]=He["[object Map]"]=He["[object Number]"]=He[$e]=He["[object RegExp]"]=He["[object Set]"]=He["[object String]"]=He["[object Symbol]"]=He["[object Uint8Array]"]=He["[object Uint8ClampedArray]"]=He["[object Uint16Array]"]=He["[object Uint32Array]"]=!0,He["[object Error]"]=He[Be]=He["[object WeakMap]"]=!1;function Je(t){return Ge(t,5)}var Ve,Ke=function(t,e,i){for(var s=-1,n=Object(t),r=i(t),o=r.length;o--;){var a=r[Ve?o:++s];if(!1===e(n[a],a,n))break}return t};function Xe(t,e,i){(void 0!==i&&!tt(t[e],i)||void 0===i&&!(e in t))&&Y(t,e,i)}function Ze(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}function Qe(t,e,i,s,n,r,o){var a=Ze(t,i),c=Ze(e,i),h=o.get(c);if(h)Xe(t,i,h);else{var l,u=r?r(a,c,i+"",t,e,o):void 0,d=void 0===u;if(d){var p=m(c),f=!p&&wt(c),y=!p&&!f&&At(c);u=c,p||f||y?m(a)?u=a:w(l=a)&&at(l)?u=q(a):f?(d=!1,u=re(c,!0)):y?(d=!1,u=Le(c,!0)):u=[]:function(t){if(!w(t)||"[object Object]"!=b(t))return!1;var e=Vt(t);if(null===e)return!0;var i=Qt.call(e,"constructor")&&e.constructor;return"function"==typeof i&&i instanceof i&&Zt.call(i)==Yt}(c)||yt(c)?(u=a,yt(a)?u=function(t){return st(t,Ft(t))}(a):_(a)&&!j(a)||(u=Pe(c))):d=!1}d&&(o.set(c,u),n(u,c,s,r,o),o.delete(c)),Xe(t,i,u)}}function Ye(t,e,i,s,n){t!==e&&Ke(e,(function(r,o){if(n||(n=new te),_(r))Qe(t,e,o,i,Ye,s,n);else{var a=s?s(Ze(t,o),r,o+"",t,e,n):void 0;void 0===a&&(a=r),Xe(t,o,a)}}),Ft)}var ti,ei=(ti=function(t,e,i){Ye(t,e,i)},rt((function(t,e){var i=-1,s=e.length,n=s>1?e[s-1]:void 0,r=s>2?e[2]:void 0;for(n=ti.length>3&&"function"==typeof n?(s--,n):void 0,r&&function(t,e,i){if(!_(i))return!1;var s=typeof e;return!!("number"==s?at(i)&&Q(e,i.length):"string"==s&&e in i)&&tt(i[e],t)}(e[0],e[1],r)&&(n=s<3?void 0:n,s=1),t=Object(t);++i<s;){var o=e[i];o&&ti(t,o,i,n)}return t})));let ii=null;try{ii=localStorage.getItem("debug")||""}catch(t){"undefined"!=typeof window&&"undefined"!=typeof localStorage&&console.warn("Error checking window.debug")}const si=t=>ii&&new RegExp(ii).test(t)?(...e)=>console.log(t,...e):()=>{},ni=si("rpc:ClientManager");class ri{constructor(t){this.options=t,this.inflightCallsByKey={},this.interceptors={request:[],response:[]},this.addResponseInterceptor=t=>{if("function"!=typeof t)throw new Error("cannot add interceptor that is not a function");this.interceptors.response.push(t)},this.addRequestInterceptor=t=>{if("function"!=typeof t)throw new Error("cannot add interceptor that is not a function");this.interceptors.request.push(t)},this.clearCache=t=>{ni("clearCache"),this.cache&&(t?this.cache.setCachedResponse(t,void 0):this.cache.clearCache())},this.getCachedResponse=t=>{var e;return ni("getCachedResponse",t),null===(e=null==this?void 0:this.cache)||void 0===e?void 0:e.getCachedResponse(t)},this.getInFlightCallCount=()=>(ni("getInFlightCallCount"),Object.keys(this.inflightCallsByKey).length),this.manageClientRequest=t=>e(this,void 0,void 0,(function*(){ni("manageClientRequest",t);const i=yield this.interceptRequestMutator(t),s=a(i);if(this.inflightCallsByKey.hasOwnProperty(s))return ni("manageClientRequest using an existing in-flight call",s),this.inflightCallsByKey[s].then((e=>{const i=Je(e);return t.correlationId&&(i.correlationId=t.correlationId),i}));const n=(()=>e(this,void 0,void 0,(function*(){const t=yield this.sendRequestWithTransport(i),e=yield this.interceptResponseMutator(t,i);return this.cache&&e&&this.cache.setCachedResponse(i,e),e})))().then((t=>(delete this.inflightCallsByKey[s],t))).catch((t=>{throw delete this.inflightCallsByKey[s],t}));return this.inflightCallsByKey[s]=n,yield n})),this.setIdentity=t=>{ni("setIdentity",t),this.transports.forEach((e=>e.setIdentity(t)))},this.interceptRequestMutator=t=>e(this,void 0,void 0,(function*(){let e=t;if(this.interceptors.request.length){ni("interceptRequestMutator(), original request:",t);for(const t of this.interceptors.request)e=yield t(e)}return e})),this.interceptResponseMutator=(t,i)=>e(this,void 0,void 0,(function*(){let e=t;if(this.interceptors.response.length){ni("interceptResponseMutator",i,t);for(const s of this.interceptors.response)try{e=yield s(e,i)}catch(s){throw ni("caught response interceptor, request:",i,"original response:",t,"mutated response:",e),s}}return e})),this.sendRequestWithTransport=t=>e(this,void 0,void 0,(function*(){let e;ni("sendRequestWithTransport",t);let i=0;for(;!e&&this.transports[i];){const s=this.transports[i];if(s.isConnected()){ni(`sendRequestWithTransport trying ${this.transports[i].name}`,t);try{let i;const n=new Promise(((e,s)=>{i=setTimeout((()=>{s(new r(`Procedure ${t.procedure}`))}),this.options.deadlineMs)}));e=yield Promise.race([n,s.sendRequest(t)]).then((t=>(clearTimeout(i),t)))}catch(t){if(!(t instanceof r||t instanceof n))throw t;ni(`sending request with ${this.transports[i].name} failed, trying next transport`),i++}}else i++}if(!e&&!this.transports[i])throw new s(`Procedure ${t.procedure} did not get a response from any transports`);if(!e)throw new s(`Procedure ${t.procedure} did not get a response from the remote`);return e})),this.cache=t.cache,t.requestInterceptor&&this.interceptors.request.push(t.requestInterceptor),t.responseInterceptor&&this.interceptors.response.push(t.responseInterceptor),this.transports=t.transports}}class oi{constructor(t){this.cacheOptions=t}clearCache(){}getCachedResponse(t){}setCachedResponse(t,e){}}oi.DEFAULT_CACHE_MAX_AGE_MS=3e5,oi.DEFAULT_CACHE_MAX_SIZE=100;const ai="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,ci="function"==typeof AbortController?AbortController:class{constructor(){this.signal=new ui}abort(){this.signal.dispatchEvent("abort")}},hi="function"==typeof AbortSignal,li="function"==typeof ci.AbortSignal,ui=hi?AbortSignal:li?ci.AbortController:class{constructor(){this.aborted=!1,this._listeners=[]}dispatchEvent(t){if("abort"===t){this.aborted=!0;const e={type:t,target:this};this.onabort(e),this._listeners.forEach((t=>t(e)),this)}}onabort(){}addEventListener(t,e){"abort"===t&&this._listeners.push(e)}removeEventListener(t,e){"abort"===t&&(this._listeners=this._listeners.filter((t=>t!==e)))}},di=new Set,pi=(t,e)=>{const i=`LRU_CACHE_OPTION_${t}`;vi(i)&&gi(i,`${t} option`,`options.${e}`,Si)},fi=(t,e)=>{const i=`LRU_CACHE_METHOD_${t}`;if(vi(i)){const{prototype:s}=Si,{get:n}=Object.getOwnPropertyDescriptor(s,t);gi(i,`${t} method`,`cache.${e}()`,n)}},yi=(...t)=>{"object"==typeof process&&process&&"function"==typeof process.emitWarning?process.emitWarning(...t):console.error(...t)},vi=t=>!di.has(t),gi=(t,e,i,s)=>{di.add(t);yi(`The ${e} is deprecated. Please use ${i} instead.`,"DeprecationWarning",t,s)},bi=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),wi=t=>bi(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?mi:null:null;class mi extends Array{constructor(t){super(t),this.fill(0)}}class _i{constructor(t){if(0===t)return[];const e=wi(t);this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}}class Si{constructor(t={}){const{max:e=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:r,updateAgeOnHas:o,allowStale:a,dispose:c,disposeAfter:h,noDisposeOnSet:l,noUpdateTTL:u,maxSize:d=0,sizeCalculation:p,fetchMethod:f,fetchContext:y,noDeleteOnFetchRejection:v,noDeleteOnStaleGet:g}=t,{length:b,maxAge:w,stale:m}=t instanceof Si?{}:t;if(0!==e&&!bi(e))throw new TypeError("max option must be a nonnegative integer");const _=e?wi(e):Array;if(!_)throw new Error("invalid max value: "+e);if(this.max=e,this.maxSize=d,this.sizeCalculation=p||b,this.sizeCalculation){if(!this.maxSize)throw new TypeError("cannot set sizeCalculation without setting maxSize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(this.fetchMethod=f||null,this.fetchMethod&&"function"!=typeof this.fetchMethod)throw new TypeError("fetchMethod must be a function if specified");if(this.fetchContext=y,!this.fetchMethod&&void 0!==y)throw new TypeError("cannot set fetchContext without fetchMethod");if(this.keyMap=new Map,this.keyList=new Array(e).fill(null),this.valList=new Array(e).fill(null),this.next=new _(e),this.prev=new _(e),this.head=0,this.tail=0,this.free=new _i(e),this.initialFill=1,this.size=0,"function"==typeof c&&(this.dispose=c),"function"==typeof h?(this.disposeAfter=h,this.disposed=[]):(this.disposeAfter=null,this.disposed=null),this.noDisposeOnSet=!!l,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!v,0!==this.maxSize){if(!bi(this.maxSize))throw new TypeError("maxSize must be a positive integer if specified");this.initializeSizeTracking()}if(this.allowStale=!!a||!!m,this.noDeleteOnStaleGet=!!g,this.updateAgeOnGet=!!r,this.updateAgeOnHas=!!o,this.ttlResolution=bi(s)||0===s?s:1,this.ttlAutopurge=!!n,this.ttl=i||w||0,this.ttl){if(!bi(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.initializeTTLTracking()}if(0===this.max&&0===this.ttl&&0===this.maxSize)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.max&&!this.maxSize){const t="LRU_CACHE_UNBOUNDED";if(vi(t)){di.add(t);yi("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",t,Si)}}m&&pi("stale","allowStale"),w&&pi("maxAge","ttl"),b&&pi("length","sizeCalculation")}getRemainingTTL(t){return this.has(t,{updateAgeOnHas:!1})?1/0:0}initializeTTLTracking(){this.ttls=new mi(this.max),this.starts=new mi(this.max),this.setItemTTL=(t,e,i=ai.now())=>{if(this.starts[t]=0!==e?i:0,this.ttls[t]=e,0!==e&&this.ttlAutopurge){const i=setTimeout((()=>{this.isStale(t)&&this.delete(this.keyList[t])}),e+1);i.unref&&i.unref()}},this.updateItemAge=t=>{this.starts[t]=0!==this.ttls[t]?ai.now():0};let t=0;const e=()=>{const e=ai.now();if(this.ttlResolution>0){t=e;const i=setTimeout((()=>t=0),this.ttlResolution);i.unref&&i.unref()}return e};this.getRemainingTTL=i=>{const s=this.keyMap.get(i);return void 0===s?0:0===this.ttls[s]||0===this.starts[s]?1/0:this.starts[s]+this.ttls[s]-(t||e())},this.isStale=i=>0!==this.ttls[i]&&0!==this.starts[i]&&(t||e())-this.starts[i]>this.ttls[i]}updateItemAge(t){}setItemTTL(t,e,i){}isStale(t){return!1}initializeSizeTracking(){this.calculatedSize=0,this.sizes=new mi(this.max),this.removeItemSize=t=>{this.calculatedSize-=this.sizes[t],this.sizes[t]=0},this.requireSize=(t,e,i,s)=>{if(!bi(i)){if(!s)throw new TypeError("invalid size value (must be positive integer)");if("function"!=typeof s)throw new TypeError("sizeCalculation must be a function");if(i=s(e,t),!bi(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return i},this.addItemSize=(t,e)=>{this.sizes[t]=e;const i=this.maxSize-this.sizes[t];for(;this.calculatedSize>i;)this.evict(!0);this.calculatedSize+=this.sizes[t]}}removeItemSize(t){}addItemSize(t,e){}requireSize(t,e,i,s){if(i||s)throw new TypeError("cannot set size without setting maxSize on cache")}*indexes({allowStale:t=this.allowStale}={}){if(this.size)for(let e=this.tail;this.isValidIndex(e)&&(!t&&this.isStale(e)||(yield e),e!==this.head);)e=this.prev[e]}*rindexes({allowStale:t=this.allowStale}={}){if(this.size)for(let e=this.head;this.isValidIndex(e)&&(!t&&this.isStale(e)||(yield e),e!==this.tail);)e=this.next[e]}isValidIndex(t){return this.keyMap.get(this.keyList[t])===t}*entries(){for(const t of this.indexes())yield[this.keyList[t],this.valList[t]]}*rentries(){for(const t of this.rindexes())yield[this.keyList[t],this.valList[t]]}*keys(){for(const t of this.indexes())yield this.keyList[t]}*rkeys(){for(const t of this.rindexes())yield this.keyList[t]}*values(){for(const t of this.indexes())yield this.valList[t]}*rvalues(){for(const t of this.rindexes())yield this.valList[t]}[Symbol.iterator](){return this.entries()}find(t,e={}){for(const i of this.indexes())if(t(this.valList[i],this.keyList[i],this))return this.get(this.keyList[i],e)}forEach(t,e=this){for(const i of this.indexes())t.call(e,this.valList[i],this.keyList[i],this)}rforEach(t,e=this){for(const i of this.rindexes())t.call(e,this.valList[i],this.keyList[i],this)}get prune(){return fi("prune","purgeStale"),this.purgeStale}purgeStale(){let t=!1;for(const e of this.rindexes({allowStale:!0}))this.isStale(e)&&(this.delete(this.keyList[e]),t=!0);return t}dump(){const t=[];for(const e of this.indexes({allowStale:!0})){const i=this.keyList[e],s=this.valList[e],n={value:this.isBackgroundFetch(s)?s.__staleWhileFetching:s};if(this.ttls){n.ttl=this.ttls[e];const t=ai.now()-this.starts[e];n.start=Math.floor(Date.now()-t)}this.sizes&&(n.size=this.sizes[e]),t.unshift([i,n])}return t}load(t){this.clear();for(const[e,i]of t){if(i.start){const t=Date.now()-i.start;i.start=ai.now()-t}this.set(e,i.value,i)}}dispose(t,e,i){}set(t,e,{ttl:i=this.ttl,start:s,noDisposeOnSet:n=this.noDisposeOnSet,size:r=0,sizeCalculation:o=this.sizeCalculation,noUpdateTTL:a=this.noUpdateTTL}={}){if(r=this.requireSize(t,e,r,o),this.maxSize&&r>this.maxSize)return this;let c=0===this.size?void 0:this.keyMap.get(t);if(void 0===c)c=this.newIndex(),this.keyList[c]=t,this.valList[c]=e,this.keyMap.set(t,c),this.next[this.tail]=c,this.prev[c]=this.tail,this.tail=c,this.size++,this.addItemSize(c,r),a=!1;else{const i=this.valList[c];e!==i&&(this.isBackgroundFetch(i)?i.__abortController.abort():n||(this.dispose(i,t,"set"),this.disposeAfter&&this.disposed.push([i,t,"set"])),this.removeItemSize(c),this.valList[c]=e,this.addItemSize(c,r)),this.moveToTail(c)}if(0===i||0!==this.ttl||this.ttls||this.initializeTTLTracking(),a||this.setItemTTL(c,i,s),this.disposeAfter)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift());return this}newIndex(){return 0===this.size?this.tail:this.size===this.max&&0!==this.max?this.evict(!1):0!==this.free.length?this.free.pop():this.initialFill++}pop(){if(this.size){const t=this.valList[this.head];return this.evict(!0),t}}evict(t){const e=this.head,i=this.keyList[e],s=this.valList[e];return this.isBackgroundFetch(s)?s.__abortController.abort():(this.dispose(s,i,"evict"),this.disposeAfter&&this.disposed.push([s,i,"evict"])),this.removeItemSize(e),t&&(this.keyList[e]=null,this.valList[e]=null,this.free.push(e)),this.head=this.next[e],this.keyMap.delete(i),this.size--,e}has(t,{updateAgeOnHas:e=this.updateAgeOnHas}={}){const i=this.keyMap.get(t);return void 0!==i&&!this.isStale(i)&&(e&&this.updateItemAge(i),!0)}peek(t,{allowStale:e=this.allowStale}={}){const i=this.keyMap.get(t);if(void 0!==i&&(e||!this.isStale(i))){const t=this.valList[i];return this.isBackgroundFetch(t)?t.__staleWhileFetching:t}}backgroundFetch(t,e,i,s){const n=void 0===e?void 0:this.valList[e];if(this.isBackgroundFetch(n))return n;const r=new ci,o={signal:r.signal,options:i,context:s},a=new Promise((e=>e(this.fetchMethod(t,n,o)))).then((e=>(r.signal.aborted||this.set(t,e,o.options),e)),(s=>{if(this.valList[e]===a){!i.noDeleteOnFetchRejection||void 0===a.__staleWhileFetching?this.delete(t):this.valList[e]=a.__staleWhileFetching}if(a.__returned===a)throw s}));return a.__abortController=r,a.__staleWhileFetching=n,a.__returned=null,void 0===e?(this.set(t,a,o.options),e=this.keyMap.get(t)):this.valList[e]=a,a}isBackgroundFetch(t){return t&&"object"==typeof t&&"function"==typeof t.then&&Object.prototype.hasOwnProperty.call(t,"__staleWhileFetching")&&Object.prototype.hasOwnProperty.call(t,"__returned")&&(t.__returned===t||null===t.__returned)}async fetch(t,{allowStale:e=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,ttl:n=this.ttl,noDisposeOnSet:r=this.noDisposeOnSet,size:o=0,sizeCalculation:a=this.sizeCalculation,noUpdateTTL:c=this.noUpdateTTL,noDeleteOnFetchRejection:h=this.noDeleteOnFetchRejection,fetchContext:l=this.fetchContext,forceRefresh:u=!1}={}){if(!this.fetchMethod)return this.get(t,{allowStale:e,updateAgeOnGet:i,noDeleteOnStaleGet:s});const d={allowStale:e,updateAgeOnGet:i,noDeleteOnStaleGet:s,ttl:n,noDisposeOnSet:r,size:o,sizeCalculation:a,noUpdateTTL:c,noDeleteOnFetchRejection:h};let p=this.keyMap.get(t);if(void 0===p){const e=this.backgroundFetch(t,p,d,l);return e.__returned=e}{const s=this.valList[p];if(this.isBackgroundFetch(s))return e&&void 0!==s.__staleWhileFetching?s.__staleWhileFetching:s.__returned=s;if(!u&&!this.isStale(p))return this.moveToTail(p),i&&this.updateItemAge(p),s;const n=this.backgroundFetch(t,p,d,l);return e&&void 0!==n.__staleWhileFetching?n.__staleWhileFetching:n.__returned=n}}get(t,{allowStale:e=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet}={}){const n=this.keyMap.get(t);if(void 0!==n){const r=this.valList[n],o=this.isBackgroundFetch(r);if(this.isStale(n))return o?e?r.__staleWhileFetching:void 0:(s||this.delete(t),e?r:void 0);if(o)return;return this.moveToTail(n),i&&this.updateItemAge(n),r}}connect(t,e){this.prev[e]=t,this.next[t]=e}moveToTail(t){t!==this.tail&&(t===this.head?this.head=this.next[t]:this.connect(this.prev[t],this.next[t]),this.connect(this.tail,t),this.tail=t)}get del(){return fi("del","delete"),this.delete}delete(t){let e=!1;if(0!==this.size){const i=this.keyMap.get(t);if(void 0!==i)if(e=!0,1===this.size)this.clear();else{this.removeItemSize(i);const e=this.valList[i];this.isBackgroundFetch(e)?e.__abortController.abort():(this.dispose(e,t,"delete"),this.disposeAfter&&this.disposed.push([e,t,"delete"])),this.keyMap.delete(t),this.keyList[i]=null,this.valList[i]=null,i===this.tail?this.tail=this.prev[i]:i===this.head?this.head=this.next[i]:(this.next[this.prev[i]]=this.next[i],this.prev[this.next[i]]=this.prev[i]),this.size--,this.free.push(i)}}if(this.disposed)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift());return e}clear(){for(const t of this.rindexes({allowStale:!0})){const e=this.valList[t];if(this.isBackgroundFetch(e))e.__abortController.abort();else{const i=this.keyList[t];this.dispose(e,i,"delete"),this.disposeAfter&&this.disposed.push([e,i,"delete"])}}if(this.keyMap.clear(),this.valList.fill(null),this.keyList.fill(null),this.ttls&&(this.ttls.fill(0),this.starts.fill(0)),this.sizes&&this.sizes.fill(0),this.head=0,this.tail=0,this.initialFill=1,this.free.length=0,this.calculatedSize=0,this.size=0,this.disposed)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift())}get reset(){return fi("reset","clear"),this.clear}get length(){return((t,e)=>{const i=`LRU_CACHE_PROPERTY_${t}`;if(vi(i)){const{prototype:s}=Si,{get:n}=Object.getOwnPropertyDescriptor(s,t);gi(i,`${t} property`,`cache.${e}`,n)}})("length","size"),this.size}static get AbortController(){return ci}static get AbortSignal(){return ui}}var ji=Si;const Ci=si("rpc:InMemoryCache");class Ti{constructor(t){this.clearCache=()=>{var t;Ci("clearCache"),null===(t=this.cachedResponseByParams)||void 0===t||t.clear()},this.getCachedResponse=t=>{var e;Ci("getCachedResponse, key: ",t);let i=null===(e=this.cachedResponseByParams)||void 0===e?void 0:e.get(a(t));return"string"==typeof i&&(i=JSON.parse(i)),i},this.setCachedResponse=(t,e)=>{var i,s;Ci("setCachedResponse",t,e);const n=a(t);if(!e)return null===(i=this.cachedResponseByParams)||void 0===i?void 0:i.del(n);const r=Object.assign({},e);delete r.correlationId,null===(s=this.cachedResponseByParams)||void 0===s||s.set(n,r?JSON.stringify(r):void 0)},this.cachedResponseByParams=new ji({max:(null==t?void 0:t.cacheMaxSize)||Ti.DEFAULT_CACHE_MAX_SIZE,ttl:(null==t?void 0:t.cacheMaxAgeMs)||Ti.DEFAULT_CACHE_MAX_AGE_MS})}}Ti.DEFAULT_CACHE_MAX_AGE_MS=3e5,Ti.DEFAULT_CACHE_MAX_SIZE=100;class Oi{constructor(t){const{code:e,correlationId:i,data:s,message:n,success:r}=t;if("number"!=typeof e)throw new Error("code must be a number");if(this.code=e,i&&"string"!=typeof i)throw new Error("correlationId must be a string");if(this.correlationId=i,this.data=s,n&&"string"!=typeof n)throw new Error("message must be a string");if(this.message=n,"boolean"!=typeof r)throw new Error("success must be a boolean");this.success=r}}const Ai=si("rpc:HTTPTransport");class ki{constructor(t){this.options=t,this.networkIsConnected=!1,this.name="HttpTransport",this.isConnected=()=>{var t;return"undefined"!=typeof window?!!(null===(t=null===window||void 0===window?void 0:window.navigator)||void 0===t?void 0:t.onLine):this.networkIsConnected},this.sendRequest=t=>e(this,void 0,void 0,(function*(){Ai("sendRequest",t);const e=JSON.stringify(Object.assign({identity:this.identity},t)),i=yield null===window||void 0===window?void 0:window.fetch(this.host,{body:e,cache:"default",credentials:"omit",headers:{"Content-Type":"application/json"},method:"POST",mode:"cors",redirect:"follow",referrerPolicy:"origin"}),s=yield i.text();if(!s)throw new Error("No response received from remote");const n=JSON.parse(s);return new Oi(n)})),this.setIdentity=t=>{Ai("setIdentity",t),this.identity=t},this.host=t.host}}class Ii{constructor(t){this.reject=t=>{this.rejectPromise&&this.rejectPromise(t)},this.resolve=t=>{this.resolvePromise&&this.resolvePromise(t)},this.promise=new Promise(((i,s)=>e(this,void 0,void 0,(function*(){const e=setTimeout((()=>{s(new Error("PromiseWraper timeout"))}),t||3e4);this.rejectPromise=t=>{clearTimeout(e),s(t)},this.resolvePromise=t=>{clearTimeout(e),i(t)}}))))}}const Mi=t=>new Promise((e=>setTimeout(e,t))),Ei=si("rpc:WebSocketTransport");class Ri{constructor(t){this.options=t,this.connectedToRemote=!1,this.isWaitingForIdentityConfirmation=!1,this.pendingPromisesForResponse={},this.serverMessageHandlers=[],this.websocketId=void 0,this.name="WebSocketTransport",this.isConnected=()=>this.connectedToRemote&&!!this.websocket,this.sendClientMessageToServer=t=>{var e;let i=t;try{i=JSON.stringify({clientMessage:t})}catch(e){console.warn('WebSocketTransport.sendClientMessage() unable to stringify "msg"',t)}null===(e=this.websocket)||void 0===e||e.send(i)},this.sendRequest=t=>e(this,void 0,void 0,(function*(){for(Ei("sendRequest",t);this.isWaitingForIdentityConfirmation;)Ei("waiting for identity confirmation"),yield Mi(100);return this.sendCall(t)})),this.setIdentity=t=>e(this,void 0,void 0,(function*(){if(Ei("setIdentity",t),!t)return this.identity=void 0,void(yield this.resetConnection());this.identity=t,this.connectedToRemote?this.isWaitingForIdentityConfirmation?Ei('setIdentity returning early because "this.isWaitingForIdentityConfirmation=true"'):(this.isWaitingForIdentityConfirmation=!0,this.sendCall({identity:t}).then((()=>{Ei("setIdentity with remote complete")})).catch((t=>{Ei("setIdentity with remote error",t)})).finally((()=>{this.isWaitingForIdentityConfirmation=!1}))):Ei("setIdentity is not connected to remote")})),this.subscribeToServerMessages=t=>{this.serverMessageHandlers.push(t)},this.unsubscribeFromServerMessages=t=>{this.serverMessageHandlers=this.serverMessageHandlers.filter((e=>e!==t))},this.connect=()=>{if(Ei("connect",this.host),this.websocket)return void Ei("connect() returning early, websocket already exists");this.websocketId=Math.random(),this.websocket=new WebSocket(this.host);const t=this.websocket;t.onopen=()=>{console.info(`[${(new Date).toLocaleTimeString()}] WebSocket connected`),this.setConnectedToRemote(!0)},t.onmessage=t=>{this.handleWebSocketMsg(t)},t.onclose=t=>{this.connectedToRemote?console.info(`[${(new Date).toLocaleTimeString()}] WebSocket closed`,t.reason):Ei("WebSocket closed, it was not connected to the remote"),this.setConnectedToRemote(!1),this.isWaitingForIdentityConfirmation=!1,this.websocket=void 0,this.websocketId=void 0,Object.entries(this.pendingPromisesForResponse).forEach((([t,e])=>{e.reject(new n("Websocket disconnected"))})),t.wasClean||setTimeout((()=>{this.connect()}),1e3)},t.onerror=e=>{this.connectedToRemote?console.error("WebSocket encountered error: ",e):Ei("WebSocket errored, it was not connected to the remote"),t.close()}},this.disconnect=t=>{var e;Ei("disconnect"),this.setConnectedToRemote(!1),this.isWaitingForIdentityConfirmation=!1,null===(e=this.websocket)||void 0===e||e.close(1e3,t),this.websocket=void 0,this.websocketId=void 0},this.handleServerMessage=t=>{this.serverMessageHandlers.forEach((e=>{try{e(t.serverMessage)}catch(i){console.warn("WebSocketTransport.handleServerMessage() a serverMessageHandler errored when calling",t,"handler func:",e),console.error(i)}}))},this.handleWebSocketMsg=t=>{let e;Ei("handleWebSocketMsg",t);try{e=JSON.parse(t.data)}catch(t){console.error("error parsing WS msg",t)}if("serverMessage"in e)return void this.handleServerMessage(e);const i=new Oi(e);if(!i.correlationId)return void console.error("RPCClient WebSocketTransport received unexpected msg from the server, not correlationId found in response.",e);const s=this.pendingPromisesForResponse[i.correlationId];s?s.resolve(i):console.warn("rcvd WS msg/response that doesn't match any pending RPC's",e)},this.resetConnection=()=>e(this,void 0,void 0,(function*(){Ei("resetConnection"),this.disconnect("WebSocketTransport#resetConnection"),yield Mi(100),this.connect()})),this.sendCall=t=>e(this,void 0,void 0,(function*(){var e;Ei("sendCall",t);const i=Math.random().toString();t.correlationId=t.correlationId||i;let s=new Ii(Ri.DEFAULT_TIMEOUT_MS);return null===(e=this.websocket)||void 0===e||e.send(JSON.stringify(t)),this.pendingPromisesForResponse[t.correlationId]=s,yield s.promise.finally((()=>{delete this.pendingPromisesForResponse[t.correlationId]}))})),this.setConnectedToRemote=t=>{Ei(`setConnectedToRemote: ${t}`),this.connectedToRemote=t,this.options.onConnectionStatusChange&&this.options.onConnectionStatusChange(t),t&&this.identity&&this.setIdentity(this.identity)},Ei("new WebSocketTransport()"),this.host=t.host,this.connect()}}Ri.DEFAULT_TIMEOUT_MS=1e4;const xi=t=>{const e=t.split("::");return{procedure:e[1],scope:e[0]||"global",version:e[2]||"1"}};class zi{constructor(){this.events={},this.publish=(t,i)=>e(this,void 0,void 0,(function*(){const e=this.events[t];e&&e.forEach((function(t){t.call(t,i)}))})),this.subscribe=(t,e)=>{this.events[t]||(this.events[t]=[]),this.events[t].push(e)},this.unsubscribe=(t,e)=>{if(!this.events[t])return;let i=this.events[t].indexOf(e);this.events[t].splice(i)}}}const Li={HTTP_HOST_OR_TRANSPORT_REQUIRED:"http host or tansport is required",INTERCEPTOR_MUSTBE_FUNC:"interceptors must be a function"};class Fi{constructor(t){var s,n,r,o,c,h;if(this.options=t,this.webSocketConnectionChangeListeners=[],this.vent=new zi,this.onWebSocketConnectionStatusChange=t=>{this.options.onWebSocketConnectionStatusChange&&this.options.onWebSocketConnectionStatusChange(t),this.webSocketConnectionChangeListeners.forEach((e=>e(t)))},this.call=(t,s)=>e(this,void 0,void 0,(function*(){if(!t)throw new Error('RPCClient.call(request) requires a "request" param');let e;e="string"==typeof t?xi(t):t,s&&(e.args=s);const n=new i(e);if(!n.procedure&&!n.identity)throw new TypeError('RPCClient#call requires a "identity" or "procedure" prop and received neither');n.identity||(n.identity={}),n.identity=ei(Object.assign({},this.identity),n.identity);const r=yield this.callManager.manageClientRequest(n);if(!r.success)throw r;const o=a(e);return this.vent.publish(o,null==r?void 0:r.data),r})),this.clearCache=t=>{this.callManager.clearCache(t)},this.getCallCache=(t,e)=>{let i;i="string"==typeof t?xi(t):t,e&&(i.args=e);const s=this.callManager.getCachedResponse(i);if(s)return s},this.getIdentity=()=>this.identity?Je(this.identity):this.identity,this.getInFlightCallCount=()=>this.callManager.getInFlightCallCount(),this.getWebSocketConnected=()=>{var t;return!!(null===(t=null==this?void 0:this.webSocketTransport)||void 0===t?void 0:t.isConnected())},this.makeProcedure=t=>{const e=this;let i;return i="string"==typeof t?xi(t):t,function(t){return e.call(Object.assign(Object.assign({},i),{args:t}))}},this.registerResponseInterceptor=t=>{this.callManager.addResponseInterceptor(t)},this.registerRequestInterceptor=t=>{this.callManager.addRequestInterceptor(t)},this.registerWebSocketConnectionStatusChangeListener=t=>{this.webSocketConnectionChangeListeners.push(t)},this.sendClientMessageToServer=t=>{this.webSocketTransport?this.webSocketTransport.isConnected()?this.webSocketTransport.sendClientMessageToServer(t):console.info("RPCClient.sendClientMessageToServer() cannot send because the websocket is not connected"):console.warn("RPCClient.sendClientMessageToServer() unable to send because RPCClient has no websocket configuration")},this.setIdentity=t=>{let e=Je(t);this.identity=t,this.callManager.setIdentity(e)},this.setIdentityMetadata=t=>{var e;null!==(e=this.identity)&&void 0!==e||(this.identity={});const i=Je(this.identity);i.metadata=t,this.identity.metadata=t,this.callManager.setIdentity(i)},!(null===(s=null==t?void 0:t.hosts)||void 0===s?void 0:s.http)&&!(null===(n=null==t?void 0:t.transports)||void 0===n?void 0:n.http))throw new Error(Li.HTTP_HOST_OR_TRANSPORT_REQUIRED);if(t.requestInterceptor&&"function"!=typeof t.requestInterceptor)throw new Error(Li.INTERCEPTOR_MUSTBE_FUNC);if(t.responseInterceptor&&"function"!=typeof t.responseInterceptor)throw new Error(Li.INTERCEPTOR_MUSTBE_FUNC);let l;const u={cacheMaxAgeMs:null==t?void 0:t.cacheMaxAgeMs};l="browser"==t.cacheType?new oi(u):new Ti(u);const d=[];(null===(r=t.transports)||void 0===r?void 0:r.websocket)?d.push(t.transports.websocket):(null===(o=null==t?void 0:t.hosts)||void 0===o?void 0:o.websocket)&&(this.webSocketTransport=new Ri({host:t.hosts.websocket,onConnectionStatusChange:this.onWebSocketConnectionStatusChange}),d.push(this.webSocketTransport)),(null===(c=t.transports)||void 0===c?void 0:c.http)?d.push(t.transports.http):(null===(h=null==t?void 0:t.hosts)||void 0===h?void 0:h.http)&&(this.httpTransport=new ki({host:t.hosts.http}),d.push(this.httpTransport)),this.callManager=new ri({cache:l,deadlineMs:t.deadlineMs||Fi.DEFAULT_DEADLINE_MS,requestInterceptor:t.requestInterceptor,responseInterceptor:t.responseInterceptor,transports:d})}subscribe(t,e){const i="string"==typeof t.request?xi(t.request):t.request,s=a(Object.assign(Object.assign({},i),{args:t.args}));this.vent.subscribe(s,e)}unsubscribe(t,e){const i="string"==typeof t.request?xi(t.request):t.request,s=a(Object.assign(Object.assign({},i),{args:t.args}));this.vent.unsubscribe(s,e)}subscribeToServerMessages(t){this.webSocketTransport?this.webSocketTransport.subscribeToServerMessages(t):console.warn("RPCClient.subscribeToServerMessages() cannot subscribe because RPCClient has no websocket configuration")}unsubscribeFromServerMessages(t){var e;null===(e=this.webSocketTransport)||void 0===e||e.unsubscribeFromServerMessages(t)}}Fi.DEFAULT_DEADLINE_MS=1e4,t.RPCClient=Fi,t.RPCResponse=Oi,Object.defineProperty(t,"__esModule",{value:!0})})); | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).RPCClient={})}(this,(function(t){"use strict";function e(t,e,i,s){return new(i||(i=Promise))((function(n,r){function o(t){try{c(s.next(t))}catch(t){r(t)}}function a(t){try{c(s.throw(t))}catch(t){r(t)}}function c(t){var e;t.done?n(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,a)}c((s=s.apply(t,e||[])).next())}))}class i{constructor(t){const{args:e,correlationId:i,identity:s,procedure:n,scope:r,version:o}=t;if(this.args=e,i&&"string"!=typeof i)throw new Error("correlationId must be a string");if(this.correlationId=i||Math.random().toString(),s){if("object"!=typeof s)throw new Error("identity must be an object");if(s.authorization&&"string"!=typeof s.authorization)throw new Error("identity.authorization must be a string");if(s.deviceName&&"string"!=typeof s.deviceName)throw new Error("identity.deviceName must be a string");if(s.metadata&&"object"!=typeof s.metadata)throw new Error("identity.metadata must be a object");this.identity=s}if(n&&"string"!=typeof n)throw new Error("procedure must be string");if(this.procedure=n,r&&"string"!=typeof r)throw new Error("scope must be string");if(this.scope=r,o&&"string"!=typeof o)throw new Error("version must be string");this.version=o}}class s extends Error{}class n extends Error{}class r extends Error{}function o(t){if("[object Object]"!==Object.prototype.toString.call(t))return!1;const e=Object.getPrototypeOf(t);return null===e||e===Object.prototype}const a=t=>t.args?`${t.scope}${t.procedure}${t.version}${function(t,e){e||(e={}),"function"==typeof e&&(e={cmp:e});var i,s="boolean"==typeof e.cycles&&e.cycles,n=e.cmp&&(i=e.cmp,function(t){return function(e,s){var n={key:e,value:t[e]},r={key:s,value:t[s]};return i(n,r)}}),r=[];return function t(e){if(e&&e.toJSON&&"function"==typeof e.toJSON&&(e=e.toJSON()),void 0!==e){if("number"==typeof e)return isFinite(e)?""+e:"null";if("object"!=typeof e)return JSON.stringify(e);var i,o;if(Array.isArray(e)){for(o="[",i=0;i<e.length;i++)i&&(o+=","),o+=t(e[i])||"null";return o+"]"}if(null===e)return"null";if(-1!==r.indexOf(e)){if(s)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var a=r.push(e)-1,c=Object.keys(e).sort(n&&n(e));for(o="",i=0;i<c.length;i++){var h=c[i],l=t(e[h]);l&&(o&&(o+=","),o+=JSON.stringify(h)+":"+l)}return r.splice(a,1),"{"+o+"}"}}(t)}(function(t,e={}){if(!o(t)&&!Array.isArray(t))throw new TypeError("Expected a plain object or array");const{deep:i,compare:s}=e,n=[],r=[],a=t=>{const e=n.indexOf(t);if(-1!==e)return r[e];const i=[];return n.push(t),r.push(i),i.push(...t.map((t=>Array.isArray(t)?a(t):o(t)?c(t):t))),i},c=t=>{const e=n.indexOf(t);if(-1!==e)return r[e];const h={},l=Object.keys(t).sort(s);n.push(t),r.push(h);for(const e of l){const s=t[e];let n;n=i&&Array.isArray(s)?a(s):i&&o(s)?c(s):s,Object.defineProperty(h,e,Object.assign(Object.assign({},Object.getOwnPropertyDescriptor(t,e)),{value:n}))}return h};return Array.isArray(t)?i?a(t):t.slice():c(t)}(t.args||{},{deep:!0}))}`:`${t.scope}${t.procedure}${t.version}`;var c="object"==typeof global&&global&&global.Object===Object&&global,h="object"==typeof self&&self&&self.Object===Object&&self,l=c||h||Function("return this")(),u=l.Symbol,d=Object.prototype,p=d.hasOwnProperty,f=d.toString,y=u?u.toStringTag:void 0;var v=Object.prototype.toString;var g=u?u.toStringTag:void 0;function b(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":g&&g in Object(t)?function(t){var e=p.call(t,y),i=t[y];try{t[y]=void 0;var s=!0}catch(t){}var n=f.call(t);return s&&(e?t[y]=i:delete t[y]),n}(t):function(t){return v.call(t)}(t)}function w(t){return null!=t&&"object"==typeof t}var m=Array.isArray;function _(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}function S(t){return t}function j(t){if(!_(t))return!1;var e=b(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}var C,T=l["__core-js_shared__"],O=(C=/[^.]+$/.exec(T&&T.keys&&T.keys.IE_PROTO||""))?"Symbol(src)_1."+C:"";var A=Function.prototype.toString;function k(t){if(null!=t){try{return A.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var E=/^\[object .+?Constructor\]$/,I=Function.prototype,M=Object.prototype,x=I.toString,z=M.hasOwnProperty,R=RegExp("^"+x.call(z).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function L(t){return!(!_(t)||(e=t,O&&O in e))&&(j(t)?R:E).test(k(t));var e}function F(t,e){var i=function(t,e){return null==t?void 0:t[e]}(t,e);return L(i)?i:void 0}var P=F(l,"WeakMap"),D=Object.create,W=function(){function t(){}return function(e){if(!_(e))return{};if(D)return D(e);t.prototype=e;var i=new t;return t.prototype=void 0,i}}();function U(t,e,i){switch(i.length){case 0:return t.call(e);case 1:return t.call(e,i[0]);case 2:return t.call(e,i[0],i[1]);case 3:return t.call(e,i[0],i[1],i[2])}return t.apply(e,i)}function q(t,e){var i=-1,s=t.length;for(e||(e=Array(s));++i<s;)e[i]=t[i];return e}var N=Date.now;var B,$,H,G=function(){try{var t=F(Object,"defineProperty");return t({},"",{}),t}catch(t){}}(),J=G,V=J?function(t,e){return J(t,"toString",{configurable:!0,enumerable:!1,value:(i=e,function(){return i}),writable:!0});var i}:S,K=(B=V,$=0,H=0,function(){var t=N(),e=16-(t-H);if(H=t,e>0){if(++$>=800)return arguments[0]}else $=0;return B.apply(void 0,arguments)}),X=K;var Z=/^(?:0|[1-9]\d*)$/;function Q(t,e){var i=typeof t;return!!(e=null==e?9007199254740991:e)&&("number"==i||"symbol"!=i&&Z.test(t))&&t>-1&&t%1==0&&t<e}function Y(t,e,i){"__proto__"==e&&J?J(t,e,{configurable:!0,enumerable:!0,value:i,writable:!0}):t[e]=i}function tt(t,e){return t===e||t!=t&&e!=e}var et=Object.prototype.hasOwnProperty;function it(t,e,i){var s=t[e];et.call(t,e)&&tt(s,i)&&(void 0!==i||e in t)||Y(t,e,i)}function st(t,e,i,s){var n=!i;i||(i={});for(var r=-1,o=e.length;++r<o;){var a=e[r],c=s?s(i[a],t[a],a,i,t):void 0;void 0===c&&(c=t[a]),n?Y(i,a,c):it(i,a,c)}return i}var nt=Math.max;function rt(t,e){return X(function(t,e,i){return e=nt(void 0===e?t.length-1:e,0),function(){for(var s=arguments,n=-1,r=nt(s.length-e,0),o=Array(r);++n<r;)o[n]=s[e+n];n=-1;for(var a=Array(e+1);++n<e;)a[n]=s[n];return a[e]=i(o),U(t,this,a)}}(t,e,S),t+"")}function ot(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=9007199254740991}function at(t){return null!=t&&ot(t.length)&&!j(t)}var ct=Object.prototype;function ht(t){var e=t&&t.constructor;return t===("function"==typeof e&&e.prototype||ct)}function lt(t){return w(t)&&"[object Arguments]"==b(t)}var ut=Object.prototype,dt=ut.hasOwnProperty,pt=ut.propertyIsEnumerable,ft=lt(function(){return arguments}())?lt:function(t){return w(t)&&dt.call(t,"callee")&&!pt.call(t,"callee")},yt=ft;var vt="object"==typeof t&&t&&!t.nodeType&&t,gt=vt&&"object"==typeof module&&module&&!module.nodeType&&module,bt=gt&>.exports===vt?l.Buffer:void 0,wt=(bt?bt.isBuffer:void 0)||function(){return!1},mt={};function _t(t){return function(e){return t(e)}}mt["[object Float32Array]"]=mt["[object Float64Array]"]=mt["[object Int8Array]"]=mt["[object Int16Array]"]=mt["[object Int32Array]"]=mt["[object Uint8Array]"]=mt["[object Uint8ClampedArray]"]=mt["[object Uint16Array]"]=mt["[object Uint32Array]"]=!0,mt["[object Arguments]"]=mt["[object Array]"]=mt["[object ArrayBuffer]"]=mt["[object Boolean]"]=mt["[object DataView]"]=mt["[object Date]"]=mt["[object Error]"]=mt["[object Function]"]=mt["[object Map]"]=mt["[object Number]"]=mt["[object Object]"]=mt["[object RegExp]"]=mt["[object Set]"]=mt["[object String]"]=mt["[object WeakMap]"]=!1;var St="object"==typeof t&&t&&!t.nodeType&&t,jt=St&&"object"==typeof module&&module&&!module.nodeType&&module,Ct=jt&&jt.exports===St&&c.process,Tt=function(){try{var t=jt&&jt.require&&jt.require("util").types;return t||Ct&&Ct.binding&&Ct.binding("util")}catch(t){}}(),Ot=Tt&&Tt.isTypedArray,At=Ot?_t(Ot):function(t){return w(t)&&ot(t.length)&&!!mt[b(t)]},kt=Object.prototype.hasOwnProperty;function Et(t,e){var i=m(t),s=!i&&yt(t),n=!i&&!s&&wt(t),r=!i&&!s&&!n&&At(t),o=i||s||n||r,a=o?function(t,e){for(var i=-1,s=Array(t);++i<t;)s[i]=e(i);return s}(t.length,String):[],c=a.length;for(var h in t)!e&&!kt.call(t,h)||o&&("length"==h||n&&("offset"==h||"parent"==h)||r&&("buffer"==h||"byteLength"==h||"byteOffset"==h)||Q(h,c))||a.push(h);return a}function It(t,e){return function(i){return t(e(i))}}var Mt=It(Object.keys,Object),xt=Object.prototype.hasOwnProperty;function zt(t){return at(t)?Et(t):function(t){if(!ht(t))return Mt(t);var e=[];for(var i in Object(t))xt.call(t,i)&&"constructor"!=i&&e.push(i);return e}(t)}var Rt=Object.prototype.hasOwnProperty;function Lt(t){if(!_(t))return function(t){var e=[];if(null!=t)for(var i in Object(t))e.push(i);return e}(t);var e=ht(t),i=[];for(var s in t)("constructor"!=s||!e&&Rt.call(t,s))&&i.push(s);return i}function Ft(t){return at(t)?Et(t,!0):Lt(t)}var Pt=F(Object,"create");var Dt=Object.prototype.hasOwnProperty;var Wt=Object.prototype.hasOwnProperty;function Ut(t){var e=-1,i=null==t?0:t.length;for(this.clear();++e<i;){var s=t[e];this.set(s[0],s[1])}}function qt(t,e){for(var i=t.length;i--;)if(tt(t[i][0],e))return i;return-1}Ut.prototype.clear=function(){this.__data__=Pt?Pt(null):{},this.size=0},Ut.prototype.delete=function(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e},Ut.prototype.get=function(t){var e=this.__data__;if(Pt){var i=e[t];return"__lodash_hash_undefined__"===i?void 0:i}return Dt.call(e,t)?e[t]:void 0},Ut.prototype.has=function(t){var e=this.__data__;return Pt?void 0!==e[t]:Wt.call(e,t)},Ut.prototype.set=function(t,e){var i=this.__data__;return this.size+=this.has(t)?0:1,i[t]=Pt&&void 0===e?"__lodash_hash_undefined__":e,this};var Nt=Array.prototype.splice;function Bt(t){var e=-1,i=null==t?0:t.length;for(this.clear();++e<i;){var s=t[e];this.set(s[0],s[1])}}Bt.prototype.clear=function(){this.__data__=[],this.size=0},Bt.prototype.delete=function(t){var e=this.__data__,i=qt(e,t);return!(i<0)&&(i==e.length-1?e.pop():Nt.call(e,i,1),--this.size,!0)},Bt.prototype.get=function(t){var e=this.__data__,i=qt(e,t);return i<0?void 0:e[i][1]},Bt.prototype.has=function(t){return qt(this.__data__,t)>-1},Bt.prototype.set=function(t,e){var i=this.__data__,s=qt(i,t);return s<0?(++this.size,i.push([t,e])):i[s][1]=e,this};var $t=F(l,"Map");function Ht(t,e){var i,s,n=t.__data__;return("string"==(s=typeof(i=e))||"number"==s||"symbol"==s||"boolean"==s?"__proto__"!==i:null===i)?n["string"==typeof e?"string":"hash"]:n.map}function Gt(t){var e=-1,i=null==t?0:t.length;for(this.clear();++e<i;){var s=t[e];this.set(s[0],s[1])}}function Jt(t,e){for(var i=-1,s=e.length,n=t.length;++i<s;)t[n+i]=e[i];return t}Gt.prototype.clear=function(){this.size=0,this.__data__={hash:new Ut,map:new($t||Bt),string:new Ut}},Gt.prototype.delete=function(t){var e=Ht(this,t).delete(t);return this.size-=e?1:0,e},Gt.prototype.get=function(t){return Ht(this,t).get(t)},Gt.prototype.has=function(t){return Ht(this,t).has(t)},Gt.prototype.set=function(t,e){var i=Ht(this,t),s=i.size;return i.set(t,e),this.size+=i.size==s?0:1,this};var Vt=It(Object.getPrototypeOf,Object),Kt=Function.prototype,Xt=Object.prototype,Zt=Kt.toString,Qt=Xt.hasOwnProperty,Yt=Zt.call(Object);function te(t){var e=this.__data__=new Bt(t);this.size=e.size}te.prototype.clear=function(){this.__data__=new Bt,this.size=0},te.prototype.delete=function(t){var e=this.__data__,i=e.delete(t);return this.size=e.size,i},te.prototype.get=function(t){return this.__data__.get(t)},te.prototype.has=function(t){return this.__data__.has(t)},te.prototype.set=function(t,e){var i=this.__data__;if(i instanceof Bt){var s=i.__data__;if(!$t||s.length<199)return s.push([t,e]),this.size=++i.size,this;i=this.__data__=new Gt(s)}return i.set(t,e),this.size=i.size,this};var ee="object"==typeof t&&t&&!t.nodeType&&t,ie=ee&&"object"==typeof module&&module&&!module.nodeType&&module,se=ie&&ie.exports===ee?l.Buffer:void 0,ne=se?se.allocUnsafe:void 0;function re(t,e){if(e)return t.slice();var i=t.length,s=ne?ne(i):new t.constructor(i);return t.copy(s),s}function oe(){return[]}var ae=Object.prototype.propertyIsEnumerable,ce=Object.getOwnPropertySymbols,he=ce?function(t){return null==t?[]:(t=Object(t),function(t,e){for(var i=-1,s=null==t?0:t.length,n=0,r=[];++i<s;){var o=t[i];e(o,i,t)&&(r[n++]=o)}return r}(ce(t),(function(e){return ae.call(t,e)})))}:oe;var le=Object.getOwnPropertySymbols?function(t){for(var e=[];t;)Jt(e,he(t)),t=Vt(t);return e}:oe;function ue(t,e,i){var s=e(t);return m(t)?s:Jt(s,i(t))}function de(t){return ue(t,zt,he)}function pe(t){return ue(t,Ft,le)}var fe=F(l,"DataView"),ye=F(l,"Promise"),ve=F(l,"Set"),ge="[object Map]",be="[object Promise]",we="[object Set]",me="[object WeakMap]",_e="[object DataView]",Se=k(fe),je=k($t),Ce=k(ye),Te=k(ve),Oe=k(P),Ae=b;(fe&&Ae(new fe(new ArrayBuffer(1)))!=_e||$t&&Ae(new $t)!=ge||ye&&Ae(ye.resolve())!=be||ve&&Ae(new ve)!=we||P&&Ae(new P)!=me)&&(Ae=function(t){var e=b(t),i="[object Object]"==e?t.constructor:void 0,s=i?k(i):"";if(s)switch(s){case Se:return _e;case je:return ge;case Ce:return be;case Te:return we;case Oe:return me}return e});var ke=Ae,Ee=Object.prototype.hasOwnProperty;var Ie=l.Uint8Array;function Me(t){var e=new t.constructor(t.byteLength);return new Ie(e).set(new Ie(t)),e}var xe=/\w*$/;var ze=u?u.prototype:void 0,Re=ze?ze.valueOf:void 0;function Le(t,e){var i=e?Me(t.buffer):t.buffer;return new t.constructor(i,t.byteOffset,t.length)}function Fe(t,e,i){var s,n,r,o=t.constructor;switch(e){case"[object ArrayBuffer]":return Me(t);case"[object Boolean]":case"[object Date]":return new o(+t);case"[object DataView]":return function(t,e){var i=e?Me(t.buffer):t.buffer;return new t.constructor(i,t.byteOffset,t.byteLength)}(t,i);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return Le(t,i);case"[object Map]":case"[object Set]":return new o;case"[object Number]":case"[object String]":return new o(t);case"[object RegExp]":return(r=new(n=t).constructor(n.source,xe.exec(n))).lastIndex=n.lastIndex,r;case"[object Symbol]":return s=t,Re?Object(Re.call(s)):{}}}function Pe(t){return"function"!=typeof t.constructor||ht(t)?{}:W(Vt(t))}var De=Tt&&Tt.isMap,We=De?_t(De):function(t){return w(t)&&"[object Map]"==ke(t)};var Ue=Tt&&Tt.isSet,qe=Ue?_t(Ue):function(t){return w(t)&&"[object Set]"==ke(t)},Ne="[object Arguments]",Be="[object Function]",$e="[object Object]",He={};function Ge(t,e,i,s,n,r){var o,a=1&e,c=2&e,h=4&e;if(i&&(o=n?i(t,s,n,r):i(t)),void 0!==o)return o;if(!_(t))return t;var l=m(t);if(l){if(o=function(t){var e=t.length,i=new t.constructor(e);return e&&"string"==typeof t[0]&&Ee.call(t,"index")&&(i.index=t.index,i.input=t.input),i}(t),!a)return q(t,o)}else{var u=ke(t),d=u==Be||"[object GeneratorFunction]"==u;if(wt(t))return re(t,a);if(u==$e||u==Ne||d&&!n){if(o=c||d?{}:Pe(t),!a)return c?function(t,e){return st(t,le(t),e)}(t,function(t,e){return t&&st(e,Ft(e),t)}(o,t)):function(t,e){return st(t,he(t),e)}(t,function(t,e){return t&&st(e,zt(e),t)}(o,t))}else{if(!He[u])return n?t:{};o=Fe(t,u,a)}}r||(r=new te);var p=r.get(t);if(p)return p;r.set(t,o),qe(t)?t.forEach((function(s){o.add(Ge(s,e,i,s,t,r))})):We(t)&&t.forEach((function(s,n){o.set(n,Ge(s,e,i,n,t,r))}));var f=l?void 0:(h?c?pe:de:c?Ft:zt)(t);return function(t,e){for(var i=-1,s=null==t?0:t.length;++i<s&&!1!==e(t[i],i,t););}(f||t,(function(s,n){f&&(s=t[n=s]),it(o,n,Ge(s,e,i,n,t,r))})),o}He[Ne]=He["[object Array]"]=He["[object ArrayBuffer]"]=He["[object DataView]"]=He["[object Boolean]"]=He["[object Date]"]=He["[object Float32Array]"]=He["[object Float64Array]"]=He["[object Int8Array]"]=He["[object Int16Array]"]=He["[object Int32Array]"]=He["[object Map]"]=He["[object Number]"]=He[$e]=He["[object RegExp]"]=He["[object Set]"]=He["[object String]"]=He["[object Symbol]"]=He["[object Uint8Array]"]=He["[object Uint8ClampedArray]"]=He["[object Uint16Array]"]=He["[object Uint32Array]"]=!0,He["[object Error]"]=He[Be]=He["[object WeakMap]"]=!1;function Je(t){return Ge(t,5)}var Ve,Ke=function(t,e,i){for(var s=-1,n=Object(t),r=i(t),o=r.length;o--;){var a=r[Ve?o:++s];if(!1===e(n[a],a,n))break}return t};function Xe(t,e,i){(void 0!==i&&!tt(t[e],i)||void 0===i&&!(e in t))&&Y(t,e,i)}function Ze(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}function Qe(t,e,i,s,n,r,o){var a=Ze(t,i),c=Ze(e,i),h=o.get(c);if(h)Xe(t,i,h);else{var l,u=r?r(a,c,i+"",t,e,o):void 0,d=void 0===u;if(d){var p=m(c),f=!p&&wt(c),y=!p&&!f&&At(c);u=c,p||f||y?m(a)?u=a:w(l=a)&&at(l)?u=q(a):f?(d=!1,u=re(c,!0)):y?(d=!1,u=Le(c,!0)):u=[]:function(t){if(!w(t)||"[object Object]"!=b(t))return!1;var e=Vt(t);if(null===e)return!0;var i=Qt.call(e,"constructor")&&e.constructor;return"function"==typeof i&&i instanceof i&&Zt.call(i)==Yt}(c)||yt(c)?(u=a,yt(a)?u=function(t){return st(t,Ft(t))}(a):_(a)&&!j(a)||(u=Pe(c))):d=!1}d&&(o.set(c,u),n(u,c,s,r,o),o.delete(c)),Xe(t,i,u)}}function Ye(t,e,i,s,n){t!==e&&Ke(e,(function(r,o){if(n||(n=new te),_(r))Qe(t,e,o,i,Ye,s,n);else{var a=s?s(Ze(t,o),r,o+"",t,e,n):void 0;void 0===a&&(a=r),Xe(t,o,a)}}),Ft)}var ti,ei=(ti=function(t,e,i){Ye(t,e,i)},rt((function(t,e){var i=-1,s=e.length,n=s>1?e[s-1]:void 0,r=s>2?e[2]:void 0;for(n=ti.length>3&&"function"==typeof n?(s--,n):void 0,r&&function(t,e,i){if(!_(i))return!1;var s=typeof e;return!!("number"==s?at(i)&&Q(e,i.length):"string"==s&&e in i)&&tt(i[e],t)}(e[0],e[1],r)&&(n=s<3?void 0:n,s=1),t=Object(t);++i<s;){var o=e[i];o&&ti(t,o,i,n)}return t})));let ii=null;try{ii=localStorage.getItem("debug")||""}catch(t){"undefined"!=typeof window&&"undefined"!=typeof localStorage&&console.warn("Error checking window.debug")}const si=t=>ii&&new RegExp(ii).test(t)?(...e)=>console.log(t,...e):()=>{},ni=si("rpc:ClientManager");class ri{constructor(t){this.options=t,this.inflightCallsByKey={},this.interceptors={request:[],response:[]},this.addResponseInterceptor=t=>{if("function"!=typeof t)throw new Error("cannot add interceptor that is not a function");this.interceptors.response.push(t)},this.addRequestInterceptor=t=>{if("function"!=typeof t)throw new Error("cannot add interceptor that is not a function");this.interceptors.request.push(t)},this.clearCache=t=>{ni("clearCache"),this.cache&&(t?this.cache.setCachedResponse(t,void 0):this.cache.clearCache())},this.getCachedResponse=t=>{var e;return ni("getCachedResponse",t),null===(e=null==this?void 0:this.cache)||void 0===e?void 0:e.getCachedResponse(t)},this.getInFlightCallCount=()=>(ni("getInFlightCallCount"),Object.keys(this.inflightCallsByKey).length),this.manageClientRequest=t=>e(this,void 0,void 0,(function*(){ni("manageClientRequest",t);const i=yield this.interceptRequestMutator(t),s=a(i);if(this.inflightCallsByKey.hasOwnProperty(s))return ni("manageClientRequest using an existing in-flight call",s),this.inflightCallsByKey[s].then((e=>{const i=Je(e);return t.correlationId&&(i.correlationId=t.correlationId),i}));const n=(()=>e(this,void 0,void 0,(function*(){const t=yield this.sendRequestWithTransport(i),e=yield this.interceptResponseMutator(t,i);return this.cache&&e&&this.cache.setCachedResponse(i,e),e})))().then((t=>(delete this.inflightCallsByKey[s],t))).catch((t=>{throw delete this.inflightCallsByKey[s],t}));return this.inflightCallsByKey[s]=n,yield n})),this.setIdentity=t=>{ni("setIdentity",t),this.transports.forEach((e=>e.setIdentity(t)))},this.interceptRequestMutator=t=>e(this,void 0,void 0,(function*(){let e=t;if(this.interceptors.request.length){ni("interceptRequestMutator(), original request:",t);for(const t of this.interceptors.request)e=yield t(e)}return e})),this.interceptResponseMutator=(t,i)=>e(this,void 0,void 0,(function*(){let e=t;if(this.interceptors.response.length){ni("interceptResponseMutator",i,t);for(const s of this.interceptors.response)try{e=yield s(e,i)}catch(s){throw ni("caught response interceptor, request:",i,"original response:",t,"mutated response:",e),s}}return e})),this.sendRequestWithTransport=t=>e(this,void 0,void 0,(function*(){let e;ni("sendRequestWithTransport",t);let i=0;for(;!e&&this.transports[i];){const s=this.transports[i];if(s.isConnected()){ni(`sendRequestWithTransport trying ${this.transports[i].name}`,t);try{let i;const n=new Promise(((e,s)=>{i=setTimeout((()=>{s(new r(`Procedure ${t.procedure}`))}),this.options.deadlineMs)}));e=yield Promise.race([n,s.sendRequest(t)]).then((t=>(clearTimeout(i),t)))}catch(t){if(!(t instanceof r||t instanceof n))throw t;ni(`sending request with ${this.transports[i].name} failed, trying next transport`),i++}}else i++}if(!e&&!this.transports[i])throw new s(`Procedure ${t.procedure} did not get a response from any transports`);if(!e)throw new s(`Procedure ${t.procedure} did not get a response from the remote`);return e})),this.cache=t.cache,t.requestInterceptor&&this.interceptors.request.push(t.requestInterceptor),t.responseInterceptor&&this.interceptors.response.push(t.responseInterceptor),this.transports=t.transports}}class oi{constructor(t){this.cacheOptions=t}clearCache(){}getCachedResponse(t){}setCachedResponse(t,e){}}oi.DEFAULT_CACHE_MAX_AGE_MS=3e5,oi.DEFAULT_CACHE_MAX_SIZE=100;const ai="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,ci="function"==typeof AbortController?AbortController:class{constructor(){this.signal=new ui}abort(){this.signal.dispatchEvent("abort")}},hi="function"==typeof AbortSignal,li="function"==typeof ci.AbortSignal,ui=hi?AbortSignal:li?ci.AbortController:class{constructor(){this.aborted=!1,this._listeners=[]}dispatchEvent(t){if("abort"===t){this.aborted=!0;const e={type:t,target:this};this.onabort(e),this._listeners.forEach((t=>t(e)),this)}}onabort(){}addEventListener(t,e){"abort"===t&&this._listeners.push(e)}removeEventListener(t,e){"abort"===t&&(this._listeners=this._listeners.filter((t=>t!==e)))}},di=new Set,pi=(t,e)=>{const i=`LRU_CACHE_OPTION_${t}`;vi(i)&&gi(i,`${t} option`,`options.${e}`,Si)},fi=(t,e)=>{const i=`LRU_CACHE_METHOD_${t}`;if(vi(i)){const{prototype:s}=Si,{get:n}=Object.getOwnPropertyDescriptor(s,t);gi(i,`${t} method`,`cache.${e}()`,n)}},yi=(...t)=>{"object"==typeof process&&process&&"function"==typeof process.emitWarning?process.emitWarning(...t):console.error(...t)},vi=t=>!di.has(t),gi=(t,e,i,s)=>{di.add(t);yi(`The ${e} is deprecated. Please use ${i} instead.`,"DeprecationWarning",t,s)},bi=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),wi=t=>bi(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?mi:null:null;class mi extends Array{constructor(t){super(t),this.fill(0)}}class _i{constructor(t){if(0===t)return[];const e=wi(t);this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}}class Si{constructor(t={}){const{max:e=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:r,updateAgeOnHas:o,allowStale:a,dispose:c,disposeAfter:h,noDisposeOnSet:l,noUpdateTTL:u,maxSize:d=0,maxEntrySize:p=0,sizeCalculation:f,fetchMethod:y,fetchContext:v,noDeleteOnFetchRejection:g,noDeleteOnStaleGet:b}=t,{length:w,maxAge:m,stale:_}=t instanceof Si?{}:t;if(0!==e&&!bi(e))throw new TypeError("max option must be a nonnegative integer");const S=e?wi(e):Array;if(!S)throw new Error("invalid max value: "+e);if(this.max=e,this.maxSize=d,this.maxEntrySize=p||this.maxSize,this.sizeCalculation=f||w,this.sizeCalculation){if(!this.maxSize&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(this.fetchMethod=y||null,this.fetchMethod&&"function"!=typeof this.fetchMethod)throw new TypeError("fetchMethod must be a function if specified");if(this.fetchContext=v,!this.fetchMethod&&void 0!==v)throw new TypeError("cannot set fetchContext without fetchMethod");if(this.keyMap=new Map,this.keyList=new Array(e).fill(null),this.valList=new Array(e).fill(null),this.next=new S(e),this.prev=new S(e),this.head=0,this.tail=0,this.free=new _i(e),this.initialFill=1,this.size=0,"function"==typeof c&&(this.dispose=c),"function"==typeof h?(this.disposeAfter=h,this.disposed=[]):(this.disposeAfter=null,this.disposed=null),this.noDisposeOnSet=!!l,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!g,0!==this.maxEntrySize){if(0!==this.maxSize&&!bi(this.maxSize))throw new TypeError("maxSize must be a positive integer if specified");if(!bi(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.initializeSizeTracking()}if(this.allowStale=!!a||!!_,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!r,this.updateAgeOnHas=!!o,this.ttlResolution=bi(s)||0===s?s:1,this.ttlAutopurge=!!n,this.ttl=i||m||0,this.ttl){if(!bi(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.initializeTTLTracking()}if(0===this.max&&0===this.ttl&&0===this.maxSize)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.max&&!this.maxSize){const t="LRU_CACHE_UNBOUNDED";if(vi(t)){di.add(t);yi("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",t,Si)}}_&&pi("stale","allowStale"),m&&pi("maxAge","ttl"),w&&pi("length","sizeCalculation")}getRemainingTTL(t){return this.has(t,{updateAgeOnHas:!1})?1/0:0}initializeTTLTracking(){this.ttls=new mi(this.max),this.starts=new mi(this.max),this.setItemTTL=(t,e,i=ai.now())=>{if(this.starts[t]=0!==e?i:0,this.ttls[t]=e,0!==e&&this.ttlAutopurge){const i=setTimeout((()=>{this.isStale(t)&&this.delete(this.keyList[t])}),e+1);i.unref&&i.unref()}},this.updateItemAge=t=>{this.starts[t]=0!==this.ttls[t]?ai.now():0};let t=0;const e=()=>{const e=ai.now();if(this.ttlResolution>0){t=e;const i=setTimeout((()=>t=0),this.ttlResolution);i.unref&&i.unref()}return e};this.getRemainingTTL=i=>{const s=this.keyMap.get(i);return void 0===s?0:0===this.ttls[s]||0===this.starts[s]?1/0:this.starts[s]+this.ttls[s]-(t||e())},this.isStale=i=>0!==this.ttls[i]&&0!==this.starts[i]&&(t||e())-this.starts[i]>this.ttls[i]}updateItemAge(t){}setItemTTL(t,e,i){}isStale(t){return!1}initializeSizeTracking(){this.calculatedSize=0,this.sizes=new mi(this.max),this.removeItemSize=t=>{this.calculatedSize-=this.sizes[t],this.sizes[t]=0},this.requireSize=(t,e,i,s)=>{if(!bi(i)){if(!s)throw new TypeError("invalid size value (must be positive integer)");if("function"!=typeof s)throw new TypeError("sizeCalculation must be a function");if(i=s(e,t),!bi(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return i},this.addItemSize=(t,e)=>{this.sizes[t]=e;const i=this.maxSize-this.sizes[t];for(;this.calculatedSize>i;)this.evict(!0);this.calculatedSize+=this.sizes[t]}}removeItemSize(t){}addItemSize(t,e){}requireSize(t,e,i,s){if(i||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache")}*indexes({allowStale:t=this.allowStale}={}){if(this.size)for(let e=this.tail;this.isValidIndex(e)&&(!t&&this.isStale(e)||(yield e),e!==this.head);)e=this.prev[e]}*rindexes({allowStale:t=this.allowStale}={}){if(this.size)for(let e=this.head;this.isValidIndex(e)&&(!t&&this.isStale(e)||(yield e),e!==this.tail);)e=this.next[e]}isValidIndex(t){return this.keyMap.get(this.keyList[t])===t}*entries(){for(const t of this.indexes())yield[this.keyList[t],this.valList[t]]}*rentries(){for(const t of this.rindexes())yield[this.keyList[t],this.valList[t]]}*keys(){for(const t of this.indexes())yield this.keyList[t]}*rkeys(){for(const t of this.rindexes())yield this.keyList[t]}*values(){for(const t of this.indexes())yield this.valList[t]}*rvalues(){for(const t of this.rindexes())yield this.valList[t]}[Symbol.iterator](){return this.entries()}find(t,e={}){for(const i of this.indexes())if(t(this.valList[i],this.keyList[i],this))return this.get(this.keyList[i],e)}forEach(t,e=this){for(const i of this.indexes())t.call(e,this.valList[i],this.keyList[i],this)}rforEach(t,e=this){for(const i of this.rindexes())t.call(e,this.valList[i],this.keyList[i],this)}get prune(){return fi("prune","purgeStale"),this.purgeStale}purgeStale(){let t=!1;for(const e of this.rindexes({allowStale:!0}))this.isStale(e)&&(this.delete(this.keyList[e]),t=!0);return t}dump(){const t=[];for(const e of this.indexes({allowStale:!0})){const i=this.keyList[e],s=this.valList[e],n={value:this.isBackgroundFetch(s)?s.__staleWhileFetching:s};if(this.ttls){n.ttl=this.ttls[e];const t=ai.now()-this.starts[e];n.start=Math.floor(Date.now()-t)}this.sizes&&(n.size=this.sizes[e]),t.unshift([i,n])}return t}load(t){this.clear();for(const[e,i]of t){if(i.start){const t=Date.now()-i.start;i.start=ai.now()-t}this.set(e,i.value,i)}}dispose(t,e,i){}set(t,e,{ttl:i=this.ttl,start:s,noDisposeOnSet:n=this.noDisposeOnSet,size:r=0,sizeCalculation:o=this.sizeCalculation,noUpdateTTL:a=this.noUpdateTTL}={}){if(r=this.requireSize(t,e,r,o),this.maxEntrySize&&r>this.maxEntrySize)return this;let c=0===this.size?void 0:this.keyMap.get(t);if(void 0===c)c=this.newIndex(),this.keyList[c]=t,this.valList[c]=e,this.keyMap.set(t,c),this.next[this.tail]=c,this.prev[c]=this.tail,this.tail=c,this.size++,this.addItemSize(c,r),a=!1;else{const i=this.valList[c];e!==i&&(this.isBackgroundFetch(i)?i.__abortController.abort():n||(this.dispose(i,t,"set"),this.disposeAfter&&this.disposed.push([i,t,"set"])),this.removeItemSize(c),this.valList[c]=e,this.addItemSize(c,r)),this.moveToTail(c)}if(0===i||0!==this.ttl||this.ttls||this.initializeTTLTracking(),a||this.setItemTTL(c,i,s),this.disposeAfter)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift());return this}newIndex(){return 0===this.size?this.tail:this.size===this.max&&0!==this.max?this.evict(!1):0!==this.free.length?this.free.pop():this.initialFill++}pop(){if(this.size){const t=this.valList[this.head];return this.evict(!0),t}}evict(t){const e=this.head,i=this.keyList[e],s=this.valList[e];return this.isBackgroundFetch(s)?s.__abortController.abort():(this.dispose(s,i,"evict"),this.disposeAfter&&this.disposed.push([s,i,"evict"])),this.removeItemSize(e),t&&(this.keyList[e]=null,this.valList[e]=null,this.free.push(e)),this.head=this.next[e],this.keyMap.delete(i),this.size--,e}has(t,{updateAgeOnHas:e=this.updateAgeOnHas}={}){const i=this.keyMap.get(t);return void 0!==i&&!this.isStale(i)&&(e&&this.updateItemAge(i),!0)}peek(t,{allowStale:e=this.allowStale}={}){const i=this.keyMap.get(t);if(void 0!==i&&(e||!this.isStale(i))){const t=this.valList[i];return this.isBackgroundFetch(t)?t.__staleWhileFetching:t}}backgroundFetch(t,e,i,s){const n=void 0===e?void 0:this.valList[e];if(this.isBackgroundFetch(n))return n;const r=new ci,o={signal:r.signal,options:i,context:s},a=new Promise((e=>e(this.fetchMethod(t,n,o)))).then((e=>(r.signal.aborted||this.set(t,e,o.options),e)),(s=>{if(this.valList[e]===a){!i.noDeleteOnFetchRejection||void 0===a.__staleWhileFetching?this.delete(t):this.valList[e]=a.__staleWhileFetching}if(a.__returned===a)throw s}));return a.__abortController=r,a.__staleWhileFetching=n,a.__returned=null,void 0===e?(this.set(t,a,o.options),e=this.keyMap.get(t)):this.valList[e]=a,a}isBackgroundFetch(t){return t&&"object"==typeof t&&"function"==typeof t.then&&Object.prototype.hasOwnProperty.call(t,"__staleWhileFetching")&&Object.prototype.hasOwnProperty.call(t,"__returned")&&(t.__returned===t||null===t.__returned)}async fetch(t,{allowStale:e=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,ttl:n=this.ttl,noDisposeOnSet:r=this.noDisposeOnSet,size:o=0,sizeCalculation:a=this.sizeCalculation,noUpdateTTL:c=this.noUpdateTTL,noDeleteOnFetchRejection:h=this.noDeleteOnFetchRejection,fetchContext:l=this.fetchContext,forceRefresh:u=!1}={}){if(!this.fetchMethod)return this.get(t,{allowStale:e,updateAgeOnGet:i,noDeleteOnStaleGet:s});const d={allowStale:e,updateAgeOnGet:i,noDeleteOnStaleGet:s,ttl:n,noDisposeOnSet:r,size:o,sizeCalculation:a,noUpdateTTL:c,noDeleteOnFetchRejection:h};let p=this.keyMap.get(t);if(void 0===p){const e=this.backgroundFetch(t,p,d,l);return e.__returned=e}{const s=this.valList[p];if(this.isBackgroundFetch(s))return e&&void 0!==s.__staleWhileFetching?s.__staleWhileFetching:s.__returned=s;if(!u&&!this.isStale(p))return this.moveToTail(p),i&&this.updateItemAge(p),s;const n=this.backgroundFetch(t,p,d,l);return e&&void 0!==n.__staleWhileFetching?n.__staleWhileFetching:n.__returned=n}}get(t,{allowStale:e=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet}={}){const n=this.keyMap.get(t);if(void 0!==n){const r=this.valList[n],o=this.isBackgroundFetch(r);if(this.isStale(n))return o?e?r.__staleWhileFetching:void 0:(s||this.delete(t),e?r:void 0);if(o)return;return this.moveToTail(n),i&&this.updateItemAge(n),r}}connect(t,e){this.prev[e]=t,this.next[t]=e}moveToTail(t){t!==this.tail&&(t===this.head?this.head=this.next[t]:this.connect(this.prev[t],this.next[t]),this.connect(this.tail,t),this.tail=t)}get del(){return fi("del","delete"),this.delete}delete(t){let e=!1;if(0!==this.size){const i=this.keyMap.get(t);if(void 0!==i)if(e=!0,1===this.size)this.clear();else{this.removeItemSize(i);const e=this.valList[i];this.isBackgroundFetch(e)?e.__abortController.abort():(this.dispose(e,t,"delete"),this.disposeAfter&&this.disposed.push([e,t,"delete"])),this.keyMap.delete(t),this.keyList[i]=null,this.valList[i]=null,i===this.tail?this.tail=this.prev[i]:i===this.head?this.head=this.next[i]:(this.next[this.prev[i]]=this.next[i],this.prev[this.next[i]]=this.prev[i]),this.size--,this.free.push(i)}}if(this.disposed)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift());return e}clear(){for(const t of this.rindexes({allowStale:!0})){const e=this.valList[t];if(this.isBackgroundFetch(e))e.__abortController.abort();else{const i=this.keyList[t];this.dispose(e,i,"delete"),this.disposeAfter&&this.disposed.push([e,i,"delete"])}}if(this.keyMap.clear(),this.valList.fill(null),this.keyList.fill(null),this.ttls&&(this.ttls.fill(0),this.starts.fill(0)),this.sizes&&this.sizes.fill(0),this.head=0,this.tail=0,this.initialFill=1,this.free.length=0,this.calculatedSize=0,this.size=0,this.disposed)for(;this.disposed.length;)this.disposeAfter(...this.disposed.shift())}get reset(){return fi("reset","clear"),this.clear}get length(){return((t,e)=>{const i=`LRU_CACHE_PROPERTY_${t}`;if(vi(i)){const{prototype:s}=Si,{get:n}=Object.getOwnPropertyDescriptor(s,t);gi(i,`${t} property`,`cache.${e}`,n)}})("length","size"),this.size}static get AbortController(){return ci}static get AbortSignal(){return ui}}var ji=Si;const Ci=si("rpc:InMemoryCache");class Ti{constructor(t){this.clearCache=()=>{var t;Ci("clearCache"),null===(t=this.cachedResponseByParams)||void 0===t||t.clear()},this.getCachedResponse=t=>{var e;Ci("getCachedResponse, key: ",t);let i=null===(e=this.cachedResponseByParams)||void 0===e?void 0:e.get(a(t));return"string"==typeof i&&(i=JSON.parse(i)),i},this.setCachedResponse=(t,e)=>{var i,s;Ci("setCachedResponse",t,e);const n=a(t);if(!e)return null===(i=this.cachedResponseByParams)||void 0===i?void 0:i.del(n);const r=Object.assign({},e);delete r.correlationId,null===(s=this.cachedResponseByParams)||void 0===s||s.set(n,r?JSON.stringify(r):void 0)},this.cachedResponseByParams=new ji({max:(null==t?void 0:t.cacheMaxSize)||Ti.DEFAULT_CACHE_MAX_SIZE,ttl:(null==t?void 0:t.cacheMaxAgeMs)||Ti.DEFAULT_CACHE_MAX_AGE_MS})}}Ti.DEFAULT_CACHE_MAX_AGE_MS=3e5,Ti.DEFAULT_CACHE_MAX_SIZE=100;class Oi{constructor(t){const{code:e,correlationId:i,data:s,message:n,success:r}=t;if("number"!=typeof e)throw new Error("code must be a number");if(this.code=e,i&&"string"!=typeof i)throw new Error("correlationId must be a string");if(this.correlationId=i,this.data=s,n&&"string"!=typeof n)throw new Error("message must be a string");if(this.message=n,"boolean"!=typeof r)throw new Error("success must be a boolean");this.success=r}}const Ai=si("rpc:HTTPTransport");class ki{constructor(t){this.options=t,this.networkIsConnected=!1,this.name="HttpTransport",this.isConnected=()=>{var t;return"undefined"!=typeof window?!!(null===(t=null===window||void 0===window?void 0:window.navigator)||void 0===t?void 0:t.onLine):this.networkIsConnected},this.sendRequest=t=>e(this,void 0,void 0,(function*(){Ai("sendRequest",t);const e=JSON.stringify(Object.assign({identity:this.identity},t)),i=yield null===window||void 0===window?void 0:window.fetch(this.host,{body:e,cache:"default",credentials:"omit",headers:{"Content-Type":"application/json"},method:"POST",mode:"cors",redirect:"follow",referrerPolicy:"origin"}),s=yield i.text();if(!s)throw new Error("No response received from remote");const n=JSON.parse(s);return new Oi(n)})),this.setIdentity=t=>{Ai("setIdentity",t),this.identity=t},this.host=t.host}}class Ei{constructor(t){this.reject=t=>{this.rejectPromise&&this.rejectPromise(t)},this.resolve=t=>{this.resolvePromise&&this.resolvePromise(t)},this.promise=new Promise(((i,s)=>e(this,void 0,void 0,(function*(){const e=setTimeout((()=>{s(new Error("PromiseWraper timeout"))}),t||3e4);this.rejectPromise=t=>{clearTimeout(e),s(t)},this.resolvePromise=t=>{clearTimeout(e),i(t)}}))))}}const Ii=t=>new Promise((e=>setTimeout(e,t))),Mi=si("rpc:WebSocketTransport");class xi{constructor(t){this.options=t,this.connectedToRemote=!1,this.isWaitingForIdentityConfirmation=!1,this.pendingPromisesForResponse={},this.serverMessageHandlers=[],this.websocketId=void 0,this.name="WebSocketTransport",this.isConnected=()=>this.connectedToRemote&&!!this.websocket,this.sendClientMessageToServer=t=>{var e;let i=t;try{i=JSON.stringify({clientMessage:t})}catch(e){console.warn('WebSocketTransport.sendClientMessage() unable to stringify "msg"',t)}null===(e=this.websocket)||void 0===e||e.send(i)},this.sendRequest=t=>e(this,void 0,void 0,(function*(){for(Mi("sendRequest",t);this.isWaitingForIdentityConfirmation;)Mi("waiting for identity confirmation"),yield Ii(100);return this.sendCall(t)})),this.setIdentity=t=>e(this,void 0,void 0,(function*(){if(Mi("setIdentity",t),!t)return this.identity=void 0,void(yield this.resetConnection());this.identity=t,this.connectedToRemote?this.isWaitingForIdentityConfirmation?Mi('setIdentity returning early because "this.isWaitingForIdentityConfirmation=true"'):(this.isWaitingForIdentityConfirmation=!0,this.sendCall({identity:t}).then((()=>{Mi("setIdentity with remote complete")})).catch((t=>{Mi("setIdentity with remote error",t)})).finally((()=>{this.isWaitingForIdentityConfirmation=!1}))):Mi("setIdentity is not connected to remote")})),this.subscribeToServerMessages=t=>{this.serverMessageHandlers.push(t)},this.unsubscribeFromServerMessages=t=>{this.serverMessageHandlers=this.serverMessageHandlers.filter((e=>e!==t))},this.connect=()=>{if(Mi("connect",this.host),this.websocket)return void Mi("connect() returning early, websocket already exists");this.websocketId=Math.random(),this.websocket=new WebSocket(this.host);const t=this.websocket;t.onopen=()=>{console.info(`[${(new Date).toLocaleTimeString()}] WebSocket connected`),this.setConnectedToRemote(!0)},t.onmessage=t=>{this.handleWebSocketMsg(t)},t.onclose=t=>{this.connectedToRemote?console.info(`[${(new Date).toLocaleTimeString()}] WebSocket closed`,t.reason):Mi("WebSocket closed, it was not connected to the remote"),this.setConnectedToRemote(!1),this.isWaitingForIdentityConfirmation=!1,this.websocket=void 0,this.websocketId=void 0,Object.entries(this.pendingPromisesForResponse).forEach((([t,e])=>{e.reject(new n("Websocket disconnected"))})),t.wasClean||setTimeout((()=>{this.connect()}),1e3)},t.onerror=e=>{this.connectedToRemote?console.error("WebSocket encountered error: ",e):Mi("WebSocket errored, it was not connected to the remote"),t.close()}},this.disconnect=t=>{var e;Mi("disconnect"),this.setConnectedToRemote(!1),this.isWaitingForIdentityConfirmation=!1,null===(e=this.websocket)||void 0===e||e.close(1e3,t),this.websocket=void 0,this.websocketId=void 0},this.handleServerMessage=t=>{this.serverMessageHandlers.forEach((e=>{try{e(t.serverMessage)}catch(i){console.warn("WebSocketTransport.handleServerMessage() a serverMessageHandler errored when calling",t,"handler func:",e),console.error(i)}}))},this.handleWebSocketMsg=t=>{let e;Mi("handleWebSocketMsg",t);try{e=JSON.parse(t.data)}catch(t){console.error("error parsing WS msg",t)}if("serverMessage"in e)return void this.handleServerMessage(e);const i=new Oi(e);if(!i.correlationId)return void console.error("RPCClient WebSocketTransport received unexpected msg from the server, not correlationId found in response.",e);const s=this.pendingPromisesForResponse[i.correlationId];s?s.resolve(i):console.warn("rcvd WS msg/response that doesn't match any pending RPC's",e)},this.resetConnection=()=>e(this,void 0,void 0,(function*(){Mi("resetConnection"),this.disconnect("WebSocketTransport#resetConnection"),yield Ii(100),this.connect()})),this.sendCall=t=>e(this,void 0,void 0,(function*(){var e;Mi("sendCall",t);const i=Math.random().toString();t.correlationId=t.correlationId||i;let s=new Ei(xi.DEFAULT_TIMEOUT_MS);return null===(e=this.websocket)||void 0===e||e.send(JSON.stringify(t)),this.pendingPromisesForResponse[t.correlationId]=s,yield s.promise.finally((()=>{delete this.pendingPromisesForResponse[t.correlationId]}))})),this.setConnectedToRemote=t=>{Mi(`setConnectedToRemote: ${t}`),this.connectedToRemote=t,this.options.onConnectionStatusChange&&this.options.onConnectionStatusChange(t),t&&this.identity&&this.setIdentity(this.identity)},Mi("new WebSocketTransport()"),this.host=t.host,this.connect()}}xi.DEFAULT_TIMEOUT_MS=1e4;const zi=t=>{const e=t.split("::");return{procedure:e[1],scope:e[0]||"global",version:e[2]||"1"}};class Ri{constructor(){this.events={},this.publish=(t,i)=>e(this,void 0,void 0,(function*(){const e=this.events[t];e&&e.forEach((function(t){t.call(t,i)}))})),this.subscribe=(t,e)=>{this.events[t]||(this.events[t]=[]),this.events[t].push(e)},this.unsubscribe=(t,e)=>{if(!this.events[t])return;let i=this.events[t].indexOf(e);this.events[t].splice(i)}}}const Li={HTTP_HOST_OR_TRANSPORT_REQUIRED:"http host or tansport is required",INTERCEPTOR_MUSTBE_FUNC:"interceptors must be a function"};class Fi{constructor(t){var s,n,r,o,c,h;if(this.options=t,this.webSocketConnectionChangeListeners=[],this.vent=new Ri,this.onWebSocketConnectionStatusChange=t=>{this.options.onWebSocketConnectionStatusChange&&this.options.onWebSocketConnectionStatusChange(t),this.webSocketConnectionChangeListeners.forEach((e=>e(t)))},this.call=(t,s)=>e(this,void 0,void 0,(function*(){if(!t)throw new Error('RPCClient.call(request) requires a "request" param');let e;e="string"==typeof t?zi(t):t,s&&(e.args=s);const n=new i(e);if(!n.procedure&&!n.identity)throw new TypeError('RPCClient#call requires a "identity" or "procedure" prop and received neither');n.identity||(n.identity={}),n.identity=ei(Object.assign({},this.identity),n.identity);const r=yield this.callManager.manageClientRequest(n);if(!r.success)throw r;const o=a(e);return this.vent.publish(o,null==r?void 0:r.data),r})),this.clearCache=t=>{this.callManager.clearCache(t)},this.getCallCache=(t,e)=>{let i;i="string"==typeof t?zi(t):t,e&&(i.args=e);const s=this.callManager.getCachedResponse(i);if(s)return s},this.getIdentity=()=>this.identity?Je(this.identity):this.identity,this.getInFlightCallCount=()=>this.callManager.getInFlightCallCount(),this.getWebSocketConnected=()=>{var t;return!!(null===(t=null==this?void 0:this.webSocketTransport)||void 0===t?void 0:t.isConnected())},this.makeProcedure=t=>{const e=this;let i;return i="string"==typeof t?zi(t):t,function(t){return e.call(Object.assign(Object.assign({},i),{args:t}))}},this.registerResponseInterceptor=t=>{this.callManager.addResponseInterceptor(t)},this.registerRequestInterceptor=t=>{this.callManager.addRequestInterceptor(t)},this.registerWebSocketConnectionStatusChangeListener=t=>{this.webSocketConnectionChangeListeners.push(t)},this.sendClientMessageToServer=t=>{this.webSocketTransport?this.webSocketTransport.isConnected()?this.webSocketTransport.sendClientMessageToServer(t):console.info("RPCClient.sendClientMessageToServer() cannot send because the websocket is not connected"):console.warn("RPCClient.sendClientMessageToServer() unable to send because RPCClient has no websocket configuration")},this.setIdentity=t=>{let e=Je(t);this.identity=t,this.callManager.setIdentity(e)},this.setIdentityMetadata=t=>{var e;null!==(e=this.identity)&&void 0!==e||(this.identity={});const i=Je(this.identity);i.metadata=t,this.identity.metadata=t,this.callManager.setIdentity(i)},!(null===(s=null==t?void 0:t.hosts)||void 0===s?void 0:s.http)&&!(null===(n=null==t?void 0:t.transports)||void 0===n?void 0:n.http))throw new Error(Li.HTTP_HOST_OR_TRANSPORT_REQUIRED);if(t.requestInterceptor&&"function"!=typeof t.requestInterceptor)throw new Error(Li.INTERCEPTOR_MUSTBE_FUNC);if(t.responseInterceptor&&"function"!=typeof t.responseInterceptor)throw new Error(Li.INTERCEPTOR_MUSTBE_FUNC);let l;const u={cacheMaxAgeMs:null==t?void 0:t.cacheMaxAgeMs};l="browser"==t.cacheType?new oi(u):new Ti(u);const d=[];(null===(r=t.transports)||void 0===r?void 0:r.websocket)?d.push(t.transports.websocket):(null===(o=null==t?void 0:t.hosts)||void 0===o?void 0:o.websocket)&&(this.webSocketTransport=new xi({host:t.hosts.websocket,onConnectionStatusChange:this.onWebSocketConnectionStatusChange}),d.push(this.webSocketTransport)),(null===(c=t.transports)||void 0===c?void 0:c.http)?d.push(t.transports.http):(null===(h=null==t?void 0:t.hosts)||void 0===h?void 0:h.http)&&(this.httpTransport=new ki({host:t.hosts.http}),d.push(this.httpTransport)),this.callManager=new ri({cache:l,deadlineMs:t.deadlineMs||Fi.DEFAULT_DEADLINE_MS,requestInterceptor:t.requestInterceptor,responseInterceptor:t.responseInterceptor,transports:d})}subscribe(t,e){const i="string"==typeof t.request?zi(t.request):t.request,s=a(Object.assign(Object.assign({},i),{args:t.args}));this.vent.subscribe(s,e)}unsubscribe(t,e){const i="string"==typeof t.request?zi(t.request):t.request,s=a(Object.assign(Object.assign({},i),{args:t.args}));this.vent.unsubscribe(s,e)}subscribeToServerMessages(t){this.webSocketTransport?this.webSocketTransport.subscribeToServerMessages(t):console.warn("RPCClient.subscribeToServerMessages() cannot subscribe because RPCClient has no websocket configuration")}unsubscribeFromServerMessages(t){var e;null===(e=this.webSocketTransport)||void 0===e||e.unsubscribeFromServerMessages(t)}}Fi.DEFAULT_DEADLINE_MS=1e4,t.RPCClient=Fi,t.RPCResponse=Oi,Object.defineProperty(t,"__esModule",{value:!0})})); | ||
//# sourceMappingURL=umd.js.map |
{ | ||
"name": "@therms/rpc-client", | ||
"version": "2.10.0", | ||
"version": "2.10.1", | ||
"description": "RPC framework, browser client lib", | ||
@@ -5,0 +5,0 @@ "private": false, |
@@ -22,4 +22,2 @@ import autoExternal from 'rollup-plugin-auto-external' | ||
format: 'es', | ||
preserveModules: true, | ||
preserveModulesRoot: 'src/', | ||
sourcemap: true, | ||
@@ -45,7 +43,3 @@ }, | ||
plugins: [ | ||
commonjs({ | ||
// non-CommonJS modules will be ignored, but you can also | ||
// specifically include/exclude files | ||
// include: ['./index.js', 'node_modules/**'], | ||
}), | ||
commonjs(), | ||
@@ -52,0 +46,0 @@ nodeResolve(), |
@@ -9,6 +9,2 @@ { | ||
"module": "ES2015" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, | ||
"lib": [ | ||
"ESNext", | ||
"dom" | ||
] /* Specify library files to be included in the compilation. */, | ||
"allowJs": true /* Allow javascript files to be compiled. */, | ||
@@ -15,0 +11,0 @@ "checkJs": true /* Report errors in .js files. */, |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
488371
73
2718