cross-tab-worker-databus 0.21.57 → 0.21.59
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/README.md +1 -1
- package/README.zh.md +1 -1
- package/dist/centrifuge-session.d.ts.map +1 -1
- package/dist/centrifuge.js +1 -1
- package/dist/centrifuge.js.map +2 -2
- package/dist/centrifuge.shared.worker.js +1682 -644
- package/dist/centrifuge.shared.worker.js.map +3 -3
- package/dist/centrifuge.worker.js +1682 -644
- package/dist/centrifuge.worker.js.map +3 -3
- package/dist/{chunk-ZH7VP3IY.js → chunk-SGZG6775.js} +3 -3
- package/dist/chunk-SGZG6775.js.map +7 -0
- package/dist/cjs/centrifuge.cjs +2 -2
- package/dist/cjs/centrifuge.cjs.map +2 -2
- package/dist/cjs/index.cjs +2 -2
- package/dist/cjs/index.cjs.map +2 -2
- package/dist/core/environment.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/docs/api.md +4 -0
- package/docs/configuration.md +1 -1
- package/docs/roadmap.md +1 -1
- package/docs/zh/api.md +4 -0
- package/docs/zh/configuration.md +1 -1
- package/docs/zh/roadmap.md +1 -1
- package/package.json +13 -13
- package/dist/chunk-ZH7VP3IY.js.map +0 -7
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../node_modules/.pnpm/centrifuge@5.
|
|
4
|
-
"sourcesContent": ["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\r\n\r\n\r\nfunction __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nvar events = {exports: {}};\n\nvar hasRequiredEvents;\n\nfunction requireEvents () {\n\tif (hasRequiredEvents) return events.exports;\n\thasRequiredEvents = 1;\n\n\tvar R = typeof Reflect === 'object' ? Reflect : null;\n\tvar ReflectApply = R && typeof R.apply === 'function'\n\t ? R.apply\n\t : function ReflectApply(target, receiver, args) {\n\t return Function.prototype.apply.call(target, receiver, args);\n\t };\n\n\tvar ReflectOwnKeys;\n\tif (R && typeof R.ownKeys === 'function') {\n\t ReflectOwnKeys = R.ownKeys;\n\t} else if (Object.getOwnPropertySymbols) {\n\t ReflectOwnKeys = function ReflectOwnKeys(target) {\n\t return Object.getOwnPropertyNames(target)\n\t .concat(Object.getOwnPropertySymbols(target));\n\t };\n\t} else {\n\t ReflectOwnKeys = function ReflectOwnKeys(target) {\n\t return Object.getOwnPropertyNames(target);\n\t };\n\t}\n\n\tfunction ProcessEmitWarning(warning) {\n\t if (console && console.warn) console.warn(warning);\n\t}\n\n\tvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n\t return value !== value;\n\t};\n\n\tfunction EventEmitter() {\n\t EventEmitter.init.call(this);\n\t}\n\tevents.exports = EventEmitter;\n\tevents.exports.once = once;\n\n\t// Backwards-compat with node 0.10.x\n\tEventEmitter.EventEmitter = EventEmitter;\n\n\tEventEmitter.prototype._events = undefined;\n\tEventEmitter.prototype._eventsCount = 0;\n\tEventEmitter.prototype._maxListeners = undefined;\n\n\t// By default EventEmitters will print a warning if more than 10 listeners are\n\t// added to it. This is a useful default which helps finding memory leaks.\n\tvar defaultMaxListeners = 10;\n\n\tfunction checkListener(listener) {\n\t if (typeof listener !== 'function') {\n\t throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n\t }\n\t}\n\n\tObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n\t enumerable: true,\n\t get: function() {\n\t return defaultMaxListeners;\n\t },\n\t set: function(arg) {\n\t if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n\t throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n\t }\n\t defaultMaxListeners = arg;\n\t }\n\t});\n\n\tEventEmitter.init = function() {\n\n\t if (this._events === undefined ||\n\t this._events === Object.getPrototypeOf(this)._events) {\n\t this._events = Object.create(null);\n\t this._eventsCount = 0;\n\t }\n\n\t this._maxListeners = this._maxListeners || undefined;\n\t};\n\n\t// Obviously not all Emitters should be limited to 10. This function allows\n\t// that to be increased. Set to zero for unlimited.\n\tEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n\t if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n\t throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n\t }\n\t this._maxListeners = n;\n\t return this;\n\t};\n\n\tfunction _getMaxListeners(that) {\n\t if (that._maxListeners === undefined)\n\t return EventEmitter.defaultMaxListeners;\n\t return that._maxListeners;\n\t}\n\n\tEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n\t return _getMaxListeners(this);\n\t};\n\n\tEventEmitter.prototype.emit = function emit(type) {\n\t var args = [];\n\t for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n\t var doError = (type === 'error');\n\n\t var events = this._events;\n\t if (events !== undefined)\n\t doError = (doError && events.error === undefined);\n\t else if (!doError)\n\t return false;\n\n\t // If there is no 'error' event listener then throw.\n\t if (doError) {\n\t var er;\n\t if (args.length > 0)\n\t er = args[0];\n\t if (er instanceof Error) {\n\t // Note: The comments on the `throw` lines are intentional, they show\n\t // up in Node's output if this results in an unhandled exception.\n\t throw er; // Unhandled 'error' event\n\t }\n\t // At least give some kind of context to the user\n\t var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n\t err.context = er;\n\t throw err; // Unhandled 'error' event\n\t }\n\n\t var handler = events[type];\n\n\t if (handler === undefined)\n\t return false;\n\n\t if (typeof handler === 'function') {\n\t ReflectApply(handler, this, args);\n\t } else {\n\t var len = handler.length;\n\t var listeners = arrayClone(handler, len);\n\t for (var i = 0; i < len; ++i)\n\t ReflectApply(listeners[i], this, args);\n\t }\n\n\t return true;\n\t};\n\n\tfunction _addListener(target, type, listener, prepend) {\n\t var m;\n\t var events;\n\t var existing;\n\n\t checkListener(listener);\n\n\t events = target._events;\n\t if (events === undefined) {\n\t events = target._events = Object.create(null);\n\t target._eventsCount = 0;\n\t } else {\n\t // To avoid recursion in the case that type === \"newListener\"! Before\n\t // adding it to the listeners, first emit \"newListener\".\n\t if (events.newListener !== undefined) {\n\t target.emit('newListener', type,\n\t listener.listener ? listener.listener : listener);\n\n\t // Re-assign `events` because a newListener handler could have caused the\n\t // this._events to be assigned to a new object\n\t events = target._events;\n\t }\n\t existing = events[type];\n\t }\n\n\t if (existing === undefined) {\n\t // Optimize the case of one listener. Don't need the extra array object.\n\t existing = events[type] = listener;\n\t ++target._eventsCount;\n\t } else {\n\t if (typeof existing === 'function') {\n\t // Adding the second element, need to change to array.\n\t existing = events[type] =\n\t prepend ? [listener, existing] : [existing, listener];\n\t // If we've already got an array, just append.\n\t } else if (prepend) {\n\t existing.unshift(listener);\n\t } else {\n\t existing.push(listener);\n\t }\n\n\t // Check for listener leak\n\t m = _getMaxListeners(target);\n\t if (m > 0 && existing.length > m && !existing.warned) {\n\t existing.warned = true;\n\t // No error code for this since it is a Warning\n\t // eslint-disable-next-line no-restricted-syntax\n\t var w = new Error('Possible EventEmitter memory leak detected. ' +\n\t existing.length + ' ' + String(type) + ' listeners ' +\n\t 'added. Use emitter.setMaxListeners() to ' +\n\t 'increase limit');\n\t w.name = 'MaxListenersExceededWarning';\n\t w.emitter = target;\n\t w.type = type;\n\t w.count = existing.length;\n\t ProcessEmitWarning(w);\n\t }\n\t }\n\n\t return target;\n\t}\n\n\tEventEmitter.prototype.addListener = function addListener(type, listener) {\n\t return _addListener(this, type, listener, false);\n\t};\n\n\tEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\n\tEventEmitter.prototype.prependListener =\n\t function prependListener(type, listener) {\n\t return _addListener(this, type, listener, true);\n\t };\n\n\tfunction onceWrapper() {\n\t if (!this.fired) {\n\t this.target.removeListener(this.type, this.wrapFn);\n\t this.fired = true;\n\t if (arguments.length === 0)\n\t return this.listener.call(this.target);\n\t return this.listener.apply(this.target, arguments);\n\t }\n\t}\n\n\tfunction _onceWrap(target, type, listener) {\n\t var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n\t var wrapped = onceWrapper.bind(state);\n\t wrapped.listener = listener;\n\t state.wrapFn = wrapped;\n\t return wrapped;\n\t}\n\n\tEventEmitter.prototype.once = function once(type, listener) {\n\t checkListener(listener);\n\t this.on(type, _onceWrap(this, type, listener));\n\t return this;\n\t};\n\n\tEventEmitter.prototype.prependOnceListener =\n\t function prependOnceListener(type, listener) {\n\t checkListener(listener);\n\t this.prependListener(type, _onceWrap(this, type, listener));\n\t return this;\n\t };\n\n\t// Emits a 'removeListener' event if and only if the listener was removed.\n\tEventEmitter.prototype.removeListener =\n\t function removeListener(type, listener) {\n\t var list, events, position, i, originalListener;\n\n\t checkListener(listener);\n\n\t events = this._events;\n\t if (events === undefined)\n\t return this;\n\n\t list = events[type];\n\t if (list === undefined)\n\t return this;\n\n\t if (list === listener || list.listener === listener) {\n\t if (--this._eventsCount === 0)\n\t this._events = Object.create(null);\n\t else {\n\t delete events[type];\n\t if (events.removeListener)\n\t this.emit('removeListener', type, list.listener || listener);\n\t }\n\t } else if (typeof list !== 'function') {\n\t position = -1;\n\n\t for (i = list.length - 1; i >= 0; i--) {\n\t if (list[i] === listener || list[i].listener === listener) {\n\t originalListener = list[i].listener;\n\t position = i;\n\t break;\n\t }\n\t }\n\n\t if (position < 0)\n\t return this;\n\n\t if (position === 0)\n\t list.shift();\n\t else {\n\t spliceOne(list, position);\n\t }\n\n\t if (list.length === 1)\n\t events[type] = list[0];\n\n\t if (events.removeListener !== undefined)\n\t this.emit('removeListener', type, originalListener || listener);\n\t }\n\n\t return this;\n\t };\n\n\tEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\n\tEventEmitter.prototype.removeAllListeners =\n\t function removeAllListeners(type) {\n\t var listeners, events, i;\n\n\t events = this._events;\n\t if (events === undefined)\n\t return this;\n\n\t // not listening for removeListener, no need to emit\n\t if (events.removeListener === undefined) {\n\t if (arguments.length === 0) {\n\t this._events = Object.create(null);\n\t this._eventsCount = 0;\n\t } else if (events[type] !== undefined) {\n\t if (--this._eventsCount === 0)\n\t this._events = Object.create(null);\n\t else\n\t delete events[type];\n\t }\n\t return this;\n\t }\n\n\t // emit removeListener for all listeners on all events\n\t if (arguments.length === 0) {\n\t var keys = Object.keys(events);\n\t var key;\n\t for (i = 0; i < keys.length; ++i) {\n\t key = keys[i];\n\t if (key === 'removeListener') continue;\n\t this.removeAllListeners(key);\n\t }\n\t this.removeAllListeners('removeListener');\n\t this._events = Object.create(null);\n\t this._eventsCount = 0;\n\t return this;\n\t }\n\n\t listeners = events[type];\n\n\t if (typeof listeners === 'function') {\n\t this.removeListener(type, listeners);\n\t } else if (listeners !== undefined) {\n\t // LIFO order\n\t for (i = listeners.length - 1; i >= 0; i--) {\n\t this.removeListener(type, listeners[i]);\n\t }\n\t }\n\n\t return this;\n\t };\n\n\tfunction _listeners(target, type, unwrap) {\n\t var events = target._events;\n\n\t if (events === undefined)\n\t return [];\n\n\t var evlistener = events[type];\n\t if (evlistener === undefined)\n\t return [];\n\n\t if (typeof evlistener === 'function')\n\t return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n\t return unwrap ?\n\t unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n\t}\n\n\tEventEmitter.prototype.listeners = function listeners(type) {\n\t return _listeners(this, type, true);\n\t};\n\n\tEventEmitter.prototype.rawListeners = function rawListeners(type) {\n\t return _listeners(this, type, false);\n\t};\n\n\tEventEmitter.listenerCount = function(emitter, type) {\n\t if (typeof emitter.listenerCount === 'function') {\n\t return emitter.listenerCount(type);\n\t } else {\n\t return listenerCount.call(emitter, type);\n\t }\n\t};\n\n\tEventEmitter.prototype.listenerCount = listenerCount;\n\tfunction listenerCount(type) {\n\t var events = this._events;\n\n\t if (events !== undefined) {\n\t var evlistener = events[type];\n\n\t if (typeof evlistener === 'function') {\n\t return 1;\n\t } else if (evlistener !== undefined) {\n\t return evlistener.length;\n\t }\n\t }\n\n\t return 0;\n\t}\n\n\tEventEmitter.prototype.eventNames = function eventNames() {\n\t return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n\t};\n\n\tfunction arrayClone(arr, n) {\n\t var copy = new Array(n);\n\t for (var i = 0; i < n; ++i)\n\t copy[i] = arr[i];\n\t return copy;\n\t}\n\n\tfunction spliceOne(list, index) {\n\t for (; index + 1 < list.length; index++)\n\t list[index] = list[index + 1];\n\t list.pop();\n\t}\n\n\tfunction unwrapListeners(arr) {\n\t var ret = new Array(arr.length);\n\t for (var i = 0; i < ret.length; ++i) {\n\t ret[i] = arr[i].listener || arr[i];\n\t }\n\t return ret;\n\t}\n\n\tfunction once(emitter, name) {\n\t return new Promise(function (resolve, reject) {\n\t function errorListener(err) {\n\t emitter.removeListener(name, resolver);\n\t reject(err);\n\t }\n\n\t function resolver() {\n\t if (typeof emitter.removeListener === 'function') {\n\t emitter.removeListener('error', errorListener);\n\t }\n\t resolve([].slice.call(arguments));\n\t }\n\t eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n\t if (name !== 'error') {\n\t addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n\t }\n\t });\n\t}\n\n\tfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n\t if (typeof emitter.on === 'function') {\n\t eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n\t }\n\t}\n\n\tfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n\t if (typeof emitter.on === 'function') {\n\t if (flags.once) {\n\t emitter.once(name, listener);\n\t } else {\n\t emitter.on(name, listener);\n\t }\n\t } else if (typeof emitter.addEventListener === 'function') {\n\t // EventTarget does not have `error` event semantics like Node\n\t // EventEmitters, we do not listen for `error` events here.\n\t emitter.addEventListener(name, function wrapListener(arg) {\n\t // IE does not have builtin `{ once: true }` support so we\n\t // have to do it manually.\n\t if (flags.once) {\n\t emitter.removeEventListener(name, wrapListener);\n\t }\n\t listener(arg);\n\t });\n\t } else {\n\t throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n\t }\n\t}\n\treturn events.exports;\n}\n\nvar eventsExports = requireEvents();\nvar EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventsExports);\n\nvar errorCodes;\n(function (errorCodes) {\n errorCodes[errorCodes[\"timeout\"] = 1] = \"timeout\";\n errorCodes[errorCodes[\"transportClosed\"] = 2] = \"transportClosed\";\n errorCodes[errorCodes[\"clientDisconnected\"] = 3] = \"clientDisconnected\";\n errorCodes[errorCodes[\"clientClosed\"] = 4] = \"clientClosed\";\n errorCodes[errorCodes[\"clientConnectToken\"] = 5] = \"clientConnectToken\";\n errorCodes[errorCodes[\"clientRefreshToken\"] = 6] = \"clientRefreshToken\";\n errorCodes[errorCodes[\"subscriptionUnsubscribed\"] = 7] = \"subscriptionUnsubscribed\";\n errorCodes[errorCodes[\"subscriptionSubscribeToken\"] = 8] = \"subscriptionSubscribeToken\";\n errorCodes[errorCodes[\"subscriptionRefreshToken\"] = 9] = \"subscriptionRefreshToken\";\n errorCodes[errorCodes[\"transportWriteError\"] = 10] = \"transportWriteError\";\n errorCodes[errorCodes[\"connectionClosed\"] = 11] = \"connectionClosed\";\n errorCodes[errorCodes[\"badConfiguration\"] = 12] = \"badConfiguration\";\n errorCodes[errorCodes[\"subscriptionGetState\"] = 13] = \"subscriptionGetState\";\n errorCodes[errorCodes[\"sharedPollGetSignature\"] = 14] = \"sharedPollGetSignature\";\n})(errorCodes || (errorCodes = {}));\nvar connectingCodes;\n(function (connectingCodes) {\n connectingCodes[connectingCodes[\"connectCalled\"] = 0] = \"connectCalled\";\n connectingCodes[connectingCodes[\"transportClosed\"] = 1] = \"transportClosed\";\n connectingCodes[connectingCodes[\"noPing\"] = 2] = \"noPing\";\n connectingCodes[connectingCodes[\"subscribeTimeout\"] = 3] = \"subscribeTimeout\";\n connectingCodes[connectingCodes[\"unsubscribeError\"] = 4] = \"unsubscribeError\";\n})(connectingCodes || (connectingCodes = {}));\nvar disconnectedCodes;\n(function (disconnectedCodes) {\n disconnectedCodes[disconnectedCodes[\"disconnectCalled\"] = 0] = \"disconnectCalled\";\n disconnectedCodes[disconnectedCodes[\"unauthorized\"] = 1] = \"unauthorized\";\n disconnectedCodes[disconnectedCodes[\"badProtocol\"] = 2] = \"badProtocol\";\n disconnectedCodes[disconnectedCodes[\"messageSizeLimit\"] = 3] = \"messageSizeLimit\";\n // Server-sent: the connection's cached state and/or token are no longer valid.\n // The client clears the connection token (to force getToken), invalidates all\n // subscription state, and reconnects. Delivered as a Disconnect push or a raw\n // WebSocket close code.\n disconnectedCodes[disconnectedCodes[\"stateInvalidated\"] = 3014] = \"stateInvalidated\";\n})(disconnectedCodes || (disconnectedCodes = {}));\nvar subscribingCodes;\n(function (subscribingCodes) {\n subscribingCodes[subscribingCodes[\"subscribeCalled\"] = 0] = \"subscribeCalled\";\n subscribingCodes[subscribingCodes[\"transportClosed\"] = 1] = \"transportClosed\";\n})(subscribingCodes || (subscribingCodes = {}));\nvar unsubscribedCodes;\n(function (unsubscribedCodes) {\n unsubscribedCodes[unsubscribedCodes[\"unsubscribeCalled\"] = 0] = \"unsubscribeCalled\";\n unsubscribedCodes[unsubscribedCodes[\"unauthorized\"] = 1] = \"unauthorized\";\n unsubscribedCodes[unsubscribedCodes[\"clientClosed\"] = 2] = \"clientClosed\";\n // Server-sent (in an Unsubscribe push): this subscription's cached state\n // and/or token are no longer valid. The client clears the subscription state\n // and resubscribes (this is a temporary unsubscribe, code >= 2500).\n unsubscribedCodes[unsubscribedCodes[\"stateInvalidated\"] = 2502] = \"stateInvalidated\";\n})(unsubscribedCodes || (unsubscribedCodes = {}));\nvar subscriptionFlags;\n(function (subscriptionFlags) {\n subscriptionFlags[subscriptionFlags[\"channelCompaction\"] = 1] = \"channelCompaction\";\n subscriptionFlags[subscriptionFlags[\"rejectUnrecovered\"] = 2] = \"rejectUnrecovered\";\n})(subscriptionFlags || (subscriptionFlags = {}));\n\n/** State of client. */\nvar State;\n(function (State) {\n State[\"Disconnected\"] = \"disconnected\";\n State[\"Connecting\"] = \"connecting\";\n State[\"Connected\"] = \"connected\";\n})(State || (State = {}));\n/** State of Subscription */\nvar SubscriptionState;\n(function (SubscriptionState) {\n SubscriptionState[\"Unsubscribed\"] = \"unsubscribed\";\n SubscriptionState[\"Subscribing\"] = \"subscribing\";\n SubscriptionState[\"Subscribed\"] = \"subscribed\";\n})(SubscriptionState || (SubscriptionState = {}));\n\n/** @internal */\nfunction startsWith(value, prefix) {\n return value.lastIndexOf(prefix, 0) === 0;\n}\n/** @internal */\nfunction isFunction(value) {\n if (value === undefined || value === null) {\n return false;\n }\n return typeof value === 'function';\n}\n/** @internal */\nfunction log(level, args) {\n if (globalThis.console) {\n const logger = globalThis.console[level];\n if (isFunction(logger)) {\n logger.apply(globalThis.console, args);\n }\n }\n}\nfunction randomInt(min, max) {\n return Math.floor(Math.random() * (max - min + 1) + min);\n}\n/** @internal */\nfunction backoff(step, min, max) {\n // Full jitter technique, see:\n // https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/\n if (step > 31) {\n step = 31;\n }\n const interval = randomInt(0, Math.min(max, min * Math.pow(2, step)));\n return Math.min(max, min + interval);\n}\n/** @internal */\nfunction errorExists(data) {\n return 'error' in data && data.error !== null;\n}\n/** @internal */\nfunction ttlMilliseconds(ttl) {\n // https://stackoverflow.com/questions/12633405/what-is-the-maximum-delay-for-setinterval\n return Math.min(ttl * 1000, 2147483647);\n}\n/** @internal */\nfunction localStorageItem(key) {\n // Accessing localStorage is not always safe: it may be null (Safari in\n // private browsing mode), or even throw on property access (when access to\n // storage is denied by the browser settings).\n try {\n if (typeof localStorage === 'undefined' || localStorage === null || !isFunction(localStorage.getItem)) {\n return null;\n }\n return localStorage.getItem(key);\n }\n catch (e) {\n return null;\n }\n}\n\n// Internal-only \u2014 phases the SDK walks through during a map subscribe.\n// Not exposed on the public surface; kept here so it doesn't leak via\n// `export * from \"./types\"` in index.ts.\nvar MapPhase;\n(function (MapPhase) {\n MapPhase[MapPhase[\"Live\"] = 0] = \"Live\";\n MapPhase[MapPhase[\"Stream\"] = 1] = \"Stream\";\n MapPhase[MapPhase[\"State\"] = 2] = \"State\";\n})(MapPhase || (MapPhase = {}));\n/** Base subscription to a channel \u2014 all subscription logic lives here. */\nclass BaseSubscription extends EventEmitter {\n /** Subscription constructor should not be used directly, create subscriptions using Client method. */\n constructor(centrifuge, channel, options) {\n super();\n this._resubscribeTimeout = null;\n this._refreshTimeout = null;\n // Stream getState callback (external state for stream subscriptions)\n this._getState = null;\n // Map subscription state\n this._map = false;\n this._mapPresenceType = 1; // 1=MAP, 2=MAP_CLIENTS, 3=MAP_USERS\n // @ts-ignore \u2013 this is used for tracking map subscription phase state.\n this._mapPhase = null;\n this._mapStateBuffer = []; // Buffer snapshot entries\n this._mapStreamBuffer = []; // Buffer stream entries during catch-up\n this._mapCursor = ''; // Pagination cursor\n this._mapPageSize = 0; // Page size (0 = use server default)\n this._mapUnrecoverableStrategy = 'from_scratch';\n // Publish debounce state (protocol-level, controlled by server)\n this._debounceMs = 0;\n this._debouncePending = new Map();\n // Shared poll subscription state\n this._sharedPoll = false;\n this._sharedPollEpoch = '';\n this._sharedPollTrackedItems = new Map(); // key \u2192 version\n this._sharedPollGetSignature = null;\n // TTL-driven and 109-driven consolidating refresh (one call to getSignature\n // covering all tracked keys, replaces the library with one entry).\n this._sharedPollSignatureRefreshTimeout = null;\n this._sharedPollSignatureRefreshAttempts = 0;\n // Per-track-command transient retry (track call failed with temporary error).\n this._sharedPollTrackRetryTimeout = null;\n this._sharedPollTrackRetryAttempts = 0;\n // Replay-getSignature retry (Phase 2 of _sharedPollReplayTrack failed). Held\n // separately so it can't clobber the refresh timer or accumulate backoff\n // attempts onto refresh failures.\n this._sharedPollReplayRetryTimeout = null;\n this._sharedPollReplayRetryAttempts = 0;\n // Library of HMAC signatures previously obtained for track() calls.\n // Each entry covers the exact key set originally signed; reused on reconnect\n // so we don't hit the application's getSignature endpoint for every client\n // during mass reconnect storms. Periodic refresh consolidates entries into\n // one combined signature covering all currently tracked keys.\n this._sharedPollSignatures = [];\n // Earliest scheduled refresh time (unix milliseconds) across all received\n // track responses. Server returns MIN ttl per response; SDK keeps the\n // single earliest deadline as the refresh target. Cleared on consolidation\n // refresh and on explicit unsubscribe.\n this._sharedPollSignatureRefreshTargetMs = null;\n // Guard against concurrent refresh calls \u2014 multiple 109 errors during\n // reconnect replay could otherwise trigger overlapping getSignature calls.\n this._sharedPollSignatureRefreshInFlight = false;\n this.channel = channel;\n this.state = SubscriptionState.Unsubscribed;\n this._centrifuge = centrifuge;\n this._token = '';\n this._getToken = null;\n this._data = null;\n this._getData = null;\n this._recover = false;\n this._offset = null;\n this._epoch = null;\n this._id = 0;\n this._recoverable = false;\n this._positioned = false;\n this._joinLeave = false;\n this._minResubscribeDelay = 500;\n this._maxResubscribeDelay = 20000;\n this._resubscribeTimeout = null;\n this._resubscribeAttempts = 0;\n this._promises = {};\n this._promiseId = 0;\n this._inflight = false;\n this._refreshTimeout = null;\n this._delta = '';\n this._delta_negotiated = false;\n this._tagsFilter = null;\n this._prevValueMap = new Map();\n this._unsubPromise = Promise.resolve();\n this._deltaNumPubs = 0;\n this._deltaNumFull = 0;\n this._deltaNumDelta = 0;\n this._deltaBytesReceived = 0;\n this._deltaBytesDecoded = 0;\n this._setOptions(options);\n this.type = this._sharedPoll ? 'shared_poll' : this._map ? 'map' : 'stream';\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n if (this._centrifuge._debugEnabled) {\n this.on('state', (ctx) => {\n this._debug('subscription state', channel, ctx.oldState, '->', ctx.newState);\n });\n this.on('error', (ctx) => {\n this._debug('subscription error', channel, ctx);\n });\n }\n else {\n // Avoid unhandled exception in EventEmitter for non-set error handler.\n this.on('error', function () { Function.prototype(); });\n }\n }\n /** ready returns a Promise which resolves upon subscription goes to Subscribed\n * state and rejects in case of subscription goes to Unsubscribed state.\n * Optional timeout can be passed.*/\n ready(timeout) {\n if (this.state === SubscriptionState.Unsubscribed) {\n return Promise.reject({ code: errorCodes.subscriptionUnsubscribed, message: this.state });\n }\n if (this.state === SubscriptionState.Subscribed) {\n return Promise.resolve();\n }\n return new Promise((res, rej) => {\n const ctx = {\n resolve: res,\n reject: rej\n };\n if (timeout) {\n ctx.timeout = setTimeout(function () {\n rej({ code: errorCodes.timeout, message: 'timeout' });\n }, timeout);\n }\n this._promises[this._nextPromiseId()] = ctx;\n });\n }\n /** subscribe to a channel.*/\n subscribe() {\n if (this._isSubscribed()) {\n return;\n }\n this._resubscribeAttempts = 0;\n this._setSubscribing(subscribingCodes.subscribeCalled, 'subscribe called');\n }\n /** unsubscribe from a channel, keeping position state.*/\n unsubscribe() {\n this._unsubPromise = this._setUnsubscribed(unsubscribedCodes.unsubscribeCalled, 'unsubscribe called', true);\n }\n _debouncedPublish(key, data, isMap) {\n const existing = this._debouncePending.get(key);\n if (existing) {\n // Update pending value, mark as dirty, keep existing timer.\n existing.data = data;\n existing.dirty = true;\n return Promise.resolve({});\n }\n // First publish for this key \u2014 send immediately, start debounce timer.\n const entry = { data, dirty: false, timer: null };\n entry.timer = setTimeout(() => {\n const pending = this._debouncePending.get(key);\n if (!pending || !pending.dirty) {\n // No new data since last send \u2014 just clean up.\n this._debouncePending.delete(key);\n return;\n }\n // Send the latest pending value, reset dirty flag, restart timer.\n pending.dirty = false;\n const sendData = pending.data;\n const sendFn = isMap\n ? this._centrifuge.mapPublish(this.channel, key, sendData)\n : this._centrifuge.publish(this.channel, sendData);\n sendFn.catch(() => { });\n // Restart timer for next window.\n pending.timer = setTimeout(() => {\n const p = this._debouncePending.get(key);\n if (!p || !p.dirty) {\n this._debouncePending.delete(key);\n return;\n }\n // Recursive \u2014 but in practice debounce windows are short.\n this._debouncePending.delete(key);\n this._debouncedPublish(key, p.data, isMap);\n }, this._debounceMs);\n }, this._debounceMs);\n this._debouncePending.set(key, entry);\n // Send first publish immediately.\n const sendFn = isMap\n ? this._centrifuge.mapPublish(this.channel, key, data)\n : this._centrifuge.publish(this.channel, data);\n return sendFn;\n }\n _cancelDebounce(key) {\n const existing = this._debouncePending.get(key);\n if (existing) {\n clearTimeout(existing.timer);\n this._debouncePending.delete(key);\n }\n }\n _cancelAllDebounce() {\n for (const [, entry] of this._debouncePending) {\n clearTimeout(entry.timer);\n }\n this._debouncePending.clear();\n }\n /** get online presence for a channel.*/\n presence() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._methodCall();\n return this._centrifuge.presence(this.channel);\n });\n }\n /** presence stats for a channel (num clients and unique users).*/\n presenceStats() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._methodCall();\n return this._centrifuge.presenceStats(this.channel);\n });\n }\n /**\n * Sets server-side tags filter for the subscription.\n * This only applies on the next subscription attempt, not the current one.\n * Cannot be used together with delta option.\n *\n * @param tagsFilter - Filter configuration object or null to remove filter\n * @throws {Error} If both delta and tagsFilter are configured\n *\n * @example\n * ```typescript\n * // Simple equality filter\n * sub.setTagsFilter({\n * key: 'ticker',\n * cmp: 'eq',\n * val: 'BTC'\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Complex filter with logical operators\n * sub.setTagsFilter({\n * op: 'and',\n * nodes: [\n * { key: 'ticker', cmp: 'eq', val: 'BTC' },\n * { key: 'price', cmp: 'gt', val: '50000' }\n * ]\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Filter with IN operator\n * sub.setTagsFilter({\n * key: 'ticker',\n * cmp: 'in',\n * vals: ['BTC', 'ETH', 'SOL']\n * });\n * ```\n */\n setTagsFilter(tagsFilter) {\n if (tagsFilter && this._delta) {\n throw new Error('cannot use delta and tagsFilter together');\n }\n this._tagsFilter = tagsFilter;\n // For map subscriptions, changing the filter invalidates the local state \u2014\n // the next subscribe must go through full STATE phase, not stream recovery.\n if (this._map) {\n this._recover = false;\n this._offset = null;\n this._epoch = null;\n }\n }\n /** setData allows setting subscription data. This only applied on the next subscription attempt,\n * Note that if getData callback is configured, it will override this value during resubscriptions. */\n setData(data) {\n this._data = data;\n }\n /** deltaStats returns delta compression statistics for this subscription.\n * Only meaningful when delta compression is enabled (delta: 'fossil'). */\n deltaStats() {\n const bytesDecoded = this._deltaBytesDecoded;\n return {\n numPublications: this._deltaNumPubs,\n numFullPayloads: this._deltaNumFull,\n numDeltaPayloads: this._deltaNumDelta,\n bytesReceived: this._deltaBytesReceived,\n bytesDecoded: bytesDecoded,\n compressionRatio: bytesDecoded > 0 ? 1 - this._deltaBytesReceived / bytesDecoded : 0,\n };\n }\n _methodCall() {\n if (this._isSubscribed()) {\n return Promise.resolve();\n }\n if (this._isUnsubscribed()) {\n return Promise.reject({\n code: errorCodes.subscriptionUnsubscribed,\n message: this.state\n });\n }\n return new Promise((resolve, reject) => {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n const timeoutDuration = this._centrifuge._config.timeout;\n const timeout = setTimeout(() => {\n reject({ code: errorCodes.timeout, message: 'timeout' });\n }, timeoutDuration);\n this._promises[this._nextPromiseId()] = {\n timeout,\n resolve,\n reject\n };\n });\n }\n _nextPromiseId() {\n return ++this._promiseId;\n }\n _needRecover() {\n return this._recover === true;\n }\n _isUnsubscribed() {\n return this.state === SubscriptionState.Unsubscribed;\n }\n _isSubscribing() {\n return this.state === SubscriptionState.Subscribing;\n }\n _isSubscribed() {\n return this.state === SubscriptionState.Subscribed;\n }\n _setState(newState) {\n if (this.state !== newState) {\n const oldState = this.state;\n this.state = newState;\n this.emit('state', { newState, oldState, channel: this.channel });\n return true;\n }\n return false;\n }\n _usesToken() {\n return this._token !== '' || this._getToken !== null;\n }\n _clearSubscribingState() {\n this._resubscribeAttempts = 0;\n this._clearResubscribeTimeout();\n }\n _clearSubscribedState() {\n this._clearRefreshTimeout();\n this._cancelAllDebounce();\n this._clearSharedPollSignatureRefresh();\n this._clearSharedPollTrackRetry();\n this._clearSharedPollReplayRetry();\n // Drop the stale refresh target \u2014 the replay after reconnect will set a\n // fresh one from the next batch of track responses.\n this._sharedPollSignatureRefreshTargetMs = null;\n // Reset the in-flight guard so refresh can run again after reconnect.\n this._sharedPollSignatureRefreshInFlight = false;\n // NOTE: do NOT clear _sharedPollSignatures or _sharedPollTrackedItems.\n // They persist across reconnects so _sharedPollReplayTrack can re-send\n // tracks using the cached signatures \u2014 avoids hitting getSignature for\n // every client during mass reconnect storms. Cleared only on explicit\n // unsubscribe via _setUnsubscribed.\n }\n /** Called on \"state invalidated\" \u2014 unsubscribe code 2502 for this channel,\n * or connection disconnect code 3014. Clears the token (next subscribe\n * fetches a fresh one) and the fossil delta base (every subscription type\n * uses _prevValueMap; a stale base would corrupt decoding of the first\n * publication after re-subscribe).\n *\n * Map subscriptions restart from scratch: their recovery position and\n * materialized-state buffers are dropped so the next subscribe does a full\n * STATE re-sync.\n *\n * Stream/shared-poll subscriptions instead reset the recovery position to a\n * sentinel epoch (\"_\") the server can never match (offset 0), leaving\n * _recover untouched: a recoverable subscription then resubscribes with\n * was_recovering=true, recovered=false (so the app reloads via its existing\n * recovery-failure path rather than treating it as a brand-new first\n * subscribe), while a non-recoverable one simply resubscribes. The real\n * epoch/offset are adopted from the subscribe reply. */\n _invalidateState() {\n this._token = '';\n this._prevValueMap = new Map();\n if (this._map) {\n this._offset = null;\n this._epoch = null;\n this._recover = false;\n this._mapStateBuffer = [];\n this._mapStreamBuffer = [];\n this._mapCursor = '';\n this._mapPhase = null;\n }\n else {\n this._offset = 0;\n this._epoch = '_';\n }\n }\n _setSubscribed(result) {\n if (!this._isSubscribing()) {\n return;\n }\n this._clearSubscribingState();\n if (result.id) {\n this._id = result.id;\n }\n if (result.recoverable) {\n this._recover = true;\n this._offset = result.offset || 0;\n this._epoch = result.epoch || '';\n }\n if (result.delta) {\n this._delta_negotiated = true;\n }\n else {\n this._delta_negotiated = false;\n }\n if (result.publish_debounce) {\n this._debounceMs = result.publish_debounce;\n }\n if (this._sharedPoll) {\n const newEpoch = result.epoch || '';\n if (this._sharedPollEpoch !== '' && this._sharedPollEpoch !== newEpoch) {\n // Epoch changed (server restart, mode change, node switch) \u2014\n // stored synthetic versions are invalid, reset to 0.\n for (const key of this._sharedPollTrackedItems.keys()) {\n this._sharedPollTrackedItems.set(key, 0);\n }\n }\n this._sharedPollEpoch = newEpoch;\n }\n this._setState(SubscriptionState.Subscribed);\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n const ctx = this._centrifuge._getSubscribeContext(this.channel, result);\n this.emit('subscribed', ctx);\n this._resolvePromises();\n const pubs = result.publications;\n if (pubs && pubs.length > 0) {\n for (const i in pubs) {\n if (!pubs.hasOwnProperty(i)) {\n continue;\n }\n this._handlePublication(pubs[i]);\n }\n }\n if (result.expires === true) {\n this._refreshTimeout = setTimeout(() => this._refresh(), ttlMilliseconds(result.ttl));\n }\n }\n _setSubscribing(code, reason) {\n return __awaiter(this, void 0, void 0, function* () {\n if (this._isSubscribing()) {\n return;\n }\n if (this._isSubscribed()) {\n this._clearSubscribedState();\n }\n // Channel compaction: the numeric channel id is scoped to the connected\n // session \u2014 drop it when moving back to subscribing (e.g. on reconnect). The\n // next subscribe reply re-establishes it (the server may reuse the same id).\n this._id = 0;\n if (this._setState(SubscriptionState.Subscribing)) {\n this.emit('subscribing', { channel: this.channel, code: code, reason: reason });\n }\n // @ts-ignore \u2013 for performance reasons only await _unsubPromise for emulution case where it's required.\n if (this._centrifuge._transport && this._centrifuge._transport.emulation()) {\n yield this._unsubPromise;\n }\n if (!this._isSubscribing()) {\n return;\n }\n this._subscribe();\n });\n }\n _subscribe() {\n this._debug('subscribing on', this.channel);\n if (!this._isTransportOpen()) {\n this._debug('delay subscribe on', this.channel, 'till connected');\n return null;\n }\n if (this._inflight) {\n return null;\n }\n this._inflight = true;\n // Route to map subscribe flow if map mode is enabled\n if (this._map) {\n this._mapSubscribe();\n return null;\n }\n // Stream getState: call app's callback to load state + get position.\n // Only called when we don't have a saved position (first subscribe or after\n // position reset due to failed recovery). On normal reconnects with a valid\n // saved position, we skip getState and let the server try recovery \u2014 getState\n // is only called again if recovery fails (see _setSubscribed).\n if (this._getState && this._offset === null) {\n this._loadStreamState();\n return null;\n }\n if (this._canSubscribeWithoutGettingToken()) {\n return this._subscribeWithoutToken();\n }\n this._getSubscriptionToken()\n .then(token => this._handleTokenResponse(token))\n .catch(e => this._handleTokenError(e));\n return null;\n }\n _isTransportOpen() {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n return this._centrifuge._transportIsOpen;\n }\n _canSubscribeWithoutGettingToken() {\n return !this._usesToken() || !!this._token;\n }\n _subscribeWithoutToken() {\n if (this._getData) {\n this._getDataAndSubscribe(this._token);\n return null;\n }\n else {\n return this._sendSubscribe(this._token);\n }\n }\n /** Load stream position from app via getState callback, then proceed to subscribe\n * with recovery from that position. Called only when _offset is null:\n * - Initial subscribe (no saved position)\n * - After position reset due to failed recovery (see _setSubscribed)\n *\n * NOT called on normal reconnects where the SDK has a saved position \u2014 in that\n * case recovery is attempted first, and getState is only invoked if recovery fails.\n *\n * The app's getState callback should:\n * 1. Read cf_stream_top_position (or equivalent) FIRST to capture the stream position\n * 2. Then read its own data from the database/API\n * 3. Render/update the UI\n * 4. Return the captured stream position\n *\n * This order is critical: reading position first ensures it's a lower bound.\n * Recovered publications may overlap with data the app already loaded \u2014 this\n * requires idempotent updates or offset-based dedup. */\n _loadStreamState() {\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n this._getState().then(result => {\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n // Store stream position from app's source of truth.\n this._offset = result.offset;\n this._epoch = result.epoch;\n this._recover = true;\n // Proceed with normal subscribe flow (token \u2192 sendSubscribe).\n if (this._canSubscribeWithoutGettingToken()) {\n this._subscribeWithoutToken();\n }\n else {\n this._getSubscriptionToken()\n .then(token => this._handleTokenResponse(token))\n .catch(e => this._handleTokenError(e));\n }\n }).catch(e => {\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n // Match map subscription error handling: route through _subscribeError\n // which emits error event and schedules resubscribe for temporary errors\n // (code < 100), matching the map's _handleMapSubscribeError pattern.\n this._inflight = false;\n this._subscribeError({\n code: errorCodes.subscriptionGetState,\n message: (e === null || e === void 0 ? void 0 : e.toString()) || 'getState failed',\n temporary: true,\n });\n });\n }\n _getDataAndSubscribe(token) {\n if (!this._getData) {\n this._inflight = false;\n return;\n }\n this._getData({ channel: this.channel })\n .then(data => {\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n this._data = data;\n this._sendSubscribe(token);\n })\n .catch(e => this._handleGetDataError(e));\n }\n _handleGetDataError(error) {\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n if (error instanceof UnauthorizedError) {\n this._inflight = false;\n this._failUnauthorized();\n return;\n }\n this.emit('error', {\n type: 'subscribeData',\n channel: this.channel,\n error: {\n code: errorCodes.badConfiguration,\n message: (error === null || error === void 0 ? void 0 : error.toString()) || ''\n }\n });\n this._inflight = false;\n this._scheduleResubscribe();\n }\n _handleTokenResponse(token) {\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n if (!token) {\n this._inflight = false;\n this._failUnauthorized();\n return;\n }\n this._token = token;\n if (this._getData) {\n this._getDataAndSubscribe(token);\n }\n else {\n this._sendSubscribe(token);\n }\n }\n _handleTokenError(error) {\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n if (error instanceof UnauthorizedError) {\n this._inflight = false;\n this._failUnauthorized();\n return;\n }\n this.emit('error', {\n type: 'subscribeToken',\n channel: this.channel,\n error: {\n code: errorCodes.subscriptionSubscribeToken,\n message: (error === null || error === void 0 ? void 0 : error.toString()) || ''\n }\n });\n this._inflight = false;\n this._scheduleResubscribe();\n }\n _sendSubscribe(token) {\n if (!this._isTransportOpen()) {\n this._inflight = false;\n return null;\n }\n const cmd = this._buildSubscribeCommand(token);\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._call(cmd).then(resolveCtx => {\n this._inflight = false;\n const result = resolveCtx.reply.subscribe;\n this._handleSubscribeResponse(result);\n if (resolveCtx.next) {\n resolveCtx.next();\n }\n }, rejectCtx => {\n this._inflight = false;\n this._handleSubscribeError(rejectCtx.error);\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n });\n return cmd;\n }\n _buildSubscribeCommand(token) {\n const req = { channel: this.channel };\n if (token)\n req.token = token;\n if (this._data)\n req.data = this._data;\n // Shared poll: simple subscribe with type=4, no positioning/recovery fields.\n if (this._sharedPoll) {\n req.type = 4;\n if (this._delta)\n req.delta = this._delta;\n return { subscribe: req };\n }\n if (this._positioned)\n req.positioned = true;\n if (this._recoverable)\n req.recoverable = true;\n if (this._joinLeave)\n req.join_leave = true;\n req.flag = subscriptionFlags.channelCompaction;\n if (this._getState) {\n req.flag |= subscriptionFlags.rejectUnrecovered;\n }\n if (this._needRecover()) {\n req.recover = true;\n const offset = this._getOffset();\n if (offset)\n req.offset = offset;\n const epoch = this._getEpoch();\n if (epoch)\n req.epoch = epoch;\n }\n if (this._delta)\n req.delta = this._delta;\n if (this._tagsFilter)\n req.tf = this._tagsFilter;\n return { subscribe: req };\n }\n _debug(...args) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._debug(...args);\n }\n _handleSubscribeError(error) {\n if (!this._isSubscribing()) {\n return;\n }\n if (error.code === errorCodes.timeout) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._disconnect(connectingCodes.subscribeTimeout, 'subscribe timeout', true);\n return;\n }\n if (error.code === 112 && this._getState) {\n // Unrecoverable position with getState: reset position so next\n // subscribe attempt calls getState() to reload app state from scratch.\n this._offset = null;\n this._epoch = null;\n this._recover = false;\n this._prevValueMap = new Map();\n this._scheduleResubscribe();\n return;\n }\n this._subscribeError(error);\n }\n _handleSubscribeResponse(result) {\n if (!this._isSubscribing()) {\n return;\n }\n this._setSubscribed(result);\n // After shared poll subscribe, replay tracked items if any.\n if (this._sharedPoll) {\n this._sharedPollReplayTrack();\n }\n }\n _setUnsubscribed(code, reason, sendUnsubscribe) {\n if (this._isUnsubscribed()) {\n return Promise.resolve();\n }\n let promise = Promise.resolve();\n if (this._isSubscribed()) {\n if (sendUnsubscribe) {\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n promise = this._centrifuge._unsubscribe(this);\n }\n this._clearSubscribedState();\n }\n else if (this._isSubscribing()) {\n if (this._inflight && sendUnsubscribe) {\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n promise = this._centrifuge._unsubscribe(this);\n }\n this._clearSubscribingState();\n }\n this._inflight = false;\n // Channel compaction: the numeric channel id is scoped to the active\n // subscription. Drop it so a push for the old id (e.g. one in flight when we\n // unsubscribe) is no longer routed to this subscription.\n this._id = 0;\n this._sharedPollEpoch = '';\n // Explicit unsubscribe \u2014 drop all shared-poll state so a subsequent\n // subscribe starts cold. Reconnects use _clearSubscribedState (above)\n // which preserves the signature library and tracked items.\n this._sharedPollSignatures = [];\n this._sharedPollTrackedItems.clear();\n this._sharedPollSignatureRefreshInFlight = false;\n this._sharedPollSignatureRefreshTargetMs = null;\n this._cancelAllDebounce();\n if (this._setState(SubscriptionState.Unsubscribed)) {\n this.emit('unsubscribed', { channel: this.channel, code: code, reason: reason });\n }\n this._rejectPromises({ code: errorCodes.subscriptionUnsubscribed, message: this.state });\n return promise;\n }\n _handlePublication(pub) {\n if (this._delta && this._delta_negotiated) {\n // For map and shared poll subs, delta is per-key.\n // For non-map subs, delta is a single chain regardless of pub.key.\n const deltaKey = (this._map || this._sharedPoll) ? (pub.key || '') : '';\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n const { newData, newPrevValue, isDelta, wireBytes, fullBytes } = this._centrifuge._codec.applyDeltaIfNeeded(pub, this._prevValueMap.get(deltaKey));\n pub.data = newData;\n this._deltaNumPubs++;\n this._deltaBytesReceived += wireBytes;\n this._deltaBytesDecoded += fullBytes;\n if (isDelta) {\n this._deltaNumDelta++;\n }\n else {\n this._deltaNumFull++;\n }\n if (pub.removed) {\n this._prevValueMap.delete(deltaKey);\n }\n else {\n this._prevValueMap.set(deltaKey, newPrevValue);\n }\n }\n let ctx;\n if (this._sharedPoll) {\n // Ignore publications for keys the user is no longer tracking.\n // Common race: SDK replays a cached signature batch on reconnect with\n // some keys the user untracked locally; the chained untrack hasn't\n // reached the server yet, so the server may push updates for those\n // keys in the meantime. Without this guard those updates would\n // re-insert the keys into _sharedPollTrackedItems and emit 'update'\n // events the user already opted out of.\n if (pub.key && !this._sharedPollTrackedItems.has(pub.key)) {\n return;\n }\n // Update locally tracked versions.\n if (pub.key) {\n if (pub.removed) {\n this._sharedPollTrackedItems.delete(pub.key);\n }\n else if (pub.version) {\n this._sharedPollTrackedItems.set(pub.key, pub.version);\n }\n }\n ctx = this._getSharedPollUpdateContext(pub);\n }\n else if (this._map) {\n ctx = this._getMapUpdateContext(pub);\n }\n else {\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n ctx = this._centrifuge._getPublicationContext(this.channel, pub);\n }\n this.emit('publication', ctx);\n if (this._map || this._sharedPoll) {\n this.emit('update', ctx);\n }\n if (pub.offset) {\n this._offset = pub.offset;\n }\n if (pub.epoch) {\n this._epoch = pub.epoch;\n }\n }\n /** Seed per-key delta tracking from state/stream entries.\n * Handles JSON-escaped data (server-side delta escaping) and protobuf data.\n * Decodes escaped data back to original format for user consumption. */\n _seedDeltaTracking(pub) {\n if (!this._delta || !pub.key)\n return;\n if (typeof pub.data === 'string') {\n // JSON transport with server-side delta escaping.\n // Store raw bytes for delta, decode for user.\n const rawBytes = pub.data;\n const encoded = new TextEncoder().encode(rawBytes);\n if (!pub.removed) {\n this._prevValueMap.set(pub.key, encoded);\n }\n else {\n this._prevValueMap.delete(pub.key);\n }\n // Count as full payload in delta stats. Use the UTF-8 byte length, not\n // rawBytes.length (JS string length counts UTF-16 code units, which\n // undercounts any non-ASCII content).\n const byteLen = encoded.length;\n this._deltaNumPubs++;\n this._deltaNumFull++;\n this._deltaBytesReceived += byteLen;\n this._deltaBytesDecoded += byteLen;\n pub.data = JSON.parse(rawBytes);\n }\n else if (pub.data instanceof Uint8Array) {\n // Protobuf transport.\n if (!pub.removed) {\n this._prevValueMap.set(pub.key, pub.data);\n }\n else {\n this._prevValueMap.delete(pub.key);\n }\n // Count as full payload in delta stats.\n const byteLen = pub.data.length;\n this._deltaNumPubs++;\n this._deltaNumFull++;\n this._deltaBytesReceived += byteLen;\n this._deltaBytesDecoded += byteLen;\n }\n }\n _handleJoin(join) {\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n const info = this._centrifuge._getJoinLeaveContext(join.info);\n this.emit('join', { channel: this.channel, info: info });\n }\n _handleLeave(leave) {\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n const info = this._centrifuge._getJoinLeaveContext(leave.info);\n this.emit('leave', { channel: this.channel, info: info });\n }\n _resolvePromises() {\n for (const id in this._promises) {\n if (!this._promises.hasOwnProperty(id)) {\n continue;\n }\n if (this._promises[id].timeout) {\n clearTimeout(this._promises[id].timeout);\n }\n this._promises[id].resolve();\n delete this._promises[id];\n }\n }\n _rejectPromises(err) {\n for (const id in this._promises) {\n if (!this._promises.hasOwnProperty(id)) {\n continue;\n }\n if (this._promises[id].timeout) {\n clearTimeout(this._promises[id].timeout);\n }\n this._promises[id].reject(err);\n delete this._promises[id];\n }\n }\n _scheduleResubscribe() {\n if (!this._isSubscribing()) {\n this._debug('not in subscribing state, skip resubscribe scheduling', this.channel);\n return;\n }\n const self = this;\n const delay = this._getResubscribeDelay();\n this._resubscribeTimeout = setTimeout(function () {\n if (self._isSubscribing()) {\n self._subscribe();\n }\n }, delay);\n this._debug('resubscribe scheduled after ' + delay, this.channel);\n }\n _subscribeError(err) {\n if (!this._isSubscribing()) {\n return;\n }\n if (err.code < 100 || err.code === 109 || err.temporary === true) {\n if (err.code === 109) { // Token expired error.\n this._token = '';\n }\n const errContext = {\n channel: this.channel,\n type: 'subscribe',\n error: err\n };\n if (this._centrifuge.state === State.Connected) {\n this.emit('error', errContext);\n }\n this._scheduleResubscribe();\n }\n else {\n this._setUnsubscribed(err.code, err.message, false);\n }\n }\n _getResubscribeDelay() {\n const delay = backoff(this._resubscribeAttempts, this._minResubscribeDelay, this._maxResubscribeDelay);\n this._resubscribeAttempts++;\n return delay;\n }\n _setOptions(options) {\n if (!options) {\n return;\n }\n if (options.since) {\n this._offset = options.since.offset || 0;\n this._epoch = options.since.epoch || '';\n this._recover = true;\n }\n if (options.data) {\n this._data = options.data;\n }\n if (options.getData) {\n this._getData = options.getData;\n }\n if (options.minResubscribeDelay !== undefined) {\n this._minResubscribeDelay = options.minResubscribeDelay;\n }\n if (options.maxResubscribeDelay !== undefined) {\n this._maxResubscribeDelay = options.maxResubscribeDelay;\n }\n if (options.token) {\n this._token = options.token;\n }\n if (options.getToken) {\n this._getToken = options.getToken;\n }\n if (options.positioned === true) {\n this._positioned = true;\n }\n if (options.recoverable === true) {\n this._recoverable = true;\n }\n if (options.joinLeave === true) {\n this._joinLeave = true;\n }\n if (options.delta) {\n if (options.delta !== 'fossil') {\n throw new Error('unsupported delta format');\n }\n this._delta = options.delta;\n }\n if (options.tagsFilter) {\n this._tagsFilter = options.tagsFilter;\n }\n if (this._tagsFilter && this._delta) {\n throw new Error('cannot use delta and tagsFilter together');\n }\n // Stream getState option\n if (options.getState) {\n this._getState = options.getState;\n this._recover = true; // getState implies recovery\n }\n // Map subscription options\n if (options.map === true) {\n this._map = true;\n }\n if (options.mapPageSize !== undefined) {\n this._mapPageSize = options.mapPageSize;\n }\n // Presence type for presence subscriptions (2=clients, 3=users)\n if (options.mapPresenceType !== undefined) {\n this._mapPresenceType = options.mapPresenceType;\n this._map = true; // Presence subscriptions are always map subscriptions\n }\n if (options.mapUnrecoverableStrategy) {\n this._mapUnrecoverableStrategy = options.mapUnrecoverableStrategy;\n }\n // Shared poll subscription options\n if (options.sharedPoll === true) {\n this._sharedPoll = true;\n }\n if (options.sharedPollGetSignature) {\n this._sharedPollGetSignature = options.sharedPollGetSignature;\n }\n }\n _getOffset() {\n const offset = this._offset;\n if (offset !== null) {\n return offset;\n }\n return 0;\n }\n _getEpoch() {\n const epoch = this._epoch;\n if (epoch !== null) {\n return epoch;\n }\n return '';\n }\n _clearRefreshTimeout() {\n if (this._refreshTimeout !== null) {\n clearTimeout(this._refreshTimeout);\n this._refreshTimeout = null;\n }\n }\n _clearResubscribeTimeout() {\n if (this._resubscribeTimeout !== null) {\n clearTimeout(this._resubscribeTimeout);\n this._resubscribeTimeout = null;\n }\n }\n _getSubscriptionToken() {\n this._debug('get subscription token for channel', this.channel);\n const ctx = {\n channel: this.channel\n };\n const getToken = this._getToken;\n if (getToken === null) {\n this.emit('error', {\n type: 'configuration',\n channel: this.channel,\n error: {\n code: errorCodes.badConfiguration,\n message: 'provide a function to get channel subscription token'\n }\n });\n return Promise.reject(new UnauthorizedError(''));\n }\n return getToken(ctx);\n }\n _refresh() {\n this._clearRefreshTimeout();\n const self = this;\n this._getSubscriptionToken().then(function (token) {\n if (!self._isSubscribed()) {\n return;\n }\n if (!token) {\n self._failUnauthorized();\n return;\n }\n self._token = token;\n const req = {\n channel: self.channel,\n token: token\n };\n const msg = {\n 'sub_refresh': req\n };\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n self._centrifuge._call(msg).then(resolveCtx => {\n const result = resolveCtx.reply.sub_refresh;\n self._refreshResponse(result);\n if (resolveCtx.next) {\n resolveCtx.next();\n }\n }, rejectCtx => {\n self._refreshError(rejectCtx.error);\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n });\n }).catch(function (e) {\n if (e instanceof UnauthorizedError) {\n self._failUnauthorized();\n return;\n }\n self.emit('error', {\n type: 'refreshToken',\n channel: self.channel,\n error: {\n code: errorCodes.subscriptionRefreshToken,\n message: e !== undefined ? e.toString() : ''\n }\n });\n self._refreshTimeout = setTimeout(() => self._refresh(), self._getRefreshRetryDelay());\n });\n }\n _refreshResponse(result) {\n if (!this._isSubscribed()) {\n return;\n }\n this._debug('subscription token refreshed, channel', this.channel);\n this._clearRefreshTimeout();\n if (result.expires === true) {\n this._refreshTimeout = setTimeout(() => this._refresh(), ttlMilliseconds(result.ttl));\n }\n }\n _refreshError(err) {\n if (!this._isSubscribed()) {\n return;\n }\n if (err.code < 100 || err.temporary === true) {\n this.emit('error', {\n type: 'refresh',\n channel: this.channel,\n error: err\n });\n this._refreshTimeout = setTimeout(() => this._refresh(), this._getRefreshRetryDelay());\n }\n else {\n this._setUnsubscribed(err.code, err.message, true);\n }\n }\n _getRefreshRetryDelay() {\n return backoff(0, 10000, 20000);\n }\n _failUnauthorized() {\n this._setUnsubscribed(unsubscribedCodes.unauthorized, 'unauthorized', true);\n }\n // ============ Shared Poll Internal Helpers ============\n // Send ONE or MORE signature batches in a single sub_refresh frame.\n // Splits across frames when the estimated payload exceeds the wire frame\n // budget \u2014 keeps each request well under the 64k Centrifugo frame limit.\n _sendTrackRequest(batches, untrackKeys) {\n if (batches.length === 0)\n return Promise.resolve();\n // Estimate ~80 bytes per signature + ~40 bytes per item (key + varint + framing).\n // ~60KB budget leaves headroom for envelope, channel name, and reply.\n const maxBytes = 60000;\n const frames = [];\n let current = [];\n // Reserve space for inline untrack keys in the first frame.\n let currentBytes = 100; // envelope baseline\n if (untrackKeys && untrackKeys.length > 0) {\n for (const key of untrackKeys)\n currentBytes += key.length + 4;\n }\n for (const b of batches) {\n let cost = 100;\n for (const it of b.items)\n cost += it.key.length + 16;\n if (current.length > 0 && currentBytes + cost > maxBytes) {\n frames.push(current);\n current = [];\n currentBytes = 100;\n }\n current.push(b);\n currentBytes += cost;\n }\n if (current.length > 0)\n frames.push(current);\n const send = (frame, frameUntrackKeys) => new Promise((resolve, reject) => {\n const req = {\n channel: this.channel,\n type: 1,\n track: frame.map(b => ({\n signature: b.signature,\n items: b.items.map(i => i.version > 0 ? i : { key: i.key }),\n })),\n };\n if (frameUntrackKeys && frameUntrackKeys.length > 0) {\n req.untrack = frameUntrackKeys;\n }\n const msg = { 'sub_refresh': req };\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._call(msg).then(resolveCtx => {\n this._handleTrackResponse(resolveCtx.reply.sub_refresh);\n if (resolveCtx.next)\n resolveCtx.next();\n resolve();\n }, rejectCtx => {\n if (rejectCtx.next)\n rejectCtx.next();\n reject(rejectCtx.error);\n });\n });\n // Sequential dispatch: a frame failure stops further frames so the SDK\n // doesn't end up with some frames committed server-side and others not\n // \u2014 which would otherwise lead to retry-with-duplicate-publications.\n // Inline untrack keys go only in the first frame.\n return frames.reduce((chain, frame, idx) => chain.then(() => send(frame, idx === 0 ? untrackKeys : undefined)), Promise.resolve());\n }\n _sendUntrackRequest(keys) {\n return new Promise((resolve, reject) => {\n const req = {\n channel: this.channel,\n type: 2,\n untrack: keys,\n };\n const msg = { 'sub_refresh': req };\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._call(msg).then(resolveCtx => {\n if (resolveCtx.next) {\n resolveCtx.next();\n }\n resolve();\n }, rejectCtx => {\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n reject(rejectCtx.error);\n });\n });\n }\n _handleTrackResponse(result) {\n // Track succeeded \u2014 reset retry state.\n this._clearSharedPollTrackRetry();\n // Process cached items from server (publications across all batches in the request).\n if (result && result.items && result.items.length > 0) {\n for (const pub of result.items) {\n this._handlePublication(pub);\n }\n }\n // Server returns MIN ttl across all batches in this request. Keep the\n // EARLIEST deadline received across all responses as the refresh target.\n // Refreshing too early is harmless (cheap getSignature call); refreshing\n // too late risks 109 errors mid-replay, so we err earlier.\n if (result && result.expires === true && result.ttl > 0) {\n const targetMs = Date.now() + result.ttl * 1000;\n this._maybeScheduleSharedPollSignatureRefresh(targetMs);\n }\n }\n // Reschedule the consolidating refresh timer if `targetMs` is earlier than\n // the currently scheduled target. No-op when a sooner refresh is already\n // pending. Pass null to clear and reset (e.g. after consolidation succeeded).\n _maybeScheduleSharedPollSignatureRefresh(targetMs) {\n if (targetMs === null) {\n this._sharedPollSignatureRefreshTargetMs = null;\n this._clearSharedPollSignatureRefresh();\n return;\n }\n if (!this._isSubscribed())\n return;\n if (this._sharedPollSignatureRefreshTargetMs !== null &&\n targetMs >= this._sharedPollSignatureRefreshTargetMs) {\n return; // existing timer fires sooner\n }\n this._sharedPollSignatureRefreshTargetMs = targetMs;\n this._clearSharedPollSignatureRefresh();\n this._sharedPollSignatureRefreshTimeout = setTimeout(() => this._sharedPollRefreshSignature(), Math.max(0, targetMs - Date.now()));\n }\n _clearSharedPollSignatureRefresh() {\n if (this._sharedPollSignatureRefreshTimeout !== null) {\n clearTimeout(this._sharedPollSignatureRefreshTimeout);\n this._sharedPollSignatureRefreshTimeout = null;\n }\n this._sharedPollSignatureRefreshAttempts = 0;\n // Do not clear the target here \u2014 _maybeScheduleSharedPollSignatureRefresh\n // owns target lifecycle. This helper only stops the timer and resets\n // backoff so the next reschedule starts fresh.\n }\n _clearSharedPollTrackRetry() {\n if (this._sharedPollTrackRetryTimeout !== null) {\n clearTimeout(this._sharedPollTrackRetryTimeout);\n this._sharedPollTrackRetryTimeout = null;\n }\n this._sharedPollTrackRetryAttempts = 0;\n }\n _clearSharedPollReplayRetry() {\n if (this._sharedPollReplayRetryTimeout !== null) {\n clearTimeout(this._sharedPollReplayRetryTimeout);\n this._sharedPollReplayRetryTimeout = null;\n }\n this._sharedPollReplayRetryAttempts = 0;\n }\n _handleTrackError(err) {\n if (!this._isSubscribed()) {\n return;\n }\n this.emit('error', {\n type: 'track',\n channel: this.channel,\n error: err,\n });\n // Error 109 (token expired) on a track command means the signature has\n // expired past the server's grace period. Trigger a refresh \u2014 getSignature\n // will issue a fresh consolidated signature that replaces stale ones.\n // The in-flight guard inside _sharedPollRefreshSignature prevents\n // duplicate refresh calls when multiple track retries all hit 109.\n if (err.code === 109) {\n this._sharedPollRefreshSignature();\n return;\n }\n if (err.code < 100 || err.temporary === true) {\n // Temporary error \u2014 retry full track replay with backoff.\n this._sharedPollTrackRetryTimeout = setTimeout(() => this._sharedPollReplayTrack(), backoff(this._sharedPollTrackRetryAttempts++, 1000, 15000));\n }\n }\n // _sharedPollRefreshSignature obtains a fresh consolidated signature\n // covering all currently tracked keys, then replaces the library with the\n // single new entry. Triggered by the TTL timer (server's `expires/ttl`\n // response) and by 109 errors on track commands. The in-flight guard\n // collapses concurrent refresh attempts into one.\n _sharedPollRefreshSignature() {\n this._clearSharedPollSignatureRefresh();\n if (!this._isSubscribed())\n return;\n if (!this._sharedPollGetSignature)\n return;\n if (this._sharedPollTrackedItems.size === 0)\n return;\n if (this._sharedPollSignatureRefreshInFlight)\n return;\n // Reset the global refresh target \u2014 the timer that pointed at this\n // moment has already fired, and the in-flight refresh will publish a\n // fresh deadline via the consolidated track response. Resetting here\n // (not after consolidation success) lets any concurrent track() call\n // that lands during getSignature still set a tighter target if its\n // signature is shorter-lived than the consolidated one.\n this._sharedPollSignatureRefreshTargetMs = null;\n this._sharedPollSignatureRefreshInFlight = true;\n const keys = Array.from(this._sharedPollTrackedItems.keys());\n const self = this;\n this._sharedPollGetSignature({ keys }).then(result => {\n self._sharedPollSignatureRefreshInFlight = false;\n if (!self._isSubscribed())\n return;\n self._sharedPollSignatureRefreshAttempts = 0;\n // Handle revoked keys (keys not in the returned set).\n const returnedKeys = new Set(result.keys);\n const revokedKeys = [];\n for (const key of keys) {\n if (!returnedKeys.has(key)) {\n self._sharedPollTrackedItems.delete(key);\n revokedKeys.push(key);\n self.emit('update', {\n channel: self.channel,\n key: key,\n data: null,\n removed: true,\n });\n }\n }\n // Tell the server to stop tracking revoked keys \u2014 otherwise the server\n // keeps broadcasting them and the SDK silently drops the publications.\n if (revokedKeys.length > 0) {\n self._sendUntrackRequest(revokedKeys).catch(err => {\n self.emit('error', { type: 'untrack', channel: self.channel, error: err });\n });\n }\n // Re-track only keys covered by the returned signature.\n const items = [];\n for (const key of result.keys) {\n const version = self._sharedPollTrackedItems.get(key);\n if (version !== undefined) {\n items.push({ key, version });\n }\n }\n // Replace the signature library with the consolidated entry. Keep\n // any entries that cover keys NOT in the consolidation \u2014 those keys\n // may have been added via a concurrent track() while getSignature was\n // in flight and their signatures must remain available for reconnect.\n const consolidatedKeySet = new Set(result.keys);\n const uncovered = self._sharedPollSignatures.filter(entry => entry.keys.some(k => self._sharedPollTrackedItems.has(k) && !consolidatedKeySet.has(k)));\n // Target was already reset at refresh start; any concurrent track()\n // during getSignature has set its own target if its TTL was tighter.\n // The consolidated track response below will set a target unless\n // something earlier is already in place.\n self._sharedPollSignatures = items.length > 0\n ? [{ keys: result.keys, signature: result.signature }, ...uncovered]\n : uncovered;\n if (items.length === 0)\n return;\n self._sendTrackRequest([{ items, signature: result.signature }]).catch(err => {\n self._handleTrackError(err);\n });\n }).catch(e => {\n self._sharedPollSignatureRefreshInFlight = false;\n self.emit('error', {\n type: 'signatureRefresh',\n channel: self.channel,\n error: {\n code: errorCodes.sharedPollGetSignature,\n message: e !== undefined ? e.toString() : ''\n }\n });\n // Retry after delay with exponential backoff.\n self._sharedPollSignatureRefreshTimeout = setTimeout(() => self._sharedPollRefreshSignature(), backoff(self._sharedPollSignatureRefreshAttempts++, 5000, 30000));\n });\n }\n // _sharedPollReplayTrack runs after subscribe completes \u2014 on initial\n // subscribe AND after every reconnect. It reuses every cached signature\n // in _sharedPollSignatures so that mass reconnects don't trigger mass\n // getSignature calls on the application backend.\n //\n // For each cached batch:\n // - Build a track command with the batch's ORIGINAL key set (HMAC was\n // signed over those keys, so the full set must be sent). Versions are\n // CURRENT per-connection versions, so the server pushes only what's\n // changed.\n // - Any keys in the batch that were locally untracked() since the original\n // track() are sent in the same frame's `untrack` field \u2014 the server\n // validates the full HMAC then removes them immediately, avoiding a\n // separate round-trip.\n //\n // getSignature is invoked only when there are no cached signatures (e.g.\n // initial subscribe where track(keys) was called without explicit sig).\n // Once a signature is expired beyond the server's grace period, the next\n // track command returns error 109 \u2014 _handleTrackError then triggers\n // _sharedPollRefreshSignature for a fresh consolidated signature.\n _sharedPollReplayTrack() {\n if (!this._isSubscribed())\n return;\n if (this._sharedPollTrackedItems.size === 0 && this._sharedPollSignatures.length === 0)\n return;\n // Phase 1: replay every cached signature batch in a SINGLE sub_refresh\n // frame (multi-batch wire format). The server validates each batch's\n // HMAC independently and merges the response. All-or-nothing semantics:\n // one failed signature \u2192 the whole replay fails and _handleTrackError\n // drives a consolidating refresh.\n //\n // After this block `coveredKeys` is the set of currently-tracked keys\n // that already have a signature in the library \u2014 any tracked key not\n // in this set needs a fresh getSignature in Phase 2.\n const coveredKeys = new Set();\n const replayBatches = [];\n const allUntrackedInReplay = [];\n for (const entry of this._sharedPollSignatures) {\n // Items: ORIGINAL key set + current per-connection versions. Keys that\n // were untracked locally still go in items (HMAC needs the full batch);\n // a single chained untrack runs after the multi-batch track resolves\n // to converge server-side state.\n const items = entry.keys.map(key => {\n var _a;\n return ({\n key,\n version: (_a = this._sharedPollTrackedItems.get(key)) !== null && _a !== void 0 ? _a : 0,\n });\n });\n replayBatches.push({ items, signature: entry.signature });\n for (const k of entry.keys) {\n if (this._sharedPollTrackedItems.has(k)) {\n coveredKeys.add(k);\n }\n else {\n allUntrackedInReplay.push(k);\n }\n }\n }\n if (replayBatches.length > 0) {\n // Pass untracked keys inline \u2014 server validates HMAC over the full batch\n // then immediately removes the stale keys in the same handler, eliminating\n // the previous two-round-trip track\u2192untrack sequence.\n this._sendTrackRequest(replayBatches, allUntrackedInReplay).catch(err => {\n this._handleTrackError(err);\n });\n }\n // Phase 2: any tracked items NOT covered by a cached signature need\n // a fresh getSignature. This handles two cases:\n // - initial subscribe where track(keys) was called without explicit\n // sig (library starts empty, all keys uncovered);\n // - mixed track(keys) + track(items, sig) before subscribe \u2014 the\n // explicit batch sits in the library, but auto-tracked keys still\n // need a signature.\n const uncoveredKeys = [];\n for (const key of this._sharedPollTrackedItems.keys()) {\n if (!coveredKeys.has(key))\n uncoveredKeys.push(key);\n }\n if (uncoveredKeys.length === 0)\n return;\n if (!this._sharedPollGetSignature) {\n this.emit('error', {\n type: 'track',\n channel: this.channel,\n error: { code: errorCodes.sharedPollGetSignature, message: 'getSignature callback required for tracked keys without an explicit signature' },\n });\n return;\n }\n const self = this;\n this._sharedPollGetSignature({ keys: uncoveredKeys }).then(result => {\n if (!self._isSubscribed())\n return;\n self._clearSharedPollReplayRetry();\n // Handle revoked keys (keys we asked about that the backend didn't authorize).\n const returnedKeys = new Set(result.keys);\n const revokedKeys = [];\n for (const key of uncoveredKeys) {\n if (!returnedKeys.has(key)) {\n self._sharedPollTrackedItems.delete(key);\n revokedKeys.push(key);\n self.emit('update', {\n channel: self.channel,\n key: key,\n data: null,\n removed: true,\n });\n }\n }\n if (revokedKeys.length > 0) {\n self._sendUntrackRequest(revokedKeys).catch(err => {\n self.emit('error', { type: 'untrack', channel: self.channel, error: err });\n });\n }\n const items = [];\n for (const key of result.keys) {\n const version = self._sharedPollTrackedItems.get(key);\n if (version !== undefined) {\n items.push({ key, version });\n }\n }\n if (items.length === 0)\n return;\n // Cache the obtained signature for subsequent reconnect replays.\n self._sharedPollSignatures.push({\n keys: result.keys,\n signature: result.signature,\n });\n self._sendTrackRequest([{ items, signature: result.signature }]).catch(err => {\n self._handleTrackError(err);\n });\n }).catch(e => {\n self.emit('error', {\n type: 'signatureRefresh',\n channel: self.channel,\n error: {\n code: errorCodes.sharedPollGetSignature,\n message: e !== undefined ? e.toString() : ''\n }\n });\n // Replay-getSignature retry uses its OWN backoff state \u2014 separate from\n // the refresh timer so a stuck replay can't delay the next TTL refresh.\n self._sharedPollReplayRetryTimeout = setTimeout(() => self._sharedPollReplayTrack(), backoff(self._sharedPollReplayRetryAttempts++, 5000, 30000));\n });\n }\n // ============ Keyed Subscription Methods ============\n /** Entry point for map subscriptions */\n _mapSubscribe() {\n this._debug('starting map subscribe on', this.channel);\n // Initialize buffers and phase\n this._mapStateBuffer = [];\n this._mapStreamBuffer = [];\n this._mapCursor = '';\n // Preserve _prevValueMap when recovering \u2014 the server will send deltas\n // against the values the client already has from the previous session.\n // Only clear when starting from scratch (no recovery position).\n if (!(this._recover && this._offset !== null && this._epoch !== null)) {\n this._prevValueMap = new Map();\n }\n this._mapPhase = MapPhase.State;\n // If we have a position from `since`, we may skip snapshot and go to stream\n if (this._recover && this._offset !== null && this._epoch !== null) {\n this._debug('map subscribe: recovering from position, skipping to stream phase');\n this._mapPhase = MapPhase.Stream;\n this._fetchStream();\n return;\n }\n // Get token if needed, then start fetching snapshot\n if (this._canSubscribeWithoutGettingToken()) {\n this._fetchSnapshot();\n }\n else {\n this._getSubscriptionToken()\n .then(token => {\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n if (!token) {\n this._inflight = false;\n this._failUnauthorized();\n return;\n }\n this._token = token;\n this._fetchSnapshot();\n })\n .catch(e => this._handleTokenError(e));\n }\n }\n /** Fetch a page of snapshot data */\n _fetchSnapshot(cursor) {\n if (!this._isSubscribing() || !this._isTransportOpen()) {\n this._inflight = false;\n return;\n }\n const cmd = this._buildMapSubscribeCommand(MapPhase.State, cursor);\n this._debug('map subscribe: fetching snapshot page', cursor ? `cursor=${cursor}` : 'initial');\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._call(cmd).then(resolveCtx => {\n const result = resolveCtx.reply.subscribe;\n this._handleMapStateResponse(result);\n if (resolveCtx.next) {\n resolveCtx.next();\n }\n }, rejectCtx => {\n this._handleMapSubscribeError(rejectCtx.error);\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n });\n }\n /** Process snapshot response */\n _handleMapStateResponse(result) {\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n // Check if server forced LIVE transition during STATE phase.\n // This happens on the last state page when server decides to skip STREAM phase\n // (streamless mode, or positioned mode with stream close enough).\n // Note: phase=0 may be omitted by JSON serializer, so !result.phase handles both 0 and undefined.\n if (!result.phase) {\n this._debug('map subscribe: server forced LIVE transition during state pagination');\n // _handleMapLiveResponse will process result.state and result.publications.\n this._handleMapLiveResponse(result);\n return;\n }\n // Store epoch/offset from first response. Both are frozen for the duration\n // of state pagination to maintain consistency: the stream catch-up must start\n // from where the first state page was captured, not from a later stream.Top().\n if (!this._epoch && result.epoch) {\n this._epoch = result.epoch;\n this._offset = result.offset || 0;\n }\n // Validate epoch on subsequent pages - if epoch changed, restart\n if (this._epoch && result.epoch && this._epoch !== result.epoch) {\n this._debug('map subscribe: epoch changed during snapshot pagination, restarting');\n this._mapStateBuffer = [];\n this._mapCursor = '';\n this._epoch = null;\n this._offset = null;\n this._prevValueMap = new Map();\n this._fetchSnapshot();\n return;\n }\n // Append state entries to snapshot buffer (state field, not publications).\n if (result.state && result.state.length > 0) {\n for (const pub of result.state) {\n this._seedDeltaTracking(pub);\n this._mapStateBuffer.push(this._getMapUpdateContext(pub));\n }\n }\n // Check if there's more data to fetch\n if (result.cursor) {\n this._mapCursor = result.cursor;\n this._fetchSnapshot(this._mapCursor);\n return;\n }\n // No more snapshot pages, transition to next phase\n this._transitionFromSnapshot();\n }\n /** Transition from STATE to STREAM phase after snapshot pagination completes */\n _transitionFromSnapshot() {\n this._debug('map subscribe: snapshot complete, transitioning to stream phase');\n // After STATE pagination, move to STREAM phase.\n // Client sends phase=1 requests, server decides when to go LIVE\n // by responding with phase=0.\n this._mapPhase = MapPhase.Stream;\n this._fetchStream();\n }\n /** Fetch stream data (offset-based catch-up) */\n _fetchStream() {\n if (!this._isSubscribing() || !this._isTransportOpen()) {\n this._inflight = false;\n return;\n }\n const cmd = this._buildMapSubscribeCommand(MapPhase.Stream);\n this._debug('map subscribe: fetching stream from offset', this._offset);\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._call(cmd).then(resolveCtx => {\n const result = resolveCtx.reply.subscribe;\n this._handleMapStreamResponse(result);\n if (resolveCtx.next) {\n resolveCtx.next();\n }\n }, rejectCtx => {\n this._handleMapSubscribeError(rejectCtx.error);\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n });\n }\n /** Process stream response */\n _handleMapStreamResponse(result) {\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n // Check if server forced LIVE transition (server-controlled).\n // When server decides client is close enough, it returns phase=0 (LIVE).\n // Note: phase=0 may be omitted by JSON serializer, so !result.phase handles both 0 and undefined.\n if (!result.phase) {\n this._debug('map subscribe: server forced LIVE transition during stream');\n this._handleMapLiveResponse(result);\n return;\n }\n // Validate epoch - if changed, we need to restart\n if (this._epoch && result.epoch && this._epoch !== result.epoch) {\n this._debug('map subscribe: epoch changed during stream, restarting');\n this._mapStateBuffer = [];\n this._mapStreamBuffer = [];\n this._epoch = null;\n this._offset = null;\n this._prevValueMap = new Map();\n this._mapPhase = MapPhase.State;\n this._fetchSnapshot();\n return;\n }\n // Append publications to stream buffer\n if (result.publications && result.publications.length > 0) {\n for (const pub of result.publications) {\n this._seedDeltaTracking(pub);\n this._mapStreamBuffer.push(this._getMapUpdateContext(pub));\n }\n }\n // Update offset from result. Server returns the last publication's actual\n // offset for intermediate STREAM pages (not stream.Top()), so this correctly\n // tracks the client's position for the next request.\n if (result.offset !== undefined) {\n this._offset = result.offset;\n }\n // Server controls LIVE transition. If server responded with phase=1,\n // we continue STREAM pagination. Server will respond with phase=0 when ready.\n this._fetchStream();\n }\n /** Process live response - complete the map subscription */\n _handleMapLiveResponse(result) {\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n this._inflight = false;\n // Validate epoch one more time\n if (this._epoch && result.epoch && this._epoch !== result.epoch) {\n this._debug('map subscribe: epoch changed during live transition, restarting');\n this._mapStateBuffer = [];\n this._mapStreamBuffer = [];\n this._epoch = null;\n this._offset = null;\n this._prevValueMap = new Map();\n this._inflight = true;\n this._mapPhase = MapPhase.State;\n this._fetchSnapshot();\n return;\n }\n // Handle state from live response (present when state-to-live transition happens).\n if (result.state && result.state.length > 0) {\n for (const pub of result.state) {\n this._seedDeltaTracking(pub);\n this._mapStateBuffer.push(this._getMapUpdateContext(pub));\n }\n }\n // Append any remaining publications from the live response to stream buffer.\n // Recovery publications may be delta-encoded \u2014 decode before buffering.\n // Use result.delta (not this._delta_negotiated which is set later).\n if (result.publications && result.publications.length > 0) {\n for (const pub of result.publications) {\n if (this._delta && result.delta) {\n // Delta negotiated: decode and update tracking in one block.\n const deltaKey = pub.key || '';\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n const { newData, newPrevValue, isDelta, wireBytes, fullBytes } = this._centrifuge._codec.applyDeltaIfNeeded(pub, this._prevValueMap.get(deltaKey));\n pub.data = newData;\n this._deltaNumPubs++;\n this._deltaBytesReceived += wireBytes;\n this._deltaBytesDecoded += fullBytes;\n if (isDelta) {\n this._deltaNumDelta++;\n }\n else {\n this._deltaNumFull++;\n }\n if (pub.removed) {\n this._prevValueMap.delete(deltaKey);\n }\n else {\n this._prevValueMap.set(deltaKey, newPrevValue);\n }\n }\n else if (this._delta && pub.key) {\n // Delta requested but not negotiated: seed tracking with raw data.\n if (pub.removed) {\n this._prevValueMap.delete(pub.key);\n }\n else {\n this._prevValueMap.set(pub.key, pub.data);\n }\n }\n this._mapStreamBuffer.push(this._getMapUpdateContext(pub));\n }\n }\n // Update final offset/epoch \u2014 use || 0/'' to handle zero values omitted by JSON/protobuf.\n this._offset = result.offset || 0;\n this._epoch = result.epoch || '';\n // Clear subscribing state\n this._clearSubscribingState();\n // Store subscription ID if provided\n if (result.id) {\n this._id = result.id;\n }\n // Set recoverable state - enable recovery for reconnects.\n // In streamless mode server omits recoverable (JSON: undefined, protobuf: false).\n this._recover = result.recoverable === true;\n // Handle delta negotiation\n if (result.delta) {\n this._delta_negotiated = true;\n }\n else {\n this._delta_negotiated = false;\n }\n // Set publish debounce from subscribe result.\n if (result.publish_debounce) {\n this._debounceMs = result.publish_debounce;\n }\n // Transition to subscribed state\n this._setState(SubscriptionState.Subscribed);\n // Build subscribed context with state entries\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n const ctx = this._centrifuge._getSubscribeContext(this.channel, result);\n ctx.state = this._mapStateBuffer;\n // Emit subscribed event\n this.emit('subscribed', ctx);\n this._resolvePromises();\n // Emit sync event \u2014 complete state for simplified state management.\n // Skipped on successful recovery (app already has rendered state; stream\n // catch-up is emitted as individual update events).\n if (!ctx.recovered) {\n if (this._mapStreamBuffer.length > 0) {\n // Apply stream catch-up buffer to state by key (last value wins, removed deletes).\n // Produces a single sync snapshot that reflects state as of LIVE transition.\n const stateMap = new Map();\n for (const entry of this._mapStateBuffer) {\n stateMap.set(entry.key, entry);\n }\n for (const entry of this._mapStreamBuffer) {\n if (entry.removed) {\n stateMap.delete(entry.key);\n }\n else {\n stateMap.set(entry.key, entry);\n }\n }\n this._mapStateBuffer = Array.from(stateMap.values());\n this._mapStreamBuffer = []; // Already applied \u2014 don't emit as updates.\n }\n this.emit('sync', { entries: this._mapStateBuffer });\n }\n // Flush remaining stream buffer as publication and update events.\n // On recovery (sync skipped above) \u2014 app already has state and just needs\n // incremental changes.\n for (const pub of this._mapStreamBuffer) {\n this.emit('publication', pub);\n this.emit('update', pub);\n }\n // Clear buffers\n this._mapStateBuffer = [];\n this._mapStreamBuffer = [];\n this._mapPhase = null;\n // Handle token expiry\n if (result.expires === true) {\n this._refreshTimeout = setTimeout(() => this._refresh(), ttlMilliseconds(result.ttl));\n }\n }\n /** Handle errors during map subscription process */\n _handleMapSubscribeError(error) {\n this._inflight = false;\n if (!this._isSubscribing()) {\n return;\n }\n if (error.code === errorCodes.timeout) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._disconnect(connectingCodes.subscribeTimeout, 'subscribe timeout', true);\n return;\n }\n // Clear map state on error\n this._mapStateBuffer = [];\n this._mapStreamBuffer = [];\n this._mapPhase = null;\n this._prevValueMap = new Map();\n // Handle unrecoverable position error (code 112) based on strategy\n if (error.code === 112) {\n if (this._mapUnrecoverableStrategy === 'from_scratch') {\n // Reset position and resubscribe from snapshot\n this._debug('map subscribe: unrecoverable position, restarting from scratch');\n this._offset = null;\n this._epoch = null;\n this._recover = false;\n this._scheduleResubscribe();\n return;\n }\n // 'fatal' strategy: fall through to _subscribeError which will unsubscribe\n }\n this._subscribeError(error);\n }\n /** Build map subscribe command for a specific phase */\n _buildMapSubscribeCommand(phase, cursor) {\n const req = {\n channel: this.channel,\n type: this._mapPresenceType || 1, // 1=MAP, 2=MAP_CLIENTS, 3=MAP_USERS\n phase: phase,\n };\n if (this._token)\n req.token = this._token;\n if (this._tagsFilter)\n req.tf = this._tagsFilter;\n if (this._delta)\n req.delta = this._delta;\n req.flag = subscriptionFlags.channelCompaction;\n // STATE phase\n if (phase === MapPhase.State) {\n if (this._mapPageSize > 0)\n req.limit = this._mapPageSize;\n if (cursor)\n req.cursor = cursor;\n // Epoch validation after first page\n if (this._epoch) {\n req.offset = this._offset;\n req.epoch = this._epoch;\n }\n else {\n // First request of the flow \u2014 include custom data.\n if (this._data)\n req.data = this._data;\n }\n }\n // STREAM phase\n if (phase === MapPhase.Stream) {\n if (this._mapPageSize > 0)\n req.limit = this._mapPageSize;\n req.offset = this._offset;\n req.epoch = this._epoch;\n if (this._recover) {\n req.recover = true;\n // First request of the flow (skipped STATE) \u2014 include custom data for authorization.\n if (this._mapStreamBuffer.length === 0) {\n if (this._data)\n req.data = this._data;\n }\n }\n }\n return { subscribe: req };\n }\n /** Convert raw publication to MapUpdateContext */\n _getMapUpdateContext(pub) {\n const ctx = {\n channel: this.channel,\n data: pub.data,\n key: pub.key || '',\n };\n if (pub.removed === true) {\n ctx.removed = true;\n }\n if (pub.offset !== undefined) {\n ctx.offset = pub.offset;\n }\n if (pub.info) {\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n ctx.info = this._centrifuge._getJoinLeaveContext(pub.info);\n }\n if (pub.tags) {\n ctx.tags = pub.tags;\n }\n return ctx;\n }\n /** Convert raw publication to SharedPollUpdateContext */\n _getSharedPollUpdateContext(pub) {\n const ctx = {\n channel: this.channel,\n key: pub.key || '',\n data: pub.data,\n };\n if (pub.removed === true) {\n ctx.removed = true;\n }\n if (pub.version !== undefined) {\n ctx.version = pub.version;\n }\n return ctx;\n }\n}\n/** Stream subscription with publish/history methods. */\nclass Subscription extends BaseSubscription {\n /** Publish data to the channel. */\n publish(data) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._methodCall();\n // Debounce per channel (key = \"\" for stream publishes).\n if (this._debounceMs > 0) {\n return this._debouncedPublish('', data, false);\n }\n return this._centrifuge.publish(this.channel, data);\n });\n }\n /** history for a channel. By default it does not return publications (only current\n * StreamPosition data) \u2013 provide an explicit limit > 0 to load publications.*/\n history(opts) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._methodCall();\n return this._centrifuge.history(this.channel, opts);\n });\n }\n}\n/** Map subscription with publish/remove methods. */\nclass MapSubscription extends BaseSubscription {\n /** Publish data to a key. */\n publish(key, data) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._methodCall();\n if (this._debounceMs > 0) {\n return this._debouncedPublish(key, data, true);\n }\n return this._centrifuge.mapPublish(this.channel, key, data);\n });\n }\n /** Remove a key. */\n remove(key) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._methodCall();\n // Cancel any pending debounced publish for this key.\n this._cancelDebounce(key);\n return this._centrifuge.mapRemove(this.channel, key);\n });\n }\n}\n/** Shared poll subscription with track/untrack/trackedKeys. */\nclass SharedPollSubscription extends BaseSubscription {\n /** Track items in a shared poll subscription.\n *\n * Overloads:\n * - `track(keys: string[])` \u2014 pass key names only (version defaults to 0).\n * Requires `getSignature` callback in subscription options. The SDK\n * automatically obtains a signature before sending the track request.\n * - `track(items: SharedPollTrackItem[], signature: string)` \u2014 pass items\n * with explicit versions and a pre-computed HMAC signature.\n *\n * Items are stored in local state immediately. If subscribed, the track request\n * is sent right away. If not yet subscribed, items will be sent via replay\n * (with a fresh signature from getSignature) after subscribe completes.\n *\n * **Fire-and-forget** (similar to subscribe/unsubscribe): returns void and never\n * throws for in-flight failures. Subscribe to the `error` event to observe\n * failures: `type: 'track'` covers both the server-side track request and\n * the `getSignature` callback when using `track(keys)`. Server-revoked keys\n * arrive as synthetic `update` events with `removed: true`. */\n track(keysOrItems, signature) {\n if (keysOrItems.length === 0) {\n return; // Nothing to track \u2014 avoid wasteful getSignature call.\n }\n let items;\n const sig = signature;\n if (typeof keysOrItems[0] === 'string') {\n const keys = keysOrItems;\n items = keys.map(k => ({ key: k, version: 0 }));\n }\n else {\n items = keysOrItems;\n }\n // Update per-connection tracked items (use max(existing, new) so a stale\n // page load can't downgrade a version already advanced by a publication).\n for (const item of items) {\n const existing = this._sharedPollTrackedItems.get(item.key);\n if (existing === undefined || item.version > existing) {\n this._sharedPollTrackedItems.set(item.key, item.version);\n }\n }\n if (sig !== undefined) {\n // Explicit signature path \u2014 append to library and (if subscribed) send.\n this._sharedPollSignatures.push({\n keys: items.map(i => i.key),\n signature: sig,\n });\n if (this._isSubscribed()) {\n this._sendTrackRequest([{ items, signature: sig }]).catch(err => {\n this._handleTrackError(err);\n });\n }\n // If not subscribed yet, _sharedPollReplayTrack will fire after subscribe.\n return;\n }\n // Auto-obtain signature via getSignature callback.\n if (!this._sharedPollGetSignature) {\n this.emit('error', {\n type: 'track',\n channel: this.channel,\n error: { code: errorCodes.sharedPollGetSignature, message: 'getSignature callback required for track(keys)' },\n });\n return;\n }\n if (!this._isSubscribed()) {\n // Defer the getSignature call until after subscribe \u2014 _sharedPollReplayTrack\n // will obtain a signature covering all tracked keys at once.\n return;\n }\n const keys = items.map(i => i.key);\n this._sharedPollGetSignature({ keys }).then(result => {\n if (!this._isSubscribed())\n return;\n // Handle revoked keys.\n const returnedKeys = new Set(result.keys);\n const revokedKeys = [];\n for (const key of keys) {\n if (!returnedKeys.has(key)) {\n this._sharedPollTrackedItems.delete(key);\n revokedKeys.push(key);\n this.emit('update', {\n channel: this.channel,\n key: key,\n data: null,\n removed: true,\n });\n }\n }\n // Server may already be tracking some of these from a prior track() with\n // a different signature \u2014 send untrack so it stops broadcasting them.\n if (revokedKeys.length > 0) {\n this._sendUntrackRequest(revokedKeys).catch(err => {\n this.emit('error', { type: 'untrack', channel: this.channel, error: err });\n });\n }\n // Track authorized keys.\n const authorizedItems = [];\n for (const key of result.keys) {\n const version = this._sharedPollTrackedItems.get(key);\n if (version !== undefined) {\n authorizedItems.push({ key, version });\n }\n }\n if (authorizedItems.length === 0)\n return;\n // Cache the obtained signature for reconnect replay.\n this._sharedPollSignatures.push({\n keys: result.keys,\n signature: result.signature,\n });\n this._sendTrackRequest([{ items: authorizedItems, signature: result.signature }]).catch(err => {\n this._handleTrackError(err);\n });\n }).catch(e => {\n this.emit('error', {\n type: 'track',\n channel: this.channel,\n error: { code: errorCodes.sharedPollGetSignature, message: e !== undefined ? e.toString() : 'getSignature failed' },\n });\n });\n }\n /** Stop tracking specific keys in a shared poll subscription.\n * Keys are removed from local state immediately. If subscribed, the untrack\n * request is sent right away. If not yet subscribed, the keys simply won't\n * be included in the replay after subscribe completes.\n *\n * **Fire-and-forget** (similar to subscribe/unsubscribe): returns void and never\n * throws for in-flight failures. Subscribe to the `error` event with\n * `type: 'untrack'` to observe failures of the untrack request. */\n untrack(keys) {\n for (const key of keys) {\n this._sharedPollTrackedItems.delete(key);\n }\n // Drop any signature entries whose ENTIRE key set is now untracked \u2014\n // they contribute nothing to reconnect replays and would grow unboundedly\n // in long-running sessions with many track/untrack cycles. Entries where\n // at least one key is still tracked are kept intact: pruning them would\n // cause those live keys to lose their signature on the next reconnect.\n this._sharedPollSignatures = this._sharedPollSignatures.filter(entry => entry.keys.some(k => this._sharedPollTrackedItems.has(k)));\n if (this._isSubscribed()) {\n this._sendUntrackRequest(keys).catch(err => {\n this.emit('error', {\n type: 'untrack',\n channel: this.channel,\n error: err,\n });\n });\n }\n }\n /** Returns the set of currently tracked keys in a shared poll subscription. */\n trackedKeys() {\n return new Set(this._sharedPollTrackedItems.keys());\n }\n}\n\n/** @internal */\nclass SockjsTransport {\n constructor(endpoint, options) {\n this.endpoint = endpoint;\n this.options = options;\n this._transport = null;\n }\n name() {\n return 'sockjs';\n }\n subName() {\n return 'sockjs-' + this._transport.transport;\n }\n emulation() {\n return false;\n }\n supported() {\n return this.options.sockjs !== null;\n }\n initialize(_protocol, callbacks) {\n this._transport = new this.options.sockjs(this.endpoint, null, this.options.sockjsOptions);\n this._transport.onopen = () => {\n callbacks.onOpen();\n };\n this._transport.onerror = e => {\n callbacks.onError(e);\n };\n this._transport.onclose = closeEvent => {\n callbacks.onClose(closeEvent);\n };\n this._transport.onmessage = event => {\n callbacks.onMessage(event.data);\n };\n }\n close() {\n this._transport.close();\n }\n send(data) {\n this._transport.send(data);\n }\n}\n\n/** @internal */\nclass WebsocketTransport {\n constructor(endpoint, options) {\n this.endpoint = endpoint;\n this.options = options;\n this._transport = null;\n }\n name() {\n return 'websocket';\n }\n subName() {\n return 'websocket';\n }\n emulation() {\n return false;\n }\n supported() {\n return this.options.websocket !== undefined && this.options.websocket !== null;\n }\n initialize(protocol, callbacks) {\n let subProtocol = '';\n if (protocol === 'protobuf') {\n subProtocol = 'centrifuge-protobuf';\n }\n if (subProtocol !== '') {\n this._transport = new this.options.websocket(this.endpoint, subProtocol);\n }\n else {\n this._transport = new this.options.websocket(this.endpoint);\n }\n if (protocol === 'protobuf') {\n this._transport.binaryType = 'arraybuffer';\n }\n this._transport.onopen = () => {\n callbacks.onOpen();\n };\n this._transport.onerror = e => {\n callbacks.onError(e);\n };\n this._transport.onclose = closeEvent => {\n callbacks.onClose(closeEvent);\n };\n this._transport.onmessage = event => {\n callbacks.onMessage(event.data);\n };\n }\n close() {\n this._transport.close();\n }\n send(data) {\n this._transport.send(data);\n }\n}\n\n/** @internal */\nclass HttpStreamTransport {\n constructor(endpoint, options) {\n this.endpoint = endpoint;\n this.options = options;\n this._abortController = null;\n this._utf8decoder = new TextDecoder();\n this._protocol = 'json';\n }\n name() {\n return 'http_stream';\n }\n subName() {\n return 'http_stream';\n }\n emulation() {\n return true;\n }\n _handleErrors(response) {\n if (!response.ok)\n throw new Error(response.status);\n return response;\n }\n _fetchEventTarget(self, endpoint, options) {\n const eventTarget = new EventTarget();\n // fetch with connection timeout maybe? https://github.com/github/fetch/issues/175\n const fetchFunc = self.options.fetch;\n fetchFunc(endpoint, options)\n .then(self._handleErrors)\n .then(response => {\n eventTarget.dispatchEvent(new Event('open'));\n let jsonStreamBuf = '';\n let jsonStreamPos = 0;\n let protoStreamBuf = new Uint8Array();\n const reader = response.body.getReader();\n return new self.options.readableStream({\n start(controller) {\n function pump() {\n return reader.read().then(({ done, value }) => {\n // When no more data needs to be consumed, close the stream\n if (done) {\n eventTarget.dispatchEvent(new Event('close'));\n controller.close();\n return;\n }\n try {\n if (self._protocol === 'json') {\n // stream: true keeps decoder state across reads so a multi-byte\n // UTF-8 character split across two chunks is not corrupted into\n // replacement characters.\n jsonStreamBuf += self._utf8decoder.decode(value, { stream: true });\n while (jsonStreamPos < jsonStreamBuf.length) {\n if (jsonStreamBuf[jsonStreamPos] === '\\n') {\n const line = jsonStreamBuf.substring(0, jsonStreamPos);\n eventTarget.dispatchEvent(new MessageEvent('message', { data: line }));\n jsonStreamBuf = jsonStreamBuf.substring(jsonStreamPos + 1);\n jsonStreamPos = 0;\n }\n else {\n ++jsonStreamPos;\n }\n }\n }\n else {\n const mergedArray = new Uint8Array(protoStreamBuf.length + value.length);\n mergedArray.set(protoStreamBuf);\n mergedArray.set(value, protoStreamBuf.length);\n protoStreamBuf = mergedArray;\n while (true) {\n const result = self.options.decoder.decodeReply(protoStreamBuf);\n if (result.ok) {\n const data = protoStreamBuf.slice(0, result.pos);\n eventTarget.dispatchEvent(new MessageEvent('message', { data: data }));\n protoStreamBuf = protoStreamBuf.slice(result.pos);\n continue;\n }\n break;\n }\n }\n }\n catch (error) {\n // @ts-ignore - improve later.\n eventTarget.dispatchEvent(new Event('error', { detail: error }));\n eventTarget.dispatchEvent(new Event('close'));\n controller.close();\n return;\n }\n pump();\n }).catch(function (e) {\n // @ts-ignore - improve later.\n eventTarget.dispatchEvent(new Event('error', { detail: e }));\n eventTarget.dispatchEvent(new Event('close'));\n controller.close();\n return;\n });\n }\n return pump();\n }\n });\n })\n .catch(error => {\n // @ts-ignore - improve later.\n eventTarget.dispatchEvent(new Event('error', { detail: error }));\n eventTarget.dispatchEvent(new Event('close'));\n });\n return eventTarget;\n }\n supported() {\n return this.options.fetch !== null &&\n this.options.readableStream !== null &&\n typeof TextDecoder !== 'undefined' &&\n typeof AbortController !== 'undefined' &&\n typeof EventTarget !== 'undefined' &&\n typeof Event !== 'undefined' &&\n typeof MessageEvent !== 'undefined' &&\n typeof Error !== 'undefined';\n }\n initialize(protocol, callbacks, initialData) {\n this._protocol = protocol;\n this._abortController = new AbortController();\n let headers;\n let body;\n if (protocol === 'json') {\n headers = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n };\n body = initialData;\n }\n else {\n headers = {\n 'Accept': 'application/octet-stream',\n 'Content-Type': 'application/octet-stream'\n };\n body = initialData;\n }\n const fetchOptions = {\n method: 'POST',\n headers: headers,\n body: body,\n mode: 'cors',\n credentials: 'same-origin',\n signal: this._abortController.signal\n };\n const eventTarget = this._fetchEventTarget(this, this.endpoint, fetchOptions);\n eventTarget.addEventListener('open', () => {\n callbacks.onOpen();\n });\n eventTarget.addEventListener('error', (e) => {\n this._abortController.abort();\n callbacks.onError(e);\n });\n eventTarget.addEventListener('close', () => {\n this._abortController.abort();\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n });\n eventTarget.addEventListener('message', (e) => {\n callbacks.onMessage(e.data);\n });\n }\n close() {\n this._abortController.abort();\n }\n send(data, session, node) {\n let headers;\n let body;\n const req = {\n session: session,\n node: node,\n data: data\n };\n if (this._protocol === 'json') {\n headers = {\n 'Content-Type': 'application/json'\n };\n body = JSON.stringify(req);\n }\n else {\n headers = {\n 'Content-Type': 'application/octet-stream'\n };\n body = this.options.encoder.encodeEmulationRequest(req);\n }\n const fetchFunc = this.options.fetch;\n const fetchOptions = {\n method: 'POST',\n headers: headers,\n body: body,\n mode: 'cors',\n credentials: 'same-origin',\n };\n fetchFunc(this.options.emulationEndpoint, fetchOptions);\n }\n}\n\n/** @internal */\nclass SseTransport {\n constructor(endpoint, options) {\n this.endpoint = endpoint;\n this.options = options;\n this._protocol = 'json';\n this._transport = null;\n this._onClose = null;\n }\n name() {\n return 'sse';\n }\n subName() {\n return 'sse';\n }\n emulation() {\n return true;\n }\n supported() {\n return this.options.eventsource !== null && this.options.fetch !== null;\n }\n initialize(_protocol, callbacks, initialData) {\n let url;\n if (globalThis && globalThis.document && globalThis.document.baseURI) {\n // Handle case when endpoint is relative, like //example.com/connection/sse\n url = new URL(this.endpoint, globalThis.document.baseURI);\n }\n else {\n url = new URL(this.endpoint);\n }\n url.searchParams.append('cf_connect', initialData);\n const eventsourceOptions = {};\n const eventSource = new this.options.eventsource(url.toString(), eventsourceOptions);\n this._transport = eventSource;\n const self = this;\n eventSource.onopen = function () {\n callbacks.onOpen();\n };\n eventSource.onerror = function (e) {\n eventSource.close();\n callbacks.onError(e);\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n };\n eventSource.onmessage = function (e) {\n callbacks.onMessage(e.data);\n };\n self._onClose = function () {\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n };\n }\n close() {\n this._transport.close();\n if (this._onClose !== null) {\n this._onClose();\n }\n }\n send(data, session, node) {\n const req = {\n session: session,\n node: node,\n data: data\n };\n const headers = {\n 'Content-Type': 'application/json'\n };\n const body = JSON.stringify(req);\n const fetchFunc = this.options.fetch;\n const fetchOptions = {\n method: 'POST',\n headers: headers,\n body: body,\n mode: 'cors',\n credentials: 'same-origin',\n };\n fetchFunc(this.options.emulationEndpoint, fetchOptions);\n }\n}\n\n/** @internal */\nclass WebtransportTransport {\n constructor(endpoint, options) {\n this.endpoint = endpoint;\n this.options = options;\n this._transport = null;\n this._stream = null;\n this._writer = null;\n this._utf8decoder = new TextDecoder();\n this._protocol = 'json';\n }\n name() {\n return 'webtransport';\n }\n subName() {\n return 'webtransport';\n }\n emulation() {\n return false;\n }\n supported() {\n return this.options.webtransport !== undefined && this.options.webtransport !== null;\n }\n initialize(protocol, callbacks) {\n return __awaiter(this, void 0, void 0, function* () {\n let url;\n if (globalThis && globalThis.document && globalThis.document.baseURI) {\n // Handle case when endpoint is relative, like //example.com/connection/webtransport\n url = new URL(this.endpoint, globalThis.document.baseURI);\n }\n else {\n url = new URL(this.endpoint);\n }\n if (protocol === 'protobuf') {\n url.searchParams.append('cf_protocol', 'protobuf');\n }\n this._protocol = protocol;\n const eventTarget = new EventTarget();\n this._transport = new this.options.webtransport(url.toString());\n this._transport.closed.then(() => {\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n }).catch(() => {\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n });\n try {\n yield this._transport.ready;\n }\n catch (_a) {\n this.close();\n return;\n }\n let stream;\n try {\n stream = yield this._transport.createBidirectionalStream();\n }\n catch (_b) {\n this.close();\n return;\n }\n this._stream = stream;\n this._writer = this._stream.writable.getWriter();\n eventTarget.addEventListener('close', () => {\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n });\n eventTarget.addEventListener('message', (e) => {\n callbacks.onMessage(e.data);\n });\n this._startReading(eventTarget);\n callbacks.onOpen();\n });\n }\n _startReading(eventTarget) {\n return __awaiter(this, void 0, void 0, function* () {\n const reader = this._stream.readable.getReader();\n let jsonStreamBuf = '';\n let jsonStreamPos = 0;\n let protoStreamBuf = new Uint8Array();\n try {\n while (true) {\n const { done, value } = yield reader.read();\n if (value && value.length > 0) {\n if (this._protocol === 'json') {\n // stream: true keeps decoder state across reads so a multi-byte\n // UTF-8 character split across two chunks is not corrupted into\n // replacement characters.\n jsonStreamBuf += this._utf8decoder.decode(value, { stream: true });\n while (jsonStreamPos < jsonStreamBuf.length) {\n if (jsonStreamBuf[jsonStreamPos] === '\\n') {\n const line = jsonStreamBuf.substring(0, jsonStreamPos);\n eventTarget.dispatchEvent(new MessageEvent('message', { data: line }));\n jsonStreamBuf = jsonStreamBuf.substring(jsonStreamPos + 1);\n jsonStreamPos = 0;\n }\n else {\n ++jsonStreamPos;\n }\n }\n }\n else {\n const mergedArray = new Uint8Array(protoStreamBuf.length + value.length);\n mergedArray.set(protoStreamBuf);\n mergedArray.set(value, protoStreamBuf.length);\n protoStreamBuf = mergedArray;\n while (true) {\n const result = this.options.decoder.decodeReply(protoStreamBuf);\n if (result.ok) {\n const data = protoStreamBuf.slice(0, result.pos);\n eventTarget.dispatchEvent(new MessageEvent('message', { data: data }));\n protoStreamBuf = protoStreamBuf.slice(result.pos);\n continue;\n }\n break;\n }\n }\n }\n if (done) {\n break;\n }\n }\n }\n catch (_a) {\n eventTarget.dispatchEvent(new Event('close'));\n }\n });\n }\n close() {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n if (this._writer) {\n yield this._writer.close();\n }\n this._transport.close();\n }\n catch (e) {\n // already closed.\n }\n });\n }\n send(data) {\n return __awaiter(this, void 0, void 0, function* () {\n let binary;\n if (this._protocol === 'json') {\n // Need extra \\n since WT is non-frame protocol. \n binary = new TextEncoder().encode(data + '\\n');\n }\n else {\n binary = data;\n }\n try {\n yield this._writer.write(binary);\n }\n catch (e) {\n this.close();\n }\n });\n }\n}\n\n/*\nCopyright 2014-2024 Dmitry Chestnykh (JavaScript port)\nCopyright 2007 D. Richard Hipp (original C version)\n\nFossil SCM delta compression algorithm, this is only the applyDelta part extracted\nfrom https://github.com/dchest/fossil-delta-js. The code was slightly modified\nto strip unnecessary parts. The copyright on top of this file is from the original\nrepo on Github licensed under Simplified BSD License.\n*/\nconst zValue = [\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1,\n -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,\n 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36, -1, 37,\n 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,\n 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,\n];\n// Reader reads bytes, chars, ints from array.\nclass Reader {\n constructor(array) {\n this.a = array; // source array\n this.pos = 0; // current position in array\n }\n haveBytes() {\n return this.pos < this.a.length;\n }\n getByte() {\n const b = this.a[this.pos];\n this.pos++;\n if (this.pos > this.a.length)\n throw new RangeError(\"out of bounds\");\n return b;\n }\n getChar() {\n return String.fromCharCode(this.getByte());\n }\n // Read base64-encoded unsigned integer.\n getInt() {\n let v = 0;\n let c;\n while (this.haveBytes() && (c = zValue[0x7f & this.getByte()]) >= 0) {\n v = (v << 6) + c;\n }\n this.pos--;\n return v >>> 0;\n }\n}\n// Write writes an array.\nclass Writer {\n constructor() {\n this.a = [];\n }\n toByteArray(sourceType) {\n if (Array.isArray(sourceType)) {\n return this.a;\n }\n return new Uint8Array(this.a);\n }\n // Copy from array at start to end.\n putArray(a, start, end) {\n // TODO: optimize.\n for (let i = start; i < end; i++)\n this.a.push(a[i]);\n }\n}\n// Return a 32-bit checksum of the array.\nfunction checksum(arr) {\n let sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0, z = 0, N = arr.length;\n //TODO measure if this unrolling is helpful.\n while (N >= 16) {\n sum0 = (sum0 + arr[z + 0]) | 0;\n sum1 = (sum1 + arr[z + 1]) | 0;\n sum2 = (sum2 + arr[z + 2]) | 0;\n sum3 = (sum3 + arr[z + 3]) | 0;\n sum0 = (sum0 + arr[z + 4]) | 0;\n sum1 = (sum1 + arr[z + 5]) | 0;\n sum2 = (sum2 + arr[z + 6]) | 0;\n sum3 = (sum3 + arr[z + 7]) | 0;\n sum0 = (sum0 + arr[z + 8]) | 0;\n sum1 = (sum1 + arr[z + 9]) | 0;\n sum2 = (sum2 + arr[z + 10]) | 0;\n sum3 = (sum3 + arr[z + 11]) | 0;\n sum0 = (sum0 + arr[z + 12]) | 0;\n sum1 = (sum1 + arr[z + 13]) | 0;\n sum2 = (sum2 + arr[z + 14]) | 0;\n sum3 = (sum3 + arr[z + 15]) | 0;\n z += 16;\n N -= 16;\n }\n while (N >= 4) {\n sum0 = (sum0 + arr[z + 0]) | 0;\n sum1 = (sum1 + arr[z + 1]) | 0;\n sum2 = (sum2 + arr[z + 2]) | 0;\n sum3 = (sum3 + arr[z + 3]) | 0;\n z += 4;\n N -= 4;\n }\n sum3 = (((((sum3 + (sum2 << 8)) | 0) + (sum1 << 16)) | 0) + (sum0 << 24)) | 0;\n switch (N) {\n //@ts-ignore fallthrough is needed.\n case 3:\n sum3 = (sum3 + (arr[z + 2] << 8)) | 0; /* falls through */\n //@ts-ignore fallthrough is needed.\n case 2:\n sum3 = (sum3 + (arr[z + 1] << 16)) | 0; /* falls through */\n case 1:\n sum3 = (sum3 + (arr[z + 0] << 24)) | 0; /* falls through */\n }\n return sum3 >>> 0;\n}\n/**\n * Apply a delta byte array to a source byte array, returning the target byte array.\n */\nfunction applyDelta(source, delta) {\n let total = 0;\n const zDelta = new Reader(delta);\n const lenSrc = source.length;\n const lenDelta = delta.length;\n const limit = zDelta.getInt();\n if (zDelta.getChar() !== \"\\n\")\n throw new Error(\"size integer not terminated by '\\\\n'\");\n const zOut = new Writer();\n while (zDelta.haveBytes()) {\n const cnt = zDelta.getInt();\n let ofst;\n switch (zDelta.getChar()) {\n case \"@\":\n ofst = zDelta.getInt();\n if (zDelta.haveBytes() && zDelta.getChar() !== \",\")\n throw new Error(\"copy command not terminated by ','\");\n total += cnt;\n if (total > limit)\n throw new Error(\"copy exceeds output file size\");\n if (ofst + cnt > lenSrc)\n throw new Error(\"copy extends past end of input\");\n zOut.putArray(source, ofst, ofst + cnt);\n break;\n case \":\":\n total += cnt;\n if (total > limit)\n throw new Error(\"insert command gives an output larger than predicted\");\n if (cnt > lenDelta)\n throw new Error(\"insert count exceeds size of delta\");\n zOut.putArray(zDelta.a, zDelta.pos, zDelta.pos + cnt);\n zDelta.pos += cnt;\n break;\n case \";\":\n {\n const out = zOut.toByteArray(source);\n if (cnt !== checksum(out))\n throw new Error(\"bad checksum\");\n if (total !== limit)\n throw new Error(\"generated size does not match predicted size\");\n return out;\n }\n default:\n throw new Error(\"unknown delta operator\");\n }\n }\n throw new Error(\"unterminated delta\");\n}\n\n/** @internal */\nclass JsonCodec {\n name() {\n return 'json';\n }\n encodeCommands(commands) {\n return commands.map(c => JSON.stringify(c)).join('\\n');\n }\n decodeReplies(data) {\n return data.trim().split('\\n').map(r => JSON.parse(r));\n }\n applyDeltaIfNeeded(pub, prevValue) {\n let newData, newPrevValue, wireBytes;\n let isDelta;\n if (pub.delta) {\n isDelta = true;\n // JSON string delta.\n const deltaBytes = new TextEncoder().encode(pub.data);\n const valueArray = applyDelta(prevValue, deltaBytes);\n newData = JSON.parse(new TextDecoder().decode(valueArray));\n newPrevValue = valueArray;\n wireBytes = deltaBytes.length;\n }\n else {\n isDelta = false;\n // Full data as JSON string.\n newData = JSON.parse(pub.data);\n newPrevValue = new TextEncoder().encode(pub.data);\n wireBytes = newPrevValue.length;\n }\n // wireBytes is the UTF-8 byte length of pub.data, not its JS string length\n // (.length counts UTF-16 code units, which undercounts any non-ASCII content).\n return { newData, newPrevValue, isDelta, wireBytes, fullBytes: newPrevValue.length };\n }\n}\n\nconst defaults = {\n headers: {},\n token: '',\n getToken: null,\n data: null,\n getData: null,\n debug: false,\n name: 'js',\n version: '',\n fetch: null,\n readableStream: null,\n websocket: null,\n eventsource: null,\n sockjs: null,\n sockjsOptions: {},\n emulationEndpoint: '/emulation',\n minReconnectDelay: 500,\n maxReconnectDelay: 20000,\n timeout: 5000,\n maxServerPingDelay: 10000,\n networkEventTarget: null,\n};\nclass UnauthorizedError extends Error {\n constructor(message) {\n super(message);\n this.name = this.constructor.name;\n }\n}\n/** Centrifuge is a Centrifuge/Centrifugo bidirectional client. */\nclass Centrifuge extends EventEmitter {\n /** Constructs Centrifuge client. Call connect() method to start connecting. */\n constructor(endpoint, options) {\n super();\n this._reconnectTimeout = null;\n this._refreshTimeout = null;\n this._serverPingTimeout = null;\n this.state = State.Disconnected;\n this._transportIsOpen = false;\n this._endpoint = endpoint;\n this._emulation = false;\n this._transports = [];\n this._currentTransportIndex = 0;\n this._triedAllTransports = false;\n this._transportWasOpen = false;\n this._transport = null;\n this._transportId = 0;\n this._deviceWentOffline = false;\n this._transportClosed = true;\n this._codec = new JsonCodec();\n this._reconnecting = false;\n this._reconnectTimeout = null;\n this._reconnectAttempts = 0;\n this._client = null;\n this._session = '';\n this._node = '';\n this._subs = {};\n this._serverSubs = {};\n this._commandId = 0;\n this._commands = [];\n this._batching = false;\n this._refreshRequired = false;\n this._refreshTimeout = null;\n this._callbacks = {};\n this._token = '';\n this._data = null;\n this._dispatchPromise = Promise.resolve();\n this._serverPing = 0;\n this._serverPingTimeout = null;\n this._sendPong = false;\n this._promises = {};\n this._promiseId = 0;\n this._debugEnabled = false;\n this._networkEventsSet = false;\n this._config = Object.assign(Object.assign({}, defaults), options);\n this._configure();\n if (this._debugEnabled) {\n this.on('state', (ctx) => {\n this._debug('client state', ctx.oldState, '->', ctx.newState);\n });\n this.on('error', (ctx) => {\n this._debug('client error', ctx);\n });\n }\n else {\n // Avoid unhandled exception in EventEmitter for non-set error handler.\n this.on('error', function () { Function.prototype(); });\n }\n }\n /** newSubscription allocates new Subscription to a channel. Since server only allows\n * one subscription per channel per client this method throws if client already has\n * channel subscription in internal registry.\n * */\n newSubscription(channel, options) {\n if (this.getSubscription(channel) !== null) {\n throw new Error('Subscription to the channel ' + channel + ' already exists');\n }\n const sub = new Subscription(this, channel, options);\n this._subs[channel] = sub;\n return sub;\n }\n /** newMapSubscription allocates new map Subscription to a channel. Since server only allows\n * one subscription per channel per client this method throws if client already has\n * channel subscription in internal registry.\n *\n * Experimental. Requires Centrifugo >= v6.8.0. API may change in a backwards-incompatible\n * way in subsequent minor releases. */\n newMapSubscription(channel, options) {\n if (this.getSubscription(channel) !== null) {\n throw new Error('Subscription to the channel ' + channel + ' already exists');\n }\n const sub = new MapSubscription(this, channel, {\n token: options === null || options === void 0 ? void 0 : options.token,\n getToken: options === null || options === void 0 ? void 0 : options.getToken,\n data: options === null || options === void 0 ? void 0 : options.data,\n minResubscribeDelay: options === null || options === void 0 ? void 0 : options.minResubscribeDelay,\n maxResubscribeDelay: options === null || options === void 0 ? void 0 : options.maxResubscribeDelay,\n delta: options === null || options === void 0 ? void 0 : options.delta,\n tagsFilter: options === null || options === void 0 ? void 0 : options.tagsFilter,\n map: true,\n mapPageSize: options === null || options === void 0 ? void 0 : options.pageSize,\n mapUnrecoverableStrategy: options === null || options === void 0 ? void 0 : options.unrecoverableStrategy,\n });\n this._subs[channel] = sub;\n return sub;\n }\n /** Create a map subscription for observing individual connections (clients presence).\n * Each entry has key=clientId and contains full ClientInfo.\n * Use this to track connections per channel.\n * The channel should be the full presence channel name (e.g., \"$clients:games\").\n *\n * Experimental. Requires Centrifugo >= v6.8.0. API may change in a backwards-incompatible\n * way in subsequent minor releases. */\n newMapClientsSubscription(channel, options) {\n if (this.getSubscription(channel) !== null) {\n throw new Error('Subscription to the channel ' + channel + ' already exists');\n }\n const sub = new MapSubscription(this, channel, {\n token: options === null || options === void 0 ? void 0 : options.token,\n getToken: options === null || options === void 0 ? void 0 : options.getToken,\n data: options === null || options === void 0 ? void 0 : options.data,\n minResubscribeDelay: options === null || options === void 0 ? void 0 : options.minResubscribeDelay,\n maxResubscribeDelay: options === null || options === void 0 ? void 0 : options.maxResubscribeDelay,\n delta: options === null || options === void 0 ? void 0 : options.delta,\n tagsFilter: options === null || options === void 0 ? void 0 : options.tagsFilter,\n map: true,\n mapPresenceType: 2, // MAP_CLIENTS_PRESENCE\n mapPageSize: options === null || options === void 0 ? void 0 : options.pageSize,\n mapUnrecoverableStrategy: options === null || options === void 0 ? void 0 : options.unrecoverableStrategy,\n });\n this._subs[channel] = sub;\n return sub;\n }\n /** Create a map subscription for observing unique users (users presence).\n * Each entry has key=userId (no ClientInfo stored).\n * User entries expire via TTL, providing debounce for quick reconnects.\n * The channel should be the full presence channel name (e.g., \"$users:games\").\n *\n * Experimental. Requires Centrifugo >= v6.8.0. API may change in a backwards-incompatible\n * way in subsequent minor releases. */\n newMapUsersSubscription(channel, options) {\n if (this.getSubscription(channel) !== null) {\n throw new Error('Subscription to the channel ' + channel + ' already exists');\n }\n const sub = new MapSubscription(this, channel, {\n token: options === null || options === void 0 ? void 0 : options.token,\n getToken: options === null || options === void 0 ? void 0 : options.getToken,\n data: options === null || options === void 0 ? void 0 : options.data,\n minResubscribeDelay: options === null || options === void 0 ? void 0 : options.minResubscribeDelay,\n maxResubscribeDelay: options === null || options === void 0 ? void 0 : options.maxResubscribeDelay,\n delta: options === null || options === void 0 ? void 0 : options.delta,\n tagsFilter: options === null || options === void 0 ? void 0 : options.tagsFilter,\n map: true,\n mapPresenceType: 3, // MAP_USERS_PRESENCE\n mapPageSize: options === null || options === void 0 ? void 0 : options.pageSize,\n mapUnrecoverableStrategy: options === null || options === void 0 ? void 0 : options.unrecoverableStrategy,\n });\n this._subs[channel] = sub;\n return sub;\n }\n /** newSharedPollSubscription allocates a new shared poll Subscription to a channel.\n * Shared poll subscriptions use server-side polling to aggregate interest sets\n * and deliver periodic updates with version tracking. Track items after subscribing\n * using the track() method on the returned Subscription.\n *\n * Experimental. Requires Centrifugo >= v6.8.0. API may change in a backwards-incompatible\n * way in subsequent minor releases. */\n newSharedPollSubscription(channel, options) {\n if (this.getSubscription(channel) !== null) {\n throw new Error('Subscription to the channel ' + channel + ' already exists');\n }\n const sub = new SharedPollSubscription(this, channel, {\n token: options === null || options === void 0 ? void 0 : options.token,\n getToken: options === null || options === void 0 ? void 0 : options.getToken,\n data: options === null || options === void 0 ? void 0 : options.data,\n minResubscribeDelay: options === null || options === void 0 ? void 0 : options.minResubscribeDelay,\n maxResubscribeDelay: options === null || options === void 0 ? void 0 : options.maxResubscribeDelay,\n delta: options === null || options === void 0 ? void 0 : options.delta,\n sharedPoll: true,\n sharedPollGetSignature: options === null || options === void 0 ? void 0 : options.getSignature,\n });\n this._subs[channel] = sub;\n return sub;\n }\n /** getSubscription returns Subscription if it's registered in the internal\n * registry or null. */\n getSubscription(channel) {\n return this._getSub(channel);\n }\n /** Get a map subscription by channel. */\n getMapSubscription(channel) {\n return this._getSub(channel);\n }\n /** Get a shared poll subscription by channel. */\n getSharedPollSubscription(channel) {\n return this._getSub(channel);\n }\n /** removeSubscription allows removing Subcription from the internal registry. */\n removeSubscription(sub) {\n if (!sub) {\n return;\n }\n if (sub.state !== SubscriptionState.Unsubscribed) {\n sub.unsubscribe();\n }\n this._removeSubscription(sub);\n }\n /** Remove a map subscription. */\n removeMapSubscription(sub) {\n this.removeSubscription(sub);\n }\n /** Remove a shared poll subscription. */\n removeSharedPollSubscription(sub) {\n this.removeSubscription(sub);\n }\n /** Get a map with all current client-side subscriptions. */\n subscriptions() {\n return this._subs;\n }\n /** Get all map subscriptions. */\n mapSubscriptions() {\n const result = {};\n for (const [ch, sub] of Object.entries(this._subs)) {\n if (sub.type === 'map')\n result[ch] = sub;\n }\n return result;\n }\n /** Get all shared poll subscriptions. */\n sharedPollSubscriptions() {\n const result = {};\n for (const [ch, sub] of Object.entries(this._subs)) {\n if (sub.type === 'shared_poll')\n result[ch] = sub;\n }\n return result;\n }\n /** ready returns a Promise which resolves upon client goes to Connected\n * state and rejects in case of client goes to Disconnected or Failed state.\n * Users can provide optional timeout in milliseconds. */\n ready(timeout) {\n return __awaiter(this, void 0, void 0, function* () {\n switch (this.state) {\n case State.Disconnected:\n throw { code: errorCodes.clientDisconnected, message: 'client disconnected' };\n case State.Connected:\n return;\n default:\n return new Promise((resolve, reject) => {\n const ctx = { resolve, reject };\n if (timeout) {\n ctx.timeout = setTimeout(() => {\n reject({ code: errorCodes.timeout, message: 'timeout' });\n }, timeout);\n }\n this._promises[this._nextPromiseId()] = ctx;\n });\n }\n });\n }\n /** connect to a server. */\n connect() {\n if (this._isConnected()) {\n this._debug('connect called when already connected');\n return;\n }\n if (this._isConnecting()) {\n this._debug('connect called when already connecting');\n return;\n }\n this._debug('connect called');\n this._reconnectAttempts = 0;\n this._startConnecting();\n }\n /** disconnect from a server. */\n disconnect() {\n this._disconnect(disconnectedCodes.disconnectCalled, 'disconnect called', false);\n }\n /** setToken allows setting connection token. Or resetting used token to be empty. */\n setToken(token) {\n this._token = token;\n }\n /** setData allows setting connection data. This only affects the next connection attempt,\n * not the current one. Note that if getData callback is configured, it will override\n * this value during reconnects. */\n setData(data) {\n this._data = data;\n }\n /** setHeaders allows setting connection emulated headers. */\n setHeaders(headers) {\n this._config.headers = headers;\n }\n /** send asynchronous data to a server (without any response from a server\n * expected, see rpc method if you need response). */\n send(data) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = {\n send: {\n data\n }\n };\n yield this._methodCall();\n const sent = this._transportSendCommands([cmd]); // can send message to server without id set\n if (!sent) {\n throw this._createErrorObject(errorCodes.transportWriteError, 'transport write error');\n }\n });\n }\n /** rpc to a server - i.e. a call which waits for a response with data. */\n rpc(method, data) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = {\n rpc: {\n method,\n data\n }\n };\n yield this._methodCall();\n const result = yield this._callPromise(cmd, (reply) => reply.rpc);\n return {\n data: result.data\n };\n });\n }\n /** publish data to a channel. */\n publish(channel, data) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = {\n publish: {\n channel,\n data\n }\n };\n yield this._methodCall();\n yield this._callPromise(cmd, () => ({}));\n return {};\n });\n }\n /** Publish data to a key in a map channel without holding a MapSubscription.\n * Use this when you need to write to a map channel from outside a subscription\n * context (e.g. a standalone publisher). When you already hold a MapSubscription,\n * prefer `sub.publish(key, data)` instead \u2014 it enforces the method-call guard and\n * applies debounce configuration. */\n mapPublish(channel, key, data) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = {\n publish: { channel, type: 1, key, data }\n };\n yield this._methodCall();\n yield this._callPromise(cmd, () => ({}));\n return {};\n });\n }\n /** Remove a key from a map channel without holding a MapSubscription.\n * Use this when you need to remove a key from outside a subscription context.\n * When you already hold a MapSubscription, prefer `sub.remove(key)` instead \u2014\n * it enforces the method-call guard and cancels any pending debounced publish. */\n mapRemove(channel, key) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = {\n publish: { channel, type: 1, key, removed: true }\n };\n yield this._methodCall();\n yield this._callPromise(cmd, () => ({}));\n return {};\n });\n }\n /** history for a channel. By default it does not return publications (only current\n * StreamPosition data) \u2013 provide an explicit limit > 0 to load publications.*/\n history(channel, options) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = {\n history: this._getHistoryRequest(channel, options)\n };\n yield this._methodCall();\n const result = yield this._callPromise(cmd, (reply) => reply.history);\n const publications = [];\n if (result.publications) {\n for (let i = 0; i < result.publications.length; i++) {\n publications.push(this._getPublicationContext(channel, result.publications[i]));\n }\n }\n return {\n publications,\n epoch: result.epoch || '',\n offset: result.offset || 0\n };\n });\n }\n /** presence for a channel. */\n presence(channel) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = {\n presence: {\n channel\n }\n };\n yield this._methodCall();\n const result = yield this._callPromise(cmd, (reply) => reply.presence);\n const clients = result.presence;\n for (const clientId in clients) {\n if (Object.prototype.hasOwnProperty.call(clients, clientId)) {\n const rawClient = clients[clientId];\n const connInfo = rawClient['conn_info'];\n const chanInfo = rawClient['chan_info'];\n if (connInfo) {\n rawClient.connInfo = connInfo;\n }\n if (chanInfo) {\n rawClient.chanInfo = chanInfo;\n }\n }\n }\n return { clients };\n });\n }\n presenceStats(channel) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = {\n 'presence_stats': {\n channel\n }\n };\n yield this._methodCall();\n const result = yield this._callPromise(cmd, (reply) => {\n return reply.presence_stats;\n });\n return {\n numUsers: result.num_users,\n numClients: result.num_clients\n };\n });\n }\n /** start command batching (collect into temporary buffer without sending to a server)\n * until stopBatching called.*/\n startBatching() {\n // start collecting messages without sending them to Centrifuge until flush\n // method called\n this._batching = true;\n }\n /** stop batching commands and flush collected commands to the\n * network (all in one request/frame).*/\n stopBatching() {\n const self = this;\n // Why so nested? Two levels here requred to deal with promise resolving queue.\n // In Subscription case we wait 2 futures before sending data to connection.\n // Otherwise _batching becomes false before batching decision has a chance to be executed.\n Promise.resolve().then(function () {\n Promise.resolve().then(function () {\n self._batching = false;\n self._flush();\n });\n });\n }\n _debug(...args) {\n if (!this._debugEnabled) {\n return;\n }\n log('debug', args);\n }\n _codecName() {\n return this._codec.name();\n }\n /** @internal */\n _formatOverride() {\n return;\n }\n _configure() {\n if (!('Promise' in globalThis)) {\n throw new Error('Promise polyfill required');\n }\n if (!this._endpoint) {\n throw new Error('endpoint configuration required');\n }\n if (this._config.token !== null) {\n this._token = this._config.token;\n }\n if (this._config.data !== null) {\n this._data = this._config.data;\n }\n this._codec = new JsonCodec();\n this._formatOverride();\n if (this._config.debug === true || localStorageItem('centrifuge.debug')) {\n this._debugEnabled = true;\n }\n this._debug('config', this._config);\n if (typeof this._endpoint === 'string') ;\n else if (Array.isArray(this._endpoint)) {\n this._transports = this._endpoint;\n this._emulation = true;\n for (const i in this._transports) {\n if (this._transports.hasOwnProperty(i)) {\n const transportConfig = this._transports[i];\n if (!transportConfig.endpoint || !transportConfig.transport) {\n throw new Error('malformed transport configuration');\n }\n const transportName = transportConfig.transport;\n if (['websocket', 'http_stream', 'sse', 'sockjs', 'webtransport'].indexOf(transportName) < 0) {\n throw new Error('unsupported transport name: ' + transportName);\n }\n }\n }\n }\n else {\n throw new Error('unsupported url configuration type: only string or array of objects are supported');\n }\n }\n _setState(newState) {\n if (this.state !== newState) {\n this._reconnecting = false;\n const oldState = this.state;\n this.state = newState;\n this.emit('state', { newState, oldState });\n return true;\n }\n return false;\n }\n _isDisconnected() {\n return this.state === State.Disconnected;\n }\n _isConnecting() {\n return this.state === State.Connecting;\n }\n _isConnected() {\n return this.state === State.Connected;\n }\n _nextCommandId() {\n return ++this._commandId;\n }\n _setNetworkEvents() {\n if (this._networkEventsSet) {\n return;\n }\n let eventTarget = null;\n if (this._config.networkEventTarget !== null) {\n eventTarget = this._config.networkEventTarget;\n }\n else if (typeof globalThis.addEventListener !== 'undefined') {\n eventTarget = globalThis;\n }\n if (eventTarget) {\n eventTarget.addEventListener('offline', () => {\n this._debug('offline event triggered');\n if (this.state === State.Connected || this.state === State.Connecting) {\n this._disconnect(connectingCodes.transportClosed, 'transport closed', true);\n this._deviceWentOffline = true;\n }\n });\n eventTarget.addEventListener('online', () => {\n this._debug('online event triggered');\n if (this.state !== State.Connecting) {\n return;\n }\n if (this._deviceWentOffline && !this._transportClosed) {\n // This is a workaround for mobile Safari where close callback may be\n // not issued upon device going to the flight mode. We know for sure\n // that transport close was called, so we start reconnecting. In this\n // case if the close callback will be issued for some reason after some\n // time \u2013 it will be ignored due to transport ID mismatch.\n this._deviceWentOffline = false;\n this._transportClosed = true;\n }\n this._clearReconnectTimeout();\n this._startReconnecting();\n });\n this._networkEventsSet = true;\n }\n }\n _getReconnectDelay() {\n const delay = backoff(this._reconnectAttempts, this._config.minReconnectDelay, this._config.maxReconnectDelay);\n this._reconnectAttempts += 1;\n return delay;\n }\n _clearOutgoingRequests() {\n // fire errbacks of registered outgoing calls.\n for (const id in this._callbacks) {\n if (this._callbacks.hasOwnProperty(id)) {\n const callbacks = this._callbacks[id];\n clearTimeout(callbacks.timeout);\n const errback = callbacks.errback;\n if (!errback) {\n continue;\n }\n errback({ error: this._createErrorObject(errorCodes.connectionClosed, 'connection closed') });\n }\n }\n this._callbacks = {};\n }\n _clearConnectedState() {\n this._client = null;\n this._clearServerPingTimeout();\n this._clearRefreshTimeout();\n // fire events for client-side subscriptions.\n for (const channel in this._subs) {\n if (!this._subs.hasOwnProperty(channel)) {\n continue;\n }\n const sub = this._subs[channel];\n if (sub.state === SubscriptionState.Subscribed) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n sub._setSubscribing(subscribingCodes.transportClosed, 'transport closed');\n }\n }\n // fire events for server-side subscriptions.\n for (const channel in this._serverSubs) {\n if (this._serverSubs.hasOwnProperty(channel)) {\n this.emit('subscribing', { channel: channel });\n }\n }\n }\n _handleWriteError(commands) {\n for (const command of commands) {\n const id = command.id;\n if (!(id in this._callbacks)) {\n continue;\n }\n const callbacks = this._callbacks[id];\n clearTimeout(this._callbacks[id].timeout);\n delete this._callbacks[id];\n const errback = callbacks.errback;\n errback({ error: this._createErrorObject(errorCodes.transportWriteError, 'transport write error') });\n }\n }\n _transportSendCommands(commands) {\n if (!commands.length) {\n return true;\n }\n if (!this._transport) {\n return false;\n }\n try {\n this._transport.send(this._codec.encodeCommands(commands), this._session, this._node);\n }\n catch (e) {\n this._debug('error writing commands', e);\n this._handleWriteError(commands);\n return false;\n }\n return true;\n }\n _advanceTransportIndex() {\n this._currentTransportIndex++;\n if (this._currentTransportIndex >= this._transports.length) {\n this._triedAllTransports = true;\n this._currentTransportIndex = 0;\n }\n }\n _initializeTransport() {\n let websocket;\n if (this._config.websocket !== null) {\n websocket = this._config.websocket;\n }\n else {\n if (!(typeof globalThis.WebSocket !== 'function' && typeof globalThis.WebSocket !== 'object')) {\n websocket = globalThis.WebSocket;\n }\n }\n let sockjs = null;\n if (this._config.sockjs !== null) {\n sockjs = this._config.sockjs;\n }\n else {\n if (typeof globalThis.SockJS !== 'undefined') {\n sockjs = globalThis.SockJS;\n }\n }\n let eventsource = null;\n if (this._config.eventsource !== null) {\n eventsource = this._config.eventsource;\n }\n else {\n if (typeof globalThis.EventSource !== 'undefined') {\n eventsource = globalThis.EventSource;\n }\n }\n let fetchFunc = null;\n if (this._config.fetch !== null) {\n fetchFunc = this._config.fetch;\n }\n else {\n if (typeof globalThis.fetch !== 'undefined') {\n fetchFunc = globalThis.fetch;\n }\n }\n let readableStream = null;\n if (this._config.readableStream !== null) {\n readableStream = this._config.readableStream;\n }\n else {\n if (typeof globalThis.ReadableStream !== 'undefined') {\n readableStream = globalThis.ReadableStream;\n }\n }\n if (!this._emulation) {\n if (startsWith(this._endpoint, 'http')) {\n throw new Error('Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport');\n }\n else {\n this._debug('client will use websocket');\n this._transport = new WebsocketTransport(this._endpoint, {\n websocket: websocket\n });\n if (!this._transport.supported()) {\n throw new Error('WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options');\n }\n }\n }\n else {\n if (this._currentTransportIndex >= this._transports.length) {\n this._triedAllTransports = true;\n this._currentTransportIndex = 0;\n }\n let count = 0;\n while (true) {\n if (count >= this._transports.length) {\n throw new Error('no supported transport found');\n }\n const transportConfig = this._transports[this._currentTransportIndex];\n const transportName = transportConfig.transport;\n const transportEndpoint = transportConfig.endpoint;\n if (transportName === 'websocket') {\n this._debug('trying websocket transport');\n this._transport = new WebsocketTransport(transportEndpoint, {\n websocket: websocket\n });\n if (!this._transport.supported()) {\n this._debug('websocket transport not available');\n this._advanceTransportIndex();\n count++;\n continue;\n }\n }\n else if (transportName === 'webtransport') {\n this._debug('trying webtransport transport');\n this._transport = new WebtransportTransport(transportEndpoint, {\n webtransport: globalThis.WebTransport,\n decoder: this._codec,\n encoder: this._codec\n });\n if (!this._transport.supported()) {\n this._debug('webtransport transport not available');\n this._advanceTransportIndex();\n count++;\n continue;\n }\n }\n else if (transportName === 'http_stream') {\n this._debug('trying http_stream transport');\n this._transport = new HttpStreamTransport(transportEndpoint, {\n fetch: fetchFunc,\n readableStream: readableStream,\n emulationEndpoint: this._config.emulationEndpoint,\n decoder: this._codec,\n encoder: this._codec\n });\n if (!this._transport.supported()) {\n this._debug('http_stream transport not available');\n this._advanceTransportIndex();\n count++;\n continue;\n }\n }\n else if (transportName === 'sse') {\n this._debug('trying sse transport');\n this._transport = new SseTransport(transportEndpoint, {\n eventsource: eventsource,\n fetch: fetchFunc,\n emulationEndpoint: this._config.emulationEndpoint,\n });\n if (!this._transport.supported()) {\n this._debug('sse transport not available');\n this._advanceTransportIndex();\n count++;\n continue;\n }\n }\n else if (transportName === 'sockjs') {\n this._debug('trying sockjs');\n this._transport = new SockjsTransport(transportEndpoint, {\n sockjs: sockjs,\n sockjsOptions: this._config.sockjsOptions\n });\n if (!this._transport.supported()) {\n this._debug('sockjs transport not available');\n this._advanceTransportIndex();\n count++;\n continue;\n }\n }\n else {\n throw new Error('unknown transport ' + transportName);\n }\n break;\n }\n }\n const self = this;\n const transport = this._transport;\n const transportId = this._nextTransportId();\n self._debug(\"id of transport\", transportId);\n let wasOpen = false;\n const initialCommands = [];\n if (this._transport.emulation()) {\n const connectCommand = self._sendConnect(true);\n initialCommands.push(connectCommand);\n }\n this._setNetworkEvents();\n const initialData = this._codec.encodeCommands(initialCommands);\n this._transportClosed = false;\n let connectTimeout;\n connectTimeout = setTimeout(function () {\n transport.close();\n }, this._config.timeout);\n this._transport.initialize(this._codecName(), {\n onOpen: function () {\n if (connectTimeout) {\n clearTimeout(connectTimeout);\n connectTimeout = null;\n }\n if (self._transportId != transportId) {\n self._debug('open callback from non-actual transport');\n transport.close();\n return;\n }\n wasOpen = true;\n self._debug(transport.subName(), 'transport open');\n if (transport.emulation()) {\n return;\n }\n self._transportIsOpen = true;\n self._transportWasOpen = true;\n self.startBatching();\n self._sendConnect(false);\n self._sendSubscribeCommands();\n self.stopBatching();\n //@ts-ignore must be used only for debug and test purposes. Exposed only for non-emulation transport.\n self.emit('__centrifuge_debug:connect_frame_sent', {});\n },\n onError: function (e) {\n if (self._transportId != transportId) {\n self._debug('error callback from non-actual transport');\n return;\n }\n self._debug('transport level error', e);\n },\n onClose: function (closeEvent) {\n if (connectTimeout) {\n clearTimeout(connectTimeout);\n connectTimeout = null;\n }\n if (self._transportId != transportId) {\n self._debug('close callback from non-actual transport');\n return;\n }\n self._debug(transport.subName(), 'transport closed');\n self._transportClosed = true;\n self._transportIsOpen = false;\n let reason = 'connection closed';\n let needReconnect = true;\n let code = 0;\n if (closeEvent && 'code' in closeEvent && closeEvent.code) {\n code = closeEvent.code;\n }\n if (closeEvent && closeEvent.reason) {\n try {\n const advice = JSON.parse(closeEvent.reason);\n reason = advice.reason;\n needReconnect = advice.reconnect;\n }\n catch (e) {\n reason = closeEvent.reason;\n if ((code >= 3500 && code < 4000) || (code >= 4500 && code < 5000)) {\n needReconnect = false;\n }\n }\n }\n if (code < 3000) {\n if (code === 1009) {\n code = disconnectedCodes.messageSizeLimit;\n reason = 'message size limit exceeded';\n needReconnect = false;\n }\n else {\n code = connectingCodes.transportClosed;\n reason = 'transport closed';\n }\n if (self._emulation && !self._transportWasOpen) {\n self._advanceTransportIndex();\n }\n }\n else {\n // Codes >= 3000 are sent from a server application level.\n self._transportWasOpen = true;\n }\n if (self._isConnecting() && !wasOpen) {\n self.emit('error', {\n type: 'transport',\n error: {\n code: errorCodes.transportClosed,\n message: 'transport closed'\n },\n transport: transport.name()\n });\n }\n self._reconnecting = false;\n self._disconnect(code, reason, needReconnect);\n },\n onMessage: function (data) {\n self._dataReceived(data);\n }\n }, initialData);\n //@ts-ignore must be used only for debug and test purposes.\n self.emit('__centrifuge_debug:transport_initialized', {});\n }\n _sendConnect(skipSending) {\n const connectCommand = this._constructConnectCommand();\n const self = this;\n this._call(connectCommand, skipSending).then(resolveCtx => {\n const result = resolveCtx.reply.connect;\n self._connectResponse(result);\n if (resolveCtx.next) {\n resolveCtx.next();\n }\n }, rejectCtx => {\n self._connectError(rejectCtx.error);\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n });\n return connectCommand;\n }\n _startReconnecting() {\n this._debug('start reconnecting');\n if (!this._isConnecting()) {\n this._debug('stop reconnecting: client not in connecting state');\n return;\n }\n if (this._reconnecting) {\n this._debug('reconnect already in progress, return from reconnect routine');\n return;\n }\n if (this._transportClosed === false) {\n this._debug('waiting for transport close');\n return;\n }\n this._reconnecting = true;\n const emptyToken = this._token === '';\n const needTokenRefresh = this._refreshRequired || (emptyToken && this._config.getToken !== null);\n if (!needTokenRefresh) {\n if (this._config.getData) {\n this._config.getData().then(data => {\n if (!this._isConnecting()) {\n return;\n }\n this._data = data;\n this._initializeTransport();\n })\n .catch(e => this._handleGetDataError(e));\n }\n else {\n this._initializeTransport();\n }\n return;\n }\n const self = this;\n this._getToken().then(function (token) {\n if (!self._isConnecting()) {\n return;\n }\n if (token == null || token == undefined) {\n self._failUnauthorized();\n return;\n }\n self._token = token;\n self._debug('connection token refreshed');\n if (self._config.getData) {\n self._config.getData().then(function (data) {\n if (!self._isConnecting()) {\n return;\n }\n self._data = data;\n self._initializeTransport();\n })\n .catch(e => self._handleGetDataError(e));\n }\n else {\n self._initializeTransport();\n }\n }).catch(function (e) {\n if (!self._isConnecting()) {\n return;\n }\n if (e instanceof UnauthorizedError) {\n self._failUnauthorized();\n return;\n }\n self.emit('error', {\n 'type': 'connectToken',\n 'error': {\n code: errorCodes.clientConnectToken,\n message: e !== undefined ? e.toString() : ''\n }\n });\n const delay = self._getReconnectDelay();\n self._debug('error on getting connection token, reconnect after ' + delay + ' milliseconds', e);\n self._reconnecting = false;\n self._reconnectTimeout = setTimeout(() => {\n self._startReconnecting();\n }, delay);\n });\n }\n _handleGetDataError(e) {\n if (e instanceof UnauthorizedError) {\n this._failUnauthorized();\n return;\n }\n this.emit('error', {\n type: 'connectData',\n error: {\n code: errorCodes.badConfiguration,\n message: (e === null || e === void 0 ? void 0 : e.toString()) || ''\n }\n });\n const delay = this._getReconnectDelay();\n this._debug('error on getting connect data, reconnect after ' + delay + ' milliseconds', e);\n this._reconnecting = false;\n this._reconnectTimeout = setTimeout(() => {\n this._startReconnecting();\n }, delay);\n }\n _connectError(err) {\n if (this.state !== State.Connecting) {\n return;\n }\n if (err.code === 109) { // token expired.\n // next connect attempt will try to refresh token.\n this._refreshRequired = true;\n }\n if (err.code < 100 || err.temporary === true || err.code === 109) {\n this.emit('error', {\n 'type': 'connect',\n 'error': err\n });\n this._debug('closing transport due to connect error');\n this._disconnect(err.code, err.message, true);\n }\n else {\n this._disconnect(err.code, err.message, false);\n }\n }\n _scheduleReconnect() {\n if (!this._isConnecting()) {\n return;\n }\n let isInitialHandshake = false;\n if (this._emulation && !this._transportWasOpen && !this._triedAllTransports) {\n isInitialHandshake = true;\n }\n let delay = this._getReconnectDelay();\n if (isInitialHandshake) {\n delay = 0;\n }\n this._debug('reconnect after ' + delay + ' milliseconds');\n this._clearReconnectTimeout();\n this._reconnectTimeout = setTimeout(() => {\n this._startReconnecting();\n }, delay);\n }\n _constructConnectCommand() {\n const req = {};\n if (this._token) {\n req.token = this._token;\n }\n if (this._data) {\n req.data = this._data;\n }\n if (this._config.name) {\n req.name = this._config.name;\n }\n if (this._config.version) {\n req.version = this._config.version;\n }\n if (Object.keys(this._config.headers).length > 0) {\n req.headers = this._config.headers;\n }\n const subs = {};\n let hasSubs = false;\n for (const channel in this._serverSubs) {\n if (this._serverSubs.hasOwnProperty(channel) && this._serverSubs[channel].recoverable) {\n hasSubs = true;\n const sub = {\n 'recover': true\n };\n if (this._serverSubs[channel].offset) {\n sub['offset'] = this._serverSubs[channel].offset;\n }\n if (this._serverSubs[channel].epoch) {\n sub['epoch'] = this._serverSubs[channel].epoch;\n }\n subs[channel] = sub;\n }\n }\n if (hasSubs) {\n req.subs = subs;\n }\n return {\n connect: req\n };\n }\n _getHistoryRequest(channel, options) {\n const req = {\n channel: channel\n };\n if (options !== undefined) {\n if (options.since) {\n req.since = {\n offset: options.since.offset\n };\n if (options.since.epoch) {\n req.since.epoch = options.since.epoch;\n }\n }\n if (options.limit !== undefined) {\n req.limit = options.limit;\n }\n if (options.reverse === true) {\n req.reverse = true;\n }\n }\n return req;\n }\n _methodCall() {\n if (this._isConnected()) {\n return Promise.resolve();\n }\n return new Promise((res, rej) => {\n const timeout = setTimeout(function () {\n rej({ code: errorCodes.timeout, message: 'timeout' });\n }, this._config.timeout);\n this._promises[this._nextPromiseId()] = {\n timeout: timeout,\n resolve: res,\n reject: rej\n };\n });\n }\n _callPromise(cmd, resultCB) {\n return new Promise((resolve, reject) => {\n this._call(cmd, false).then((resolveCtx) => {\n var _a;\n const result = resultCB(resolveCtx.reply);\n resolve(result);\n (_a = resolveCtx.next) === null || _a === void 0 ? void 0 : _a.call(resolveCtx);\n }, (rejectCtx) => {\n var _a;\n reject(rejectCtx.error);\n (_a = rejectCtx.next) === null || _a === void 0 ? void 0 : _a.call(rejectCtx);\n });\n });\n }\n _dataReceived(data) {\n if (this._serverPing > 0) {\n this._waitServerPing();\n }\n const replies = this._codec.decodeReplies(data);\n // We have to guarantee order of events in replies processing - i.e. start processing\n // next reply only when we finished processing of current one. Without syncing things in\n // this way we could get wrong publication events order as reply promises resolve\n // on next loop tick so for loop continues before we finished emitting all reply events.\n this._dispatchPromise = this._dispatchPromise.then(() => {\n let finishDispatch;\n this._dispatchPromise = new Promise(resolve => {\n finishDispatch = resolve;\n });\n this._dispatchSynchronized(replies, finishDispatch);\n });\n }\n _dispatchSynchronized(replies, finishDispatch) {\n let p = Promise.resolve();\n for (const i in replies) {\n if (replies.hasOwnProperty(i)) {\n p = p.then(() => {\n return this._dispatchReply(replies[i]);\n });\n }\n }\n p.then(() => {\n finishDispatch();\n });\n }\n _dispatchReply(reply) {\n let next;\n const p = new Promise(resolve => {\n next = resolve;\n });\n if (reply === undefined || reply === null) {\n this._debug('dispatch: got undefined or null reply');\n next();\n return p;\n }\n const id = reply.id;\n if (id && id > 0) {\n this._handleReply(reply, next);\n }\n else {\n if (!reply.push) {\n this._handleServerPing(next);\n }\n else {\n this._handlePush(reply.push, next);\n }\n }\n return p;\n }\n _call(cmd, skipSending) {\n return new Promise((resolve, reject) => {\n cmd.id = this._nextCommandId();\n this._registerCall(cmd.id, resolve, reject);\n if (!skipSending) {\n this._addCommand(cmd);\n }\n });\n }\n _startConnecting() {\n this._debug('start connecting');\n if (this._setState(State.Connecting)) {\n this.emit('connecting', { code: connectingCodes.connectCalled, reason: 'connect called' });\n }\n this._client = null;\n this._startReconnecting();\n }\n _disconnect(code, reason, reconnect) {\n if (code === disconnectedCodes.stateInvalidated) {\n // State invalidated: clear connection token (forcing a fresh one via\n // getToken on reconnect) and invalidate all subscription state. Done here\n // (the shared funnel) so it fires whether it arrives as a Disconnect push\n // or as a raw WebSocket close code \u2014 and before _clearConnectedState below\n // moves subscriptions to subscribing for the resubscribe. Runs ahead of the\n // isDisconnected guard so the invalidation is unconditional.\n this._token = '';\n this._refreshRequired = true;\n for (const channel in this._subs) {\n if (this._subs.hasOwnProperty(channel)) {\n // @ts-ignore \u2013 _invalidateState is internal.\n this._subs[channel]._invalidateState();\n }\n }\n // Server-side subscriptions carry their own cached recovery position,\n // separate from the client-side subscriptions above \u2014 reset it to the\n // same unrecoverable sentinel so the next connect can't recover from\n // now-invalidated state.\n for (const channel in this._serverSubs) {\n if (this._serverSubs.hasOwnProperty(channel)) {\n this._serverSubs[channel].offset = 0;\n this._serverSubs[channel].epoch = '_';\n }\n }\n }\n if (this._isDisconnected()) {\n return;\n }\n // we mark transport is closed right away, because _clearConnectedState will move subscriptions to subscribing state\n // if transport will still be open at this time, subscribe frames will be sent to closing transport\n this._transportIsOpen = false;\n const previousState = this.state;\n this._reconnecting = false;\n const ctx = {\n code: code,\n reason: reason\n };\n let needEvent;\n if (reconnect) {\n needEvent = this._setState(State.Connecting);\n }\n else {\n needEvent = this._setState(State.Disconnected);\n this._rejectPromises({ code: errorCodes.clientDisconnected, message: 'disconnected' });\n }\n this._clearOutgoingRequests();\n if (previousState === State.Connecting) {\n this._clearReconnectTimeout();\n }\n if (previousState === State.Connected) {\n this._clearConnectedState();\n }\n if (needEvent) {\n if (this._isConnecting()) {\n this.emit('connecting', ctx);\n }\n else {\n this.emit('disconnected', ctx);\n }\n }\n if (this._transport) {\n this._debug(\"closing existing transport\");\n const transport = this._transport;\n this._transport = null;\n transport.close(); // Close only after setting this._transport to null to avoid recursion when calling transport close().\n // Need to mark as closed here, because connect call may be sync called after disconnect,\n // transport onClose callback will not be called yet\n this._transportClosed = true;\n this._nextTransportId();\n }\n else {\n this._debug(\"no transport to close\");\n }\n this._scheduleReconnect();\n }\n _failUnauthorized() {\n this._disconnect(disconnectedCodes.unauthorized, 'unauthorized', false);\n }\n _getToken() {\n this._debug('get connection token');\n if (!this._config.getToken) {\n this.emit('error', {\n type: 'configuration',\n error: {\n code: errorCodes.badConfiguration,\n message: 'token expired but no getToken function set in the configuration'\n }\n });\n return Promise.reject(new UnauthorizedError(''));\n }\n return this._config.getToken({});\n }\n _refresh() {\n const clientId = this._client;\n const self = this;\n this._getToken().then(function (token) {\n if (clientId !== self._client) {\n return;\n }\n if (!token) {\n self._failUnauthorized();\n return;\n }\n self._token = token;\n self._debug('connection token refreshed');\n if (!self._isConnected()) {\n return;\n }\n const cmd = {\n refresh: { token: self._token }\n };\n self._call(cmd, false).then(resolveCtx => {\n const result = resolveCtx.reply.refresh;\n self._refreshResponse(result);\n if (resolveCtx.next) {\n resolveCtx.next();\n }\n }, rejectCtx => {\n self._refreshError(rejectCtx.error);\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n });\n }).catch(function (e) {\n if (!self._isConnected()) {\n return;\n }\n if (e instanceof UnauthorizedError) {\n self._failUnauthorized();\n return;\n }\n self.emit('error', {\n type: 'refreshToken',\n error: {\n code: errorCodes.clientRefreshToken,\n message: e !== undefined ? e.toString() : ''\n }\n });\n self._refreshTimeout = setTimeout(() => self._refresh(), self._getRefreshRetryDelay());\n });\n }\n _refreshError(err) {\n if (err.code < 100 || err.temporary === true) {\n this.emit('error', {\n type: 'refresh',\n error: err\n });\n this._refreshTimeout = setTimeout(() => this._refresh(), this._getRefreshRetryDelay());\n }\n else {\n this._disconnect(err.code, err.message, false);\n }\n }\n _getRefreshRetryDelay() {\n return backoff(0, 5000, 10000);\n }\n _refreshResponse(result) {\n if (this._refreshTimeout) {\n clearTimeout(this._refreshTimeout);\n this._refreshTimeout = null;\n }\n if (result.expires) {\n this._client = result.client;\n this._refreshTimeout = setTimeout(() => this._refresh(), ttlMilliseconds(result.ttl));\n }\n }\n _removeSubscription(sub) {\n if (sub === null) {\n return;\n }\n delete this._subs[sub.channel];\n }\n _unsubscribe(sub) {\n if (!this._transportIsOpen) {\n return Promise.resolve();\n }\n const req = {\n channel: sub.channel\n };\n const cmd = { unsubscribe: req };\n const self = this;\n const unsubscribePromise = new Promise((resolve, _) => {\n this._call(cmd, false).then(resolveCtx => {\n resolve();\n if (resolveCtx.next) {\n resolveCtx.next();\n }\n }, rejectCtx => {\n resolve();\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n self._disconnect(connectingCodes.unsubscribeError, 'unsubscribe error', true);\n });\n });\n return unsubscribePromise;\n }\n _getSub(channel, id) {\n if (id && id > 0) {\n for (const ch in this._subs) {\n if (this._subs.hasOwnProperty(ch)) {\n const sub = this._subs[ch];\n // @ts-ignore \u2013 we are accessing private property for internal use\n if (sub._id === id) {\n return sub;\n }\n }\n }\n return null;\n }\n const sub = this._subs[channel];\n if (!sub) {\n return null;\n }\n return sub;\n }\n _isServerSub(channel) {\n return this._serverSubs[channel] !== undefined;\n }\n _sendSubscribeCommands() {\n const commands = [];\n for (const channel in this._subs) {\n if (!this._subs.hasOwnProperty(channel)) {\n continue;\n }\n const sub = this._subs[channel];\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n if (sub._inflight === true) {\n continue;\n }\n if (sub.state === SubscriptionState.Subscribing) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n const cmd = sub._subscribe();\n if (cmd) {\n commands.push(cmd);\n }\n }\n }\n return commands;\n }\n _connectResponse(result) {\n this._transportIsOpen = true;\n this._transportWasOpen = true;\n this._reconnectAttempts = 0;\n this._refreshRequired = false;\n if (this._isConnected()) {\n return;\n }\n this._client = result.client;\n this._setState(State.Connected);\n if (this._refreshTimeout) {\n clearTimeout(this._refreshTimeout);\n }\n if (result.expires) {\n this._refreshTimeout = setTimeout(() => this._refresh(), ttlMilliseconds(result.ttl));\n }\n this._session = result.session;\n this._node = result.node;\n this.startBatching();\n this._sendSubscribeCommands();\n this.stopBatching();\n const ctx = {\n client: result.client,\n transport: this._transport.subName()\n };\n if (result.data) {\n ctx.data = result.data;\n }\n this.emit('connected', ctx);\n this._resolvePromises();\n this._processServerSubs(result.subs || {});\n if (result.ping && result.ping > 0) {\n this._serverPing = result.ping * 1000;\n this._sendPong = result.pong === true;\n this._waitServerPing();\n }\n else {\n this._serverPing = 0;\n }\n }\n _processServerSubs(subs) {\n for (const channel in subs) {\n if (!subs.hasOwnProperty(channel)) {\n continue;\n }\n const sub = subs[channel];\n this._serverSubs[channel] = {\n 'offset': sub.offset,\n 'epoch': sub.epoch,\n 'recoverable': sub.recoverable || false\n };\n const subCtx = this._getSubscribeContext(channel, sub);\n this.emit('subscribed', subCtx);\n }\n for (const channel in subs) {\n if (!subs.hasOwnProperty(channel)) {\n continue;\n }\n const sub = subs[channel];\n if (sub.recovered) {\n const pubs = sub.publications;\n if (pubs && pubs.length > 0) {\n for (const i in pubs) {\n if (pubs.hasOwnProperty(i)) {\n this._handlePublication(channel, pubs[i]);\n }\n }\n }\n }\n }\n for (const channel in this._serverSubs) {\n if (!this._serverSubs.hasOwnProperty(channel)) {\n continue;\n }\n if (!subs[channel]) {\n this.emit('unsubscribed', { channel: channel });\n delete this._serverSubs[channel];\n }\n }\n }\n _clearRefreshTimeout() {\n if (this._refreshTimeout !== null) {\n clearTimeout(this._refreshTimeout);\n this._refreshTimeout = null;\n }\n }\n _clearReconnectTimeout() {\n if (this._reconnectTimeout !== null) {\n clearTimeout(this._reconnectTimeout);\n this._reconnectTimeout = null;\n }\n }\n _clearServerPingTimeout() {\n if (this._serverPingTimeout !== null) {\n clearTimeout(this._serverPingTimeout);\n this._serverPingTimeout = null;\n }\n }\n _waitServerPing() {\n if (this._config.maxServerPingDelay === 0) {\n return;\n }\n if (!this._isConnected()) {\n return;\n }\n this._clearServerPingTimeout();\n this._serverPingTimeout = setTimeout(() => {\n if (!this._isConnected()) {\n return;\n }\n this._disconnect(connectingCodes.noPing, 'no ping', true);\n }, this._serverPing + this._config.maxServerPingDelay);\n }\n _getSubscribeContext(channel, result) {\n const ctx = {\n channel: channel,\n positioned: false,\n recoverable: false,\n wasRecovering: false,\n recovered: false,\n hasRecoveredPublications: false,\n };\n if (result.recovered) {\n ctx.recovered = true;\n }\n if (result.positioned) {\n ctx.positioned = true;\n }\n if (result.recoverable) {\n ctx.recoverable = true;\n }\n if (result.was_recovering) {\n ctx.wasRecovering = true;\n }\n let epoch = '';\n if ('epoch' in result) {\n epoch = result.epoch;\n }\n let offset = 0;\n if ('offset' in result) {\n offset = result.offset;\n }\n if (ctx.positioned || ctx.recoverable) {\n ctx.streamPosition = {\n 'offset': offset,\n 'epoch': epoch\n };\n }\n if (Array.isArray(result.publications) && result.publications.length > 0) {\n ctx.hasRecoveredPublications = true;\n }\n if (result.data) {\n ctx.data = result.data;\n }\n return ctx;\n }\n _handleReply(reply, next) {\n const id = reply.id;\n if (!(id in this._callbacks)) {\n next();\n return;\n }\n const callbacks = this._callbacks[id];\n clearTimeout(this._callbacks[id].timeout);\n delete this._callbacks[id];\n if (!errorExists(reply)) {\n const callback = callbacks.callback;\n if (!callback) {\n return;\n }\n callback({ reply, next });\n }\n else {\n const errback = callbacks.errback;\n if (!errback) {\n next();\n return;\n }\n const error = { code: reply.error.code, message: reply.error.message || '', temporary: reply.error.temporary || false };\n errback({ error, next });\n }\n }\n _handleJoin(channel, join, id) {\n const sub = this._getSub(channel, id);\n if (!sub) {\n // See _handlePublication: a compacted push with an unknown id has an empty\n // channel and no matching subscription \u2014 drop instead of crashing.\n if (channel && this._isServerSub(channel)) {\n const ctx = { channel: channel, info: this._getJoinLeaveContext(join.info) };\n this.emit('join', ctx);\n }\n return;\n }\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n sub._handleJoin(join);\n }\n _handleLeave(channel, leave, id) {\n const sub = this._getSub(channel, id);\n if (!sub) {\n // See _handlePublication: a compacted push with an unknown id has an empty\n // channel and no matching subscription \u2014 drop instead of crashing.\n if (channel && this._isServerSub(channel)) {\n const ctx = { channel: channel, info: this._getJoinLeaveContext(leave.info) };\n this.emit('leave', ctx);\n }\n return;\n }\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n sub._handleLeave(leave);\n }\n _handleUnsubscribe(channel, unsubscribe) {\n const sub = this._getSub(channel, 0);\n if (!sub && channel) {\n if (this._isServerSub(channel)) {\n delete this._serverSubs[channel];\n this.emit('unsubscribed', { channel: channel });\n }\n return;\n }\n if (unsubscribe.code < 2500) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n sub._setUnsubscribed(unsubscribe.code, unsubscribe.reason, false);\n }\n else {\n if (unsubscribe.code === unsubscribedCodes.stateInvalidated) {\n // State invalidated: clear subscription token and cached state so the\n // resubscribe gets a fresh token and re-syncs.\n // @ts-ignore \u2013 _invalidateState is internal.\n sub._invalidateState();\n }\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n sub._setSubscribing(unsubscribe.code, unsubscribe.reason);\n }\n }\n _handleSubscribe(channel, sub) {\n this._serverSubs[channel] = {\n 'offset': sub.offset,\n 'epoch': sub.epoch,\n 'recoverable': sub.recoverable || false\n };\n this.emit('subscribed', this._getSubscribeContext(channel, sub));\n }\n _handleDisconnect(disconnect) {\n const code = disconnect.code;\n let reconnect = true;\n if ((code >= 3500 && code < 4000) || (code >= 4500 && code < 5000)) {\n reconnect = false;\n }\n // State invalidation (code 3014) is handled centrally in _disconnect so it\n // covers both delivery paths: a Disconnect push (this method) and a raw\n // WebSocket close code (transport onClose \u2192 _disconnect directly).\n this._disconnect(code, disconnect.reason, reconnect);\n }\n _getPublicationContext(channel, pub) {\n const ctx = {\n channel: channel,\n data: pub.data\n };\n if (pub.offset) {\n ctx.offset = pub.offset;\n }\n if (pub.info) {\n ctx.info = this._getJoinLeaveContext(pub.info);\n }\n if (pub.tags) {\n ctx.tags = pub.tags;\n }\n return ctx;\n }\n _getJoinLeaveContext(clientInfo) {\n const info = {\n client: clientInfo.client,\n user: clientInfo.user\n };\n const connInfo = clientInfo['conn_info'];\n if (connInfo) {\n info.connInfo = connInfo;\n }\n const chanInfo = clientInfo['chan_info'];\n if (chanInfo) {\n info.chanInfo = chanInfo;\n }\n return info;\n }\n _handlePublication(channel, pub, id) {\n const sub = this._getSub(channel, id);\n if (!sub) {\n // No client-side subscription. With channel compaction the push carries a\n // numeric id and no channel, so an unknown id (e.g. a publication for a\n // subscription already unsubscribed) has an empty channel here \u2014 it must\n // be dropped, not fall through to sub._handlePublication on null.\n if (channel && this._isServerSub(channel)) {\n const ctx = this._getPublicationContext(channel, pub);\n this.emit('publication', ctx);\n if (pub.offset !== undefined) {\n this._serverSubs[channel].offset = pub.offset;\n }\n }\n return;\n }\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n sub._handlePublication(pub);\n }\n _handleMessage(message) {\n this.emit('message', { data: message.data });\n }\n _handleServerPing(next) {\n if (this._sendPong) {\n const cmd = {};\n this._transportSendCommands([cmd]);\n }\n next();\n }\n _handlePush(data, next) {\n const channel = data.channel;\n const id = data.id;\n if (data.pub) {\n this._handlePublication(channel, data.pub, id);\n }\n else if (data.message) {\n this._handleMessage(data.message);\n }\n else if (data.join) {\n this._handleJoin(channel, data.join, id);\n }\n else if (data.leave) {\n this._handleLeave(channel, data.leave, id);\n }\n else if (data.unsubscribe) {\n this._handleUnsubscribe(channel, data.unsubscribe);\n }\n else if (data.subscribe) {\n this._handleSubscribe(channel, data.subscribe);\n }\n else if (data.disconnect) {\n this._handleDisconnect(data.disconnect);\n }\n next();\n }\n _flush() {\n const commands = this._commands.slice(0);\n this._commands = [];\n this._transportSendCommands(commands);\n }\n _createErrorObject(code, message, temporary) {\n const errObject = {\n code: code,\n message: message\n };\n if (temporary) {\n errObject.temporary = true;\n }\n return errObject;\n }\n _registerCall(id, callback, errback) {\n this._callbacks[id] = {\n callback: callback,\n errback: errback,\n timeout: null\n };\n this._callbacks[id].timeout = setTimeout(() => {\n delete this._callbacks[id];\n if (isFunction(errback)) {\n errback({ error: this._createErrorObject(errorCodes.timeout, 'timeout') });\n }\n }, this._config.timeout);\n }\n _addCommand(command) {\n if (this._batching) {\n this._commands.push(command);\n }\n else {\n this._transportSendCommands([command]);\n }\n }\n _nextPromiseId() {\n return ++this._promiseId;\n }\n _nextTransportId() {\n return ++this._transportId;\n }\n _resolvePromises() {\n for (const id in this._promises) {\n if (!this._promises.hasOwnProperty(id)) {\n continue;\n }\n if (this._promises[id].timeout) {\n clearTimeout(this._promises[id].timeout);\n }\n this._promises[id].resolve();\n delete this._promises[id];\n }\n }\n _rejectPromises(err) {\n for (const id in this._promises) {\n if (!this._promises.hasOwnProperty(id)) {\n continue;\n }\n if (this._promises[id].timeout) {\n clearTimeout(this._promises[id].timeout);\n }\n this._promises[id].reject(err);\n delete this._promises[id];\n }\n }\n}\nCentrifuge.SubscriptionState = SubscriptionState;\nCentrifuge.State = State;\nCentrifuge.UnauthorizedError = UnauthorizedError;\n\nexport { Centrifuge, State, Subscription, SubscriptionState, UnauthorizedError, connectingCodes, disconnectedCodes, errorCodes, subscribingCodes, subscriptionFlags, unsubscribedCodes };\n", "import type { DataBusPublication } from './types';\n\n/**\n * Normalize legacy flat publications, metadata payload envelopes, and the\n * canonical `{ op: 'publication', publication: ... }` shape.\n *\n * `fallbackTopic` is used by transports such as Centrifuge where the channel\n * is supplied out-of-band by the client library rather than inside the data.\n */\nexport function parseDataBusPublication<TData = unknown>(\n value: unknown,\n fallbackTopic?: string\n): DataBusPublication<TData> | null {\n if (!value || typeof value !== 'object') {\n return fallbackTopic ? { topic: fallbackTopic, data: value as TData } : null;\n }\n const frame = value as Record<string, unknown>;\n const nested = frame.publication && typeof frame.publication === 'object'\n ? frame.publication as Record<string, unknown>\n : null;\n const publication = nested ?? frame;\n const topic = typeof publication.topic === 'string' ? publication.topic : fallbackTopic;\n if (!topic) return null;\n\n // Centrifuge's legacy metadata envelope carries `{ data, messageId }`\n // without a topic because the channel is provided by PublicationContext.\n const hasMetadataEnvelope = fallbackTopic !== undefined\n && Object.prototype.hasOwnProperty.call(publication, 'data')\n && (typeof publication.messageId === 'string' || typeof publication.timestamp === 'number');\n const data = nested || fallbackTopic === undefined || hasMetadataEnvelope\n ? publication.data\n : value;\n const messageId = typeof publication.messageId === 'string' && publication.messageId.length > 0\n ? publication.messageId\n : undefined;\n const timestamp = typeof publication.timestamp === 'number' && Number.isFinite(publication.timestamp)\n ? publication.timestamp\n : undefined;\n return {\n topic,\n data: data as TData,\n ...(messageId === undefined ? {} : { messageId }),\n ...(timestamp === undefined ? {} : { timestamp })\n };\n}\n", "/**\n * \u516C\u5171\u5B57\u7B26\u4E32\u5E38\u91CF \u2014\u2014 \u751F\u547D\u5468\u671F\u72B6\u6001\u3001\u89D2\u8272\u3001\u63A7\u5236\u52A8\u4F5C\u3001\u534F\u8BAE\u6D88\u606F\u7C7B\u578B\u3001\u679A\u4E3E\u4E0E\n * \u547D\u540D\u7A7A\u95F4\u524D\u7F00\u3002\n *\n * \u6240\u6709\u8FD0\u884C\u65F6\u4F7F\u7528\u7684\u5B57\u7B26\u4E32\u5B57\u9762\u91CF\u96C6\u4E2D\u5728\u6B64\u4E00\u4EFD\u503C\uFF0C\u7C7B\u578B\u5B9A\u4E49\uFF08src/core/types.ts\n * \u7B49\uFF09\u901A\u8FC7 `(typeof X)[keyof typeof X]` \u4ECE\u8FD9\u4E9B\u5E38\u91CF\u6D3E\u751F\uFF0C\u6BD4\u8F83/switch \u5904\u5F15\u7528\n * \u540C\u4E00\u5BF9\u8C61\u6210\u5458\u3002\u8FD9\u6837\u65E2\u80FD\u6D88\u9664\u6563\u843D\u5728\u5404\u6587\u4EF6\u91CC\u7684\u91CD\u590D\u5B57\u7B26\u4E32\uFF08\u907F\u514D\u5927\u5C0F\u5199\u4E0D\u7EDF\u4E00\n * \u6216\u7B14\u8BEF\uFF09\uFF0C\u53C8\u4FDD\u8BC1\u7C7B\u578B\u4E0E\u503C\u6C38\u4E0D\u9519\u4F4D\u3002\n *\n * ## \u4F7F\u7528\u7EA6\u5B9A\n *\n * - **\u65B0\u589E\u6216\u4FEE\u6539\u5B57\u7B26\u4E32\u5B57\u9762\u91CF\u65F6\uFF0C\u5148\u5230\u8FD9\u91CC\u67E5\u627E/\u589E\u8865\uFF0C\u4E0D\u8981\u5728\u4E1A\u52A1\u6587\u4EF6\u91CC\u76F4\u63A5\u5199\n * \u9B54\u6CD5\u5B57\u7B26\u4E32\u3002** \u626B\u63CF\u6B8B\u7559\u5B57\u9762\u91CF\uFF1A`rg \"'(['a-z]+)'\" src/`\u3002\n * - **\u53EA\u7528\u4E8E\u7C7B\u578B\u4F4D\u7F6E\u7684\u5E38\u91CF**\uFF08\u5373\u53EA\u51FA\u73B0\u5728 `typeof X[keyof typeof X]` \u8FD9\u7C7B\u6D3E\u751F\u91CC\u3001\n * \u4ECE\u4E0D\u53C2\u4E0E\u8FD0\u884C\u65F6\u6BD4\u8F83\u7684\uFF09\u5728\u8C03\u7528\u65B9\u7528 `import type`\uFF1B**\u5728\u8FD0\u884C\u65F6\u6BD4\u8F83/\u6784\u9020\u4E2D\u4F7F\u7528\u7684**\n * \uFF08\u5982 `WORKER_STATUS.ERROR`\u3001`TRACE_EVENT_TYPE.LIFECYCLE`\u3001\n * `PERSISTENCE_OPERATION.APPEND`\uFF09\u5FC5\u987B\u7528\u503C\u5BFC\u5165\uFF0C\u5426\u5219\u4F1A\u62A5 \"cannot be used as\n * a value because it was imported using 'import type'\"\u3002`PERSISTENCE_OPERATION`\n * \u5C5E\u4E8E\u540E\u8005\u800C\u4E0D\u662F\u7C7B\u578B\u4FA7\u7684\u4F8B\u5B50\uFF1A`replay-manager.ts` \u4EE5\u503C\u5BFC\u5165\u5B83\uFF0C\u5E76\u628A\u5B83\u7684\u6210\u5458\u4F5C\u4E3A\n * `withPersistenceRetry` \u7684\u7B2C\u4E00\u4E2A\u5B9E\u53C2\u4F20\u8FDB\u53BB\u3002\n * - **\u503C\u6D3E\u751F\u7C7B\u578B**\uFF1A`export type WorkerStatus = (typeof WORKER_STATUS)[keyof\n * typeof WORKER_STATUS]`\u3002\u8FD9\u6837\u65B0\u589E\u679A\u4E3E\u5206\u652F\u65F6\u7C7B\u578B\u81EA\u52A8\u6536\u7A84\uFF0C\u7F16\u8BD1\u5668\u4F1A\u6307\u51FA\n * \u6BCF\u4E2A\u9057\u6F0F\u7684 switch \u5206\u652F\u3002\n * - \u5206\u7EC4\u7684\u987A\u5E8F\uFF08\u72B6\u6001 / \u89D2\u8272 / \u540E\u7AEF / \u6D88\u606F\u7C7B\u578B / \u679A\u4E3E / \u524D\u7F00\uFF09\u4FDD\u6301\u7A33\u5B9A\uFF0C\u65B9\u4FBF\n * \u7EF4\u62A4\u8005\u4E00\u773C\u5B9A\u4F4D\u3002\n */\n\n// ---- \u751F\u547D\u5468\u671F\u72B6\u6001 / \u89D2\u8272 / \u53EF\u89C1\u6027 ----\nexport const WORKER_STATUS = {\n CONNECTING: 'connecting',\n CONNECTED: 'connected',\n DISCONNECTED: 'disconnected',\n ERROR: 'error',\n} as const;\n\nexport const WORKER_ROLE = {\n ACTIVE: 'active',\n STANDBY: 'standby',\n} as const;\n\nexport const TAB_VISIBILITY = {\n VISIBLE: 'visible',\n HIDDEN: 'hidden',\n} as const;\n\n// ---- Worker \u540E\u7AEF\u6A21\u5F0F\u4E0E\u89E3\u6790\u7ED3\u679C\uFF08WorkerMode / WorkerBackend\uFF09----\nexport const WORKER_MODE = {\n DEDICATED: 'dedicated',\n SHARED: 'shared',\n AUTO: 'auto',\n} as const;\n\nexport const WORKER_BACKEND = {\n DEDICATED: 'dedicated',\n SHARED: 'shared',\n LOCAL: 'local',\n} as const;\n\n// ---- \u5B58\u50A8\u4E8B\u4EF6\u901A\u9053\u56DE\u9000 ----\nexport const CHANNEL_FALLBACK = {\n NONE: 'none',\n STORAGE_EVENT: 'storage-event',\n} as const;\n\n// ---- Worker / MessagePort / BroadcastChannel \u7684 EventTarget \u4E8B\u4EF6\u540D\u5224\u522B ----\n// MessageEvent.type\uFF08'message' / 'messageerror'\uFF09\u4E0E Worker \u4E0A\u7684 'error' \u4E8B\u4EF6\u540D\uFF0C\n// \u7528\u4E8E\u73AF\u5883\u9002\u914D\u5668\u63A5\u53E3\u7B7E\u540D\u4E0E\u6D4B\u8BD5\u66FF\u8EAB\u7684 addEventListener \u771F\u5047\u5206\u652F\u3002\nexport const EVENT_TYPE = {\n MESSAGE: 'message',\n MESSAGEERROR: 'messageerror',\n ERROR: 'error',\n} as const;\n\n// ---- \u63A7\u5236\u5E73\u9762\u52A8\u4F5C\uFF08WorkerControlAction\uFF09----\nexport const CONTROL_ACTION = {\n SUBSCRIBE: 'SUBSCRIBE',\n UNSUBSCRIBE: 'UNSUBSCRIBE',\n PUBLISH: 'PUBLISH',\n} as const;\n\n// ---- BroadcastChannel \u96C6\u7FA4\u6D88\u606F\u7C7B\u578B ----\nexport const CLUSTER_MESSAGE_TYPE = {\n CONTROL: 'CONTROL',\n EVENT: 'EVENT',\n REGISTRY: 'REGISTRY',\n ROUTE_RELEASED: 'ROUTE_RELEASED',\n} as const;\n\n// ---- \u547D\u540D\u7A7A\u95F4\u524D\u7F00\u4E0E\u4E8B\u4EF6\u540D ----\nexport const DEFAULT_STORAGE_PREFIX = 'cross-tab-worker-databus';\nexport const STORAGE_CHANNEL_PREFIX = `${DEFAULT_STORAGE_PREFIX}:channel:`;\nexport const TAB_ID_STORAGE_KEY = `${DEFAULT_STORAGE_PREFIX}:tab-id`;\nexport const PUBLICATION_EVENT = 'DATABUS_PUBLICATION';\n\n// ---- \u89C4\u8303 JSON \u4FE1\u5C01\u64CD\u4F5C\u7801 ----\nexport const PUBLICATION_ENVELOPE_OP = 'publication';\n\n// ---- trace \u4E8B\u4EF6\u7C7B\u578B ----\nexport const TRACE_EVENT_TYPE = {\n LIFECYCLE: 'lifecycle',\n STATUS: 'status',\n SUBSCRIPTION: 'subscription',\n COORDINATION: 'coordination',\n ERROR: 'error',\n RELIABILITY: 'reliability',\n MESSAGE_METRICS: 'message_metrics',\n} as const;\n\n// ---- trace \u751F\u547D\u5468\u671F\u52A8\u4F5C ----\nexport const TRACE_LIFECYCLE_ACTION = {\n START: 'start',\n STOP: 'stop',\n SUSPEND: 'suspend',\n RESUME: 'resume',\n} as const;\n\n// ---- \u5185\u90E8 handler \u8C03\u7528\u6807\u7B7E\uFF08\u9694\u79BB\u5F02\u5E38\u65F6\u7684\u5206\u7C7B\u6765\u6E90\uFF09----\nexport const INVOKE_LABEL = {\n DISPATCH: 'dispatch',\n STATUS: 'status',\n ERROR_HANDLER: 'error handler',\n} as const;\n\n// ---- trace \u6A21\u5F0F\uFF08DataBusTraceMode\uFF09----\nexport const TRACE_MODE = {\n EVENTS: 'events',\n METRICS: 'metrics',\n ALL: 'all',\n} as const;\n\n// ---- trace \u9519\u8BEF\u6765\u6E90 ----\nexport const TRACE_ERROR_SOURCE = {\n TRANSPORT: 'transport',\n OPERATION: 'operation',\n} as const;\n\n// ---- reliability \u8BCA\u65AD\u64CD\u4F5C ----\nexport const RELIABILITY_OPERATION = {\n TRANSPORT_RECOVERY: 'transport_recovery',\n ROUTE_ACK: 'route_ack',\n ROUTE_MIGRATION: 'route_migration',\n // A re-election that recovered a stranded unconfirmed handoff (previous\n // owner gone, ACK never arrived). Distinct from ROUTE_MIGRATION so trace\n // consumers can tell recoveries apart from routine graceful handoffs.\n ROUTE_MIGRATION_RECOVERY: 'route_migration_recovery',\n PERSISTENCE_CLEANUP: 'persistence_cleanup',\n PERSISTENCE_RETRY: 'persistence_retry',\n DEDUP_SUPPRESSED: 'dedup_suppressed',\n} as const;\n\n// ---- \u81EA\u52A8\u6062\u590D\u5C1D\u8BD5\u7ED3\u679C ----\nexport const RECOVERY_OUTCOME = {\n SCHEDULED: 'scheduled',\n SUCCEEDED: 'succeeded',\n FAILED: 'failed',\n EXHAUSTED: 'exhausted',\n} as const;\n\n// ---- \u8BA2\u9605\u52A8\u4F5C ----\nexport const SUBSCRIPTION_ACTION = {\n SUBSCRIBE: 'subscribe',\n UNSUBSCRIBE: 'unsubscribe',\n} as const;\n\n// ---- \u56DE\u653E\u4FEE\u526A\u7B56\u7565 ----\nexport const PRUNE_STRATEGY = {\n COUNT: 'count',\n AGE: 'age',\n BOTH: 'both',\n} as const;\n\n// ---- \u6301\u4E45\u5316\u64CD\u4F5C ----\nexport const PERSISTENCE_OPERATION = {\n LOAD: 'load',\n APPEND: 'append',\n CLEAR: 'clear',\n CLEAR_TOPIC: 'clearTopic',\n CLEAR_BEFORE: 'clearBefore',\n} as const;\n\n// ---- \u6545\u969C\u6765\u6E90\uFF08DataBusFailureSource\uFF09----\nexport const FAILURE_SOURCE = {\n TRANSPORT: 'transport',\n PERSISTENCE: 'persistence',\n DISPATCH: 'dispatch',\n} as const;\n\n// ---- \u5065\u5EB7\u5224\u5B9A\u72B6\u6001\uFF08DataBusHealthSummary['state']\uFF09----\nexport const HEALTH_STATE = {\n STOPPED: 'stopped',\n STARTING: 'starting',\n HEALTHY: 'healthy',\n RECOVERING: 'recovering',\n SUSPENDED: 'suspended',\n DEGRADED: 'degraded',\n} as const;\n\n// ---- WebSocket wire \u534F\u8BAE\u64CD\u4F5C\u7801 ----\nexport const WS_OP = {\n SUBSCRIBE: 'subscribe',\n UNSUBSCRIBE: 'unsubscribe',\n PUBLISH: 'publish',\n PUBLISH_BATCH: 'publishBatch',\n} as const;\n\n// ---- Centrifuge Worker \u8F93\u5165\u6D88\u606F\u7C7B\u578B ----\nexport const CENTRIFUGE_INPUT_TYPE = {\n INIT: 'INIT',\n SUBSCRIBE: 'SUBSCRIBE',\n UNSUBSCRIBE: 'UNSUBSCRIBE',\n PUBLISH: 'PUBLISH',\n PUBLISH_BIN: 'PUBLISH_BIN',\n PING: 'PING',\n STOP: 'STOP',\n TOKEN_RESPONSE: 'TOKEN_RESPONSE',\n TOKEN_ERROR: 'TOKEN_ERROR',\n} as const;\n\n// ---- Centrifuge Worker \u8F93\u51FA\u6D88\u606F\u7C7B\u578B ----\nexport const CENTRIFUGE_OUTPUT_TYPE = {\n STATUS: 'STATUS',\n MESSAGE: 'MESSAGE',\n MESSAGE_BIN: 'MESSAGE_BIN',\n ERROR: 'ERROR',\n TOKEN_REQUEST: 'TOKEN_REQUEST',\n SESSION_REAPED: 'SESSION_REAPED',\n} as const;\n", "/**\n * \u53D1\u5E03\u5143\u6570\u636E\u5DE5\u5177 \u2014\u2014 \u6784\u9020 { messageId?, timestamp? }\uFF0C\u4EC5\u5728\u5B57\u6BB5\u5DF2\u5B9A\u4E49\u65F6\u5199\u5165\uFF0C\n * \u907F\u514D\u5F80 wire \u5E27/\u63A7\u5236\u6D88\u606F\u91CC\u585E\u7A7A\u679A\u4E3E\u5B57\u6BB5\u3002\n *\n * \u6B64\u524D cluster.ts\u3001data-bus.ts\u3001centrifuge.ts\u3001centrifuge-session.ts \u5404\u81EA\u5185\u8054\n * \u5B9E\u73B0\u4E86\u4E00\u904D `...(x === undefined ? {} : { x })` \u5C55\u5F00\uFF0C\u884C\u4E3A\u5BB9\u6613\u6F02\u79FB\uFF1B\u7EDF\u4E00\u5230\u6B64\n * \u4E00\u5904\u540E\u6240\u6709\u8C03\u7528\u65B9\u5171\u4EAB\u540C\u4E00\u8BED\u4E49\u3002\n */\nimport type { DataBusPublicationMetadata } from '../core/types';\n\n/**\n * Copy defined publication metadata without adding empty enumerable fields.\n * Returns `undefined` when neither field is set, so callers can preserve a\n * legacy \"no metadata\" argument shape (e.g. `onControl(..., undefined)`).\n */\nexport function publicationMetadata(\n messageId?: string,\n timestamp?: number\n): DataBusPublicationMetadata | undefined {\n if (messageId === undefined && timestamp === undefined) return undefined;\n return {\n ...(messageId === undefined ? {} : { messageId }),\n ...(timestamp === undefined ? {} : { timestamp })\n };\n}\n", "/**\n * \u9519\u8BEF\u5E8F\u5217\u5316\u5DE5\u5177 \u2014\u2014 \u5728 Worker \u8FB9\u754C\u5F80\u8FD4\u4F20\u8F93 Error\u3002\n *\n * Error \u5B9E\u4F8B\u65E0\u6CD5\u901A\u8FC7 postMessage \u7ED3\u6784\u5316\u514B\u9686\uFF0C\u6240\u4EE5 CentrifugeSession \u4FA7\u7528\n * serializeError \u628A\u5B83\u538B\u6210 plain object\uFF0C\u4E3B\u7EBF\u7A0B\u4FA7\u7528 deserializeWorkerError\n * \u8FD8\u539F\u6210\u771F Error\uFF08\u5E26 name/stack\uFF09\u3002\u6B64\u524D\u4E24\u4E2A\u51FD\u6570\u5206\u522B\u5185\u8054\u5728 centrifuge-session.ts\n * \u4E0E centrifuge.ts\uFF0C\u6B64\u5904\u7EDF\u4E00\u5B9A\u4E49\u5E76\u4ECE\u4E24\u5904\u5F15\u7528\u3002\n */\n\n/** Error object serialized for cross-thread transfer. */\nexport interface SerializedWorkerError {\n /** The Error's `name` (e.g. 'TypeError', 'CentrifugeError'). */\n name: string;\n /** The Error's `message`. */\n message: string;\n /** The Error's `stack` if available (for debugging). */\n stack?: string;\n /** Arbitrary context attached by the Worker (e.g. the failing operation). */\n context?: unknown;\n}\n\n/** Convert an arbitrary error into a structured-cloneable form for postMessage.\n * A non-Error value is attached as `context`, but only when it is itself\n * structured-cloneable: a function, symbol, or an object/map holding one would\n * otherwise make the serialised error unserializable, so `postMessage` would\n * throw `DataCloneError` while reporting the original failure. */\nexport function serializeError(error: unknown): SerializedWorkerError {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n ...(error.stack ? { stack: error.stack } : {})\n };\n }\n const context = error === undefined ? undefined : error;\n return {\n name: 'CentrifugeError',\n message: typeof error === 'string' ? error : 'Centrifuge worker operation failed.',\n ...(context === undefined || !isStructuredCloneable(context) ? {} : { context })\n };\n}\n\n/** True when `value` survives a structured clone. When the runtime has no\n * `structuredClone`, cloneability cannot be checked and the value is kept\n * (best effort); the eventual postMessage would fail either way. */\nfunction isStructuredCloneable(value: unknown): boolean {\n if (typeof structuredClone !== 'function') return true;\n try {\n structuredClone(value);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Reconstruct an Error instance from its serialised form. */\nexport function deserializeWorkerError(error: SerializedWorkerError): Error {\n const result = new Error(error.message);\n result.name = error.name;\n if (error.stack) result.stack = error.stack;\n if (error.context !== undefined) Object.assign(result, { context: error.context });\n return result;\n}\n\n/** Render an arbitrary rejection reason as a message, guaranteed not to throw.\n *\n * `String(value)` is *not* total: a null-prototype object has no primitive\n * conversion at all (`TypeError: Cannot convert object to primitive value`), and\n * any object can carry a `toString` that throws. Both are inside the public\n * contract, which lets a transport reject with any value \u2014 so the coercion runs\n * on the path that reports a failure, where throwing is worse than the failure\n * itself: it replaces the real reason with a message about the formatter's\n * limits, and it turns a chain ending in `.catch(error => reportError(error))`\n * from a resolved promise into a rejected one. The whole `try` covers the\n * `Error` branch too, because `instanceof` and a `.message` getter can each be\n * made to throw by the value being recorded. */\nexport function describeFailure(error: unknown): string {\n try {\n if (error instanceof Error) return error.message;\n return String(error);\n } catch {\n return `[unstringifiable ${typeof error}]`;\n }\n}\n", "/**\n * CentrifugeSession \u2014 a reusable wrapper around a single Centrifuge client.\n *\n * Provides a structured-clone-safe message protocol (INIT/SUBSCRIBE/UNSUBSCRIBE/\n * PUBLISH/STOP) so the same session class can run inside a Dedicated Worker,\n * a SharedWorker port, or directly on the main thread as a local fallback.\n */\nimport { Centrifuge } from 'centrifuge';\nimport { parseDataBusPublication } from './core/publication';\nimport type {\n PublicationContext,\n StateContext,\n Subscription,\n SubscriptionErrorContext\n} from 'centrifuge';\nimport type {\n CentrifugeWorkerConfig,\n CentrifugeWorkerInput,\n CentrifugeWorkerOutput\n} from './centrifuge-protocol';\nimport { CENTRIFUGE_INPUT_TYPE, CENTRIFUGE_OUTPUT_TYPE, WORKER_STATUS } from './utils/constants';\nimport { publicationMetadata } from './utils/metadata';\nimport { deserializeWorkerError, serializeError } from './utils/error-utils';\n\n/** Callback interface for posting messages back to the transport layer. */\nexport interface CentrifugeSessionSink<TData = unknown> {\n post(message: CentrifugeWorkerOutput<TData>, transfer?: ArrayBuffer[]): void;\n}\n\n/** A pending getToken/getChannelToken request awaiting a main-thread response. */\ninterface PendingTokenRequest {\n resolve: (token: string) => void;\n reject: (error: unknown) => void;\n}\n\n/** Centrifuge client options for token-bridge mode: the structured-clone-safe\n * subset plus the function-valued credential hooks this session installs.\n * Against the pinned SDK (5.7.4) `getToken` is the only one that is a real\n * client option (the constructor of `centrifuge.js` copies it off the config \u2014 the\n * assignment is greppable in the shipped bundle as\n * `e.getToken&&(this._getToken=e.getToken)`, and the same hook serves renewal) \u2014\n * cited by that substring rather than a file and\n * line: the installed package ships no `.d.ts` at all and the string\n * `build/types.d.ts` appears nowhere inside it, so a generated-file line number could\n * not be checked by a reader here at all;\n * `getChannelToken` appears nowhere in the package's types or build, and\n * subscriptions are created with `newSubscription(topic)` and no per-\n * subscription options \u2014 so that hook is never invoked, and the `'channelToken'`\n * request kind is produced only by the test fake. It stays because the Worker\n * protocol carries the kind: an SDK that later names it would need no change on\n * this side. Used only inside the session, never across the Worker boundary. */\ntype CentrifugeBridgedOptions = Omit<CentrifugeWorkerConfig, 'getToken' | 'getChannelToken'> & {\n getToken: () => Promise<string>;\n getChannelToken: (channel: string) => Promise<string>;\n};\n\n/**\n * Stateful Centrifuge client wrapper shared by Dedicated Worker, SharedWorker\n * ports and the main-thread local fallback. Each session owns one connection.\n */\nexport class CentrifugeSession<TData = unknown> {\n private client: Centrifuge | null = null;\n private readonly subscriptions = new Map<string, Subscription>();\n private transferable = false;\n private tokenBridge = false;\n private nextRequestId = 1;\n // Bumped on every initialize/stop. Async client callbacks capture the value\n // from the connection that created them so a stopped client cannot emit into\n // a later session instance (including the main-thread local fallback).\n private lifecycle = 0;\n private readonly pendingTokenRequests = new Map<number, PendingTokenRequest>();\n\n constructor(private readonly sink: CentrifugeSessionSink<TData>) {}\n\n /** Dispatch an incoming Worker message to the matching operation.\n * Unknown message types are ignored rather than thrown, so a future protocol\n * extension adding a new variant cannot crash an older session. */\n handle(message: CentrifugeWorkerInput): void {\n switch (message.type) {\n case CENTRIFUGE_INPUT_TYPE.INIT:\n this.initialize(message.url, message.config, message.transferable === true, message.tokenBridge === true);\n return;\n case CENTRIFUGE_INPUT_TYPE.SUBSCRIBE:\n this.subscribe(message.topic);\n return;\n case CENTRIFUGE_INPUT_TYPE.UNSUBSCRIBE:\n this.unsubscribe(message.topic);\n return;\n case CENTRIFUGE_INPUT_TYPE.PUBLISH:\n case CENTRIFUGE_INPUT_TYPE.PUBLISH_BIN:\n // Binary and JSON publish share the same Centrifuge client call; the\n // transport layer decides whether to transfer the ArrayBuffer.\n this.publish(message.topic, message.data, message.messageId, message.timestamp);\n return;\n case CENTRIFUGE_INPUT_TYPE.STOP:\n this.stop();\n return;\n case CENTRIFUGE_INPUT_TYPE.TOKEN_RESPONSE:\n this.resolveToken(message.requestId, message.token);\n return;\n case CENTRIFUGE_INPUT_TYPE.TOKEN_ERROR:\n this.rejectToken(message.requestId, deserializeWorkerError(message.error));\n return;\n default:\n return;\n }\n }\n\n /** Create the Centrifuge client, wire up lifecycle listeners, and connect. */\n private initialize(url: string, config: CentrifugeWorkerConfig, transferable: boolean, tokenBridge: boolean): void {\n if (this.client) return;\n const lifecycle = ++this.lifecycle;\n this.transferable = transferable;\n this.tokenBridge = tokenBridge;\n const clientOptions: CentrifugeWorkerConfig | CentrifugeBridgedOptions = tokenBridge\n ? {\n ...config,\n // Route credential fetches back to the main thread, where the\n // application's credentialProvider lives (config must stay\n // structured-cloneable, so functions cannot cross the boundary).\n getToken: () => this.requestToken('token', lifecycle),\n getChannelToken: (channel: string) => this.requestToken('channelToken', lifecycle, channel)\n }\n : config;\n const client = new Centrifuge(url, clientOptions);\n this.client = client;\n client.on('state', (context: StateContext) => {\n if (this.lifecycle !== lifecycle) return;\n this.post({ type: CENTRIFUGE_OUTPUT_TYPE.STATUS, status: normalizeStatus(context.newState) });\n });\n client.on('connected', () => {\n if (this.lifecycle !== lifecycle) return;\n this.post({ type: CENTRIFUGE_OUTPUT_TYPE.STATUS, status: WORKER_STATUS.CONNECTED });\n });\n client.on('disconnected', () => {\n if (this.lifecycle !== lifecycle) return;\n this.post({ type: CENTRIFUGE_OUTPUT_TYPE.STATUS, status: WORKER_STATUS.DISCONNECTED });\n });\n client.on('error', context => {\n if (this.lifecycle !== lifecycle) return;\n this.postError(context);\n });\n // Client-level publications are only for server-side subscriptions (where\n // no client Subscription object exists). For topics we have an active\n // subscription for, the subscription-level 'publication' listener handles\n // dispatch \u2014 skip here to avoid delivering the same message twice.\n client.on('publication', (context: PublicationContext) => {\n if (this.lifecycle !== lifecycle) return;\n const topic = context.channel || getPayloadTopic(context.data);\n if (!topic || this.subscriptions.has(topic)) return;\n this.postPublication(topic, context.data);\n });\n client.connect();\n }\n\n /** Subscribe to a Centrifuge channel. Reuses an existing subscription if one exists.\n * Listeners are only registered once per subscription object \u2014 a repeated\n * SUBSCRIBE for an already-tracked topic skips the listener wiring entirely,\n * avoiding the removeAllListeners + re-on churn on every duplicate message. */\n private subscribe(topic: string): void {\n if (!this.client) return this.postError(new Error('Centrifuge client is not initialized.'));\n const lifecycle = this.lifecycle;\n // If we already track this subscription, it already has our listeners \u2014\n // a duplicate SUBSCRIBE is a no-op (idempotent), matching the transport\n // contract. Only a fresh subscription needs listener wiring.\n const existing = this.subscriptions.get(topic);\n if (existing) {\n existing.subscribe();\n return;\n }\n let subscription = this.client.getSubscription(topic);\n if (!subscription) subscription = this.client.newSubscription(topic);\n // Scoped to the three events this method wires, so the client's own `state`\n // wiring is untouched \u2014 but `error` is NOT internal-listener-free: a no-op\n // `error` listener is installed on every subscription precisely\n // \"to avoid unhandled exception in EventEmitter for non-set error handler\",\n // and not by `Subscription` itself \u2014 that class body contains no `on('error')`\n // call at all (measured on the pinned copy), so the guard runs in the\n // `BaseSubscription` constructor every subscription reaches through `super`.\n // (centrifuge 5.7.4, `build/index.js`. The line number this used to cite \u2014 762\n // \u2014 matches neither the pinned copy, where the guard sits at 763-764, nor the\n // 5.7.0 copy in the store, where it is at 748; whether it drifted or was\n // mis-copied is not recoverable from here. That is the argument for quoting\n // the dependency's own comment as the locator instead of a number), and the\n // bundled emitter throws on an `error` emit with no listener\n // (`throw er; // Unhandled 'error' event` in the same file).\n // This call removes that guard,\n // and the `subscription.on('error', \u2026)` re-installation below puts one back for\n // as long as this session holds the subscription \u2014 three statements later (the\n // `unsubscribed` removal, the `subscriptions` set, the `publication` wiring), all\n // of them inside this same synchronous task, so no emit can land in between.\n // `unsubscribe()` removes both \u2014 this handler and the constructor's no-op \u2014 and\n // adds nothing back, which is settled rather than open. All twelve `emit('error')`\n // sites in `BaseSubscription` (its class body is lines 667-2673 of that file, and\n // the twelve were counted in it) sit behind a\n // `_isSubscribing()`/`_isSubscribed()` test except one: the `getToken === null`\n // emit in `_getSubscriptionToken`. Calling it \"the `badConfiguration` emit\" is\n // ambiguous and this note used to \u2014 that code is shared with the guarded\n // `_handleGetDataError` emit, so it identifies neither site on its own. And after\n // `_setUnsubscribed` has moved `state` to `Unsubscribed` no path re-enters it\n // \u2014 the resubscribe timer's callback re-tests `_isSubscribing()` before it\n // does anything, the client's reconnect pass (`_sendSubscribeCommands`)\n // drives only subscriptions whose state is already `Subscribing`, and\n // `_refresh()` is reachable only through `_refreshTimeout`, which\n // `_setUnsubscribed` clears via `_clearSubscribedState()`. What singles\n // `_refresh()` out among the four `_getSubscriptionToken()` call sites is *not*\n // the absence of a state test \u2014 an earlier draft of this note said \"the one entry\n // with no state test of its own\", and `_subscribe()`, `_loadStreamState()`'s\n // `_getState().then(\u2026)` continuation and `_mapSubscribe()` reach their calls with\n // none above them either. It is the `if` each of those three is the `else` of:\n // `_canSubscribeWithoutGettingToken()` reads `!_usesToken() || !!_token`, so\n // entering the else needs `_usesToken()` true with a falsy `_token`; every falsy\n // value the class itself writes there is `''` (its option handling is\n // `if (options.token)`), and for `''` the `_usesToken()` half is exactly\n // `_getToken !== null`, which the emit's own `if (getToken === null)` refutes. So\n // the exclusion runs through the token, not the state \u2014 and through one of the\n // token's writers: `_refresh` assigns `self._token = token` whatever an application\n // `getToken` resolved with, so a falsy value that is not `''` would put a wrapped\n // call back in reach of the emit. A throw still needs the listeners gone while the\n // object is still live, and `unsubscribe()` does not leave it live.\n // `MapSubscription` and\n // `SharedPollSubscription` have their own emit sites but never carry this\n // session's listeners \u2014 `newSubscription` constructs a plain `Subscription`.\n subscription.removeAllListeners('publication');\n subscription.removeAllListeners('error');\n subscription.removeAllListeners('unsubscribed');\n this.subscriptions.set(topic, subscription);\n subscription.on('publication', context => {\n if (this.lifecycle !== lifecycle) return;\n this.postPublication(topic, context.data);\n });\n subscription.on('error', (context: SubscriptionErrorContext) => {\n if (this.lifecycle !== lifecycle) return;\n this.postError(context);\n });\n subscription.on('unsubscribed', () => {\n if (this.lifecycle === lifecycle) this.subscriptions.delete(topic);\n });\n subscription.subscribe();\n }\n\n /** Unsubscribe from a Centrifuge channel and clean up the local reference.\n * Listeners are removed before unsubscribing so a late `unsubscribed` event\n * cannot delete a subscription that a subsequent `subscribe()` re-added. */\n private unsubscribe(topic: string): void {\n const subscription = this.subscriptions.get(topic) ?? this.client?.getSubscription(topic);\n if (!subscription) return;\n subscription.removeAllListeners('publication');\n subscription.removeAllListeners('error');\n subscription.removeAllListeners('unsubscribed');\n this.subscriptions.delete(topic);\n subscription.unsubscribe();\n }\n\n /** Publish a message to the Centrifuge channel. */\n private publish(topic: string, data: unknown, messageId?: string, timestamp?: number): void {\n if (!this.client) return this.postError(new Error('Centrifuge client is not initialized.'));\n const lifecycle = this.lifecycle;\n // Centrifuge's payload is application-defined. Preserve legacy payloads;\n // when an ID is requested, send a small metadata envelope that compatible\n // servers can echo back for end-to-end deduplication.\n const hasMetadata = messageId !== undefined || timestamp !== undefined;\n const payload = hasMetadata\n ? {\n data,\n ...(messageId === undefined ? {} : { messageId }),\n ...(timestamp === undefined ? {} : { timestamp })\n }\n : data;\n void this.client.publish(topic, payload).catch(error => {\n if (this.lifecycle === lifecycle) this.postError(error);\n });\n }\n\n /** Forward a publication to the transport. Binary payloads take the\n * zero-copy `MESSAGE_BIN` path when `transferable` is enabled; everything\n * else is structured-cloned via `MESSAGE`. An empty topic means the\n * publication carried no channel info and is silently dropped.\n *\n * That drop is uncovered and dominated: the connection-level caller tests the\n * same emptiness before calling, and the subscription-level caller reads the\n * topic out of a key this session only ever populates from a SUBSCRIBE frame.\n * Measured \u2014 deleting this line leaves the whole suite green, and the frame\n * it withholds has nowhere to land anyway: the only handler registry is the\n * DataBus's `topicHandlers`, and every write to it sits behind\n * `assertPublicTopic` (at the head of `data-bus.ts`'s `subscribe()`, `publish()`\n * and `publishBatch()`), so no `''` key can\n * exist \u2014 while `topicMatchesPattern` answers false for an empty topic against\n * both `*` and `prefix.*`, so a wildcard handler cannot see it either. Neither\n * of those is a reason to delete this guard: it is the only one *at this layer*,\n * because neither the session nor the transport calls `assertPublicTopic` \u2014 a\n * SUBSCRIBE frame naming `''` creates a real Centrifuge subscription\n * (`newSubscription` does not validate a channel), so the undeliverable\n * publication would otherwise be posted back to the main thread. Kept as the\n * boundary statement, not counted as a closed leg. */\n private postPublication(topic: string, data: unknown): void {\n if (!topic) return;\n if (this.transferable && data instanceof ArrayBuffer) {\n this.post({ type: CENTRIFUGE_OUTPUT_TYPE.MESSAGE_BIN, topic, data }, [data]);\n return;\n }\n const publication = parseDataBusPublication<TData>(data, topic);\n if (!publication) return;\n this.post({\n type: CENTRIFUGE_OUTPUT_TYPE.MESSAGE,\n topic: publication.topic,\n data: publication.data,\n ...publicationMetadata(publication.messageId, publication.timestamp)\n });\n }\n\n /** Disconnect the client and clear all subscriptions. */\n private stop(): void {\n // Invalidate callbacks from the connection being stopped before disconnect\n // so its synchronous or queued events cannot leak into a later session.\n this.lifecycle += 1;\n // Settle every in-flight credential request so a stop cannot leave the\n // Worker awaiting a main-thread response forever.\n for (const [, pending] of this.pendingTokenRequests) {\n pending.reject(new Error('Centrifuge session stopped before the credential was resolved.'));\n }\n this.pendingTokenRequests.clear();\n this.client?.disconnect();\n this.subscriptions.clear();\n this.client = null;\n this.post({ type: CENTRIFUGE_OUTPUT_TYPE.STATUS, status: WORKER_STATUS.DISCONNECTED });\n }\n\n /** Issue a credential request to the main thread and await the response.\n * Used as Centrifuge's `getToken` / `getChannelToken` when token bridging is\n * enabled; resolved or rejected by a matching TOKEN_RESPONSE / TOKEN_ERROR. */\n private requestToken(kind: 'token' | 'channelToken', lifecycle: number, channel?: string): Promise<string> {\n // The provider is installed on a specific Centrifuge client. An old client\n // must not be able to route a late credential request into a replacement\n // session merely because it retained the callback closure.\n if (this.lifecycle !== lifecycle) {\n return Promise.reject(new Error('Centrifuge client lifecycle has ended before the credential was requested.'));\n }\n const requestId = this.nextRequestId;\n this.nextRequestId += 1;\n return new Promise<string>((resolve, reject) => {\n this.pendingTokenRequests.set(requestId, { resolve, reject });\n this.post({\n type: CENTRIFUGE_OUTPUT_TYPE.TOKEN_REQUEST,\n requestId,\n kind,\n ...(channel === undefined ? {} : { channel })\n });\n });\n }\n\n private resolveToken(requestId: number, token: string): void {\n const pending = this.pendingTokenRequests.get(requestId);\n if (!pending) return;\n this.pendingTokenRequests.delete(requestId);\n pending.resolve(token);\n }\n\n private rejectToken(requestId: number, error: unknown): void {\n const pending = this.pendingTokenRequests.get(requestId);\n if (!pending) return;\n this.pendingTokenRequests.delete(requestId);\n pending.reject(error);\n }\n\n /** Forward a message to the sink (the transport layer). */\n private post(message: CentrifugeWorkerOutput<TData>, transfer?: ArrayBuffer[]): void {\n this.sink.post(message, transfer);\n }\n\n /** Serialise and report an error. The Centrifuge client handles reconnection\n * internally, so a transient error should not trigger a `STATUS: error` that\n * would cause `selectActiveWorkers()` to exclude this worker from routing.\n * Fatal errors are distinguished by the client eventually emitting\n * `disconnected` without a subsequent `connected`. */\n private postError(error: unknown): void {\n this.post({ type: CENTRIFUGE_OUTPUT_TYPE.ERROR, error: serializeError(error) });\n }\n}\n\n/** Extract a topic from a Centrifuge publication payload if one is present.\n * Handles both direct `channel` fields and the nested `push.channel` shape\n * that Centrifugo uses for some server-side push types. */\nfunction getPayloadTopic(data: unknown): string {\n if (!data || typeof data !== 'object') return '';\n const payload = data as Record<string, unknown>;\n // Prefer nested push.channel (server-side push) then fall back to top-level channel.\n const push = payload.push;\n const nested = typeof push === 'object' && push !== null ? (push as Record<string, unknown>).channel : undefined;\n const topic = nested ?? payload.channel;\n return typeof topic === 'string' ? topic : '';\n}\n\n/** Map a Centrifuge state string to the DataBus's status vocabulary.\n * 'connecting' and 'connected' pass through; anything else (e.g. 'reconnecting',\n * 'disconnected') maps to 'disconnected'. */\nconst LIVE_STATES = new Set<string>([WORKER_STATUS.CONNECTING, WORKER_STATUS.CONNECTED]);\nfunction normalizeStatus(status: string): 'connecting' | 'connected' | 'disconnected' {\n return LIVE_STATES.has(status) ? (status as 'connecting' | 'connected') : 'disconnected';\n}\n", "/**\n * Worker-thread protocol for Centrifuge WebSocket transport.\n *\n * Defines the message types exchanged between the main thread and a Web Worker\n * (dedicated or shared) that runs a centrifuge client. The worker is isolated\n * from the main thread so that WebSocket lifecycle, token refresh, and binary\n * data handling never block the UI.\n *\n * The message `type` discriminant values are derived from the constants in\n * `utils/constants.ts` so main-thread and Worker sides reference the same\n * values and can never drift apart.\n */\nimport type { Options } from 'centrifuge';\nimport type { CENTRIFUGE_INPUT_TYPE, CENTRIFUGE_OUTPUT_TYPE } from './utils/constants';\nimport type { WorkerStatus } from './core/types';\nimport type { SerializedWorkerError } from './utils/error-utils';\n\nexport type { SerializedWorkerError } from './utils/error-utils';\n\n/**\n * Default interval between main-thread PING heartbeats to a SharedWorker. The\n * SharedWorker reaps a silent port after `SESSION_TIMEOUT_MULTIPLIER` intervals.\n * Shared here so the main thread (heartbeat sender) and the SharedWorker (reaper)\n * always agree on the cadence.\n */\nexport const DEFAULT_HEARTBEAT_INTERVAL_MS = 10_000;\n/** SharedWorker per-port session timeout, expressed as a multiple of that port's\n * heartbeat interval. A live port PINGs every heartbeat interval, so a timeout of\n * several intervals tolerates throttled tabs without reaping healthy sessions. */\nexport const DEFAULT_SESSION_TIMEOUT_MULTIPLIER = 3;\n/** Default per-port session timeout in ms, derived from the heartbeat interval\n * and the multiplier. Used as the fallback when a port sends no INIT config. */\nexport const DEFAULT_SESSION_TIMEOUT_MS =\n DEFAULT_HEARTBEAT_INTERVAL_MS * DEFAULT_SESSION_TIMEOUT_MULTIPLIER;\n\n// These options reference browser APIs (WebSocket, EventSource, fetch, \u2026) that\n// do not exist inside a Worker \u2014 the worker imports its own WebSocket. Nothing\n// strips them at runtime: `buildInitInput` forwards `config.options` verbatim,\n// so this exclusion is compile-time only. A value forced through with a cast is\n// caught by the runtime gate that does exist, `assertStructuredCloneable` on the\n// same options, which throws a TypeError from the transport before any backend\n// is created \u2014 a function-valued option would otherwise die at the structured-\n// clone boundary with a DataCloneError instead.\ntype WorkerUnsafeOption =\n | 'eventsource'\n | 'fetch'\n | 'getData'\n | 'getToken'\n | 'networkEventTarget'\n | 'readableStream'\n | 'sockjs'\n | 'websocket';\n\n/** Centrifuge options safe to pass into a Worker; unsafe options are explicitly\n * excluded and set to `never` so the compiler rejects them at the call site. */\nexport type CentrifugeWorkerConfig = Omit<Partial<Options>, WorkerUnsafeOption> & {\n [Key in WorkerUnsafeOption]?: never;\n};\n\n/**\n * Async credential provider run on the main thread. Centrifuge client options\n * are structured-cloned into the Worker, so function-valued `getToken` /\n * `getChannelToken` cannot travel with the config. When a provider is set, the\n * Worker asks the main thread for each fresh token over a TOKEN_REQUEST /\n * TOKEN_RESPONSE exchange and this provider supplies it from application\n * context (async token endpoints, SecureStorage, etc.).\n */\nexport interface CentrifugeCredentialProvider {\n /** Return a fresh top-level connection token. Called on connect and refresh. */\n getToken: () => MaybePromise<string | null | undefined>;\n /** Return a channel token for a channel. Centrifuge falls back to `getToken`\n * when channel tokens are not configured by the server. */\n getChannelToken?: (channel: string) => MaybePromise<string | null | undefined>;\n}\n\n/** A value or a promise of a value. */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/** Messages sent from the main thread to the Worker. All variants are\n * structured-cloneable; `PUBLISH_BIN` carries an ArrayBuffer (transferable). */\nexport type CentrifugeWorkerInput =\n /** Initial connection: URL + config. Sent once per backend creation.\n * `transferable` enables ArrayBuffer zero-copy for subsequent PUBLISH_BIN.\n * `heartbeatIntervalMs` overrides the SharedWorker PING cadence.\n * `tokenBridge` asks the Worker to route getToken/getChannelToken back to\n * the main thread instead of holding function-valued config. */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.INIT; url: string; config: CentrifugeWorkerConfig; transferable?: boolean; heartbeatIntervalMs?: number; tokenBridge?: boolean }\n /** Subscribe to a channel. Idempotent \u2014 re-subscribing is a no-op. */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.SUBSCRIBE; topic: string }\n /** Unsubscribe from a channel. Idempotent. */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.UNSUBSCRIBE; topic: string }\n /** Publish a structured-cloneable payload to a channel. */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.PUBLISH; topic: string; data: unknown; messageId?: string; timestamp?: number }\n /** Publish an ArrayBuffer via Transferable (zero-copy when `transferable` is on). */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.PUBLISH_BIN; topic: string; data: ArrayBuffer; messageId?: string; timestamp?: number }\n /** Heartbeat from the main thread; the SharedWorker reaps silent ports. */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.PING }\n /** Disconnect the client and clear all subscriptions. */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.STOP }\n /** Fresh credential for an earlier TOKEN_REQUEST, resolved by requestId. */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.TOKEN_RESPONSE; requestId: number; token: string }\n /** A credential request failed (provider rejected or returned no token). */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.TOKEN_ERROR; requestId: number; error: SerializedWorkerError };\n\n/** Messages sent from the Worker back to the main thread. The main thread\n * routes these to the DataBusTransportHandlers via handleOutput(). */\nexport type CentrifugeWorkerOutput<TData = unknown> =\n /** Connection status changed. Maps Centrifuge states to the DataBus vocabulary. */\n | { type: typeof CENTRIFUGE_OUTPUT_TYPE.STATUS; status: WorkerStatus }\n /** A JSON publication arrived. Routed to onMessage via handleOutput. */\n | { type: typeof CENTRIFUGE_OUTPUT_TYPE.MESSAGE; topic: string; data: TData; messageId?: string; timestamp?: number }\n /** A binary publication arrived (Transferable). Routed to onMessage with the ArrayBuffer. */\n | { type: typeof CENTRIFUGE_OUTPUT_TYPE.MESSAGE_BIN; topic: string; data: ArrayBuffer; messageId?: string; timestamp?: number }\n /** A non-fatal error occurred. Does not imply disconnection (the client retries internally). */\n | { type: typeof CENTRIFUGE_OUTPUT_TYPE.ERROR; error: SerializedWorkerError }\n /** The Worker needs a fresh credential. The main thread resolves it via a\n * matching TOKEN_RESPONSE / TOKEN_ERROR carrying the same `requestId`. */\n | { type: typeof CENTRIFUGE_OUTPUT_TYPE.TOKEN_REQUEST; requestId: number; kind: 'token' | 'channelToken'; channel?: string }\n /** The SharedWorker's reaper is about to close this port, so its session and\n * WebSocket are going away with it. Sent as the last message on the port: a tab\n * whose heartbeat was merely starved (a long task, background throttling) is\n * alive and can rebuild, but only if it learns that its backend is gone. */\n | { type: typeof CENTRIFUGE_OUTPUT_TYPE.SESSION_REAPED };\n", "/**\n * Reaper for SharedWorker ports.\n *\n * A `MessagePort` has no `close` event, so the SharedWorker cannot tell whether\n * a tab died without sending STOP. The main thread therefore sends periodic\n * PING messages, and this reaper closes any session whose port has been silent\n * longer than its timeout.\n *\n * The cadence is adaptive: the reaper runs at the smallest configured heartbeat\n * interval across active ports, and stops entirely when the last port is\n * removed, so a long-lived SharedWorker does not run a perpetual no-op interval\n * between connect bursts.\n *\n * The timers and clock are injected so the reaper can be unit-tested without a\n * real worker or DOM.\n */\n\nimport {\n DEFAULT_HEARTBEAT_INTERVAL_MS,\n DEFAULT_SESSION_TIMEOUT_MS,\n DEFAULT_SESSION_TIMEOUT_MULTIPLIER\n} from '../centrifuge-protocol';\n\n/** The three teardown steps `reap()` runs on a silent port, in that order:\n * `notify` posts the loss to the main thread, `close` withdraws the port, `stop`\n * ends its session. `notify` has to go first because a closed port discards\n * anything posted after it, so this is its owner's only notice of why the\n * session ended. The three share one `try`/`catch`: a target that throws in\n * `notify` also skips `close` and `stop` for itself, which `reap()` accepts\n * rather than working around. */\nexport interface ReapTarget {\n notify(): void;\n close(): void;\n stop(): void;\n}\n\ntype SetTimer = (callback: () => void, ms: number) => number;\ntype ClearTimer = (handle: number) => void;\n\nexport class PortReaper {\n private readonly targets = new Map<MessagePort, ReapTarget>();\n private readonly lastSeenAt = new Map<MessagePort, number>();\n private readonly sessionTimeoutMs = new Map<MessagePort, number>();\n private handle: number | null = null;\n private intervalMs = DEFAULT_HEARTBEAT_INTERVAL_MS;\n\n constructor(\n private readonly now: () => number = Date.now,\n setTimer: SetTimer = (callback, ms) => setInterval(callback, ms) as unknown as number,\n clearTimer: ClearTimer = handle => clearInterval(handle)\n ) {\n this.setTimer = setTimer;\n this.clearTimer = clearTimer;\n }\n\n private readonly setTimer: SetTimer;\n private readonly clearTimer: ClearTimer;\n\n /** Track a newly connected port and its session. The default timeout applies\n * until the port sends an INIT with its own heartbeat config, at which point\n * setTimeout() overrides it. register() always calls schedule() so the\n * reaper interval starts as soon as the first port connects. */\n register(port: MessagePort, target: ReapTarget): void {\n this.targets.set(port, target);\n this.lastSeenAt.set(port, this.now());\n this.sessionTimeoutMs.set(port, DEFAULT_SESSION_TIMEOUT_MS);\n this.schedule();\n }\n\n /** Record activity on a port (any incoming message). The early return is what\n * keeps a late PING from a removed port out of `lastSeenAt`: `reap()` iterates\n * `targets`, so a row here would be unreachable rather than dangerous \u2014 measured,\n * deleting the guard passes every test in the suite, because the only difference is\n * one stale map entry per dead port. It stays as the cheap invariant that the three\n * maps hold exactly the tracked ports, which is what `reap()`'s `??` fallbacks and\n * this file's tracking contract both lean on. */\n touch(port: MessagePort): void {\n if (!this.targets.has(port)) return;\n this.lastSeenAt.set(port, this.now());\n }\n\n /** Override a port's session timeout from its INIT heartbeat config.\n * `Infinity` is the documented way to disable the PING heartbeat, and it means\n * this port can never be judged silent: `startHeartbeat()` sends nothing at all\n * once configured that way, so a timeout would be a death sentence with no\n * possible appeal. A non-finite-or-non-positive *other* value falls back to\n * the default, which keeps the timeout comparison from degenerating into\n * \"always expired\" \u2014 a NaN timeout reaps every port on the first tick. Read\n * that narrowly, because it is not a busy-loop guard: the busy-loop vector is\n * a tiny *positive* interval, which the ternary passes through untouched\n * (0.0001 \u2192 a 0.0003 ms timeout \u2192 every tick reaps everything), and the\n * reaper's own cadence is bounded elsewhere \u2014 `computeMinHeartbeat` starts\n * from DEFAULT_HEARTBEAT_INTERVAL_MS and only takes a minimum, so a payload\n * can shorten the sweep but never stretch it past 10 s. The three values\n * rejected here (NaN, 0, negative) are also rejected by\n * `assertHeartbeatInterval` at the transport constructor and so can only\n * arrive from a main thread that is not this library. No-op for untracked\n * ports (e.g. setTimeout arrives after remove/STOP). */\n setTimeout(port: MessagePort, heartbeatIntervalMs: number): void {\n if (!this.targets.has(port)) return;\n const safe = heartbeatIntervalMs === Infinity\n ? Infinity\n : Number.isFinite(heartbeatIntervalMs) && heartbeatIntervalMs > 0\n ? heartbeatIntervalMs\n : DEFAULT_HEARTBEAT_INTERVAL_MS;\n this.sessionTimeoutMs.set(port, safe * DEFAULT_SESSION_TIMEOUT_MULTIPLIER);\n this.schedule();\n }\n\n /** Remove a port (STOP message). The caller is responsible for closing the\n * port and stopping the session. No-op for untracked ports so a duplicate\n * STOP or a STOP-after-reap cannot corrupt the reaper's bookkeeping. */\n remove(port: MessagePort): void {\n if (!this.targets.has(port)) return;\n this.targets.delete(port);\n this.lastSeenAt.delete(port);\n this.sessionTimeoutMs.delete(port);\n this.schedule();\n }\n\n /** Clear all state and stop the reaper. Closes and stops every tracked\n * session so the SharedWorker does not leak WebSockets on shutdown. */\n dispose(): void {\n if (this.handle !== null) this.clearTimer(this.handle);\n this.handle = null;\n for (const target of this.targets.values()) {\n try {\n target.close();\n target.stop();\n } catch {\n // A failing target must not prevent the rest from being cleaned up.\n }\n }\n this.targets.clear();\n this.lastSeenAt.clear();\n this.sessionTimeoutMs.clear();\n }\n\n /** Recompute the reaper cadence, or stop it entirely when no ports remain.\n * Idempotent: if the interval is already running at the correct cadence,\n * no new timer is created. This guards against register/remove/setTimeout\n * each spawning redundant timers when the cadence hasn't changed. */\n private schedule(): void {\n if (this.sessionTimeoutMs.size === 0) {\n // Zero counts on the guard's false arm: reaching this line with `handle`\n // already null needs a `schedule()` call made while all three maps are empty,\n // and every caller is gated on a tracked port \u2014 `remove()` and `setTimeout()`\n // behind `targets.has(port)`, `register()` having just added one, and the reap\n // pass only after it reaped something. The two statements that null `handle`\n // are this branch itself, which requires the empty map it implies, and\n // `dispose()`, which clears all three maps and therefore takes every caller's\n // guard with it. `dispose()` also has no Worker-side caller at all \u2014 recorded\n // in configuration.md \u2014 so in the shipped SharedWorker this arm is\n // unreachable rather than merely unreached. It stays as the file's statement\n // that a null handle is never handed to `clearTimer`.\n // The null assignment is what keeps this terminating, and that is a stronger\n // statement than \"correctness\": measured, replacing it with *any* re-arm \u2014\n // including a 0 ms one \u2014 produces a mutant that **never terminates**, because\n // `setTimer(() => this.reap(), 0)` re-enters `reap()`, which reaches this\n // branch again with the maps still empty, forever. It cost a thirty-minute\n // harness run and a mutated working tree before the mutant was bounded, so the\n // measurement is recorded here: a null handle is not merely tidy here, it is\n // the only thing standing between this branch and an unbounded timer loop.\n if (this.handle !== null) this.clearTimer(this.handle);\n this.handle = null;\n return;\n }\n const minHeartbeat = this.computeMinHeartbeat();\n if (this.handle !== null && this.intervalMs === minHeartbeat) return;\n if (this.handle !== null) this.clearTimer(this.handle);\n this.intervalMs = minHeartbeat;\n this.handle = this.setTimer(() => this.reap(), minHeartbeat);\n }\n\n /** Smallest heartbeat interval among active ports, derived from each port's\n * configured session timeout. Extracted because `schedule()` derives its delay\n * from it on every re-arm. Not a test seam: nothing in `tests/` calls it\n * (grep: zero hits), and the cadence is asserted through the injected\n * `setTimer` \u2014 i.e. through the same plumbing this note used to claim it was\n * isolated from. */\n private computeMinHeartbeat(): number {\n let minHeartbeat = DEFAULT_HEARTBEAT_INTERVAL_MS;\n for (const timeout of this.sessionTimeoutMs.values()) {\n minHeartbeat = Math.min(minHeartbeat, timeout / DEFAULT_SESSION_TIMEOUT_MULTIPLIER);\n }\n return minHeartbeat;\n }\n\n /** Close sessions whose port has been silent longer than its timeout.\n * Iterates a snapshot. That is defensive rather than load-bearing: `Map`\n * iteration in JS is deletion-safe, so removing the current entry cannot skip the\n * next one, and the only case a snapshot changes is a re-entrant `register()` from\n * inside a target's own teardown \u2014 which a fresh port would survive anyway, because\n * `register()` stamps `lastSeenAt` with the current time and a zero-age port is\n * never past its timeout. Measured: iterating the live map instead passes every\n * test, so do not read this line as pinned. */\n private reap(): void {\n const now = this.now();\n let reapedAny = false;\n for (const [port, target] of Array.from(this.targets)) {\n // Both `??` arms are uncovered and dominated, and the enumeration is the\n // tracking contract above: `targets` gains a port only in `register()`,\n // which writes all three maps, and loses one only in `remove()` and in the\n // loop below, and in the whole-map `clear()`s of dispose(): a port in\n // `targets` is therefore in the other two as well. Measured \u2014 replacing the\n // first fallback with a non-null assertion leaves the whole suite green.\n // It stays because of what a half-registered port would cost: `lastSeen` 0\n // reads as silent-since-epoch, so the next tick closes a session that was\n // never late, which is a worse failure than the undefined it stands in for.\n const lastSeen = this.lastSeenAt.get(port) ?? 0;\n const timeout = this.sessionTimeoutMs.get(port) ?? DEFAULT_SESSION_TIMEOUT_MS;\n if (now - lastSeen <= timeout) continue;\n this.targets.delete(port);\n this.lastSeenAt.delete(port);\n this.sessionTimeoutMs.delete(port);\n // Announce before withdrawing, then close the port and stop the session.\n // The order matters in both directions:\n // - `notify` is the last thing this port ever delivers, and it has to\n // precede `close()`, because a closed port discards everything posted to\n // it \u2014 including the session's own `disconnected` status post. A tab whose\n // heartbeat was merely starved (a long task, the throttling a backgrounded\n // tab gets) rather than gone is alive and can rebuild its backend, but only\n // if it learns the session left. Measured in a real browser before this\n // existed: a 34 s stall got a shared-mode tab's port reaped while the bus\n // kept `state: healthy` / `status: connected` and its routes, and every\n // publication it posted went into the closed port and vanished.\n // - `close` still precedes `stop`: the STOP handler posts that\n // `disconnected` status back to the port, which must not reach the main\n // thread after it has been told outright, and a closed port can never\n // deliver a later message that would resurrect the session outside the\n // reaper's tracking.\n // All three share the existing try/catch, which isolates a failing target\n // from the *other* ports in the pass. That is the same guarantee `close`\n // already had: a step that throws also skips the steps after it for this one\n // target, which is accepted here rather than newly introduced.\n try {\n target.notify();\n target.close();\n target.stop();\n } catch {\n // A failing target must not prevent the rest from being reaped or\n // leave the reaper in a broken state for subsequent ticks.\n }\n reapedAny = true;\n }\n // Recompute the cadence (and clear the interval if the last port was reaped).\n //\n // `if (reapedAny)` is **dominated**, and the proof is a pair rather than an\n // argument: deleting it alone leaves the suite green, because `schedule()` opens\n // with its own idempotency guard, so a call at an unchanged cadence is a no-op.\n // Deleting *both* \u2014 this condition and that guard \u2014 kills three cases. So the\n // reschedule is redundant with the idempotency check a few lines above it, and\n // this reads as a leg about avoiding pointless work rather than about\n // correctness. Kept: it says the intent (recompute only when the sweep did\n // something) at the point where the sweep happened, where the next reader is\n // looking.\n if (reapedAny) this.schedule();\n }\n}", "/// <reference lib=\"webworker\" />\n\n/**\n * SharedWorker hosting one independent Centrifuge WebSocket client per tab.\n *\n * Each connecting tab receives its own MessagePort with an independent\n * CentrifugeSession and its own WebSocket connection. When a tab sends STOP,\n * its port is unregistered from the reaper and closed while the remaining tabs\n * continue to operate. There is no session map to remove it from: each\n * connection's session is a closure variable in the connect handler, and the\n * only per-port indexed state is the reaper's own maps.\n *\n * A periodic reaper (PortReaper) closes sessions for ports that have stopped\n * sending messages (e.g. crashed tabs). The reaper cadence is adaptive: it runs\n * at the smallest configured heartbeat interval across active ports, derived\n * from the `heartbeatIntervalMs` the main thread sends in the INIT message.\n * The interval is cleared when the last port is disconnected.\n */\n\nimport type { CentrifugeWorkerInput } from '../centrifuge-protocol';\nimport { CentrifugeSession } from '../centrifuge-session';\nimport { PortReaper } from './port-reaper';\nimport { CENTRIFUGE_INPUT_TYPE, CENTRIFUGE_OUTPUT_TYPE } from '../utils/constants';\n\nconst sharedWorkerScope = self as unknown as SharedWorkerGlobalScope;\n// One session per connecting port \u2014 each tab gets its own subscription scope.\nconst reaper = new PortReaper();\n\nsharedWorkerScope.addEventListener('connect', event => {\n const port = event.ports[0];\n if (!port) return;\n const session = new CentrifugeSession({\n post: (message, transfer) => {\n // Transferable buffers are forwarded when present (zero-copy ArrayBuffer);\n // otherwise the message is structured-cloned normally.\n if (transfer) port.postMessage(message, transfer as Transferable[]);\n else port.postMessage(message);\n }\n });\n reaper.register(port, {\n // Last message this port will ever deliver. The main thread's transport turns\n // it into a backend failure, which is what lets a tab whose heartbeat was\n // merely starved (long task, background throttling) recover instead of going\n // on owning routes that post into a closed port.\n notify: () => port.postMessage({ type: CENTRIFUGE_OUTPUT_TYPE.SESSION_REAPED }),\n close: () => port.close(),\n stop: () => session.handle({ type: CENTRIFUGE_INPUT_TYPE.STOP })\n });\n port.addEventListener('message', event => {\n const message = event.data as CentrifugeWorkerInput;\n reaper.touch(port);\n if (message.type === CENTRIFUGE_INPUT_TYPE.PING) return;\n if (message.type === CENTRIFUGE_INPUT_TYPE.STOP) {\n // Remove from reaper tracking first, then close the port so the\n // session's disconnected status post is discarded, then stop the\n // session to cleanly disconnect its WebSocket.\n reaper.remove(port);\n port.close();\n session.handle({ type: CENTRIFUGE_INPUT_TYPE.STOP });\n return;\n }\n // Capture the heartbeat config from the first (INIT) message so the\n // reaper uses the correct per-port timeout.\n if (message.type === CENTRIFUGE_INPUT_TYPE.INIT && typeof message.heartbeatIntervalMs === 'number') {\n reaper.setTimeout(port, message.heartbeatIntervalMs);\n }\n session.handle(message);\n });\n port.start();\n});"],
|
|
5
|
-
"mappings": ";AAiBA,SAAS,UAAU,SAAS,YAAY,GAAG,WAAW;AAClD,WAAS,MAAM,OAAO;AAAE,WAAO,iBAAiB,IAAI,QAAQ,IAAI,EAAE,SAAU,SAAS;AAAE,cAAQ,KAAK;AAAA,IAAG,CAAC;AAAA,EAAG;AAC3G,SAAO,KAAK,MAAM,IAAI,UAAU,SAAU,SAAS,QAAQ;AACvD,aAAS,UAAU,OAAO;AAAE,UAAI;AAAE,aAAK,UAAU,KAAK,KAAK,CAAC;AAAA,MAAG,SAAS,GAAG;AAAE,eAAO,CAAC;AAAA,MAAG;AAAA,IAAE;AAC1F,aAAS,SAAS,OAAO;AAAE,UAAI;AAAE,aAAK,UAAU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AAA,UAC7D,MAAK,YAAY,OAAO;AAAA,IAC/B;AAAA,EACF,CAAC;AACD,SAAO,SAAS,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA,IAKpB,QAAQ,MAAM,KAAK,YAAY,EAAE,MAAM,uBAAuB,eAAe,CAAC;AAAA,IAC9E,OAAO,MAAM,KAAK,MAAM;AAAA,IACxB,MAAM,MAAM,QAAQ,OAAO,EAAE,MAAM,sBAAsB,KAAK,CAAC;AAAA,EACjE,CAAC;AACD,OAAK,iBAAiB,WAAW,CAAAC,WAAS;AACxC,UAAM,UAAUA,OAAM;AACtB,WAAO,MAAM,IAAI;AACjB,QAAI,QAAQ,SAAS,sBAAsB,KAAM;AACjD,QAAI,QAAQ,SAAS,sBAAsB,MAAM;AAI/C,aAAO,OAAO,IAAI;AAClB,WAAK,MAAM;AACX,cAAQ,OAAO,EAAE,MAAM,sBAAsB,KAAK,CAAC;AACnD;AAAA,IACF;AAGA,QAAI,QAAQ,SAAS,sBAAsB,QAAQ,OAAO,QAAQ,wBAAwB,UAAU;AAClG,aAAO,WAAW,MAAM,QAAQ,mBAAmB;AAAA,IACrD;AACA,YAAQ,OAAO,OAAO;AAAA,EACxB,CAAC;AACD,OAAK,MAAM;AACb,CAAC;",
|
|
3
|
+
"sources": ["../node_modules/.pnpm/centrifuge@5.8.0/node_modules/centrifuge/build/index.mjs", "../src/core/publication.ts", "../src/utils/constants.ts", "../src/utils/metadata.ts", "../src/utils/error-utils.ts", "../src/centrifuge-session.ts", "../src/centrifuge-protocol.ts", "../src/workers/port-reaper.ts", "../src/workers/centrifuge.shared.worker.ts"],
|
|
4
|
+
"sourcesContent": ["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\r\n\r\n\r\nfunction __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nvar events = {exports: {}};\n\nvar hasRequiredEvents;\n\nfunction requireEvents () {\n\tif (hasRequiredEvents) return events.exports;\n\thasRequiredEvents = 1;\n\n\tvar R = typeof Reflect === 'object' ? Reflect : null;\n\tvar ReflectApply = R && typeof R.apply === 'function'\n\t ? R.apply\n\t : function ReflectApply(target, receiver, args) {\n\t return Function.prototype.apply.call(target, receiver, args);\n\t };\n\n\tvar ReflectOwnKeys;\n\tif (R && typeof R.ownKeys === 'function') {\n\t ReflectOwnKeys = R.ownKeys;\n\t} else if (Object.getOwnPropertySymbols) {\n\t ReflectOwnKeys = function ReflectOwnKeys(target) {\n\t return Object.getOwnPropertyNames(target)\n\t .concat(Object.getOwnPropertySymbols(target));\n\t };\n\t} else {\n\t ReflectOwnKeys = function ReflectOwnKeys(target) {\n\t return Object.getOwnPropertyNames(target);\n\t };\n\t}\n\n\tfunction ProcessEmitWarning(warning) {\n\t if (console && console.warn) console.warn(warning);\n\t}\n\n\tvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n\t return value !== value;\n\t};\n\n\tfunction EventEmitter() {\n\t EventEmitter.init.call(this);\n\t}\n\tevents.exports = EventEmitter;\n\tevents.exports.once = once;\n\n\t// Backwards-compat with node 0.10.x\n\tEventEmitter.EventEmitter = EventEmitter;\n\n\tEventEmitter.prototype._events = undefined;\n\tEventEmitter.prototype._eventsCount = 0;\n\tEventEmitter.prototype._maxListeners = undefined;\n\n\t// By default EventEmitters will print a warning if more than 10 listeners are\n\t// added to it. This is a useful default which helps finding memory leaks.\n\tvar defaultMaxListeners = 10;\n\n\tfunction checkListener(listener) {\n\t if (typeof listener !== 'function') {\n\t throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n\t }\n\t}\n\n\tObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n\t enumerable: true,\n\t get: function() {\n\t return defaultMaxListeners;\n\t },\n\t set: function(arg) {\n\t if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n\t throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n\t }\n\t defaultMaxListeners = arg;\n\t }\n\t});\n\n\tEventEmitter.init = function() {\n\n\t if (this._events === undefined ||\n\t this._events === Object.getPrototypeOf(this)._events) {\n\t this._events = Object.create(null);\n\t this._eventsCount = 0;\n\t }\n\n\t this._maxListeners = this._maxListeners || undefined;\n\t};\n\n\t// Obviously not all Emitters should be limited to 10. This function allows\n\t// that to be increased. Set to zero for unlimited.\n\tEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n\t if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n\t throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n\t }\n\t this._maxListeners = n;\n\t return this;\n\t};\n\n\tfunction _getMaxListeners(that) {\n\t if (that._maxListeners === undefined)\n\t return EventEmitter.defaultMaxListeners;\n\t return that._maxListeners;\n\t}\n\n\tEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n\t return _getMaxListeners(this);\n\t};\n\n\tEventEmitter.prototype.emit = function emit(type) {\n\t var args = [];\n\t for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n\t var doError = (type === 'error');\n\n\t var events = this._events;\n\t if (events !== undefined)\n\t doError = (doError && events.error === undefined);\n\t else if (!doError)\n\t return false;\n\n\t // If there is no 'error' event listener then throw.\n\t if (doError) {\n\t var er;\n\t if (args.length > 0)\n\t er = args[0];\n\t if (er instanceof Error) {\n\t // Note: The comments on the `throw` lines are intentional, they show\n\t // up in Node's output if this results in an unhandled exception.\n\t throw er; // Unhandled 'error' event\n\t }\n\t // At least give some kind of context to the user\n\t var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n\t err.context = er;\n\t throw err; // Unhandled 'error' event\n\t }\n\n\t var handler = events[type];\n\n\t if (handler === undefined)\n\t return false;\n\n\t if (typeof handler === 'function') {\n\t ReflectApply(handler, this, args);\n\t } else {\n\t var len = handler.length;\n\t var listeners = arrayClone(handler, len);\n\t for (var i = 0; i < len; ++i)\n\t ReflectApply(listeners[i], this, args);\n\t }\n\n\t return true;\n\t};\n\n\tfunction _addListener(target, type, listener, prepend) {\n\t var m;\n\t var events;\n\t var existing;\n\n\t checkListener(listener);\n\n\t events = target._events;\n\t if (events === undefined) {\n\t events = target._events = Object.create(null);\n\t target._eventsCount = 0;\n\t } else {\n\t // To avoid recursion in the case that type === \"newListener\"! Before\n\t // adding it to the listeners, first emit \"newListener\".\n\t if (events.newListener !== undefined) {\n\t target.emit('newListener', type,\n\t listener.listener ? listener.listener : listener);\n\n\t // Re-assign `events` because a newListener handler could have caused the\n\t // this._events to be assigned to a new object\n\t events = target._events;\n\t }\n\t existing = events[type];\n\t }\n\n\t if (existing === undefined) {\n\t // Optimize the case of one listener. Don't need the extra array object.\n\t existing = events[type] = listener;\n\t ++target._eventsCount;\n\t } else {\n\t if (typeof existing === 'function') {\n\t // Adding the second element, need to change to array.\n\t existing = events[type] =\n\t prepend ? [listener, existing] : [existing, listener];\n\t // If we've already got an array, just append.\n\t } else if (prepend) {\n\t existing.unshift(listener);\n\t } else {\n\t existing.push(listener);\n\t }\n\n\t // Check for listener leak\n\t m = _getMaxListeners(target);\n\t if (m > 0 && existing.length > m && !existing.warned) {\n\t existing.warned = true;\n\t // No error code for this since it is a Warning\n\t // eslint-disable-next-line no-restricted-syntax\n\t var w = new Error('Possible EventEmitter memory leak detected. ' +\n\t existing.length + ' ' + String(type) + ' listeners ' +\n\t 'added. Use emitter.setMaxListeners() to ' +\n\t 'increase limit');\n\t w.name = 'MaxListenersExceededWarning';\n\t w.emitter = target;\n\t w.type = type;\n\t w.count = existing.length;\n\t ProcessEmitWarning(w);\n\t }\n\t }\n\n\t return target;\n\t}\n\n\tEventEmitter.prototype.addListener = function addListener(type, listener) {\n\t return _addListener(this, type, listener, false);\n\t};\n\n\tEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\n\tEventEmitter.prototype.prependListener =\n\t function prependListener(type, listener) {\n\t return _addListener(this, type, listener, true);\n\t };\n\n\tfunction onceWrapper() {\n\t if (!this.fired) {\n\t this.target.removeListener(this.type, this.wrapFn);\n\t this.fired = true;\n\t if (arguments.length === 0)\n\t return this.listener.call(this.target);\n\t return this.listener.apply(this.target, arguments);\n\t }\n\t}\n\n\tfunction _onceWrap(target, type, listener) {\n\t var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n\t var wrapped = onceWrapper.bind(state);\n\t wrapped.listener = listener;\n\t state.wrapFn = wrapped;\n\t return wrapped;\n\t}\n\n\tEventEmitter.prototype.once = function once(type, listener) {\n\t checkListener(listener);\n\t this.on(type, _onceWrap(this, type, listener));\n\t return this;\n\t};\n\n\tEventEmitter.prototype.prependOnceListener =\n\t function prependOnceListener(type, listener) {\n\t checkListener(listener);\n\t this.prependListener(type, _onceWrap(this, type, listener));\n\t return this;\n\t };\n\n\t// Emits a 'removeListener' event if and only if the listener was removed.\n\tEventEmitter.prototype.removeListener =\n\t function removeListener(type, listener) {\n\t var list, events, position, i, originalListener;\n\n\t checkListener(listener);\n\n\t events = this._events;\n\t if (events === undefined)\n\t return this;\n\n\t list = events[type];\n\t if (list === undefined)\n\t return this;\n\n\t if (list === listener || list.listener === listener) {\n\t if (--this._eventsCount === 0)\n\t this._events = Object.create(null);\n\t else {\n\t delete events[type];\n\t if (events.removeListener)\n\t this.emit('removeListener', type, list.listener || listener);\n\t }\n\t } else if (typeof list !== 'function') {\n\t position = -1;\n\n\t for (i = list.length - 1; i >= 0; i--) {\n\t if (list[i] === listener || list[i].listener === listener) {\n\t originalListener = list[i].listener;\n\t position = i;\n\t break;\n\t }\n\t }\n\n\t if (position < 0)\n\t return this;\n\n\t if (position === 0)\n\t list.shift();\n\t else {\n\t spliceOne(list, position);\n\t }\n\n\t if (list.length === 1)\n\t events[type] = list[0];\n\n\t if (events.removeListener !== undefined)\n\t this.emit('removeListener', type, originalListener || listener);\n\t }\n\n\t return this;\n\t };\n\n\tEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\n\tEventEmitter.prototype.removeAllListeners =\n\t function removeAllListeners(type) {\n\t var listeners, events, i;\n\n\t events = this._events;\n\t if (events === undefined)\n\t return this;\n\n\t // not listening for removeListener, no need to emit\n\t if (events.removeListener === undefined) {\n\t if (arguments.length === 0) {\n\t this._events = Object.create(null);\n\t this._eventsCount = 0;\n\t } else if (events[type] !== undefined) {\n\t if (--this._eventsCount === 0)\n\t this._events = Object.create(null);\n\t else\n\t delete events[type];\n\t }\n\t return this;\n\t }\n\n\t // emit removeListener for all listeners on all events\n\t if (arguments.length === 0) {\n\t var keys = Object.keys(events);\n\t var key;\n\t for (i = 0; i < keys.length; ++i) {\n\t key = keys[i];\n\t if (key === 'removeListener') continue;\n\t this.removeAllListeners(key);\n\t }\n\t this.removeAllListeners('removeListener');\n\t this._events = Object.create(null);\n\t this._eventsCount = 0;\n\t return this;\n\t }\n\n\t listeners = events[type];\n\n\t if (typeof listeners === 'function') {\n\t this.removeListener(type, listeners);\n\t } else if (listeners !== undefined) {\n\t // LIFO order\n\t for (i = listeners.length - 1; i >= 0; i--) {\n\t this.removeListener(type, listeners[i]);\n\t }\n\t }\n\n\t return this;\n\t };\n\n\tfunction _listeners(target, type, unwrap) {\n\t var events = target._events;\n\n\t if (events === undefined)\n\t return [];\n\n\t var evlistener = events[type];\n\t if (evlistener === undefined)\n\t return [];\n\n\t if (typeof evlistener === 'function')\n\t return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n\t return unwrap ?\n\t unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n\t}\n\n\tEventEmitter.prototype.listeners = function listeners(type) {\n\t return _listeners(this, type, true);\n\t};\n\n\tEventEmitter.prototype.rawListeners = function rawListeners(type) {\n\t return _listeners(this, type, false);\n\t};\n\n\tEventEmitter.listenerCount = function(emitter, type) {\n\t if (typeof emitter.listenerCount === 'function') {\n\t return emitter.listenerCount(type);\n\t } else {\n\t return listenerCount.call(emitter, type);\n\t }\n\t};\n\n\tEventEmitter.prototype.listenerCount = listenerCount;\n\tfunction listenerCount(type) {\n\t var events = this._events;\n\n\t if (events !== undefined) {\n\t var evlistener = events[type];\n\n\t if (typeof evlistener === 'function') {\n\t return 1;\n\t } else if (evlistener !== undefined) {\n\t return evlistener.length;\n\t }\n\t }\n\n\t return 0;\n\t}\n\n\tEventEmitter.prototype.eventNames = function eventNames() {\n\t return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n\t};\n\n\tfunction arrayClone(arr, n) {\n\t var copy = new Array(n);\n\t for (var i = 0; i < n; ++i)\n\t copy[i] = arr[i];\n\t return copy;\n\t}\n\n\tfunction spliceOne(list, index) {\n\t for (; index + 1 < list.length; index++)\n\t list[index] = list[index + 1];\n\t list.pop();\n\t}\n\n\tfunction unwrapListeners(arr) {\n\t var ret = new Array(arr.length);\n\t for (var i = 0; i < ret.length; ++i) {\n\t ret[i] = arr[i].listener || arr[i];\n\t }\n\t return ret;\n\t}\n\n\tfunction once(emitter, name) {\n\t return new Promise(function (resolve, reject) {\n\t function errorListener(err) {\n\t emitter.removeListener(name, resolver);\n\t reject(err);\n\t }\n\n\t function resolver() {\n\t if (typeof emitter.removeListener === 'function') {\n\t emitter.removeListener('error', errorListener);\n\t }\n\t resolve([].slice.call(arguments));\n\t }\n\t eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n\t if (name !== 'error') {\n\t addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n\t }\n\t });\n\t}\n\n\tfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n\t if (typeof emitter.on === 'function') {\n\t eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n\t }\n\t}\n\n\tfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n\t if (typeof emitter.on === 'function') {\n\t if (flags.once) {\n\t emitter.once(name, listener);\n\t } else {\n\t emitter.on(name, listener);\n\t }\n\t } else if (typeof emitter.addEventListener === 'function') {\n\t // EventTarget does not have `error` event semantics like Node\n\t // EventEmitters, we do not listen for `error` events here.\n\t emitter.addEventListener(name, function wrapListener(arg) {\n\t // IE does not have builtin `{ once: true }` support so we\n\t // have to do it manually.\n\t if (flags.once) {\n\t emitter.removeEventListener(name, wrapListener);\n\t }\n\t listener(arg);\n\t });\n\t } else {\n\t throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n\t }\n\t}\n\treturn events.exports;\n}\n\nvar eventsExports = requireEvents();\nvar EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventsExports);\n\nvar errorCodes;\n(function (errorCodes) {\n errorCodes[errorCodes[\"timeout\"] = 1] = \"timeout\";\n errorCodes[errorCodes[\"transportClosed\"] = 2] = \"transportClosed\";\n errorCodes[errorCodes[\"clientDisconnected\"] = 3] = \"clientDisconnected\";\n errorCodes[errorCodes[\"clientClosed\"] = 4] = \"clientClosed\";\n errorCodes[errorCodes[\"clientConnectToken\"] = 5] = \"clientConnectToken\";\n errorCodes[errorCodes[\"clientRefreshToken\"] = 6] = \"clientRefreshToken\";\n errorCodes[errorCodes[\"subscriptionUnsubscribed\"] = 7] = \"subscriptionUnsubscribed\";\n errorCodes[errorCodes[\"subscriptionSubscribeToken\"] = 8] = \"subscriptionSubscribeToken\";\n errorCodes[errorCodes[\"subscriptionRefreshToken\"] = 9] = \"subscriptionRefreshToken\";\n errorCodes[errorCodes[\"transportWriteError\"] = 10] = \"transportWriteError\";\n errorCodes[errorCodes[\"connectionClosed\"] = 11] = \"connectionClosed\";\n errorCodes[errorCodes[\"badConfiguration\"] = 12] = \"badConfiguration\";\n errorCodes[errorCodes[\"subscriptionGetState\"] = 13] = \"subscriptionGetState\";\n errorCodes[errorCodes[\"sharedPollGetSignature\"] = 14] = \"sharedPollGetSignature\";\n})(errorCodes || (errorCodes = {}));\nvar connectingCodes;\n(function (connectingCodes) {\n connectingCodes[connectingCodes[\"connectCalled\"] = 0] = \"connectCalled\";\n connectingCodes[connectingCodes[\"transportClosed\"] = 1] = \"transportClosed\";\n connectingCodes[connectingCodes[\"noPing\"] = 2] = \"noPing\";\n connectingCodes[connectingCodes[\"subscribeTimeout\"] = 3] = \"subscribeTimeout\";\n connectingCodes[connectingCodes[\"unsubscribeError\"] = 4] = \"unsubscribeError\";\n})(connectingCodes || (connectingCodes = {}));\nvar disconnectedCodes;\n(function (disconnectedCodes) {\n disconnectedCodes[disconnectedCodes[\"disconnectCalled\"] = 0] = \"disconnectCalled\";\n disconnectedCodes[disconnectedCodes[\"unauthorized\"] = 1] = \"unauthorized\";\n disconnectedCodes[disconnectedCodes[\"badProtocol\"] = 2] = \"badProtocol\";\n disconnectedCodes[disconnectedCodes[\"messageSizeLimit\"] = 3] = \"messageSizeLimit\";\n // Server-sent: the connection's cached state and/or token are no longer valid.\n // The client clears the connection token (to force getToken), invalidates all\n // subscription state, and reconnects. Delivered as a Disconnect push or a raw\n // WebSocket close code.\n disconnectedCodes[disconnectedCodes[\"stateInvalidated\"] = 3014] = \"stateInvalidated\";\n})(disconnectedCodes || (disconnectedCodes = {}));\nvar subscribingCodes;\n(function (subscribingCodes) {\n subscribingCodes[subscribingCodes[\"subscribeCalled\"] = 0] = \"subscribeCalled\";\n subscribingCodes[subscribingCodes[\"transportClosed\"] = 1] = \"transportClosed\";\n})(subscribingCodes || (subscribingCodes = {}));\nvar unsubscribedCodes;\n(function (unsubscribedCodes) {\n unsubscribedCodes[unsubscribedCodes[\"unsubscribeCalled\"] = 0] = \"unsubscribeCalled\";\n unsubscribedCodes[unsubscribedCodes[\"unauthorized\"] = 1] = \"unauthorized\";\n unsubscribedCodes[unsubscribedCodes[\"clientClosed\"] = 2] = \"clientClosed\";\n // Server-sent (in an Unsubscribe push): this subscription's cached state\n // and/or token are no longer valid. The client clears the subscription state\n // and resubscribes (this is a temporary unsubscribe, code >= 2500).\n unsubscribedCodes[unsubscribedCodes[\"stateInvalidated\"] = 2502] = \"stateInvalidated\";\n})(unsubscribedCodes || (unsubscribedCodes = {}));\nvar subscriptionFlags;\n(function (subscriptionFlags) {\n subscriptionFlags[subscriptionFlags[\"channelCompaction\"] = 1] = \"channelCompaction\";\n subscriptionFlags[subscriptionFlags[\"rejectUnrecovered\"] = 2] = \"rejectUnrecovered\";\n})(subscriptionFlags || (subscriptionFlags = {}));\n\n/** State of client. */\nvar State;\n(function (State) {\n State[\"Disconnected\"] = \"disconnected\";\n State[\"Connecting\"] = \"connecting\";\n State[\"Connected\"] = \"connected\";\n})(State || (State = {}));\n/** State of Subscription */\nvar SubscriptionState;\n(function (SubscriptionState) {\n SubscriptionState[\"Unsubscribed\"] = \"unsubscribed\";\n SubscriptionState[\"Subscribing\"] = \"subscribing\";\n SubscriptionState[\"Subscribed\"] = \"subscribed\";\n})(SubscriptionState || (SubscriptionState = {}));\n\n/** @internal */\nfunction startsWith(value, prefix) {\n return value.lastIndexOf(prefix, 0) === 0;\n}\n/** @internal */\nfunction isFunction(value) {\n if (value === undefined || value === null) {\n return false;\n }\n return typeof value === 'function';\n}\n/** @internal */\nfunction log(level, args) {\n if (globalThis.console) {\n const logger = globalThis.console[level];\n if (isFunction(logger)) {\n logger.apply(globalThis.console, args);\n }\n }\n}\nfunction randomInt(min, max) {\n return Math.floor(Math.random() * (max - min + 1) + min);\n}\n/** @internal */\nfunction backoff(step, min, max) {\n // Full jitter technique, see:\n // https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/\n if (step > 31) {\n step = 31;\n }\n const interval = randomInt(0, Math.min(max, min * Math.pow(2, step)));\n return Math.min(max, min + interval);\n}\n/** @internal */\nfunction errorExists(data) {\n return 'error' in data && data.error !== null;\n}\n/** @internal */\nfunction ttlMilliseconds(ttl) {\n // https://stackoverflow.com/questions/12633405/what-is-the-maximum-delay-for-setinterval\n return Math.min(ttl * 1000, 2147483647);\n}\n/** @internal */\nfunction localStorageItem(key) {\n // Accessing localStorage is not always safe: it may be null (Safari in\n // private browsing mode), or even throw on property access (when access to\n // storage is denied by the browser settings).\n try {\n if (typeof localStorage === 'undefined' || localStorage === null || !isFunction(localStorage.getItem)) {\n return null;\n }\n return localStorage.getItem(key);\n }\n catch (e) {\n return null;\n }\n}\n/** @internal Reports whether a publication carries an offset. Protobuf decodes a\n * missing offset as 0 (a Long where long.js is available), which must not replace\n * a stored position. */\nfunction hasOffset(offset) {\n return offset !== undefined && offset !== null && Number(offset) > 0;\n}\n/** @internal Converts an offset of a reply or a publication to a number.\n * Over the protobuf protocol a uint64 decodes to a Long object where long.js is\n * available (it comes with protobufjs), and such an object must reach neither the\n * app \u2014 the public types declare a number, and an app storing the position gets\n * `{low, high, unsigned}` back, which compares and adds as NaN \u2014 nor the position\n * the library keeps. A position an app stored with an earlier version, and passes\n * back through `since`, has the same shape without the methods, so it is converted\n * here too. Offsets above 2^53 lose exactness, as the public type implies. */\nfunction toOffset(offset) {\n if (offset === undefined || offset === null) {\n return 0;\n }\n if (typeof offset === 'object') {\n const low = offset.low;\n const high = offset.high;\n if (typeof low === 'number' && typeof high === 'number') {\n return (high >>> 0) * 4294967296 + (low >>> 0);\n }\n }\n const value = Number(offset);\n return isNaN(value) ? 0 : value;\n}\n\n// Internal-only \u2014 phases the SDK walks through during a map subscribe.\n// Not exposed on the public surface; kept here so it doesn't leak via\n// `export * from \"./types\"` in index.ts.\nvar MapPhase;\n(function (MapPhase) {\n MapPhase[MapPhase[\"Live\"] = 0] = \"Live\";\n MapPhase[MapPhase[\"Stream\"] = 1] = \"Stream\";\n MapPhase[MapPhase[\"State\"] = 2] = \"State\";\n})(MapPhase || (MapPhase = {}));\n/** Base subscription to a channel \u2014 all subscription logic lives here. */\nclass BaseSubscription extends EventEmitter {\n /** Subscription constructor should not be used directly, create subscriptions using Client method. */\n constructor(centrifuge, channel, options) {\n super();\n this._resubscribeTimeout = null;\n this._refreshTimeout = null;\n /** The offset of the publication being dispatched, until its handler returned. See _getOffset. */\n this._pendingOffset = null;\n // @ts-ignore \u2013 this is set by a client in centrifuge.ts.\n this._removed = false;\n // Stream getState callback (external state for stream subscriptions)\n this._getState = null;\n // Map subscription state\n this._map = false;\n this._mapPresenceType = 1; // 1=MAP, 2=MAP_CLIENTS, 3=MAP_USERS\n // @ts-ignore \u2013 this is used for tracking map subscription phase state.\n this._mapPhase = null;\n // Publications of state and stream pages, decoded once the live reply tells\n // whether delta is on (see _handleMapLiveResponse).\n this._mapStateBuffer = [];\n this._mapStreamBuffer = [];\n this._mapCursor = ''; // Pagination cursor\n this._mapPageSize = 0; // Page size (0 = use server default)\n this._mapUnrecoverableStrategy = 'from_scratch';\n // Incremented when the map position is reset (setTagsFilter, state invalidation),\n // so a subscribe that completes meanwhile doesn't store its position over that.\n this._mapPositionResets = 0;\n // The subscribe flow in progress: replies and continuations of an earlier flow are\n // ignored. Every map flow and every unsubscribe starts a new one, so a subscribe\n // reply still in flight when the app calls unsubscribe() and subscribe() doesn't\n // complete the new subscribe. A map flow pages from its own stream offset and\n // epoch; the subscription position (_offset/_epoch) moves only with what the app\n // received.\n this._subscribeFlow = 0;\n // Incremented whenever the subscription stops being subscribed: a token or signature\n // obtained for an earlier subscribed period is outdated (see _refresh).\n this._refreshGeneration = 0;\n // Set while a shared poll subscription completes its subscribe: tracking changes of\n // handlers of its events go out with the replay that follows, not before it too.\n this._sharedPollReplayPending = false;\n // Incremented by every state change: an event of a change a 'state' handler\n // followed with another one is outdated, even when that one came back to the\n // same state.\n this._stateTransitions = 0;\n // Over emulation, the shared poll track / untrack requests of the channel, one\n // at a time (see _sharedPollSerial).\n this._sharedPollQueue = Promise.resolve();\n // The flow of the subscribe command (or map page) waiting for its reply.\n this._subscribeCallFlow = null;\n // Over emulation, the unsubscribe of a subscribe in flight: sent once the\n // subscribe's reply comes (see _setUnsubscribed).\n this._deferredUnsubscribe = null;\n this._mapFlowRecovering = false;\n this._mapFlowOffset = 0;\n this._mapFlowEpoch = null;\n this._mapFlowPositionResets = 0;\n // Publish debounce state (protocol-level, controlled by server)\n this._debounceMs = 0;\n this._debouncePending = new Map();\n // Shared poll subscription state\n this._sharedPoll = false;\n this._sharedPollEpoch = '';\n this._sharedPollTrackedItems = new Map(); // key \u2192 version\n this._sharedPollGetSignature = null;\n // TTL-driven and 109-driven consolidating refresh (one call to getSignature\n // covering all tracked keys, replaces the library with one entry).\n this._sharedPollSignatureRefreshTimeout = null;\n this._sharedPollSignatureRefreshAttempts = 0;\n // Per-track-command transient retry (track call failed with temporary error).\n this._sharedPollTrackRetryTimeout = null;\n this._sharedPollTrackRetryAttempts = 0;\n // Replay-getSignature retry (Phase 2 of _sharedPollReplayTrack failed). Held\n // separately so it can't clobber the refresh timer or accumulate backoff\n // attempts onto refresh failures.\n this._sharedPollReplayRetryTimeout = null;\n this._sharedPollReplayRetryAttempts = 0;\n // Library of HMAC signatures previously obtained for track() calls.\n // Each entry covers the exact key set originally signed; reused on reconnect\n // so we don't hit the application's getSignature endpoint for every client\n // during mass reconnect storms. Periodic refresh consolidates entries into\n // one combined signature covering all currently tracked keys.\n this._sharedPollSignatures = [];\n // Earliest scheduled refresh time (unix milliseconds) across all received\n // track responses. Server returns MIN ttl per response; SDK keeps the\n // single earliest deadline as the refresh target. Cleared on consolidation\n // refresh and on explicit unsubscribe.\n this._sharedPollSignatureRefreshTargetMs = null;\n // Guard against concurrent refresh calls \u2014 multiple 109 errors during\n // reconnect replay could otherwise trigger overlapping getSignature calls.\n this._sharedPollSignatureRefreshInFlight = false;\n // A refresh asked for while one was in flight for keys it doesn't cover (e.g.\n // a 109 of a key tracked since it started): run after it.\n this._sharedPollSignatureRefreshAgain = false;\n // The keys of the refresh in flight.\n this._sharedPollSignatureRefreshKeys = new Set();\n this.channel = channel;\n this.state = SubscriptionState.Unsubscribed;\n this._centrifuge = centrifuge;\n this._token = '';\n this._getToken = null;\n this._data = null;\n this._getData = null;\n this._recover = false;\n this._offset = null;\n this._epoch = null;\n this._id = 0;\n this._recoverable = false;\n this._positioned = false;\n this._joinLeave = false;\n this._minResubscribeDelay = 500;\n this._maxResubscribeDelay = 20000;\n this._resubscribeTimeout = null;\n this._resubscribeAttempts = 0;\n this._promises = {};\n this._promiseId = 0;\n this._inflight = false;\n this._refreshTimeout = null;\n this._delta = '';\n this._delta_negotiated = false;\n this._tagsFilter = null;\n this._prevValueMap = new Map();\n this._unsubPromise = Promise.resolve();\n this._deltaNumPubs = 0;\n this._deltaNumFull = 0;\n this._deltaNumDelta = 0;\n this._deltaBytesReceived = 0;\n this._deltaBytesDecoded = 0;\n this._setOptions(options);\n this.type = this._sharedPoll ? 'shared_poll' : this._map ? 'map' : 'stream';\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n if (this._centrifuge._debugEnabled) {\n this.on('state', (ctx) => {\n this._debug('subscription state', channel, ctx.oldState, '->', ctx.newState);\n });\n this.on('error', (ctx) => {\n this._debug('subscription error', channel, ctx);\n });\n }\n else {\n // Avoid unhandled exception in EventEmitter for non-set error handler.\n this.on('error', function () { Function.prototype(); });\n }\n }\n /** ready returns a Promise which resolves upon subscription goes to Subscribed\n * state and rejects in case of subscription goes to Unsubscribed state.\n * Optional timeout can be passed.*/\n ready(timeout) {\n if (this.state === SubscriptionState.Unsubscribed) {\n return Promise.reject({ code: errorCodes.subscriptionUnsubscribed, message: this.state });\n }\n if (this.state === SubscriptionState.Subscribed) {\n return Promise.resolve();\n }\n return new Promise((res, rej) => {\n const id = this._nextPromiseId();\n const ctx = {\n resolve: res,\n reject: rej\n };\n if (timeout) {\n ctx.timeout = setTimeout(() => {\n // A call that gave up waiting leaves no waiter behind.\n delete this._promises[id];\n rej({ code: errorCodes.timeout, message: 'timeout' });\n }, timeout);\n }\n this._promises[id] = ctx;\n });\n }\n /** subscribe to a channel.*/\n subscribe() {\n if (this._removed) {\n // The client no longer tracks it: the server would keep a subscription whose\n // publications are dropped, and which is never subscribed again on reconnect.\n throw new Error('Subscription to the channel ' + this.channel + ' was removed from the client');\n }\n if (this._isSubscribed()) {\n return;\n }\n if (this._isUnsubscribed()) {\n // A subscribe in progress keeps its backoff.\n this._resubscribeAttempts = 0;\n }\n this._setSubscribing(subscribingCodes.subscribeCalled, 'subscribe called');\n }\n /** unsubscribe from a channel, keeping position state.*/\n unsubscribe() {\n this._setUnsubscribed(unsubscribedCodes.unsubscribeCalled, 'unsubscribe called', true);\n }\n _debouncedPublish(key, data, isMap) {\n const existing = this._debouncePending.get(key);\n if (existing) {\n // Update pending value, mark as dirty, keep existing timer.\n existing.data = data;\n existing.dirty = true;\n return Promise.resolve({});\n }\n // First publish for this key \u2014 send immediately, start debounce timer.\n const entry = { data, dirty: false, timer: null };\n entry.timer = setTimeout(() => {\n const pending = this._debouncePending.get(key);\n if (!pending || !pending.dirty) {\n // No new data since last send \u2014 just clean up.\n this._debouncePending.delete(key);\n return;\n }\n // Send the latest pending value, reset dirty flag, restart timer.\n pending.dirty = false;\n const sendData = pending.data;\n const sendFn = isMap\n ? this._centrifuge.mapPublish(this.channel, key, sendData)\n : this._centrifuge.publish(this.channel, sendData);\n sendFn.catch(() => { });\n // Restart timer for next window.\n pending.timer = setTimeout(() => {\n const p = this._debouncePending.get(key);\n if (!p || !p.dirty) {\n this._debouncePending.delete(key);\n return;\n }\n // Recursive \u2014 but in practice debounce windows are short. Nobody awaits\n // this send, so swallow errors like the timer-driven send above does.\n this._debouncePending.delete(key);\n this._debouncedPublish(key, p.data, isMap).catch(() => { });\n }, this._debounceMs);\n }, this._debounceMs);\n this._debouncePending.set(key, entry);\n // Send first publish immediately.\n const sendFn = isMap\n ? this._centrifuge.mapPublish(this.channel, key, data)\n : this._centrifuge.publish(this.channel, data);\n return sendFn;\n }\n _cancelDebounce(key) {\n const existing = this._debouncePending.get(key);\n if (existing) {\n clearTimeout(existing.timer);\n this._debouncePending.delete(key);\n }\n }\n _cancelAllDebounce() {\n for (const [, entry] of this._debouncePending) {\n clearTimeout(entry.timer);\n }\n this._debouncePending.clear();\n }\n /** get online presence for a channel.*/\n presence() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._methodCall();\n return this._centrifuge.presence(this.channel);\n });\n }\n /** presence stats for a channel (num clients and unique users).*/\n presenceStats() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._methodCall();\n return this._centrifuge.presenceStats(this.channel);\n });\n }\n /**\n * Sets server-side tags filter for the subscription.\n * This only applies on the next subscription attempt, not the current one.\n * Cannot be used together with delta option.\n *\n * @param tagsFilter - Filter configuration object or null to remove filter\n * @throws {Error} If both delta and tagsFilter are configured\n *\n * @example\n * ```typescript\n * // Simple equality filter\n * sub.setTagsFilter({\n * key: 'ticker',\n * cmp: 'eq',\n * val: 'BTC'\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Complex filter with logical operators\n * sub.setTagsFilter({\n * op: 'and',\n * nodes: [\n * { key: 'ticker', cmp: 'eq', val: 'BTC' },\n * { key: 'price', cmp: 'gt', val: '50000' }\n * ]\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Filter with IN operator\n * sub.setTagsFilter({\n * key: 'ticker',\n * cmp: 'in',\n * vals: ['BTC', 'ETH', 'SOL']\n * });\n * ```\n */\n setTagsFilter(tagsFilter) {\n if (tagsFilter && this._delta) {\n throw new Error('cannot use delta and tagsFilter together');\n }\n this._tagsFilter = tagsFilter;\n // For map subscriptions, changing the filter invalidates the local state \u2014\n // the next subscribe must go through full STATE phase, not stream recovery.\n if (this._map) {\n this._recover = false;\n this._offset = null;\n this._epoch = null;\n this._mapPositionResets++;\n }\n }\n /** setData allows setting subscription data. This only applied on the next subscription attempt,\n * Note that if getData callback is configured, it will override this value during resubscriptions. */\n setData(data) {\n this._data = data;\n }\n /** deltaStats returns delta compression statistics for this subscription.\n * Only meaningful when delta compression is enabled (delta: 'fossil'). */\n deltaStats() {\n const bytesDecoded = this._deltaBytesDecoded;\n return {\n numPublications: this._deltaNumPubs,\n numFullPayloads: this._deltaNumFull,\n numDeltaPayloads: this._deltaNumDelta,\n bytesReceived: this._deltaBytesReceived,\n bytesDecoded: bytesDecoded,\n compressionRatio: bytesDecoded > 0 ? 1 - this._deltaBytesReceived / bytesDecoded : 0,\n };\n }\n _methodCall() {\n if (this._isSubscribed()) {\n return Promise.resolve();\n }\n if (this._isUnsubscribed()) {\n return Promise.reject({\n code: errorCodes.subscriptionUnsubscribed,\n message: this.state\n });\n }\n return new Promise((resolve, reject) => {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n const timeoutDuration = this._centrifuge._config.timeout;\n const id = this._nextPromiseId();\n const timeout = setTimeout(() => {\n delete this._promises[id];\n reject({ code: errorCodes.timeout, message: 'timeout' });\n }, timeoutDuration);\n this._promises[id] = {\n timeout,\n resolve,\n reject\n };\n });\n }\n _nextPromiseId() {\n return ++this._promiseId;\n }\n _needRecover() {\n return this._recover === true;\n }\n _isUnsubscribed() {\n return this.state === SubscriptionState.Unsubscribed;\n }\n _isSubscribing() {\n return this.state === SubscriptionState.Subscribing;\n }\n _isSubscribed() {\n return this.state === SubscriptionState.Subscribed;\n }\n _setState(newState) {\n if (this.state !== newState) {\n const oldState = this.state;\n this.state = newState;\n this._stateTransitions++;\n this.emit('state', { newState, oldState, channel: this.channel });\n return true;\n }\n return false;\n }\n _usesToken() {\n return this._token !== '' || this._getToken !== null;\n }\n _clearSubscribingState() {\n this._resubscribeAttempts = 0;\n this._clearResubscribeTimeout();\n }\n _clearSubscribedState() {\n this._clearRefreshTimeout();\n // A token refresh in progress belongs to the subscription that ends here.\n this._refreshGeneration++;\n this._cancelAllDebounce();\n this._clearSharedPollSignatureRefresh();\n this._clearSharedPollTrackRetry();\n this._clearSharedPollReplayRetry();\n // Drop the stale refresh target \u2014 the replay after reconnect will set a\n // fresh one from the next batch of track responses.\n this._sharedPollSignatureRefreshTargetMs = null;\n // Reset the in-flight guard so refresh can run again after reconnect.\n this._sharedPollSignatureRefreshInFlight = false;\n this._sharedPollSignatureRefreshAgain = false;\n // NOTE: do NOT clear _sharedPollSignatures or _sharedPollTrackedItems.\n // They persist across reconnects so _sharedPollReplayTrack can re-send\n // tracks using the cached signatures \u2014 avoids hitting getSignature for\n // every client during mass reconnect storms. Cleared only on explicit\n // unsubscribe via _setUnsubscribed.\n }\n /** Called on \"state invalidated\" \u2014 unsubscribe code 2502 for this channel,\n * or connection disconnect code 3014. Clears the token when getToken is set\n * (next subscribe fetches a fresh one) and the fossil delta base (every\n * subscription type uses _prevValueMap; a stale base would corrupt decoding\n * of the first publication after re-subscribe).\n *\n * Without getToken there is no new token to get: the subscription keeps the\n * token it has (or none) and resubscribes with it. The server rejects it if\n * it's no longer valid.\n *\n * Map subscriptions restart from scratch: their recovery position and\n * materialized-state buffers are dropped so the next subscribe does a full\n * STATE re-sync.\n *\n * Stream/shared-poll subscriptions instead reset the recovery position to a\n * sentinel epoch (\"_\") the server can never match (offset 0), leaving\n * _recover untouched: a recoverable subscription then resubscribes with\n * was_recovering=true, recovered=false (so the app reloads via its existing\n * recovery-failure path rather than treating it as a brand-new first\n * subscribe), while a non-recoverable one simply resubscribes. The real\n * epoch/offset are adopted from the subscribe reply. */\n _invalidateState() {\n if (this._getToken !== null) {\n this._token = '';\n }\n this._prevValueMap = new Map();\n if (this._map) {\n this._offset = null;\n this._epoch = null;\n this._recover = false;\n this._mapPositionResets++;\n this._mapStateBuffer = [];\n this._mapStreamBuffer = [];\n this._mapCursor = '';\n this._mapPhase = null;\n }\n else if (this._offset !== null) {\n // Only a position that exists: without one, e.g. before getState was called,\n // the next subscribe must still load the state.\n // \"_\" is a sentinel, not an epoch the server can produce: the recovery of the\n // next subscribe is meant to fail, so the app reloads through its\n // recovery-failure path instead of taking the resubscribe for a first one.\n // It has to be non-empty \u2014 an empty epoch means \"any epoch\" to the server,\n // which would let the recovery succeed from now-invalidated state.\n this._offset = 0;\n this._epoch = '_';\n }\n }\n _setSubscribed(result) {\n if (!this._isSubscribing()) {\n return;\n }\n this._clearSubscribingState();\n if (result.id) {\n this._id = result.id;\n }\n if (result.recoverable) {\n this._recover = true;\n // After a recovery the server replies with the position recovered from: each\n // recovered publication delivered below moves it. A map subscription differs:\n // its live reply carries the top of the stream (see _handleMapLiveResponse).\n this._offset = toOffset(result.offset);\n this._epoch = result.epoch || '';\n }\n else {\n // A channel the server doesn't recover is no channel to recover from. Without\n // this, a subscription given a position by `since` or getState keeps asking to\n // recover on every resubscribe, and the app is told a recovery failed\n // (wasRecovering true, recovered false) every time, though nothing was lost.\n // The flag comes from every reply, so recovery enabled later is picked up.\n this._recover = false;\n }\n if (result.delta) {\n this._delta_negotiated = true;\n }\n else {\n this._delta_negotiated = false;\n }\n if (result.publish_debounce) {\n this._debounceMs = result.publish_debounce;\n }\n if (this._sharedPoll) {\n const newEpoch = result.epoch || '';\n if (this._sharedPollEpoch !== '' && this._sharedPollEpoch !== newEpoch) {\n // Epoch changed (server restart, mode change, node switch) \u2014\n // stored synthetic versions are invalid, reset to 0.\n for (const key of this._sharedPollTrackedItems.keys()) {\n this._sharedPollTrackedItems.set(key, 0);\n }\n }\n this._sharedPollEpoch = newEpoch;\n }\n this._setState(SubscriptionState.Subscribed);\n // A 'state' handler may have unsubscribed already: no subscribed event then.\n if (!this._isSubscribed()) {\n return;\n }\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n const ctx = this._centrifuge._getSubscribeContext(this.channel, result);\n this.emit('subscribed', ctx);\n // A 'subscribed' handler may have unsubscribed, and subscribed again: promises\n // made since then wait for that subscribe.\n if (!this._isSubscribed()) {\n return;\n }\n this._resolvePromises();\n // A 'publication' handler may have unsubscribed: the rest of the recovered\n // publications must not be delivered or move the position.\n const pubs = result.publications || [];\n for (let i = 0; i < pubs.length && this._isSubscribed(); i++) {\n this._handlePublication(pubs[i]);\n }\n if (result.expires === true && this._isSubscribed()) {\n this._refreshTimeout = setTimeout(() => this._refresh(), ttlMilliseconds(result.ttl));\n }\n }\n _setSubscribing(code, reason) {\n return __awaiter(this, void 0, void 0, function* () {\n if (this._isSubscribing()) {\n return;\n }\n if (this._isSubscribed()) {\n this._clearSubscribedState();\n }\n // Channel compaction: the numeric channel id is scoped to the connected\n // session \u2014 drop it when moving back to subscribing (e.g. on reconnect). The\n // next subscribe reply re-establishes it (the server may reuse the same id).\n this._id = 0;\n // Not when a 'state' handler changed the state again: the event would come after\n // that change's own events, out of order.\n const transition = this._stateTransitions + 1;\n if (this._setState(SubscriptionState.Subscribing) && this._stateTransitions === transition) {\n this.emit('subscribing', { channel: this.channel, code: code, reason: reason });\n }\n // @ts-ignore \u2013 for performance reasons only await _unsubPromise for emulution case where it's required.\n if (this._centrifuge._transport && this._centrifuge._transport.emulation()) {\n yield this._unsubPromise;\n // Also for a subscription of this channel removed from the client: the server\n // may otherwise handle this subscribe before its unsubscribe.\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n yield this._centrifuge._removedSubscriptionUnsubscribed(this.channel);\n // And for the shared poll requests of an earlier subscription: the server\n // may otherwise apply them to this one.\n yield this._sharedPollQueue;\n }\n if (!this._isSubscribing()) {\n return;\n }\n this._subscribe();\n });\n }\n _subscribe() {\n this._debug('subscribing on', this.channel);\n if (!this._isTransportOpen()) {\n this._debug('delay subscribe on', this.channel, 'till connected');\n return null;\n }\n if (this._inflight) {\n return null;\n }\n this._inflight = true;\n // Route to map subscribe flow if map mode is enabled\n if (this._map) {\n this._mapSubscribe();\n return null;\n }\n // Stream getState: call app's callback to load state + get position.\n // Only called when we don't have a saved position (first subscribe or after\n // position reset due to failed recovery). On normal reconnects with a valid\n // saved position, we skip getState and let the server try recovery \u2014 getState\n // is only called again if recovery fails (see _setSubscribed).\n // Continuations of this flow (getState, getToken, getData) do nothing once\n // it is outdated: after unsubscribe(), maybe followed by subscribe() and a\n // flow of its own.\n const flow = this._subscribeFlow;\n if (this._getState && this._offset === null) {\n this._loadStreamState(flow);\n return null;\n }\n if (this._canSubscribeWithoutGettingToken()) {\n return this._subscribeWithoutToken(flow);\n }\n this._getSubscriptionToken()\n .then(token => this._handleTokenResponse(token, flow))\n .catch(e => this._handleTokenError(e, flow));\n return null;\n }\n _flowOutdated(flow) {\n return flow !== this._subscribeFlow;\n }\n // Over emulation commands go in separate requests the server may handle in any\n // order: an unsubscribe of a subscribe in flight could overtake it, and the\n // server would keep the subscription. The unsubscribe waits for the\n // subscribe's reply then.\n _mustDeferUnsubscribe() {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n const transport = this._centrifuge._transport;\n return this._subscribeCallFlow === this._subscribeFlow && !!transport && transport.emulation();\n }\n // Called first by the reply handlers of a subscribe command or map page. True\n // when the reply belongs to a subscribe whose unsubscribe was deferred, which is\n // handled here: the unsubscribe goes out if the subscribe succeeded. A timeout\n // leaves unknown whether the server subscribed: the client reconnects.\n _settleSubscribeCall(flow, ok, error) {\n if (this._subscribeCallFlow === flow) {\n this._subscribeCallFlow = null;\n }\n const deferred = this._deferredUnsubscribe;\n if (deferred === null || deferred.flow !== flow) {\n return false;\n }\n this._deferredUnsubscribe = null;\n if (ok) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._unsubscribe(this).then(deferred.resolve);\n return true;\n }\n deferred.resolve();\n if (error && error.code === errorCodes.timeout) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._disconnect(connectingCodes.subscribeTimeout, 'subscribe timeout', true);\n }\n return true;\n }\n _isTransportOpen() {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n return this._centrifuge._transportIsOpen;\n }\n _canSubscribeWithoutGettingToken() {\n return !this._usesToken() || !!this._token;\n }\n _subscribeWithoutToken(flow) {\n if (this._getData) {\n this._getDataAndSubscribe(this._token, flow);\n return null;\n }\n else {\n return this._sendSubscribe(this._token);\n }\n }\n /** Load stream position from app via getState callback, then proceed to subscribe\n * with recovery from that position. Called only when _offset is null:\n * - Initial subscribe (no saved position)\n * - After position reset due to failed recovery (see _setSubscribed)\n *\n * NOT called on normal reconnects where the SDK has a saved position \u2014 in that\n * case recovery is attempted first, and getState is only invoked if recovery fails.\n *\n * The app's getState callback should:\n * 1. Read cf_stream_top_position (or equivalent) FIRST to capture the stream position\n * 2. Then read its own data from the database/API\n * 3. Render/update the UI\n * 4. Return the captured stream position\n *\n * This order is critical: reading position first ensures it's a lower bound.\n * Recovered publications may overlap with data the app already loaded \u2014 this\n * requires idempotent updates or offset-based dedup. */\n _loadStreamState(flow) {\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n this._callAsync(() => this._getState()).then(result => {\n if (this._flowOutdated(flow)) {\n return;\n }\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n // Store stream position from app's source of truth.\n this._offset = toOffset(result.offset);\n this._epoch = result.epoch;\n this._recover = true;\n // Proceed with normal subscribe flow (token \u2192 sendSubscribe).\n if (this._canSubscribeWithoutGettingToken()) {\n this._subscribeWithoutToken(flow);\n }\n else {\n this._getSubscriptionToken()\n .then(token => this._handleTokenResponse(token, flow))\n .catch(e => this._handleTokenError(e, flow));\n }\n }).catch(e => {\n if (this._flowOutdated(flow)) {\n return;\n }\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n // Match map subscription error handling: route through _subscribeError\n // which emits error event and schedules resubscribe for temporary errors\n // (code < 100), matching the map's _handleMapSubscribeError pattern.\n this._inflight = false;\n this._subscribeError({\n code: errorCodes.subscriptionGetState,\n message: (e === null || e === void 0 ? void 0 : e.toString()) || 'getState failed',\n temporary: true,\n });\n });\n }\n _getDataAndSubscribe(token, flow) {\n if (!this._getData) {\n this._inflight = false;\n return;\n }\n this._callAsync(() => this._getData({ channel: this.channel }))\n .then(data => {\n if (this._flowOutdated(flow)) {\n return;\n }\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n this._data = data;\n this._sendSubscribe(token);\n })\n .catch(e => this._handleGetDataError(e, flow));\n }\n _handleGetDataError(error, flow) {\n if (this._flowOutdated(flow)) {\n return;\n }\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n if (error instanceof UnauthorizedError) {\n this._inflight = false;\n this._failUnauthorized();\n return;\n }\n this._emitError({\n type: 'subscribeData',\n channel: this.channel,\n error: {\n code: errorCodes.badConfiguration,\n message: (error === null || error === void 0 ? void 0 : error.toString()) || ''\n }\n }, () => {\n this._inflight = false;\n this._scheduleResubscribe();\n });\n }\n _handleTokenResponse(token, flow) {\n if (this._flowOutdated(flow)) {\n return;\n }\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n if (!token) {\n this._inflight = false;\n this._failUnauthorized();\n return;\n }\n this._token = token;\n if (this._getData) {\n this._getDataAndSubscribe(token, flow);\n }\n else {\n this._sendSubscribe(token);\n }\n }\n _handleTokenError(error, flow) {\n if (this._flowOutdated(flow)) {\n return;\n }\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n if (error instanceof UnauthorizedError) {\n this._inflight = false;\n this._failUnauthorized();\n return;\n }\n this._emitError({\n type: 'subscribeToken',\n channel: this.channel,\n error: {\n code: errorCodes.subscriptionSubscribeToken,\n message: (error === null || error === void 0 ? void 0 : error.toString()) || ''\n }\n }, () => {\n this._inflight = false;\n this._scheduleResubscribe();\n });\n }\n _sendSubscribe(token) {\n if (!this._isTransportOpen()) {\n this._inflight = false;\n return null;\n }\n const cmd = this._buildSubscribeCommand(token);\n const flow = this._subscribeFlow;\n this._subscribeCallFlow = flow;\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n // An exception while handling the reply stops the client (see _dispatchFailed).\n // next() is still called, so replies of a later connection aren't blocked.\n this._centrifuge._call(cmd).then(resolveCtx => {\n try {\n if (this._settleSubscribeCall(flow, true)) {\n return;\n }\n if (flow !== this._subscribeFlow) {\n // The app unsubscribed meanwhile, maybe to subscribe again.\n return;\n }\n this._inflight = false;\n this._handleSubscribeResponse(resolveCtx.reply.subscribe);\n }\n catch (err) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._dispatchFailed(err);\n }\n finally {\n if (resolveCtx.next) {\n resolveCtx.next();\n }\n }\n }, rejectCtx => {\n try {\n if (this._settleSubscribeCall(flow, false, rejectCtx.error)) {\n return;\n }\n if (flow !== this._subscribeFlow) {\n return;\n }\n this._inflight = false;\n this._handleSubscribeError(rejectCtx.error);\n }\n catch (err) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._rejectionFailed(err, rejectCtx);\n }\n finally {\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n }\n });\n return cmd;\n }\n _buildSubscribeCommand(token) {\n const req = { channel: this.channel };\n if (token)\n req.token = token;\n if (this._data)\n req.data = this._data;\n // Shared poll: simple subscribe with type=4, no positioning/recovery fields.\n if (this._sharedPoll) {\n req.type = 4;\n if (this._delta)\n req.delta = this._delta;\n return { subscribe: req };\n }\n if (this._positioned)\n req.positioned = true;\n if (this._recoverable)\n req.recoverable = true;\n if (this._joinLeave)\n req.join_leave = true;\n req.flag = subscriptionFlags.channelCompaction;\n if (this._getState) {\n req.flag |= subscriptionFlags.rejectUnrecovered;\n }\n if (this._needRecover()) {\n req.recover = true;\n const offset = this._getOffset();\n if (offset)\n req.offset = offset;\n const epoch = this._getEpoch();\n if (epoch)\n req.epoch = epoch;\n }\n if (this._delta)\n req.delta = this._delta;\n if (this._tagsFilter)\n req.tf = this._tagsFilter;\n return { subscribe: req };\n }\n _debug(...args) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._debug(...args);\n }\n /** @internal An exception escaping a handler stops the client: see Centrifuge._handlerFailed. */\n emit(event, ...args) {\n try {\n return EventEmitter.prototype.emit.call(this, event, ...args);\n }\n catch (e) {\n this._centrifuge._handlerFailed(e);\n return true;\n }\n }\n _handleSubscribeError(error) {\n if (!this._isSubscribing()) {\n return;\n }\n if (error.code === errorCodes.connectionClosed) {\n // The transport closed with the subscribe in flight: no error of the\n // subscribe, the next connection subscribes again without a backoff.\n return;\n }\n if (error.code === errorCodes.timeout) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._disconnect(connectingCodes.subscribeTimeout, 'subscribe timeout', true);\n return;\n }\n if (error.code === 112 && this._getState) {\n // Unrecoverable position with getState: reset position so next\n // subscribe attempt calls getState() to reload app state from scratch.\n this._offset = null;\n this._epoch = null;\n this._recover = false;\n this._prevValueMap = new Map();\n this._scheduleResubscribe();\n return;\n }\n this._subscribeError(error);\n }\n _handleSubscribeResponse(result) {\n if (!this._isSubscribing()) {\n return;\n }\n this._sharedPollReplayPending = this._sharedPoll;\n try {\n this._setSubscribed(result);\n }\n finally {\n this._sharedPollReplayPending = false;\n }\n // After shared poll subscribe, replay tracked items if any.\n if (this._sharedPoll) {\n this._sharedPollReplayTrack();\n }\n }\n _setUnsubscribed(code, reason, sendUnsubscribe) {\n if (this._isUnsubscribed()) {\n return Promise.resolve();\n }\n // Set before the unsubscribed event: a subscribe() from its handler waits for\n // the unsubscribe reply over emulation (see _setSubscribing).\n let promise = Promise.resolve();\n if (this._isSubscribed()) {\n if (sendUnsubscribe) {\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n promise = this._unsubPromise = this._centrifuge._unsubscribe(this);\n }\n this._clearSubscribedState();\n }\n else if (this._isSubscribing()) {\n if (this._inflight && sendUnsubscribe) {\n if (this._mustDeferUnsubscribe()) {\n const flow = this._subscribeFlow;\n promise = this._unsubPromise = new Promise(resolve => {\n this._deferredUnsubscribe = { flow, resolve };\n });\n }\n else {\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n promise = this._unsubPromise = this._centrifuge._unsubscribe(this);\n }\n }\n this._clearSubscribingState();\n }\n this._inflight = false;\n // Replies and continuations of a subscribe in progress must not complete a later one.\n this._subscribeFlow++;\n // Channel compaction: the numeric channel id is scoped to the active\n // subscription. Drop it so a push for the old id (e.g. one in flight when we\n // unsubscribe) is no longer routed to this subscription.\n this._id = 0;\n this._sharedPollEpoch = '';\n // Explicit unsubscribe \u2014 drop all shared-poll state so a subsequent\n // subscribe starts cold. Reconnects use _clearSubscribedState (above)\n // which preserves the signature library and tracked items.\n this._sharedPollSignatures = [];\n this._sharedPollTrackedItems.clear();\n this._sharedPollSignatureRefreshInFlight = false;\n this._sharedPollSignatureRefreshAgain = false;\n this._sharedPollSignatureRefreshTargetMs = null;\n this._cancelAllDebounce();\n // Waiters fail before the events: a handler subscribing again makes waiters of\n // the new subscribe, which must not fail with this one.\n this._rejectPromises({ code: errorCodes.subscriptionUnsubscribed, message: SubscriptionState.Unsubscribed });\n // Not when a 'state' handler changed the state again (see _setSubscribing).\n const transition = this._stateTransitions + 1;\n if (this._setState(SubscriptionState.Unsubscribed) && this._stateTransitions === transition) {\n this.emit('unsubscribed', { channel: this.channel, code: code, reason: reason });\n }\n return promise;\n }\n _handlePublication(pub) {\n if (this._sharedPoll && pub.key && !pub.removed && hasOffset(pub.version)) {\n // Versions dedupe: one not newer than the version held for the key is a\n // duplicate (e.g. the reply of a second track request of the key) or\n // older. Dropped before delta decoding, which would move the key's base.\n const known = this._sharedPollTrackedItems.get(pub.key);\n if (known !== undefined && known > 0 && toOffset(pub.version) <= known) {\n return;\n }\n }\n if (this._delta && this._delta_negotiated) {\n // For map and shared poll subs, delta is per-key.\n // For non-map subs, delta is a single chain regardless of pub.key.\n const deltaKey = (this._map || this._sharedPoll) ? (pub.key || '') : '';\n if (pub.removed) {\n // A removal carries no payload to decode, and ends the key's delta chain.\n this._prevValueMap.delete(deltaKey);\n }\n else {\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n const { newData, newPrevValue, isDelta, wireBytes, fullBytes } = this._centrifuge._codec.applyDeltaIfNeeded(pub, this._prevValueMap.get(deltaKey));\n pub.data = newData;\n this._deltaNumPubs++;\n this._deltaBytesReceived += wireBytes;\n this._deltaBytesDecoded += fullBytes;\n if (isDelta) {\n this._deltaNumDelta++;\n }\n else {\n this._deltaNumFull++;\n }\n this._prevValueMap.set(deltaKey, newPrevValue);\n }\n }\n let ctx;\n if (this._sharedPoll) {\n // Ignore publications for keys the user is no longer tracking.\n // Common race: SDK replays a cached signature batch on reconnect with\n // some keys the user untracked locally; the chained untrack hasn't\n // reached the server yet, so the server may push updates for those\n // keys in the meantime. Without this guard those updates would\n // re-insert the keys into _sharedPollTrackedItems and emit 'update'\n // events the user already opted out of.\n if (pub.key && !this._sharedPollTrackedItems.has(pub.key)) {\n return;\n }\n // The tracked version is the key's position: it moves with the position below.\n ctx = this._getSharedPollUpdateContext(pub);\n }\n else if (this._map) {\n ctx = this._getMapUpdateContext(pub);\n }\n else {\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n ctx = this._centrifuge._getPublicationContext(this.channel, pub);\n }\n // The position moves after the app has the publication, so the position it can\n // observe never runs ahead of what it received: a handler that throws (which\n // stops the client), or that unsubscribes before the last event, doesn't skip it. A subscribe command built\n // while a handler runs still recovers after this publication, because _getOffset\n // prefers the pending offset \u2014 a resubscribe from the handler gets no duplicate.\n if (this._map || this._sharedPoll) {\n this.emit('publication', ctx);\n if (!this._isSubscribed()) {\n return;\n }\n this._setPublicationPosition(pub);\n this.emit('update', ctx);\n }\n else {\n this._pendingOffset = hasOffset(pub.offset) ? toOffset(pub.offset) : null;\n const failures = this._centrifuge._handlerFailures;\n try {\n this.emit('publication', ctx);\n }\n finally {\n this._pendingOffset = null;\n }\n // A publication whose handler threw isn't delivered: the position stays before\n // it, so the next recovery delivers it again.\n if (this._centrifuge._handlerFailures !== failures) {\n return;\n }\n this._setPublicationPosition(pub);\n }\n }\n _setPublicationPosition(pub) {\n // Shared poll: the version of a key still tracked, which a replay of the tracked\n // keys asks from. A publication handler may have untracked it.\n if (this._sharedPoll && pub.key && this._sharedPollTrackedItems.has(pub.key)) {\n if (pub.removed) {\n this._sharedPollTrackedItems.delete(pub.key);\n }\n else if (pub.version) {\n this._sharedPollTrackedItems.set(pub.key, toOffset(pub.version));\n }\n }\n if (hasOffset(pub.offset)) {\n this._offset = toOffset(pub.offset);\n }\n if (pub.epoch) {\n this._epoch = pub.epoch;\n }\n }\n /** Seed per-key delta tracking from state/stream entries.\n * Handles JSON-escaped data (server-side delta escaping) and protobuf data.\n * Decodes escaped data back to original format for user consumption.\n * Values are escaped only when delta is negotiated: otherwise they come as\n * they are, and a string value must not be parsed. */\n _seedDeltaTracking(pub, deltaNegotiated) {\n if (!this._delta || !pub.key)\n return;\n if (pub.removed) {\n // A removal carries no payload to decode, and ends the key's delta chain.\n this._prevValueMap.delete(pub.key);\n return;\n }\n if (!deltaNegotiated) {\n this._prevValueMap.set(pub.key, pub.data);\n return;\n }\n if (typeof pub.data === 'string') {\n // JSON transport with server-side delta escaping.\n // Store raw bytes for delta, decode for user.\n const rawBytes = pub.data;\n const encoded = new TextEncoder().encode(rawBytes);\n this._prevValueMap.set(pub.key, encoded);\n // Count as full payload in delta stats. Use the UTF-8 byte length, not\n // rawBytes.length (JS string length counts UTF-16 code units, which\n // undercounts any non-ASCII content).\n const byteLen = encoded.length;\n this._deltaNumPubs++;\n this._deltaNumFull++;\n this._deltaBytesReceived += byteLen;\n this._deltaBytesDecoded += byteLen;\n pub.data = JSON.parse(rawBytes);\n }\n else if (pub.data instanceof Uint8Array) {\n // Protobuf transport.\n this._prevValueMap.set(pub.key, pub.data);\n // Count as full payload in delta stats.\n const byteLen = pub.data.length;\n this._deltaNumPubs++;\n this._deltaNumFull++;\n this._deltaBytesReceived += byteLen;\n this._deltaBytesDecoded += byteLen;\n }\n }\n _handleJoin(join) {\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n const info = this._centrifuge._getJoinLeaveContext(join.info);\n this.emit('join', { channel: this.channel, info: info });\n }\n _handleLeave(leave) {\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n const info = this._centrifuge._getJoinLeaveContext(leave.info);\n this.emit('leave', { channel: this.channel, info: info });\n }\n _resolvePromises() {\n for (const id in this._promises) {\n if (!this._promises.hasOwnProperty(id)) {\n continue;\n }\n if (this._promises[id].timeout) {\n clearTimeout(this._promises[id].timeout);\n }\n this._promises[id].resolve();\n delete this._promises[id];\n }\n }\n _rejectPromises(err) {\n for (const id in this._promises) {\n if (!this._promises.hasOwnProperty(id)) {\n continue;\n }\n if (this._promises[id].timeout) {\n clearTimeout(this._promises[id].timeout);\n }\n this._promises[id].reject(err);\n delete this._promises[id];\n }\n }\n _scheduleResubscribe() {\n if (!this._isSubscribing()) {\n this._debug('not in subscribing state, skip resubscribe scheduling', this.channel);\n return;\n }\n const self = this;\n const delay = this._getResubscribeDelay();\n // One timer at a time: a timer left armed would fire later, out of the\n // backoff, and send a subscribe the emulation waits don't cover.\n this._clearResubscribeTimeout();\n this._resubscribeTimeout = setTimeout(function () {\n self._resubscribeTimeout = null;\n if (self._isSubscribing()) {\n self._subscribe();\n }\n }, delay);\n this._debug('resubscribe scheduled after ' + delay, this.channel);\n }\n // Emits an error event, then runs the continuation: not when a handler unsubscribed,\n // maybe to subscribe again, whose new subscribe the continuation must not touch.\n _emitError(ctx, continuation) {\n const flow = this._subscribeFlow;\n try {\n this.emit('error', ctx);\n }\n finally {\n if (flow === this._subscribeFlow) {\n continuation();\n }\n }\n }\n _subscribeError(err) {\n if (!this._isSubscribing()) {\n return;\n }\n if (err.code === 109 && this._getToken === null) {\n // The token expired and there is no getToken to get another one: like a\n // connection, unauthorized (instead of subscribing again without a token).\n try {\n this.emit('error', {\n type: 'configuration',\n channel: this.channel,\n error: {\n code: errorCodes.badConfiguration,\n message: 'subscription token expired but no getToken function set'\n }\n });\n }\n catch (e) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._reportDispatchError(e);\n }\n this._setUnsubscribed(unsubscribedCodes.unauthorized, 'unauthorized', false);\n return;\n }\n if (err.code < 100 || err.code === 109 || err.temporary === true) {\n if (err.code === 109) { // Token expired error.\n this._token = '';\n }\n const errContext = {\n channel: this.channel,\n type: 'subscribe',\n error: err\n };\n if (this._centrifuge.state === State.Connected) {\n this._emitError(errContext, () => this._scheduleResubscribe());\n }\n else {\n this._scheduleResubscribe();\n }\n }\n else {\n this._setUnsubscribed(err.code, err.message, false);\n }\n }\n _getResubscribeDelay() {\n const delay = backoff(this._resubscribeAttempts, this._minResubscribeDelay, this._maxResubscribeDelay);\n this._resubscribeAttempts++;\n return delay;\n }\n _setOptions(options) {\n if (!options) {\n return;\n }\n if (options.since) {\n this._offset = toOffset(options.since.offset);\n this._epoch = options.since.epoch || '';\n this._recover = true;\n }\n if (options.data) {\n this._data = options.data;\n }\n if (options.getData) {\n this._getData = options.getData;\n }\n if (options.minResubscribeDelay !== undefined) {\n this._minResubscribeDelay = options.minResubscribeDelay;\n }\n if (options.maxResubscribeDelay !== undefined) {\n this._maxResubscribeDelay = options.maxResubscribeDelay;\n }\n if (options.token) {\n this._token = options.token;\n }\n if (options.getToken) {\n this._getToken = options.getToken;\n }\n if (options.positioned === true) {\n this._positioned = true;\n }\n if (options.recoverable === true) {\n this._recoverable = true;\n }\n if (options.joinLeave === true) {\n this._joinLeave = true;\n }\n if (options.delta) {\n if (options.delta !== 'fossil') {\n throw new Error('unsupported delta format');\n }\n this._delta = options.delta;\n }\n if (options.tagsFilter) {\n this._tagsFilter = options.tagsFilter;\n }\n if (this._tagsFilter && this._delta) {\n throw new Error('cannot use delta and tagsFilter together');\n }\n // Stream getState option\n if (options.getState) {\n this._getState = options.getState;\n this._recover = true; // getState implies recovery\n }\n // Map subscription options\n if (options.map === true) {\n this._map = true;\n }\n if (options.mapPageSize !== undefined) {\n this._mapPageSize = options.mapPageSize;\n }\n // Presence type for presence subscriptions (2=clients, 3=users)\n if (options.mapPresenceType !== undefined) {\n this._mapPresenceType = options.mapPresenceType;\n this._map = true; // Presence subscriptions are always map subscriptions\n }\n if (options.mapUnrecoverableStrategy) {\n this._mapUnrecoverableStrategy = options.mapUnrecoverableStrategy;\n }\n // Shared poll subscription options\n if (options.sharedPoll === true) {\n this._sharedPoll = true;\n }\n if (options.sharedPollGetSignature) {\n this._sharedPollGetSignature = options.sharedPollGetSignature;\n }\n }\n _getOffset() {\n // A publication being dispatched counts as delivered: a subscribe command built\n // from its handler recovers after it, while the stored position still holds the\n // previous one until that handler returned (see _handlePublication).\n if (this._pendingOffset !== null) {\n return this._pendingOffset;\n }\n const offset = this._offset;\n if (offset !== null) {\n return offset;\n }\n return 0;\n }\n _getEpoch() {\n const epoch = this._epoch;\n if (epoch !== null) {\n return epoch;\n }\n return '';\n }\n _clearRefreshTimeout() {\n if (this._refreshTimeout !== null) {\n clearTimeout(this._refreshTimeout);\n this._refreshTimeout = null;\n }\n }\n _clearResubscribeTimeout() {\n if (this._resubscribeTimeout !== null) {\n clearTimeout(this._resubscribeTimeout);\n this._resubscribeTimeout = null;\n }\n }\n _getSubscriptionToken() {\n this._debug('get subscription token for channel', this.channel);\n const ctx = {\n channel: this.channel\n };\n const getToken = this._getToken;\n if (getToken === null) {\n try {\n this.emit('error', {\n type: 'configuration',\n channel: this.channel,\n error: {\n code: errorCodes.badConfiguration,\n message: 'provide a function to get channel subscription token'\n }\n });\n }\n catch (e) {\n // The subscribe must fail as unauthorized all the same, not stay in progress.\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._reportDispatchError(e);\n }\n return Promise.reject(new UnauthorizedError(''));\n }\n return this._callAsync(() => getToken(ctx));\n }\n _refresh() {\n this._clearRefreshTimeout();\n const self = this;\n // The subscription may end while the token is loading, and a new one start, e.g.\n // after unsubscribe() or a reconnect: this refresh is outdated then.\n const generation = this._refreshGeneration;\n this._getSubscriptionToken().then(function (token) {\n if (generation !== self._refreshGeneration || !self._isSubscribed()) {\n return;\n }\n if (!token) {\n self._failUnauthorized();\n return;\n }\n self._token = token;\n const req = {\n channel: self.channel,\n token: token\n };\n const msg = {\n 'sub_refresh': req\n };\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n self._centrifuge._call(msg).then(resolveCtx => {\n try {\n self._refreshResponse(resolveCtx.reply.sub_refresh);\n }\n catch (err) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n self._centrifuge._dispatchFailed(err);\n }\n finally {\n if (resolveCtx.next) {\n resolveCtx.next();\n }\n }\n }, rejectCtx => {\n try {\n self._refreshError(rejectCtx.error);\n }\n catch (err) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n self._centrifuge._rejectionFailed(err, rejectCtx);\n }\n finally {\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n }\n });\n }).catch(function (e) {\n if (generation !== self._refreshGeneration || !self._isSubscribed()) {\n return;\n }\n if (e instanceof UnauthorizedError) {\n self._failUnauthorized();\n return;\n }\n self._emitError({\n type: 'refreshToken',\n channel: self.channel,\n error: {\n code: errorCodes.subscriptionRefreshToken,\n message: e !== undefined ? e.toString() : ''\n }\n }, () => {\n // A handler may have ended the subscription, e.g. by disconnecting the client.\n if (generation !== self._refreshGeneration || !self._isSubscribed()) {\n return;\n }\n self._refreshTimeout = setTimeout(() => self._refresh(), self._getRefreshRetryDelay());\n });\n });\n }\n _refreshResponse(result) {\n if (!this._isSubscribed()) {\n return;\n }\n this._debug('subscription token refreshed, channel', this.channel);\n this._clearRefreshTimeout();\n if (result.expires === true) {\n this._refreshTimeout = setTimeout(() => this._refresh(), ttlMilliseconds(result.ttl));\n }\n }\n _refreshError(err) {\n if (!this._isSubscribed()) {\n return;\n }\n if (err.code < 100 || err.temporary === true) {\n this._emitError({\n type: 'refresh',\n channel: this.channel,\n error: err\n }, () => {\n // A handler may have ended the subscription, e.g. by disconnecting the client.\n if (!this._isSubscribed()) {\n return;\n }\n this._refreshTimeout = setTimeout(() => this._refresh(), this._getRefreshRetryDelay());\n });\n }\n else {\n this._setUnsubscribed(err.code, err.message, true);\n }\n }\n _getRefreshRetryDelay() {\n return backoff(0, 10000, 20000);\n }\n // Calls an app callback expected to return a promise: one throwing instead of\n // returning a rejected promise fails the same way, not by throwing out of the\n // subscribe or refresh in progress.\n _callAsync(callback) {\n try {\n return Promise.resolve(callback());\n }\n catch (e) {\n return Promise.reject(e);\n }\n }\n _failUnauthorized() {\n this._setUnsubscribed(unsubscribedCodes.unauthorized, 'unauthorized', true);\n }\n // ============ Shared Poll Internal Helpers ============\n // Send ONE or MORE signature batches in a single sub_refresh frame.\n // Splits across frames when the estimated payload exceeds the wire frame\n // budget \u2014 keeps each request well under the 64k Centrifugo frame limit.\n _sendTrackRequest(batches, untrackKeys) {\n if (batches.length === 0)\n return Promise.resolve();\n // Estimate ~80 bytes per signature + ~40 bytes per item (key + varint + framing).\n // ~60KB budget leaves headroom for envelope, channel name, and reply.\n const maxBytes = 60000;\n const frames = [];\n let current = [];\n // Reserve space for inline untrack keys in the first frame.\n let currentBytes = 100; // envelope baseline\n if (untrackKeys && untrackKeys.length > 0) {\n for (const key of untrackKeys)\n currentBytes += key.length + 4;\n }\n for (const b of batches) {\n let cost = 100;\n for (const it of b.items)\n cost += it.key.length + 16;\n if (current.length > 0 && currentBytes + cost > maxBytes) {\n frames.push(current);\n current = [];\n currentBytes = 100;\n }\n current.push(b);\n currentBytes += cost;\n }\n if (current.length > 0)\n frames.push(current);\n // A failing frame stops the frames after it: a permanent error untracks the\n // keys of all of them.\n const keysFrom = (idx) => frames.slice(idx).flatMap(f => f.flatMap(b => b.items.map(i => i.key)));\n const send = (frame, idx, frameUntrackKeys) => new Promise((resolve, reject) => {\n const req = {\n channel: this.channel,\n type: 1,\n track: frame.map(b => ({\n signature: b.signature,\n items: b.items.map(i => i.version > 0 ? i : { key: i.key }),\n })),\n };\n if (frameUntrackKeys && frameUntrackKeys.length > 0) {\n req.untrack = frameUntrackKeys;\n }\n const msg = { 'sub_refresh': req };\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._call(msg).then(resolveCtx => {\n try {\n this._handleTrackResponse(resolveCtx.reply.sub_refresh, frame.flatMap(b => b.items.map(i => i.key)), frameUntrackKeys);\n }\n catch (err) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._dispatchFailed(err);\n }\n finally {\n if (resolveCtx.next)\n resolveCtx.next();\n }\n resolve();\n }, rejectCtx => {\n if (rejectCtx.next)\n rejectCtx.next();\n this._sharedPollRequestFailed(rejectCtx.error);\n // With the keys of the request, which a permanent error untracks.\n reject({ error: rejectCtx.error, keys: keysFrom(idx) });\n });\n });\n // Sequential dispatch: a frame failure stops further frames so the SDK\n // doesn't end up with some frames committed server-side and others not\n // \u2014 which would otherwise lead to retry-with-duplicate-publications.\n // Inline untrack keys go only in the first frame.\n return this._sharedPollSerial(() => frames.reduce((chain, frame, idx) => chain.then(() => send(frame, idx, idx === 0 ? untrackKeys : undefined)), Promise.resolve()));\n }\n _isEmulation() {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n const transport = this._centrifuge._transport;\n return !!transport && transport.emulation();\n }\n // Over emulation each request is a separate HTTP request the server may handle\n // in any order: a track and an untrack of a key could overtake each other. The\n // channel's requests go one at a time then, in the order made; one made for a\n // subscription that has ended by its turn is dropped.\n _sharedPollSerial(send) {\n if (!this._isEmulation()) {\n return send();\n }\n const generation = this._refreshGeneration;\n const run = this._sharedPollQueue.then(() => {\n if (generation !== this._refreshGeneration || !this._isSubscribed()) {\n return;\n }\n return send();\n });\n this._sharedPollQueue = run.then(() => undefined, () => undefined);\n return run;\n }\n // A timed-out request over emulation may still reach the server after later\n // ones: whether the keys are tracked is unknown, the client reconnects.\n _sharedPollRequestFailed(error) {\n if (error && error.code === errorCodes.timeout && this._isEmulation()) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._disconnect(connectingCodes.subscribeTimeout, 'shared poll request timeout', true);\n }\n }\n _sendUntrackRequest(keys) {\n return this._sharedPollSerial(() => new Promise((resolve, reject) => {\n const req = {\n channel: this.channel,\n type: 2,\n untrack: keys,\n };\n const msg = { 'sub_refresh': req };\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._call(msg).then(resolveCtx => {\n if (resolveCtx.next) {\n resolveCtx.next();\n }\n resolve();\n }, rejectCtx => {\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n this._sharedPollRequestFailed(rejectCtx.error);\n reject(rejectCtx.error);\n });\n }));\n }\n _handleTrackResponse(result, keys, untrackKeys) {\n // The reply to a track sent before unsubscribe() belongs to that subscription:\n // its items and versions must not reach the next one.\n if (!this._isSubscribed()) {\n return;\n }\n // Track succeeded \u2014 reset retry state.\n this._clearSharedPollTrackRetry();\n // Process cached items from server (publications across all batches in the request).\n if (result && result.items && result.items.length > 0) {\n for (const pub of result.items) {\n // A handler may have unsubscribed or disconnected: the rest must neither be\n // delivered nor move the tracked versions.\n if (!this._isSubscribed()) {\n return;\n }\n this._handlePublication(pub);\n }\n }\n if (!this._isSubscribed()) {\n return;\n }\n // Keys the request tracked at the server which the client no longer tracks,\n // e.g. removed by the server while the request was in flight: the server\n // would keep tracking them, untracked there too.\n const untracked = new Set(untrackKeys || []);\n const stale = keys.filter(key => !untracked.has(key) && !this._sharedPollTrackedItems.has(key));\n if (stale.length > 0) {\n this._sendUntrackRequest(stale).catch(err => {\n this.emit('error', { type: 'untrack', channel: this.channel, error: err });\n });\n }\n // Server returns MIN ttl across all batches in this request. Keep the\n // EARLIEST deadline received across all responses as the refresh target.\n // Refreshing too early is harmless (cheap getSignature call); refreshing\n // too late risks 109 errors mid-replay, so we err earlier.\n if (result && result.expires === true) {\n // Without a positive ttl a signature has expired already, still accepted within\n // the server's grace period: refresh it soon, or the server drops the keys\n // silently. Not at once, in case the backend keeps returning expired ones.\n const targetMs = Date.now() + (result.ttl > 0 ? result.ttl * 1000 : 1000);\n this._maybeScheduleSharedPollSignatureRefresh(targetMs);\n }\n }\n // Reschedule the consolidating refresh timer if `targetMs` is earlier than\n // the currently scheduled target. No-op when a sooner refresh is already\n // pending. Pass null to clear and reset (e.g. after consolidation succeeded).\n _maybeScheduleSharedPollSignatureRefresh(targetMs) {\n if (targetMs === null) {\n this._sharedPollSignatureRefreshTargetMs = null;\n this._clearSharedPollSignatureRefresh();\n return;\n }\n if (!this._isSubscribed())\n return;\n if (this._sharedPollSignatureRefreshTargetMs !== null &&\n targetMs >= this._sharedPollSignatureRefreshTargetMs) {\n return; // existing timer fires sooner\n }\n this._sharedPollSignatureRefreshTargetMs = targetMs;\n this._clearSharedPollSignatureRefresh();\n this._sharedPollSignatureRefreshTimeout = setTimeout(() => this._sharedPollRefreshSignature(), Math.max(0, targetMs - Date.now()));\n }\n _clearSharedPollSignatureRefresh() {\n if (this._sharedPollSignatureRefreshTimeout !== null) {\n clearTimeout(this._sharedPollSignatureRefreshTimeout);\n this._sharedPollSignatureRefreshTimeout = null;\n }\n this._sharedPollSignatureRefreshAttempts = 0;\n // Do not clear the target here \u2014 _maybeScheduleSharedPollSignatureRefresh\n // owns target lifecycle. This helper only stops the timer and resets\n // backoff so the next reschedule starts fresh.\n }\n _clearSharedPollTrackRetry() {\n if (this._sharedPollTrackRetryTimeout !== null) {\n clearTimeout(this._sharedPollTrackRetryTimeout);\n this._sharedPollTrackRetryTimeout = null;\n }\n this._sharedPollTrackRetryAttempts = 0;\n }\n _scheduleSharedPollReplayRetry() {\n if (this._sharedPollReplayRetryTimeout !== null) {\n clearTimeout(this._sharedPollReplayRetryTimeout);\n }\n this._sharedPollReplayRetryTimeout = setTimeout(() => this._sharedPollReplayTrack(), backoff(this._sharedPollReplayRetryAttempts++, 5000, 30000));\n }\n _clearSharedPollReplayRetry() {\n if (this._sharedPollReplayRetryTimeout !== null) {\n clearTimeout(this._sharedPollReplayRetryTimeout);\n this._sharedPollReplayRetryTimeout = null;\n }\n this._sharedPollReplayRetryAttempts = 0;\n }\n // Adds a signature to the library, dropping the entries whose keys it covers\n // entirely: they may have expired, and a replay sends every entry in one request,\n // which a single expired signature fails as a whole.\n _addSharedPollSignature(keys, signature) {\n const covered = new Set(keys);\n this._sharedPollSignatures = this._sharedPollSignatures.filter(entry => !entry.keys.every(key => covered.has(key)));\n this._sharedPollSignatures.push({ keys, signature });\n }\n _handleTrackError(err, keys) {\n if (!this._isSubscribed()) {\n return;\n }\n this._emitError({\n type: 'track',\n channel: this.channel,\n error: err,\n }, () => {\n // A handler may have ended the subscription, e.g. by disconnecting the client.\n if (!this._isSubscribed()) {\n return;\n }\n // Error 109 (token expired) on a track command means the signature has\n // expired past the server's grace period. Trigger a refresh \u2014 getSignature\n // will issue a fresh consolidated signature that replaces stale ones.\n // The in-flight guard inside _sharedPollRefreshSignature prevents\n // duplicate refresh calls when multiple track retries all hit 109.\n if (err.code === 109) {\n this._sharedPollRefreshSignature();\n return;\n }\n if (err.code < 100 || err.temporary === true) {\n // Temporary error \u2014 retry full track replay with backoff.\n this._sharedPollTrackRetryTimeout = setTimeout(() => this._sharedPollReplayTrack(), backoff(this._sharedPollTrackRetryAttempts++, 1000, 15000));\n return;\n }\n // A permanent error, e.g. limit exceeded or permission denied: retrying\n // fails the same way. The keys are untracked like revoked ones, also at\n // the server: an earlier request (e.g. one that timed out) may have\n // tracked them.\n this._untrackFailedKeys(keys);\n });\n }\n _untrackFailedKeys(keys) {\n const failed = keys.filter(key => this._sharedPollTrackedItems.has(key));\n if (failed.length === 0) {\n return;\n }\n for (const key of failed) {\n this._sharedPollTrackedItems.delete(key);\n }\n this._sharedPollSignatures = this._sharedPollSignatures.filter(entry => entry.keys.some(k => this._sharedPollTrackedItems.has(k)));\n this._sendUntrackRequest(failed).catch(err => {\n this.emit('error', { type: 'untrack', channel: this.channel, error: err });\n });\n for (const key of failed) {\n // A handler of an earlier removal may have ended the subscription.\n if (!this._isSubscribed()) {\n return;\n }\n this.emit('update', {\n channel: this.channel,\n key: key,\n data: null,\n removed: true,\n });\n }\n }\n // _sharedPollRefreshSignature obtains a fresh consolidated signature\n // covering all currently tracked keys, then replaces the library with the\n // single new entry. Triggered by the TTL timer (server's `expires/ttl`\n // response) and by 109 errors on track commands. The in-flight guard\n // collapses concurrent refresh attempts into one.\n _sharedPollRefreshSignature() {\n this._clearSharedPollSignatureRefresh();\n if (!this._isSubscribed())\n return;\n if (!this._sharedPollGetSignature)\n return;\n if (this._sharedPollTrackedItems.size === 0)\n return;\n if (this._sharedPollSignatureRefreshInFlight) {\n for (const key of this._sharedPollTrackedItems.keys()) {\n if (!this._sharedPollSignatureRefreshKeys.has(key)) {\n this._sharedPollSignatureRefreshAgain = true;\n break;\n }\n }\n return;\n }\n // Reset the global refresh target \u2014 the timer that pointed at this\n // moment has already fired, and the in-flight refresh will publish a\n // fresh deadline via the consolidated track response. Resetting here\n // (not after consolidation success) lets any concurrent track() call\n // that lands during getSignature still set a tighter target if its\n // signature is shorter-lived than the consolidated one.\n this._sharedPollSignatureRefreshTargetMs = null;\n this._sharedPollSignatureRefreshInFlight = true;\n const keys = Array.from(this._sharedPollTrackedItems.keys());\n this._sharedPollSignatureRefreshKeys = new Set(keys);\n const self = this;\n // A subscription ending meanwhile resets the in-flight guard for its next period.\n const generation = this._refreshGeneration;\n this._callAsync(() => this._sharedPollGetSignature({ keys })).then(result => {\n if (generation !== self._refreshGeneration)\n return;\n self._sharedPollSignatureRefreshInFlight = false;\n if (!self._isSubscribed())\n return;\n self._sharedPollSignatureRefreshAttempts = 0;\n if (self._sharedPollSignatureRefreshAgain) {\n self._sharedPollSignatureRefreshAgain = false;\n // After this refresh's track request is sent below.\n Promise.resolve().then(() => self._sharedPollRefreshSignature());\n }\n // Handle revoked keys (keys not in the returned set).\n const returnedKeys = new Set(result.keys);\n const revokedKeys = [];\n for (const key of keys) {\n if (!returnedKeys.has(key) && this._sharedPollTrackedItems.has(key)) {\n self._sharedPollTrackedItems.delete(key);\n revokedKeys.push(key);\n // A handler of an earlier removal may have ended the subscription: the\n // keys are still untracked below, but nothing more is delivered.\n if (!self._isSubscribed()) {\n continue;\n }\n self.emit('update', {\n channel: self.channel,\n key: key,\n data: null,\n removed: true,\n });\n }\n }\n // Tell the server to stop tracking revoked keys \u2014 otherwise the server\n // keeps broadcasting them and the SDK silently drops the publications.\n if (revokedKeys.length > 0) {\n self._sendUntrackRequest(revokedKeys).catch(err => {\n self.emit('error', { type: 'untrack', channel: self.channel, error: err });\n });\n }\n // Re-track only keys covered by the returned signature.\n const items = [];\n for (const key of result.keys) {\n const version = self._sharedPollTrackedItems.get(key);\n if (version !== undefined) {\n items.push({ key, version });\n }\n }\n // Replace the signature library with the consolidated entry. Keep\n // any entries that cover keys NOT in the consolidation \u2014 those keys\n // may have been added via a concurrent track() while getSignature was\n // in flight and their signatures must remain available for reconnect.\n const consolidatedKeySet = new Set(result.keys);\n const uncovered = self._sharedPollSignatures.filter(entry => entry.keys.some(k => self._sharedPollTrackedItems.has(k) && !consolidatedKeySet.has(k)));\n // Target was already reset at refresh start; any concurrent track()\n // during getSignature has set its own target if its TTL was tighter.\n // The consolidated track response below will set a target unless\n // something earlier is already in place.\n self._sharedPollSignatures = items.length > 0\n ? [{ keys: result.keys, signature: result.signature }, ...uncovered]\n : uncovered;\n if (items.length === 0)\n return;\n self._sendTrackRequest([{ items, signature: result.signature }]).catch(e => {\n self._handleTrackError(e.error, e.keys);\n });\n }).catch(e => {\n if (generation !== self._refreshGeneration)\n return;\n self._sharedPollSignatureRefreshInFlight = false;\n // The retry below covers it.\n self._sharedPollSignatureRefreshAgain = false;\n self._emitError({\n type: 'signatureRefresh',\n channel: self.channel,\n error: {\n code: errorCodes.sharedPollGetSignature,\n message: e !== undefined ? e.toString() : ''\n }\n }, () => {\n // A handler may have ended the subscription, e.g. by disconnecting the client.\n if (generation !== self._refreshGeneration || !self._isSubscribed()) {\n return;\n }\n // Retry after delay with exponential backoff.\n self._sharedPollSignatureRefreshTimeout = setTimeout(() => self._sharedPollRefreshSignature(), backoff(self._sharedPollSignatureRefreshAttempts++, 5000, 30000));\n });\n });\n }\n // _sharedPollReplayTrack runs after subscribe completes \u2014 on initial\n // subscribe AND after every reconnect. It reuses every cached signature\n // in _sharedPollSignatures so that mass reconnects don't trigger mass\n // getSignature calls on the application backend.\n //\n // For each cached batch:\n // - Build a track command with the batch's ORIGINAL key set (HMAC was\n // signed over those keys, so the full set must be sent). Versions are\n // CURRENT per-connection versions, so the server pushes only what's\n // changed.\n // - Any keys in the batch that were locally untracked() since the original\n // track() are sent in the same frame's `untrack` field \u2014 the server\n // validates the full HMAC then removes them immediately, avoiding a\n // separate round-trip.\n //\n // getSignature is invoked only when there are no cached signatures (e.g.\n // initial subscribe where track(keys) was called without explicit sig).\n // Once a signature is expired beyond the server's grace period, the next\n // track command returns error 109 \u2014 _handleTrackError then triggers\n // _sharedPollRefreshSignature for a fresh consolidated signature.\n _sharedPollReplayTrack() {\n if (!this._isSubscribed())\n return;\n if (this._sharedPollTrackedItems.size === 0 && this._sharedPollSignatures.length === 0)\n return;\n // Phase 1: replay every cached signature batch in a SINGLE sub_refresh\n // frame (multi-batch wire format). The server validates each batch's\n // HMAC independently and merges the response. All-or-nothing semantics:\n // one failed signature \u2192 the whole replay fails and _handleTrackError\n // drives a consolidating refresh.\n //\n // After this block `coveredKeys` is the set of currently-tracked keys\n // that already have a signature in the library \u2014 any tracked key not\n // in this set needs a fresh getSignature in Phase 2.\n const coveredKeys = new Set();\n const replayBatches = [];\n const allUntrackedInReplay = [];\n for (const entry of this._sharedPollSignatures) {\n // Items: ORIGINAL key set + current per-connection versions. Keys that\n // were untracked locally still go in items (HMAC needs the full batch);\n // a single chained untrack runs after the multi-batch track resolves\n // to converge server-side state.\n const items = entry.keys.map(key => {\n var _a;\n return ({\n key,\n version: (_a = this._sharedPollTrackedItems.get(key)) !== null && _a !== void 0 ? _a : 0,\n });\n });\n replayBatches.push({ items, signature: entry.signature });\n for (const k of entry.keys) {\n if (this._sharedPollTrackedItems.has(k)) {\n coveredKeys.add(k);\n }\n else {\n allUntrackedInReplay.push(k);\n }\n }\n }\n if (replayBatches.length > 0) {\n // Pass untracked keys inline \u2014 server validates HMAC over the full batch\n // then immediately removes the stale keys in the same handler, eliminating\n // the previous two-round-trip track\u2192untrack sequence.\n this._sendTrackRequest(replayBatches, allUntrackedInReplay).catch(e => {\n this._handleTrackError(e.error, e.keys);\n });\n }\n // Phase 2: any tracked items NOT covered by a cached signature need\n // a fresh getSignature. This handles two cases:\n // - initial subscribe where track(keys) was called without explicit\n // sig (library starts empty, all keys uncovered);\n // - mixed track(keys) + track(items, sig) before subscribe \u2014 the\n // explicit batch sits in the library, but auto-tracked keys still\n // need a signature.\n const uncoveredKeys = [];\n for (const key of this._sharedPollTrackedItems.keys()) {\n if (!coveredKeys.has(key))\n uncoveredKeys.push(key);\n }\n if (uncoveredKeys.length === 0)\n return;\n if (!this._sharedPollGetSignature) {\n this.emit('error', {\n type: 'track',\n channel: this.channel,\n error: { code: errorCodes.sharedPollGetSignature, message: 'getSignature callback required for tracked keys without an explicit signature' },\n });\n return;\n }\n const self = this;\n const generation = this._refreshGeneration;\n this._callAsync(() => this._sharedPollGetSignature({ keys: uncoveredKeys })).then(result => {\n // The subscription ended meanwhile, e.g. by a reconnect: its replay asks again.\n if (generation !== self._refreshGeneration || !self._isSubscribed())\n return;\n self._clearSharedPollReplayRetry();\n // Handle revoked keys (keys we asked about that the backend didn't authorize).\n const returnedKeys = new Set(result.keys);\n const revokedKeys = [];\n for (const key of uncoveredKeys) {\n if (!returnedKeys.has(key) && this._sharedPollTrackedItems.has(key)) {\n self._sharedPollTrackedItems.delete(key);\n revokedKeys.push(key);\n // A handler of an earlier removal may have ended the subscription: the\n // keys are still untracked below, but nothing more is delivered.\n if (!self._isSubscribed()) {\n continue;\n }\n self.emit('update', {\n channel: self.channel,\n key: key,\n data: null,\n removed: true,\n });\n }\n }\n if (revokedKeys.length > 0) {\n self._sendUntrackRequest(revokedKeys).catch(err => {\n self.emit('error', { type: 'untrack', channel: self.channel, error: err });\n });\n }\n const items = [];\n for (const key of result.keys) {\n const version = self._sharedPollTrackedItems.get(key);\n if (version !== undefined) {\n items.push({ key, version });\n }\n }\n if (items.length === 0)\n return;\n // Cache the obtained signature for subsequent reconnect replays.\n self._addSharedPollSignature(result.keys, result.signature);\n self._sendTrackRequest([{ items, signature: result.signature }]).catch(e => {\n self._handleTrackError(e.error, e.keys);\n });\n }).catch(e => {\n if (generation !== self._refreshGeneration || !self._isSubscribed())\n return;\n self._emitError({\n type: 'signatureRefresh',\n channel: self.channel,\n error: {\n code: errorCodes.sharedPollGetSignature,\n message: e !== undefined ? e.toString() : ''\n }\n }, () => {\n // A handler may have ended the subscription, e.g. by disconnecting the client.\n if (generation !== self._refreshGeneration || !self._isSubscribed())\n return;\n // Replay-getSignature retry uses its OWN backoff state \u2014 separate from\n // the refresh timer so a stuck replay can't delay the next TTL refresh.\n self._sharedPollReplayRetryTimeout = setTimeout(() => self._sharedPollReplayTrack(), backoff(self._sharedPollReplayRetryAttempts++, 5000, 30000));\n });\n });\n }\n // ============ Keyed Subscription Methods ============\n /** Entry point for map subscriptions */\n _mapSubscribe() {\n this._debug('starting map subscribe on', this.channel);\n const flow = ++this._subscribeFlow;\n // Decided when the first request goes, after the token if one is needed: the\n // position may be reset meanwhile (state invalidation, setTagsFilter).\n const start = () => {\n // Initialize buffers and phase\n this._mapStateBuffer = [];\n this._mapStreamBuffer = [];\n this._mapCursor = '';\n // If we have a position from `since`, we may skip snapshot and go to stream\n const recovering = this._recover && this._offset !== null && this._epoch !== null;\n // Preserve _prevValueMap when recovering \u2014 the server will send deltas\n // against the values the client already has from the previous session.\n // Only clear when starting from scratch (no recovery position).\n if (!recovering) {\n this._prevValueMap = new Map();\n }\n this._mapFlowRecovering = recovering;\n this._mapFlowOffset = recovering ? this._offset : 0;\n this._mapFlowEpoch = recovering ? this._epoch : null;\n this._mapFlowPositionResets = this._mapPositionResets;\n this._mapPhase = MapPhase.State;\n if (recovering) {\n this._debug('map subscribe: recovering from position, skipping to stream phase');\n this._mapPhase = MapPhase.Stream;\n this._fetchStream(flow);\n }\n else {\n this._fetchSnapshot(flow);\n }\n };\n // Get token if needed, then start fetching. Also when recovering: the token\n // may have been cleared, e.g. after it expired.\n if (this._canSubscribeWithoutGettingToken()) {\n start();\n }\n else {\n this._getSubscriptionToken()\n .then(token => {\n // A later flow owns the subscription now.\n if (flow !== this._subscribeFlow) {\n return;\n }\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n if (!token) {\n this._inflight = false;\n this._failUnauthorized();\n return;\n }\n this._token = token;\n start();\n })\n .catch(e => {\n this._handleTokenError(e, flow);\n });\n }\n }\n /** Fetch a page of snapshot data */\n _fetchSnapshot(flow, cursor) {\n if (!this._isSubscribing() || !this._isTransportOpen()) {\n this._inflight = false;\n return;\n }\n const cmd = this._buildMapSubscribeCommand(MapPhase.State, cursor);\n this._debug('map subscribe: fetching snapshot page', cursor ? `cursor=${cursor}` : 'initial');\n this._subscribeCallFlow = flow;\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._call(cmd).then(resolveCtx => {\n try {\n if (this._settleSubscribeCall(flow, true)) {\n return;\n }\n // The reply to a page of an earlier flow is outdated.\n if (flow === this._subscribeFlow) {\n this._handleMapStateResponse(flow, resolveCtx.reply.subscribe);\n }\n }\n catch (err) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._dispatchFailed(err);\n }\n finally {\n if (resolveCtx.next) {\n resolveCtx.next();\n }\n }\n }, rejectCtx => {\n try {\n if (this._settleSubscribeCall(flow, false, rejectCtx.error)) {\n return;\n }\n if (flow === this._subscribeFlow) {\n this._handleMapSubscribeError(rejectCtx.error);\n }\n }\n catch (err) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._rejectionFailed(err, rejectCtx);\n }\n finally {\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n }\n });\n }\n /** Process snapshot response */\n _handleMapStateResponse(flow, result) {\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n // Check if server forced LIVE transition during STATE phase.\n // This happens on the last state page when server decides to skip STREAM phase\n // (streamless mode, or positioned mode with stream close enough).\n // Note: phase=0 may be omitted by JSON serializer, so !result.phase handles both 0 and undefined.\n if (!result.phase) {\n this._debug('map subscribe: server forced LIVE transition during state pagination');\n // _handleMapLiveResponse will process result.state and result.publications.\n this._handleMapLiveResponse(flow, result);\n return;\n }\n // Store epoch/offset from first response. Both are frozen for the duration\n // of state pagination to maintain consistency: the stream catch-up must start\n // from where the first state page was captured, not from a later stream.Top().\n if (!this._mapFlowEpoch && result.epoch) {\n this._mapFlowEpoch = result.epoch;\n this._mapFlowOffset = toOffset(result.offset);\n }\n // Validate epoch on subsequent pages - if epoch changed, restart\n if (this._mapFlowEpoch && result.epoch && this._mapFlowEpoch !== result.epoch) {\n this._debug('map subscribe: epoch changed during snapshot pagination, restarting');\n this._restartMapFlow();\n this._fetchSnapshot(flow);\n return;\n }\n // Append state entries to snapshot buffer (state field, not publications).\n if (result.state && result.state.length > 0) {\n this._mapStateBuffer.push(...result.state);\n }\n // Check if there's more data to fetch\n if (result.cursor) {\n this._mapCursor = result.cursor;\n this._fetchSnapshot(flow, this._mapCursor);\n return;\n }\n // No more snapshot pages, transition to next phase\n this._transitionFromSnapshot(flow);\n }\n // The stream epoch changed during the flow: what it collected and the stored\n // position are outdated. The flow continues from a snapshot.\n _restartMapFlow() {\n this._mapStateBuffer = [];\n this._mapStreamBuffer = [];\n this._mapCursor = '';\n this._mapFlowRecovering = false;\n this._mapFlowOffset = 0;\n this._mapFlowEpoch = null;\n this._epoch = null;\n this._offset = null;\n this._recover = false;\n this._prevValueMap = new Map();\n this._mapPhase = MapPhase.State;\n }\n /** Transition from STATE to STREAM phase after snapshot pagination completes */\n _transitionFromSnapshot(flow) {\n this._debug('map subscribe: snapshot complete, transitioning to stream phase');\n // After STATE pagination, move to STREAM phase.\n // Client sends phase=1 requests, server decides when to go LIVE\n // by responding with phase=0.\n this._mapPhase = MapPhase.Stream;\n this._fetchStream(flow);\n }\n /** Fetch stream data (offset-based catch-up) */\n _fetchStream(flow) {\n if (!this._isSubscribing() || !this._isTransportOpen()) {\n this._inflight = false;\n return;\n }\n const cmd = this._buildMapSubscribeCommand(MapPhase.Stream);\n this._debug('map subscribe: fetching stream from offset', this._mapFlowOffset);\n this._subscribeCallFlow = flow;\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._call(cmd).then(resolveCtx => {\n try {\n if (this._settleSubscribeCall(flow, true)) {\n return;\n }\n // The reply to a page of an earlier flow is outdated.\n if (flow === this._subscribeFlow) {\n this._handleMapStreamResponse(flow, resolveCtx.reply.subscribe);\n }\n }\n catch (err) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._dispatchFailed(err);\n }\n finally {\n if (resolveCtx.next) {\n resolveCtx.next();\n }\n }\n }, rejectCtx => {\n try {\n if (this._settleSubscribeCall(flow, false, rejectCtx.error)) {\n return;\n }\n if (flow === this._subscribeFlow) {\n this._handleMapSubscribeError(rejectCtx.error);\n }\n }\n catch (err) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._rejectionFailed(err, rejectCtx);\n }\n finally {\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n }\n });\n }\n /** Process stream response */\n _handleMapStreamResponse(flow, result) {\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n // Check if server forced LIVE transition (server-controlled).\n // When server decides client is close enough, it returns phase=0 (LIVE).\n // Note: phase=0 may be omitted by JSON serializer, so !result.phase handles both 0 and undefined.\n if (!result.phase) {\n this._debug('map subscribe: server forced LIVE transition during stream');\n this._handleMapLiveResponse(flow, result);\n return;\n }\n // Validate epoch - if changed, we need to restart\n if (this._mapFlowEpoch && result.epoch && this._mapFlowEpoch !== result.epoch) {\n this._debug('map subscribe: epoch changed during stream, restarting');\n this._restartMapFlow();\n this._fetchSnapshot(flow);\n return;\n }\n // Append publications to stream buffer\n if (result.publications && result.publications.length > 0) {\n this._mapStreamBuffer.push(...result.publications);\n }\n // Page from the offset in the result. Server returns the last publication's\n // actual offset for intermediate STREAM pages (not stream.Top()). The stored\n // position doesn't move: these entries only reach the app with the live reply.\n if (result.offset !== undefined) {\n this._mapFlowOffset = toOffset(result.offset);\n }\n // Server controls LIVE transition. If server responded with phase=1,\n // we continue STREAM pagination. Server will respond with phase=0 when ready.\n this._fetchStream(flow);\n }\n /** Process live response - complete the map subscription */\n _handleMapLiveResponse(flow, result) {\n if (!this._isSubscribing()) {\n this._inflight = false;\n return;\n }\n this._inflight = false;\n // Validate epoch one more time\n if (this._mapFlowEpoch && result.epoch && this._mapFlowEpoch !== result.epoch) {\n this._debug('map subscribe: epoch changed during live transition, restarting');\n this._restartMapFlow();\n this._inflight = true;\n this._fetchSnapshot(flow);\n return;\n }\n // Values of state and stream pages are escaped only when delta is negotiated,\n // which only the live reply tells: decode the buffered pages now. State entries\n // (including those of this reply) first, then the stream catch-up, whose delta\n // bases the live publications below may build on.\n const deltaNegotiated = !!(this._delta && result.delta);\n const statePubs = result.state && result.state.length > 0 ? this._mapStateBuffer.concat(result.state) : this._mapStateBuffer;\n this._mapStateBuffer = statePubs.map(pub => {\n this._seedDeltaTracking(pub, deltaNegotiated);\n return this._getMapUpdateContext(pub);\n });\n this._mapStreamBuffer = this._mapStreamBuffer.map(pub => {\n this._seedDeltaTracking(pub, deltaNegotiated);\n return this._getMapUpdateContext(pub);\n });\n // Append any remaining publications from the live response to stream buffer.\n // Recovery publications may be delta-encoded \u2014 decode before buffering.\n // Use result.delta (not this._delta_negotiated which is set later).\n if (result.publications && result.publications.length > 0) {\n for (const pub of result.publications) {\n if (deltaNegotiated) {\n // Delta negotiated: decode and update tracking in one block. A removal\n // carries no payload to decode, and ends the key's delta chain.\n const deltaKey = pub.key || '';\n if (pub.removed) {\n this._prevValueMap.delete(deltaKey);\n }\n else {\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n const { newData, newPrevValue, isDelta, wireBytes, fullBytes } = this._centrifuge._codec.applyDeltaIfNeeded(pub, this._prevValueMap.get(deltaKey));\n pub.data = newData;\n this._deltaNumPubs++;\n this._deltaBytesReceived += wireBytes;\n this._deltaBytesDecoded += fullBytes;\n if (isDelta) {\n this._deltaNumDelta++;\n }\n else {\n this._deltaNumFull++;\n }\n this._prevValueMap.set(deltaKey, newPrevValue);\n }\n }\n else if (this._delta && pub.key) {\n // Delta requested but not negotiated: seed tracking with raw data.\n if (pub.removed) {\n this._prevValueMap.delete(pub.key);\n }\n else {\n this._prevValueMap.set(pub.key, pub.data);\n }\n }\n this._mapStreamBuffer.push(this._getMapUpdateContext(pub));\n }\n }\n // Final offset/epoch \u2014 use || 0/'' to handle zero values omitted by JSON/protobuf.\n const offset = toOffset(result.offset);\n const epoch = result.epoch || '';\n // Clear subscribing state\n this._clearSubscribingState();\n // Store subscription ID if provided\n if (result.id) {\n this._id = result.id;\n }\n // Recoverable state - enable recovery for reconnects.\n // In streamless mode server omits recoverable (JSON: undefined, protobuf: false).\n const recover = result.recoverable === true;\n // Handle delta negotiation\n if (result.delta) {\n this._delta_negotiated = true;\n }\n else {\n this._delta_negotiated = false;\n }\n // Set publish debounce from subscribe result.\n if (result.publish_debounce) {\n this._debounceMs = result.publish_debounce;\n }\n // Take the buffers: a handler below may unsubscribe and subscribe again,\n // which starts a new flow using them.\n let stateEntries = this._mapStateBuffer;\n let streamEntries = this._mapStreamBuffer;\n this._mapStateBuffer = [];\n this._mapStreamBuffer = [];\n this._mapPhase = null;\n // Build subscribed context with state entries\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n const ctx = this._centrifuge._getSubscribeContext(this.channel, result);\n ctx.state = stateEntries;\n // The reply's offset is the top of the stream, also after a recovery. This\n // differs from a stream subscription, whose reply after a recovery carries the\n // position recovered from (see _setSubscribed). Nor would that position cover\n // the whole catch-up here: its entries can come from several stream pages,\n // buffered until now. Until the events below reached the app, the stored\n // position must not skip what they carry: a handler, from the state event on,\n // may unsubscribe, or subscribe again, in between.\n // The position may also be reset (setTagsFilter()) since this flow started, or by\n // a handler below: it's kept then, and the next subscribe starts from scratch.\n const positionResets = this._mapFlowPositionResets;\n if (this._mapPositionResets === positionResets) {\n this._recover = recover;\n this._epoch = epoch;\n if (!ctx.recovered) {\n // Until sync, the app doesn't have the complete state: start from scratch.\n this._recover = false;\n this._offset = null;\n this._epoch = null;\n }\n else if (streamEntries.length > 0 && streamEntries[0].offset !== undefined) {\n // Before the recovered catch-up.\n this._offset = streamEntries[0].offset - 1;\n }\n else {\n this._offset = offset;\n }\n }\n // Transition to subscribed state. A 'state' handler may have unsubscribed\n // already: no subscribed event then.\n this._setState(SubscriptionState.Subscribed);\n if (!this._isSubscribed()) {\n return;\n }\n // Emit subscribed event\n this.emit('subscribed', ctx);\n // A 'subscribed', 'sync', 'publication' or 'update' handler may have\n // unsubscribed: the rest of this flow must not reach the app. If it subscribed\n // again, promises made since then wait for that subscribe.\n if (!this._isSubscribed()) {\n return;\n }\n this._resolvePromises();\n // Emit sync event \u2014 complete state for simplified state management.\n // Skipped on successful recovery (app already has rendered state; stream\n // catch-up is emitted as individual update events).\n if (!ctx.recovered) {\n if (streamEntries.length > 0) {\n // Apply stream catch-up buffer to state by key (last value wins, removed deletes).\n // Produces a single sync snapshot that reflects state as of LIVE transition.\n const stateMap = new Map();\n for (const entry of stateEntries) {\n stateMap.set(entry.key, entry);\n }\n for (const entry of streamEntries) {\n if (entry.removed) {\n stateMap.delete(entry.key);\n }\n else {\n stateMap.set(entry.key, entry);\n }\n }\n stateEntries = Array.from(stateMap.values());\n streamEntries = []; // Already applied \u2014 don't emit as updates.\n }\n if (this._mapPositionResets === positionResets) {\n this._recover = recover;\n this._offset = offset;\n this._epoch = epoch;\n }\n this.emit('sync', { entries: stateEntries });\n }\n // Flush remaining stream buffer as publication and update events.\n // On recovery (sync skipped above) \u2014 app already has state and just needs\n // incremental changes. An entry counts as delivered from its update event on,\n // as a live publication (see _handlePublication).\n for (const entry of streamEntries) {\n if (!this._isSubscribed()) {\n return;\n }\n this.emit('publication', entry);\n if (!this._isSubscribed()) {\n return;\n }\n if (entry.offset !== undefined && this._mapPositionResets === positionResets) {\n this._offset = entry.offset;\n }\n this.emit('update', entry);\n }\n if (!this._isSubscribed()) {\n return;\n }\n if (this._mapPositionResets === positionResets) {\n this._offset = offset;\n }\n // Handle token expiry\n if (result.expires === true) {\n this._refreshTimeout = setTimeout(() => this._refresh(), ttlMilliseconds(result.ttl));\n }\n }\n /** Handle errors during map subscription process */\n _handleMapSubscribeError(error) {\n this._inflight = false;\n if (!this._isSubscribing()) {\n return;\n }\n if (error.code === errorCodes.connectionClosed) {\n // See _handleSubscribeError.\n return;\n }\n if (error.code === errorCodes.timeout) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n this._centrifuge._disconnect(connectingCodes.subscribeTimeout, 'subscribe timeout', true);\n return;\n }\n // Clear map state on error. The delta bases stay with the position: a\n // recovery from it gets deltas of the values the client has.\n this._mapStateBuffer = [];\n this._mapStreamBuffer = [];\n this._mapPhase = null;\n // Handle unrecoverable position error (code 112) based on strategy\n if (error.code === 112) {\n if (this._mapUnrecoverableStrategy === 'from_scratch') {\n // Reset position and resubscribe from snapshot\n this._debug('map subscribe: unrecoverable position, restarting from scratch');\n this._prevValueMap = new Map();\n this._offset = null;\n this._epoch = null;\n this._recover = false;\n this._scheduleResubscribe();\n return;\n }\n // 'fatal' strategy: fall through to _subscribeError which will unsubscribe\n }\n this._subscribeError(error);\n }\n /** Build map subscribe command for a specific phase */\n _buildMapSubscribeCommand(phase, cursor) {\n const req = {\n channel: this.channel,\n type: this._mapPresenceType || 1, // 1=MAP, 2=MAP_CLIENTS, 3=MAP_USERS\n phase: phase,\n };\n if (this._token)\n req.token = this._token;\n if (this._tagsFilter)\n req.tf = this._tagsFilter;\n if (this._delta)\n req.delta = this._delta;\n req.flag = subscriptionFlags.channelCompaction;\n // STATE phase\n if (phase === MapPhase.State) {\n if (this._mapPageSize > 0)\n req.limit = this._mapPageSize;\n if (cursor)\n req.cursor = cursor;\n // Epoch validation after first page\n if (this._mapFlowEpoch) {\n req.offset = this._mapFlowOffset;\n req.epoch = this._mapFlowEpoch;\n }\n else {\n // First request of the flow \u2014 include custom data.\n if (this._data)\n req.data = this._data;\n }\n }\n // STREAM phase\n if (phase === MapPhase.Stream) {\n if (this._mapPageSize > 0)\n req.limit = this._mapPageSize;\n req.offset = this._mapFlowOffset;\n req.epoch = this._mapFlowEpoch;\n if (this._mapFlowRecovering) {\n req.recover = true;\n // First request of the flow (skipped STATE) \u2014 include custom data for authorization.\n if (this._mapStreamBuffer.length === 0) {\n if (this._data)\n req.data = this._data;\n }\n }\n }\n return { subscribe: req };\n }\n /** Convert raw publication to MapUpdateContext */\n _getMapUpdateContext(pub) {\n const ctx = {\n channel: this.channel,\n data: pub.data,\n key: pub.key || '',\n };\n if (pub.removed === true) {\n ctx.removed = true;\n }\n if (pub.offset !== undefined) {\n ctx.offset = toOffset(pub.offset);\n }\n if (pub.info) {\n // @ts-ignore \u2013 we are hiding some methods from public API autocompletion.\n ctx.info = this._centrifuge._getJoinLeaveContext(pub.info);\n }\n if (pub.tags) {\n ctx.tags = pub.tags;\n }\n return ctx;\n }\n /** Convert raw publication to SharedPollUpdateContext */\n _getSharedPollUpdateContext(pub) {\n const ctx = {\n channel: this.channel,\n key: pub.key || '',\n data: pub.data,\n };\n if (pub.removed === true) {\n ctx.removed = true;\n }\n if (pub.version !== undefined) {\n ctx.version = toOffset(pub.version);\n }\n return ctx;\n }\n}\n/** Stream subscription with publish/history methods. */\nclass Subscription extends BaseSubscription {\n /** Publish data to the channel. */\n publish(data) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._methodCall();\n // Debounce per channel (key = \"\" for stream publishes).\n if (this._debounceMs > 0) {\n return this._debouncedPublish('', data, false);\n }\n return this._centrifuge.publish(this.channel, data);\n });\n }\n /** history for a channel. By default it does not return publications (only current\n * StreamPosition data) \u2013 provide an explicit limit > 0 to load publications.*/\n history(opts) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._methodCall();\n return this._centrifuge.history(this.channel, opts);\n });\n }\n}\n/** Map subscription with publish/remove methods. */\nclass MapSubscription extends BaseSubscription {\n /** Publish data to a key. */\n publish(key, data) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._methodCall();\n if (this._debounceMs > 0) {\n return this._debouncedPublish(key, data, true);\n }\n return this._centrifuge.mapPublish(this.channel, key, data);\n });\n }\n /** Remove a key. */\n remove(key) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._methodCall();\n // Cancel any pending debounced publish for this key.\n this._cancelDebounce(key);\n return this._centrifuge.mapRemove(this.channel, key);\n });\n }\n}\n/** Shared poll subscription with track/untrack/trackedKeys. */\nclass SharedPollSubscription extends BaseSubscription {\n /** Track items in a shared poll subscription.\n *\n * Overloads:\n * - `track(keys: string[])` \u2014 pass key names only (version defaults to 0).\n * Requires `getSignature` callback in subscription options. The SDK\n * automatically obtains a signature before sending the track request.\n * - `track(items: SharedPollTrackItem[], signature: string)` \u2014 pass items\n * with explicit versions and a pre-computed HMAC signature.\n *\n * Items are stored in local state immediately. If subscribed, the track request\n * is sent right away. If not yet subscribed, items will be sent via replay\n * (with a fresh signature from getSignature) after subscribe completes.\n *\n * **Fire-and-forget** (similar to subscribe/unsubscribe): returns void and never\n * throws for in-flight failures. Subscribe to the `error` event to observe\n * failures: `type: 'track'` covers both the server-side track request and\n * the `getSignature` callback when using `track(keys)`. Server-revoked keys\n * arrive as synthetic `update` events with `removed: true`. */\n track(keysOrItems, signature) {\n if (keysOrItems.length === 0) {\n return; // Nothing to track \u2014 avoid wasteful getSignature call.\n }\n let items;\n const sig = signature;\n if (typeof keysOrItems[0] === 'string') {\n const keys = keysOrItems;\n items = keys.map(k => ({ key: k, version: 0 }));\n }\n else {\n items = keysOrItems;\n }\n // Update per-connection tracked items (use max(existing, new) so a stale\n // page load can't downgrade a version already advanced by a publication).\n for (const item of items) {\n // A version an app stored and restored comes back as an object, see toOffset.\n const version = toOffset(item.version);\n const existing = this._sharedPollTrackedItems.get(item.key);\n if (existing === undefined || version > existing) {\n this._sharedPollTrackedItems.set(item.key, version);\n }\n }\n if (sig !== undefined) {\n // Explicit signature path \u2014 append to library and (if subscribed) send.\n this._addSharedPollSignature(items.map(i => i.key), sig);\n if (this._isSubscribed() && !this._sharedPollReplayPending) {\n this._sendTrackRequest([{ items, signature: sig }]).catch(e => {\n this._handleTrackError(e.error, e.keys);\n });\n }\n // If not subscribed yet, or completing the subscribe, _sharedPollReplayTrack\n // sends it after subscribe.\n return;\n }\n // Auto-obtain signature via getSignature callback.\n if (!this._sharedPollGetSignature) {\n this.emit('error', {\n type: 'track',\n channel: this.channel,\n error: { code: errorCodes.sharedPollGetSignature, message: 'getSignature callback required for track(keys)' },\n });\n return;\n }\n if (!this._isSubscribed() || this._sharedPollReplayPending) {\n // Defer the getSignature call until after subscribe \u2014 _sharedPollReplayTrack\n // will obtain a signature covering all tracked keys at once.\n return;\n }\n const keys = items.map(i => i.key);\n const generation = this._refreshGeneration;\n this._callAsync(() => this._sharedPollGetSignature({ keys })).then(result => {\n // The subscription ended meanwhile, e.g. by a reconnect: its replay asks again.\n if (generation !== this._refreshGeneration || !this._isSubscribed())\n return;\n // Handle revoked keys.\n const returnedKeys = new Set(result.keys);\n const revokedKeys = [];\n for (const key of keys) {\n if (!returnedKeys.has(key) && this._sharedPollTrackedItems.has(key)) {\n this._sharedPollTrackedItems.delete(key);\n revokedKeys.push(key);\n // A handler of an earlier removal may have ended the subscription: the\n // keys are still untracked below, but nothing more is delivered.\n if (!this._isSubscribed()) {\n continue;\n }\n this.emit('update', {\n channel: this.channel,\n key: key,\n data: null,\n removed: true,\n });\n }\n }\n // Server may already be tracking some of these from a prior track() with\n // a different signature \u2014 send untrack so it stops broadcasting them.\n if (revokedKeys.length > 0) {\n this._sendUntrackRequest(revokedKeys).catch(err => {\n this.emit('error', { type: 'untrack', channel: this.channel, error: err });\n });\n }\n // A getSignature that works again: the next failure starts the backoff over.\n this._sharedPollReplayRetryAttempts = 0;\n // Track authorized keys.\n const authorizedItems = [];\n for (const key of result.keys) {\n const version = this._sharedPollTrackedItems.get(key);\n if (version !== undefined) {\n authorizedItems.push({ key, version });\n }\n }\n if (authorizedItems.length === 0)\n return;\n // Cache the obtained signature for reconnect replay.\n this._addSharedPollSignature(result.keys, result.signature);\n this._sendTrackRequest([{ items: authorizedItems, signature: result.signature }]).catch(e => {\n this._handleTrackError(e.error, e.keys);\n });\n }).catch(e => {\n if (generation !== this._refreshGeneration || !this._isSubscribed())\n return;\n this._emitError({\n type: 'track',\n channel: this.channel,\n error: { code: errorCodes.sharedPollGetSignature, message: e !== undefined ? e.toString() : 'getSignature failed' },\n }, () => {\n if (generation !== this._refreshGeneration || !this._isSubscribed())\n return;\n // Retried by the replay, which gets a signature for the keys without one.\n this._scheduleSharedPollReplayRetry();\n });\n });\n }\n /** Stop tracking specific keys in a shared poll subscription.\n * Keys are removed from local state immediately. If subscribed, the untrack\n * request is sent right away. If not yet subscribed, the keys simply won't\n * be included in the replay after subscribe completes.\n *\n * **Fire-and-forget** (similar to subscribe/unsubscribe): returns void and never\n * throws for in-flight failures. Subscribe to the `error` event with\n * `type: 'untrack'` to observe failures of the untrack request. */\n untrack(keys) {\n for (const key of keys) {\n this._sharedPollTrackedItems.delete(key);\n }\n // Drop any signature entries whose ENTIRE key set is now untracked \u2014\n // they contribute nothing to reconnect replays and would grow unboundedly\n // in long-running sessions with many track/untrack cycles. Entries where\n // at least one key is still tracked are kept intact: pruning them would\n // cause those live keys to lose their signature on the next reconnect.\n this._sharedPollSignatures = this._sharedPollSignatures.filter(entry => entry.keys.some(k => this._sharedPollTrackedItems.has(k)));\n if (this._isSubscribed()) {\n this._sendUntrackRequest(keys).catch(err => {\n this.emit('error', {\n type: 'untrack',\n channel: this.channel,\n error: err,\n });\n });\n }\n }\n /** Returns the set of currently tracked keys in a shared poll subscription. */\n trackedKeys() {\n return new Set(this._sharedPollTrackedItems.keys());\n }\n}\n\n/** @internal */\nclass SockjsTransport {\n constructor(endpoint, options) {\n this.endpoint = endpoint;\n this.options = options;\n this._transport = null;\n }\n name() {\n return 'sockjs';\n }\n subName() {\n return 'sockjs-' + this._transport.transport;\n }\n emulation() {\n return false;\n }\n supported() {\n return this.options.sockjs !== null;\n }\n initialize(_protocol, callbacks) {\n this._transport = new this.options.sockjs(this.endpoint, null, this.options.sockjsOptions);\n this._transport.onopen = () => {\n callbacks.onOpen();\n };\n this._transport.onerror = e => {\n callbacks.onError(e);\n };\n this._transport.onclose = closeEvent => {\n callbacks.onClose(closeEvent);\n };\n this._transport.onmessage = event => {\n callbacks.onMessage(event.data);\n };\n }\n close() {\n // No socket if its constructor threw in initialize().\n if (this._transport !== null) {\n this._transport.close();\n }\n }\n send(data) {\n this._transport.send(data);\n }\n}\n\n/** @internal */\nclass WebsocketTransport {\n constructor(endpoint, options) {\n this.endpoint = endpoint;\n this.options = options;\n this._transport = null;\n }\n name() {\n return 'websocket';\n }\n subName() {\n return 'websocket';\n }\n emulation() {\n return false;\n }\n supported() {\n return this.options.websocket !== undefined && this.options.websocket !== null;\n }\n initialize(protocol, callbacks) {\n let subProtocol = '';\n if (protocol === 'protobuf') {\n subProtocol = 'centrifuge-protobuf';\n }\n if (subProtocol !== '') {\n this._transport = new this.options.websocket(this.endpoint, subProtocol);\n }\n else {\n this._transport = new this.options.websocket(this.endpoint);\n }\n if (protocol === 'protobuf') {\n this._transport.binaryType = 'arraybuffer';\n }\n this._transport.onopen = () => {\n callbacks.onOpen();\n };\n this._transport.onerror = e => {\n callbacks.onError(e);\n };\n this._transport.onclose = closeEvent => {\n callbacks.onClose(closeEvent);\n };\n this._transport.onmessage = event => {\n callbacks.onMessage(event.data);\n };\n }\n close() {\n // No socket if its constructor threw in initialize().\n if (this._transport !== null) {\n this._transport.close();\n }\n }\n send(data) {\n this._transport.send(data);\n }\n}\n\n// A buffer grown beyond this for a large reply is released once the reply is cut out.\nconst maxRetainedSize = 64 * 1024;\n/** @internal Collects the chunks of a binary stream and cuts complete replies out\n * of them. Appending a chunk and cutting a reply cost their own size only, not the\n * size of what is buffered: a large reply arriving in many small chunks is not\n * copied again for every chunk. */\nclass ReplyStreamBuffer {\n constructor() {\n this._buf = new Uint8Array(0);\n this._start = 0;\n this._end = 0;\n }\n push(chunk) {\n const size = this._end - this._start;\n if (this._end + chunk.length > this._buf.length) {\n if (size + chunk.length <= this._buf.length / 2) {\n // Enough room once the data already cut out is dropped.\n this._buf.copyWithin(0, this._start, this._end);\n }\n else {\n const buf = new Uint8Array(Math.max(this._buf.length * 2, size + chunk.length));\n buf.set(this._buf.subarray(this._start, this._end));\n this._buf = buf;\n }\n this._start = 0;\n this._end = size;\n }\n this._buf.set(chunk, this._end);\n this._end += chunk.length;\n }\n // Calls onReply with a copy of each complete reply buffered, in order.\n // decodeReply tells whether the data starts with a complete reply, and where it ends.\n drain(decodeReply, onReply) {\n while (this._start < this._end) {\n const result = decodeReply(this._buf.subarray(this._start, this._end));\n if (!result.ok) {\n break;\n }\n const end = this._start + result.pos;\n const reply = this._buf.slice(this._start, end);\n this._start = end;\n onReply(reply);\n }\n const size = this._end - this._start;\n if (this._buf.length > maxRetainedSize && size <= this._buf.length / 4) {\n // Don't keep the memory of a large reply for the rest of the connection. The\n // copy costs at most a quarter of what growing the buffer did.\n this._buf = this._buf.slice(this._start, this._end);\n this._start = 0;\n this._end = size;\n }\n else if (size === 0) {\n this._start = 0;\n this._end = 0;\n }\n }\n}\n/** @internal Collects the chunks of a stream of newline-delimited text replies and\n * cuts complete lines out of them. Each chunk is scanned once, and the parts of a\n * line arriving in many chunks are joined once: a large reply doesn't make every\n * chunk cost more. */\nclass LineStreamBuffer {\n constructor() {\n this._decoder = new TextDecoder();\n this._parts = [];\n }\n // Calls onLine with each complete line, in order, without its '\\n'.\n push(chunk, onLine) {\n // stream: true keeps decoder state across reads so a multi-byte UTF-8 character\n // split across two chunks is not corrupted into replacement characters.\n const text = this._decoder.decode(chunk, { stream: true });\n let start = 0;\n let end = text.indexOf('\\n');\n while (end !== -1) {\n this._parts.push(text.substring(start, end));\n const line = this._parts.join('');\n this._parts = [];\n start = end + 1;\n onLine(line);\n end = text.indexOf('\\n', start);\n }\n if (start < text.length) {\n this._parts.push(text.substring(start));\n }\n }\n}\n\n/** @internal */\nclass HttpStreamTransport {\n constructor(endpoint, options) {\n this.endpoint = endpoint;\n this.options = options;\n this._abortController = null;\n this._protocol = 'json';\n }\n name() {\n return 'http_stream';\n }\n subName() {\n return 'http_stream';\n }\n emulation() {\n return true;\n }\n _handleErrors(response) {\n if (!response.ok)\n throw new Error(response.status);\n return response;\n }\n _fetchEventTarget(self, endpoint, options) {\n const eventTarget = new EventTarget();\n // fetch with connection timeout maybe? https://github.com/github/fetch/issues/175\n const fetchFunc = self.options.fetch;\n fetchFunc(endpoint, options)\n .then(self._handleErrors)\n .then(response => {\n eventTarget.dispatchEvent(new Event('open'));\n const jsonStreamBuf = new LineStreamBuffer();\n const protoStreamBuf = new ReplyStreamBuffer();\n const reader = response.body.getReader();\n return new self.options.readableStream({\n start(controller) {\n function pump() {\n return reader.read().then(({ done, value }) => {\n // When no more data needs to be consumed, close the stream\n if (done) {\n eventTarget.dispatchEvent(new Event('close'));\n controller.close();\n return;\n }\n try {\n if (self._protocol === 'json') {\n jsonStreamBuf.push(value, line => eventTarget.dispatchEvent(new MessageEvent('message', { data: line })));\n }\n else {\n protoStreamBuf.push(value);\n protoStreamBuf.drain(data => self.options.decoder.decodeReply(data), reply => eventTarget.dispatchEvent(new MessageEvent('message', { data: reply })));\n }\n }\n catch (error) {\n // @ts-ignore - improve later.\n eventTarget.dispatchEvent(new Event('error', { detail: error }));\n eventTarget.dispatchEvent(new Event('close'));\n controller.close();\n return;\n }\n pump();\n }).catch(function (e) {\n // @ts-ignore - improve later.\n eventTarget.dispatchEvent(new Event('error', { detail: e }));\n eventTarget.dispatchEvent(new Event('close'));\n controller.close();\n return;\n });\n }\n return pump();\n }\n });\n })\n .catch(error => {\n // @ts-ignore - improve later.\n eventTarget.dispatchEvent(new Event('error', { detail: error }));\n eventTarget.dispatchEvent(new Event('close'));\n });\n return eventTarget;\n }\n supported() {\n return this.options.fetch !== null &&\n this.options.readableStream !== null &&\n typeof TextDecoder !== 'undefined' &&\n typeof AbortController !== 'undefined' &&\n typeof EventTarget !== 'undefined' &&\n typeof Event !== 'undefined' &&\n typeof MessageEvent !== 'undefined' &&\n typeof Error !== 'undefined';\n }\n initialize(protocol, callbacks, initialData) {\n this._protocol = protocol;\n this._abortController = new AbortController();\n let headers;\n let body;\n if (protocol === 'json') {\n headers = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n };\n body = initialData;\n }\n else {\n headers = {\n 'Accept': 'application/octet-stream',\n 'Content-Type': 'application/octet-stream'\n };\n body = initialData;\n }\n const fetchOptions = {\n method: 'POST',\n headers: headers,\n body: body,\n mode: 'cors',\n credentials: 'same-origin',\n signal: this._abortController.signal\n };\n const eventTarget = this._fetchEventTarget(this, this.endpoint, fetchOptions);\n eventTarget.addEventListener('open', () => {\n callbacks.onOpen();\n });\n eventTarget.addEventListener('error', (e) => {\n this._abortController.abort();\n callbacks.onError(e);\n });\n eventTarget.addEventListener('close', () => {\n this._abortController.abort();\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n });\n eventTarget.addEventListener('message', (e) => {\n callbacks.onMessage(e.data);\n });\n }\n close() {\n // Not created if initialize() threw before creating it.\n if (this._abortController !== null) {\n this._abortController.abort();\n }\n }\n send(data, session, node) {\n let headers;\n let body;\n const req = {\n session: session,\n node: node,\n data: data\n };\n if (this._protocol === 'json') {\n headers = {\n 'Content-Type': 'application/json'\n };\n body = JSON.stringify(req);\n }\n else {\n headers = {\n 'Content-Type': 'application/octet-stream'\n };\n body = this.options.encoder.encodeEmulationRequest(req);\n }\n const fetchFunc = this.options.fetch;\n const fetchOptions = {\n method: 'POST',\n headers: headers,\n body: body,\n mode: 'cors',\n credentials: 'same-origin',\n // Closing the transport aborts requests still pending, e.g. hung in an\n // intermediary, which would otherwise keep connections of the per-host pool.\n signal: this._abortController.signal\n };\n fetchFunc(this.options.emulationEndpoint, fetchOptions).then(response => {\n // The server has no node of the session (404), e.g. the node was restarted, or\n // the server or an intermediary failed. Other statuses, e.g. a too large request\n // body, reject only this command. A session gone from a running node is answered\n // with 204: its stream ends then.\n if (response && (response.status === 404 || response.status >= 500)) {\n this.close();\n }\n }, () => {\n // The command was not delivered. Close the transport so the client\n // reconnects instead of waiting for the command timeout.\n this.close();\n });\n }\n}\n\n/** @internal */\nclass SseTransport {\n constructor(endpoint, options) {\n this.endpoint = endpoint;\n this.options = options;\n this._protocol = 'json';\n this._transport = null;\n this._onClose = null;\n this._abortController = null;\n }\n name() {\n return 'sse';\n }\n subName() {\n return 'sse';\n }\n emulation() {\n return true;\n }\n supported() {\n return this.options.eventsource !== null && this.options.fetch !== null;\n }\n initialize(_protocol, callbacks, initialData) {\n // Aborts pending emulation requests on close.\n if (typeof AbortController !== 'undefined') {\n this._abortController = new AbortController();\n }\n let url;\n if (globalThis && globalThis.document && globalThis.document.baseURI) {\n // Handle case when endpoint is relative, like //example.com/connection/sse\n url = new URL(this.endpoint, globalThis.document.baseURI);\n }\n else {\n url = new URL(this.endpoint);\n }\n url.searchParams.append('cf_connect', initialData);\n const eventsourceOptions = {};\n const eventSource = new this.options.eventsource(url.toString(), eventsourceOptions);\n this._transport = eventSource;\n const self = this;\n eventSource.onopen = function () {\n callbacks.onOpen();\n };\n eventSource.onerror = function (e) {\n eventSource.close();\n callbacks.onError(e);\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n };\n eventSource.onmessage = function (e) {\n callbacks.onMessage(e.data);\n };\n self._onClose = function () {\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n };\n }\n close() {\n if (this._abortController !== null) {\n this._abortController.abort();\n }\n // No event source if its constructor threw in initialize().\n if (this._transport !== null) {\n this._transport.close();\n }\n if (this._onClose !== null) {\n this._onClose();\n }\n }\n send(data, session, node) {\n const req = {\n session: session,\n node: node,\n data: data\n };\n const headers = {\n 'Content-Type': 'application/json'\n };\n const body = JSON.stringify(req);\n const fetchFunc = this.options.fetch;\n // Closing the transport aborts requests still pending, e.g. hung in an\n // intermediary, which would otherwise keep connections of the per-host pool.\n const signal = this._abortController !== null ? this._abortController.signal : undefined;\n const fetchOptions = {\n method: 'POST',\n headers: headers,\n body: body,\n mode: 'cors',\n credentials: 'same-origin',\n signal: signal\n };\n fetchFunc(this.options.emulationEndpoint, fetchOptions).then(response => {\n // The server has no node of the session (404), e.g. the node was restarted, or\n // the server or an intermediary failed. Other statuses, e.g. a too large request\n // body, reject only this command. A session gone from a running node is answered\n // with 204: its stream ends then.\n if (response && (response.status === 404 || response.status >= 500)) {\n this.close();\n }\n }, () => {\n // Aborted because the transport was closed already.\n if (signal && signal.aborted) {\n return;\n }\n // The command was not delivered. Close the transport so the client\n // reconnects instead of waiting for the command timeout.\n this.close();\n });\n }\n}\n\n/** @internal */\nclass WebtransportTransport {\n constructor(endpoint, options) {\n this.endpoint = endpoint;\n this.options = options;\n this._transport = null;\n this._stream = null;\n this._writer = null;\n this._protocol = 'json';\n }\n name() {\n return 'webtransport';\n }\n subName() {\n return 'webtransport';\n }\n emulation() {\n return false;\n }\n supported() {\n return this.options.webtransport !== undefined && this.options.webtransport !== null;\n }\n initialize(protocol, callbacks) {\n return __awaiter(this, void 0, void 0, function* () {\n let url;\n if (globalThis && globalThis.document && globalThis.document.baseURI) {\n // Handle case when endpoint is relative, like //example.com/connection/webtransport\n url = new URL(this.endpoint, globalThis.document.baseURI);\n }\n else {\n url = new URL(this.endpoint);\n }\n if (protocol === 'protobuf') {\n url.searchParams.append('cf_protocol', 'protobuf');\n }\n this._protocol = protocol;\n const eventTarget = new EventTarget();\n this._transport = new this.options.webtransport(url.toString());\n this._transport.closed.then(() => {\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n }).catch(() => {\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n });\n try {\n yield this._transport.ready;\n }\n catch (_a) {\n this.close();\n return;\n }\n let stream;\n try {\n stream = yield this._transport.createBidirectionalStream();\n }\n catch (_b) {\n this.close();\n return;\n }\n this._stream = stream;\n this._writer = this._stream.writable.getWriter();\n eventTarget.addEventListener('close', () => {\n callbacks.onClose({\n code: 4,\n reason: 'connection closed'\n });\n });\n eventTarget.addEventListener('message', (e) => {\n callbacks.onMessage(e.data);\n });\n this._startReading(eventTarget);\n callbacks.onOpen();\n });\n }\n _startReading(eventTarget) {\n return __awaiter(this, void 0, void 0, function* () {\n const reader = this._stream.readable.getReader();\n const jsonStreamBuf = new LineStreamBuffer();\n const protoStreamBuf = new ReplyStreamBuffer();\n try {\n while (true) {\n const { done, value } = yield reader.read();\n if (value && value.length > 0) {\n if (this._protocol === 'json') {\n jsonStreamBuf.push(value, line => eventTarget.dispatchEvent(new MessageEvent('message', { data: line })));\n }\n else {\n protoStreamBuf.push(value);\n protoStreamBuf.drain(data => this.options.decoder.decodeReply(data), reply => eventTarget.dispatchEvent(new MessageEvent('message', { data: reply })));\n }\n }\n if (done) {\n break;\n }\n }\n }\n catch (_a) {\n eventTarget.dispatchEvent(new Event('close'));\n }\n });\n }\n close() {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n if (this._writer) {\n yield this._writer.close();\n }\n this._transport.close();\n }\n catch (e) {\n // already closed.\n }\n });\n }\n send(data) {\n return __awaiter(this, void 0, void 0, function* () {\n let binary;\n if (this._protocol === 'json') {\n // Need extra \\n since WT is non-frame protocol. \n binary = new TextEncoder().encode(data + '\\n');\n }\n else {\n binary = data;\n }\n try {\n yield this._writer.write(binary);\n }\n catch (e) {\n this.close();\n }\n });\n }\n}\n\n/*\nCopyright 2014-2024 Dmitry Chestnykh (JavaScript port)\nCopyright 2007 D. Richard Hipp (original C version)\n\nFossil SCM delta compression algorithm, this is only the applyDelta part extracted\nfrom https://github.com/dchest/fossil-delta-js. The code was slightly modified\nto strip unnecessary parts. The copyright on top of this file is from the original\nrepo on Github licensed under Simplified BSD License.\n*/\nconst zValue = [\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1,\n -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,\n 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36, -1, 37,\n 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,\n 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,\n];\n// Reader reads bytes, chars, ints from array.\nclass Reader {\n constructor(array) {\n this.a = array; // source array\n this.pos = 0; // current position in array\n }\n haveBytes() {\n return this.pos < this.a.length;\n }\n getByte() {\n const b = this.a[this.pos];\n this.pos++;\n if (this.pos > this.a.length)\n throw new RangeError(\"out of bounds\");\n return b;\n }\n getChar() {\n return String.fromCharCode(this.getByte());\n }\n // Read base64-encoded unsigned integer.\n getInt() {\n let v = 0;\n let c;\n while (this.haveBytes() && (c = zValue[0x7f & this.getByte()]) >= 0) {\n v = (v << 6) + c;\n }\n this.pos--;\n return v >>> 0;\n }\n}\n// Write writes an array.\nclass Writer {\n constructor() {\n this.a = [];\n }\n toByteArray(sourceType) {\n if (Array.isArray(sourceType)) {\n return this.a;\n }\n return new Uint8Array(this.a);\n }\n // Copy from array at start to end.\n putArray(a, start, end) {\n // TODO: optimize.\n for (let i = start; i < end; i++)\n this.a.push(a[i]);\n }\n}\n// Return a 32-bit checksum of the array.\nfunction checksum(arr) {\n let sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0, z = 0, N = arr.length;\n //TODO measure if this unrolling is helpful.\n while (N >= 16) {\n sum0 = (sum0 + arr[z + 0]) | 0;\n sum1 = (sum1 + arr[z + 1]) | 0;\n sum2 = (sum2 + arr[z + 2]) | 0;\n sum3 = (sum3 + arr[z + 3]) | 0;\n sum0 = (sum0 + arr[z + 4]) | 0;\n sum1 = (sum1 + arr[z + 5]) | 0;\n sum2 = (sum2 + arr[z + 6]) | 0;\n sum3 = (sum3 + arr[z + 7]) | 0;\n sum0 = (sum0 + arr[z + 8]) | 0;\n sum1 = (sum1 + arr[z + 9]) | 0;\n sum2 = (sum2 + arr[z + 10]) | 0;\n sum3 = (sum3 + arr[z + 11]) | 0;\n sum0 = (sum0 + arr[z + 12]) | 0;\n sum1 = (sum1 + arr[z + 13]) | 0;\n sum2 = (sum2 + arr[z + 14]) | 0;\n sum3 = (sum3 + arr[z + 15]) | 0;\n z += 16;\n N -= 16;\n }\n while (N >= 4) {\n sum0 = (sum0 + arr[z + 0]) | 0;\n sum1 = (sum1 + arr[z + 1]) | 0;\n sum2 = (sum2 + arr[z + 2]) | 0;\n sum3 = (sum3 + arr[z + 3]) | 0;\n z += 4;\n N -= 4;\n }\n sum3 = (((((sum3 + (sum2 << 8)) | 0) + (sum1 << 16)) | 0) + (sum0 << 24)) | 0;\n switch (N) {\n //@ts-ignore fallthrough is needed.\n case 3:\n sum3 = (sum3 + (arr[z + 2] << 8)) | 0; /* falls through */\n //@ts-ignore fallthrough is needed.\n case 2:\n sum3 = (sum3 + (arr[z + 1] << 16)) | 0; /* falls through */\n case 1:\n sum3 = (sum3 + (arr[z + 0] << 24)) | 0; /* falls through */\n }\n return sum3 >>> 0;\n}\n/**\n * Apply a delta byte array to a source byte array, returning the target byte array.\n */\nfunction applyDelta(source, delta) {\n let total = 0;\n const zDelta = new Reader(delta);\n const lenSrc = source.length;\n const lenDelta = delta.length;\n const limit = zDelta.getInt();\n if (zDelta.getChar() !== \"\\n\")\n throw new Error(\"size integer not terminated by '\\\\n'\");\n const zOut = new Writer();\n while (zDelta.haveBytes()) {\n const cnt = zDelta.getInt();\n let ofst;\n switch (zDelta.getChar()) {\n case \"@\":\n ofst = zDelta.getInt();\n if (zDelta.haveBytes() && zDelta.getChar() !== \",\")\n throw new Error(\"copy command not terminated by ','\");\n total += cnt;\n if (total > limit)\n throw new Error(\"copy exceeds output file size\");\n if (ofst + cnt > lenSrc)\n throw new Error(\"copy extends past end of input\");\n zOut.putArray(source, ofst, ofst + cnt);\n break;\n case \":\":\n total += cnt;\n if (total > limit)\n throw new Error(\"insert command gives an output larger than predicted\");\n if (cnt > lenDelta)\n throw new Error(\"insert count exceeds size of delta\");\n zOut.putArray(zDelta.a, zDelta.pos, zDelta.pos + cnt);\n zDelta.pos += cnt;\n break;\n case \";\":\n {\n const out = zOut.toByteArray(source);\n if (cnt !== checksum(out))\n throw new Error(\"bad checksum\");\n if (total !== limit)\n throw new Error(\"generated size does not match predicted size\");\n return out;\n }\n default:\n throw new Error(\"unknown delta operator\");\n }\n }\n throw new Error(\"unterminated delta\");\n}\n\n/** @internal */\nclass JsonCodec {\n name() {\n return 'json';\n }\n encodeCommands(commands) {\n return commands.map(c => JSON.stringify(c)).join('\\n');\n }\n decodeReplies(data) {\n // Empty lines carry nothing, e.g. newlines an intermediary sends to keep a\n // stream alive: they are skipped instead of failing to parse.\n return data.split('\\n').filter(r => r.trim() !== '').map(r => JSON.parse(r));\n }\n applyDeltaIfNeeded(pub, prevValue) {\n let newData, newPrevValue, wireBytes;\n let isDelta;\n if (pub.delta) {\n isDelta = true;\n // JSON string delta.\n const deltaBytes = new TextEncoder().encode(pub.data);\n const valueArray = applyDelta(prevValue, deltaBytes);\n newData = JSON.parse(new TextDecoder().decode(valueArray));\n newPrevValue = valueArray;\n wireBytes = deltaBytes.length;\n }\n else {\n isDelta = false;\n // Full data as JSON string.\n newData = JSON.parse(pub.data);\n newPrevValue = new TextEncoder().encode(pub.data);\n wireBytes = newPrevValue.length;\n }\n // wireBytes is the UTF-8 byte length of pub.data, not its JS string length\n // (.length counts UTF-16 code units, which undercounts any non-ASCII content).\n return { newData, newPrevValue, isDelta, wireBytes, fullBytes: newPrevValue.length };\n }\n}\n\nconst defaults = {\n headers: {},\n token: '',\n getToken: null,\n data: null,\n getData: null,\n debug: false,\n name: 'js',\n version: '',\n fetch: null,\n readableStream: null,\n websocket: null,\n eventsource: null,\n sockjs: null,\n sockjsOptions: {},\n emulationEndpoint: '/emulation',\n minReconnectDelay: 500,\n maxReconnectDelay: 20000,\n timeout: 5000,\n maxServerPingDelay: 10000,\n networkEventTarget: null,\n pageEventTarget: null,\n};\nconst websocketNotFound = 'WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options';\n// A call or no-ping timer running at least this late means the event loop didn't\n// run meanwhile: the process was suspended or blocked (see _registerCall).\nconst lateCallTimer = 1000;\n// How long such a call still waits for its reply, or the connection for a ping,\n// before failing.\nconst lateCallGrace = 1000;\nfunction errorMessage(err) {\n try {\n return err instanceof Error ? err.message : String(err);\n }\n catch (e) {\n // E.g. a thrown Object.create(null): it has no string form.\n return 'value without a string form';\n }\n}\nclass UnauthorizedError extends Error {\n constructor(message) {\n super(message);\n this.name = this.constructor.name;\n }\n}\n/** Centrifuge is a Centrifuge/Centrifugo bidirectional client. */\nclass Centrifuge extends EventEmitter {\n /** Constructs Centrifuge client. Call connect() method to start connecting. */\n constructor(endpoint, options) {\n super();\n this._reconnectTimeout = null;\n this._connectTimeout = null;\n // Unsubscribes still in progress of subscriptions removed from the client, per channel.\n this._removedUnsubscribes = {};\n // The offset of the publication being dispatched, per server-side channel, until its\n // handler returned. See _handlePublication and the subs of _constructConnectCommand.\n this._pendingServerSubOffsets = {};\n this._refreshTimeout = null;\n this._serverPingTimeout = null;\n /** @internal The number of exceptions escaped from event handlers (see _handlerFailed). */\n this._handlerFailures = 0;\n this.state = State.Disconnected;\n this._transportIsOpen = false;\n this._endpoint = endpoint;\n this._emulation = false;\n this._transports = [];\n this._currentTransportIndex = 0;\n this._triedAllTransports = false;\n this._transportWasOpen = false;\n this._transport = null;\n this._transportId = 0;\n this._deviceWentOffline = false;\n this._transportClosed = true;\n this._codec = new JsonCodec();\n this._reconnecting = false;\n this._reconnectTimeout = null;\n this._connectTimeout = null;\n this._reconnectAttempts = 0;\n this._client = null;\n this._session = '';\n this._node = '';\n this._subs = {};\n this._serverSubs = {};\n this._commandId = 0;\n this._commands = [];\n this._batching = false;\n this._refreshRequired = false;\n this._refreshTimeout = null;\n this._callbacks = {};\n this._token = '';\n this._data = null;\n this._dispatchPromise = Promise.resolve();\n this._serverPing = 0;\n this._serverPingTimeout = null;\n this._sendPong = false;\n this._promises = {};\n this._promiseId = 0;\n this._debugEnabled = false;\n this._networkEvents = null;\n this._pageEvents = null;\n this._pageCached = false;\n this._stateTransitions = 0;\n this._disconnects = 0;\n this._abortedTransportId = 0;\n this._reconnectAttemptsResetPending = false;\n this._config = Object.assign(Object.assign({}, defaults), options);\n this._configure();\n if (this._debugEnabled) {\n this.on('state', (ctx) => {\n this._debug('client state', ctx.oldState, '->', ctx.newState);\n });\n this.on('error', (ctx) => {\n this._debug('client error', ctx);\n });\n }\n else {\n // Avoid unhandled exception in EventEmitter for non-set error handler.\n this.on('error', function () { Function.prototype(); });\n }\n }\n /** newSubscription allocates new Subscription to a channel. Since server only allows\n * one subscription per channel per client this method throws if client already has\n * channel subscription in internal registry.\n * */\n newSubscription(channel, options) {\n if (this.getSubscription(channel) !== null) {\n throw new Error('Subscription to the channel ' + channel + ' already exists');\n }\n const sub = new Subscription(this, channel, options);\n this._subs[channel] = sub;\n return sub;\n }\n /** newMapSubscription allocates new map Subscription to a channel. Since server only allows\n * one subscription per channel per client this method throws if client already has\n * channel subscription in internal registry.\n *\n * Experimental. Requires Centrifugo >= v6.8.0. API may change in a backwards-incompatible\n * way in subsequent minor releases. */\n newMapSubscription(channel, options) {\n if (this.getSubscription(channel) !== null) {\n throw new Error('Subscription to the channel ' + channel + ' already exists');\n }\n const sub = new MapSubscription(this, channel, {\n token: options === null || options === void 0 ? void 0 : options.token,\n getToken: options === null || options === void 0 ? void 0 : options.getToken,\n data: options === null || options === void 0 ? void 0 : options.data,\n minResubscribeDelay: options === null || options === void 0 ? void 0 : options.minResubscribeDelay,\n maxResubscribeDelay: options === null || options === void 0 ? void 0 : options.maxResubscribeDelay,\n delta: options === null || options === void 0 ? void 0 : options.delta,\n tagsFilter: options === null || options === void 0 ? void 0 : options.tagsFilter,\n map: true,\n mapPageSize: options === null || options === void 0 ? void 0 : options.pageSize,\n mapUnrecoverableStrategy: options === null || options === void 0 ? void 0 : options.unrecoverableStrategy,\n });\n this._subs[channel] = sub;\n return sub;\n }\n /** Create a map subscription for observing individual connections (clients presence).\n * Each entry has key=clientId and contains full ClientInfo.\n * Use this to track connections per channel.\n * The channel should be the full presence channel name (e.g., \"$clients:games\").\n *\n * Experimental. Requires Centrifugo >= v6.8.0. API may change in a backwards-incompatible\n * way in subsequent minor releases. */\n newMapClientsSubscription(channel, options) {\n if (this.getSubscription(channel) !== null) {\n throw new Error('Subscription to the channel ' + channel + ' already exists');\n }\n const sub = new MapSubscription(this, channel, {\n token: options === null || options === void 0 ? void 0 : options.token,\n getToken: options === null || options === void 0 ? void 0 : options.getToken,\n data: options === null || options === void 0 ? void 0 : options.data,\n minResubscribeDelay: options === null || options === void 0 ? void 0 : options.minResubscribeDelay,\n maxResubscribeDelay: options === null || options === void 0 ? void 0 : options.maxResubscribeDelay,\n delta: options === null || options === void 0 ? void 0 : options.delta,\n tagsFilter: options === null || options === void 0 ? void 0 : options.tagsFilter,\n map: true,\n mapPresenceType: 2, // MAP_CLIENTS_PRESENCE\n mapPageSize: options === null || options === void 0 ? void 0 : options.pageSize,\n mapUnrecoverableStrategy: options === null || options === void 0 ? void 0 : options.unrecoverableStrategy,\n });\n this._subs[channel] = sub;\n return sub;\n }\n /** Create a map subscription for observing unique users (users presence).\n * Each entry has key=userId (no ClientInfo stored).\n * User entries expire via TTL, providing debounce for quick reconnects.\n * The channel should be the full presence channel name (e.g., \"$users:games\").\n *\n * Experimental. Requires Centrifugo >= v6.8.0. API may change in a backwards-incompatible\n * way in subsequent minor releases. */\n newMapUsersSubscription(channel, options) {\n if (this.getSubscription(channel) !== null) {\n throw new Error('Subscription to the channel ' + channel + ' already exists');\n }\n const sub = new MapSubscription(this, channel, {\n token: options === null || options === void 0 ? void 0 : options.token,\n getToken: options === null || options === void 0 ? void 0 : options.getToken,\n data: options === null || options === void 0 ? void 0 : options.data,\n minResubscribeDelay: options === null || options === void 0 ? void 0 : options.minResubscribeDelay,\n maxResubscribeDelay: options === null || options === void 0 ? void 0 : options.maxResubscribeDelay,\n delta: options === null || options === void 0 ? void 0 : options.delta,\n tagsFilter: options === null || options === void 0 ? void 0 : options.tagsFilter,\n map: true,\n mapPresenceType: 3, // MAP_USERS_PRESENCE\n mapPageSize: options === null || options === void 0 ? void 0 : options.pageSize,\n mapUnrecoverableStrategy: options === null || options === void 0 ? void 0 : options.unrecoverableStrategy,\n });\n this._subs[channel] = sub;\n return sub;\n }\n /** newSharedPollSubscription allocates a new shared poll Subscription to a channel.\n * Shared poll subscriptions use server-side polling to aggregate interest sets\n * and deliver periodic updates with version tracking. Track items after subscribing\n * using the track() method on the returned Subscription.\n *\n * Experimental. Requires Centrifugo >= v6.8.0. API may change in a backwards-incompatible\n * way in subsequent minor releases. */\n newSharedPollSubscription(channel, options) {\n if (this.getSubscription(channel) !== null) {\n throw new Error('Subscription to the channel ' + channel + ' already exists');\n }\n const sub = new SharedPollSubscription(this, channel, {\n token: options === null || options === void 0 ? void 0 : options.token,\n getToken: options === null || options === void 0 ? void 0 : options.getToken,\n data: options === null || options === void 0 ? void 0 : options.data,\n minResubscribeDelay: options === null || options === void 0 ? void 0 : options.minResubscribeDelay,\n maxResubscribeDelay: options === null || options === void 0 ? void 0 : options.maxResubscribeDelay,\n delta: options === null || options === void 0 ? void 0 : options.delta,\n sharedPoll: true,\n sharedPollGetSignature: options === null || options === void 0 ? void 0 : options.getSignature,\n });\n this._subs[channel] = sub;\n return sub;\n }\n /** getSubscription returns Subscription if it's registered in the internal\n * registry or null. */\n getSubscription(channel) {\n return this._getSub(channel);\n }\n /** Get a map subscription by channel. */\n getMapSubscription(channel) {\n return this._getSub(channel);\n }\n /** Get a shared poll subscription by channel. */\n getSharedPollSubscription(channel) {\n return this._getSub(channel);\n }\n /** removeSubscription allows removing Subcription from the internal registry. */\n removeSubscription(sub) {\n if (!sub) {\n return;\n }\n // A subscription removed before must not remove a newer one of its channel.\n if (this._subs[sub.channel] !== sub) {\n return;\n }\n // Removed before its unsubscribed event: a handler of it may create a new\n // subscription of the channel, and must not subscribe this one again.\n delete this._subs[sub.channel];\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n sub._removed = true;\n if (sub.state !== SubscriptionState.Unsubscribed) {\n sub.unsubscribe();\n }\n this._recordRemovedUnsubscribe(sub);\n }\n /** Remove a map subscription. */\n removeMapSubscription(sub) {\n this.removeSubscription(sub);\n }\n /** Remove a shared poll subscription. */\n removeSharedPollSubscription(sub) {\n this.removeSubscription(sub);\n }\n /** Get a map with all current client-side subscriptions. */\n subscriptions() {\n return this._subs;\n }\n /** Get all map subscriptions. */\n mapSubscriptions() {\n const result = {};\n for (const [ch, sub] of Object.entries(this._subs)) {\n if (sub.type === 'map')\n result[ch] = sub;\n }\n return result;\n }\n /** Get all shared poll subscriptions. */\n sharedPollSubscriptions() {\n const result = {};\n for (const [ch, sub] of Object.entries(this._subs)) {\n if (sub.type === 'shared_poll')\n result[ch] = sub;\n }\n return result;\n }\n /** ready returns a Promise which resolves upon client goes to Connected\n * state and rejects in case of client goes to Disconnected or Failed state.\n * Users can provide optional timeout in milliseconds. */\n ready(timeout) {\n return __awaiter(this, void 0, void 0, function* () {\n switch (this.state) {\n case State.Disconnected:\n throw { code: errorCodes.clientDisconnected, message: 'client disconnected' };\n case State.Connected:\n return;\n default:\n return new Promise((resolve, reject) => {\n const id = this._nextPromiseId();\n const ctx = { resolve, reject };\n if (timeout) {\n ctx.timeout = setTimeout(() => {\n // A call that gave up waiting leaves no waiter behind.\n delete this._promises[id];\n reject({ code: errorCodes.timeout, message: 'timeout' });\n }, timeout);\n }\n this._promises[id] = ctx;\n });\n }\n });\n }\n /** connect to a server. */\n connect() {\n if (this._isConnected()) {\n this._debug('connect called when already connected');\n return;\n }\n if (this._isConnecting()) {\n this._debug('connect called when already connecting');\n return;\n }\n this._debug('connect called');\n // Throws for a configuration no retry can fix, before the state changes.\n this._validateTransportConfig();\n this._reconnectAttempts = 0;\n this._startConnecting();\n }\n /** disconnect from a server. */\n disconnect() {\n this._disconnect(disconnectedCodes.disconnectCalled, 'disconnect called', false);\n }\n /** setToken allows setting connection token. Or resetting used token to be empty. */\n setToken(token) {\n this._token = token;\n if (this._config.getToken === null) {\n // The token expired, and the app set a new one: without getToken there is no\n // other way to get it, so the next attempt uses it instead of failing on a\n // configuration error. With getToken, the next attempt still gets a new token:\n // the one set meanwhile may be the expired one.\n this._refreshRequired = false;\n }\n }\n /** setData allows setting connection data. This only affects the next connection attempt,\n * not the current one. Note that if getData callback is configured, it will override\n * this value during reconnects. */\n setData(data) {\n this._data = data;\n }\n /** setHeaders allows setting connection emulated headers. */\n setHeaders(headers) {\n this._config.headers = headers;\n }\n /** send asynchronous data to a server (without any response from a server\n * expected, see rpc method if you need response). */\n send(data) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = {\n send: {\n data\n }\n };\n yield this._methodCall();\n const sent = this._transportSendCommands([cmd]); // can send message to server without id set\n if (!sent) {\n throw this._createErrorObject(errorCodes.transportWriteError, 'transport write error');\n }\n });\n }\n /** rpc to a server - i.e. a call which waits for a response with data. */\n rpc(method, data) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = {\n rpc: {\n method,\n data\n }\n };\n yield this._methodCall();\n const result = yield this._callPromise(cmd, (reply) => reply.rpc);\n return {\n data: result.data\n };\n });\n }\n /** publish data to a channel. */\n publish(channel, data) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = {\n publish: {\n channel,\n data\n }\n };\n yield this._methodCall();\n yield this._callPromise(cmd, () => ({}));\n return {};\n });\n }\n /** Publish data to a key in a map channel without holding a MapSubscription.\n * Use this when you need to write to a map channel from outside a subscription\n * context (e.g. a standalone publisher). When you already hold a MapSubscription,\n * prefer `sub.publish(key, data)` instead \u2014 it enforces the method-call guard and\n * applies debounce configuration. */\n mapPublish(channel, key, data) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = {\n publish: { channel, type: 1, key, data }\n };\n yield this._methodCall();\n yield this._callPromise(cmd, () => ({}));\n return {};\n });\n }\n /** Remove a key from a map channel without holding a MapSubscription.\n * Use this when you need to remove a key from outside a subscription context.\n * When you already hold a MapSubscription, prefer `sub.remove(key)` instead \u2014\n * it enforces the method-call guard and cancels any pending debounced publish. */\n mapRemove(channel, key) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = {\n publish: { channel, type: 1, key, removed: true }\n };\n yield this._methodCall();\n yield this._callPromise(cmd, () => ({}));\n return {};\n });\n }\n /** history for a channel. By default it does not return publications (only current\n * StreamPosition data) \u2013 provide an explicit limit > 0 to load publications.*/\n history(channel, options) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = {\n history: this._getHistoryRequest(channel, options)\n };\n yield this._methodCall();\n const result = yield this._callPromise(cmd, (reply) => reply.history);\n const publications = [];\n if (result.publications) {\n for (let i = 0; i < result.publications.length; i++) {\n publications.push(this._getPublicationContext(channel, result.publications[i]));\n }\n }\n return {\n publications,\n epoch: result.epoch || '',\n offset: toOffset(result.offset)\n };\n });\n }\n /** presence for a channel. */\n presence(channel) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = {\n presence: {\n channel\n }\n };\n yield this._methodCall();\n const result = yield this._callPromise(cmd, (reply) => reply.presence);\n const clients = result.presence;\n for (const clientId in clients) {\n if (Object.prototype.hasOwnProperty.call(clients, clientId)) {\n const rawClient = clients[clientId];\n const connInfo = rawClient['conn_info'];\n const chanInfo = rawClient['chan_info'];\n if (connInfo) {\n rawClient.connInfo = connInfo;\n }\n if (chanInfo) {\n rawClient.chanInfo = chanInfo;\n }\n }\n }\n return { clients };\n });\n }\n presenceStats(channel) {\n return __awaiter(this, void 0, void 0, function* () {\n const cmd = {\n 'presence_stats': {\n channel\n }\n };\n yield this._methodCall();\n const result = yield this._callPromise(cmd, (reply) => {\n return reply.presence_stats;\n });\n return {\n numUsers: result.num_users,\n numClients: result.num_clients\n };\n });\n }\n /** start command batching (collect into temporary buffer without sending to a server)\n * until stopBatching called.*/\n startBatching() {\n // start collecting messages without sending them to Centrifuge until flush\n // method called\n this._batching = true;\n }\n /** stop batching commands and flush collected commands to the\n * network (all in one request/frame).*/\n stopBatching() {\n const self = this;\n // Why so nested? Two levels here requred to deal with promise resolving queue.\n // In Subscription case we wait 2 futures before sending data to connection.\n // Otherwise _batching becomes false before batching decision has a chance to be executed.\n Promise.resolve().then(function () {\n Promise.resolve().then(function () {\n self._batching = false;\n self._flush();\n });\n });\n }\n _debug(...args) {\n if (!this._debugEnabled) {\n return;\n }\n log('debug', args);\n }\n _codecName() {\n return this._codec.name();\n }\n /** @internal */\n _formatOverride() {\n return;\n }\n _configure() {\n if (!('Promise' in globalThis)) {\n throw new Error('Promise polyfill required');\n }\n if (!this._endpoint) {\n throw new Error('endpoint configuration required');\n }\n if (this._config.token !== null) {\n this._token = this._config.token;\n }\n if (this._config.data !== null) {\n this._data = this._config.data;\n }\n this._codec = new JsonCodec();\n this._formatOverride();\n if (this._config.debug === true || localStorageItem('centrifuge.debug')) {\n this._debugEnabled = true;\n }\n this._debug('config', this._config);\n if (typeof this._endpoint === 'string') ;\n else if (Array.isArray(this._endpoint)) {\n this._transports = this._endpoint;\n this._emulation = true;\n for (const i in this._transports) {\n if (this._transports.hasOwnProperty(i)) {\n const transportConfig = this._transports[i];\n if (!transportConfig.endpoint || !transportConfig.transport) {\n throw new Error('malformed transport configuration');\n }\n const transportName = transportConfig.transport;\n if (['websocket', 'http_stream', 'sse', 'sockjs', 'webtransport'].indexOf(transportName) < 0) {\n throw new Error('unsupported transport name: ' + transportName);\n }\n }\n }\n }\n else {\n throw new Error('unsupported url configuration type: only string or array of objects are supported');\n }\n }\n // Returns the number of the transition made, or 0 if the client already was in newState.\n _setState(newState) {\n if (this.state !== newState) {\n this._reconnecting = false;\n const oldState = this.state;\n this.state = newState;\n const transition = ++this._stateTransitions;\n // Keep network listeners in sync with the state before emitting: a 'state'\n // handler may call connect() or disconnect() synchronously.\n if (newState === State.Connecting) {\n this._setNetworkEvents();\n this._setPageEvents();\n }\n else if (newState === State.Disconnected) {\n this._clearNetworkEvents();\n this._clearPageEvents();\n }\n this.emit('state', { newState, oldState });\n return transition;\n }\n return 0;\n }\n // Whether an event handler made another state transition after the given one\n // (as returned by _setState), so that the given one is outdated.\n _transitionSuperseded(transition) {\n return transition !== 0 && this._stateTransitions !== transition;\n }\n _isDisconnected() {\n return this.state === State.Disconnected;\n }\n _isConnecting() {\n return this.state === State.Connecting;\n }\n _isConnected() {\n return this.state === State.Connected;\n }\n _nextCommandId() {\n return ++this._commandId;\n }\n _setNetworkEvents() {\n if (this._networkEvents !== null) {\n return;\n }\n let eventTarget = null;\n if (this._config.networkEventTarget !== null) {\n eventTarget = this._config.networkEventTarget;\n }\n else if (typeof globalThis.addEventListener !== 'undefined') {\n eventTarget = globalThis;\n }\n if (eventTarget) {\n const onOffline = () => {\n this._debug('offline event triggered');\n if (this.state === State.Connected || this.state === State.Connecting) {\n // Set first: a handler of the events emitted by the disconnect may call\n // disconnect(), which resets it.\n this._deviceWentOffline = true;\n this._disconnect(connectingCodes.transportClosed, 'transport closed', true);\n }\n };\n const onOnline = () => {\n this._debug('online event triggered');\n const wentOffline = this._deviceWentOffline;\n this._deviceWentOffline = false;\n if (this.state !== State.Connecting) {\n return;\n }\n if (wentOffline && !this._transportClosed) {\n // A reconnect attempt opened a transport while the device was offline.\n // Mobile Safari may never issue the close callback for it, so abort it\n // explicitly and start over. The transport ID changes, so a close\n // callback issued later is ignored. The rejection of a connect command\n // still pending on it is not an error to report (see _sendConnect).\n this._abortedTransportId = this._transportId;\n this._disconnect(connectingCodes.transportClosed, 'transport closed', true);\n }\n this._clearReconnectTimeout();\n this._startReconnecting();\n };\n eventTarget.addEventListener('offline', onOffline);\n eventTarget.addEventListener('online', onOnline);\n this._networkEvents = { target: eventTarget, onOffline, onOnline };\n }\n }\n // The online listener drives reconnect, so listeners stay until the client is\n // disconnected; removing them then lets a disconnected client be garbage-collected.\n _clearNetworkEvents() {\n if (this._networkEvents === null) {\n return;\n }\n const { target, onOffline, onOnline } = this._networkEvents;\n if (!isFunction(target.removeEventListener)) {\n this._debug('network event target has no removeEventListener, listeners kept');\n return;\n }\n target.removeEventListener('offline', onOffline);\n target.removeEventListener('online', onOnline);\n this._networkEvents = null;\n }\n // A page entering the back/forward cache is frozen, but the browser may keep its\n // socket open: the server then sees a client that stopped answering pings. So the\n // transport is closed when the page is hidden into the cache, and the client\n // reconnects as soon as the page is restored from it. The reconnect is scheduled\n // as usual too: its timer does not run in a frozen page, and it still reconnects\n // a page which was not frozen, or was restored without a pageshow event.\n _setPageEvents() {\n if (this._pageEvents !== null) {\n return;\n }\n let eventTarget = null;\n if (this._config.pageEventTarget !== null) {\n eventTarget = this._config.pageEventTarget;\n }\n else if (typeof globalThis.addEventListener !== 'undefined') {\n eventTarget = globalThis;\n }\n if (!eventTarget) {\n return;\n }\n const onPageHide = (e) => {\n if (!e.persisted) {\n return;\n }\n this._debug('page entered back/forward cache');\n if (this.state === State.Connected || this.state === State.Connecting) {\n // Set first: a handler of the events emitted by the disconnect may call\n // disconnect(), which resets it.\n this._pageCached = true;\n this._disconnect(connectingCodes.transportClosed, 'page entered back/forward cache', true);\n }\n };\n const onPageShow = (e) => {\n if (!e.persisted) {\n return;\n }\n this._debug('page restored from back/forward cache');\n const cached = this._pageCached;\n this._pageCached = false;\n if (!cached || this.state !== State.Connecting) {\n return;\n }\n this._clearReconnectTimeout();\n this._startReconnecting();\n };\n eventTarget.addEventListener('pagehide', onPageHide);\n eventTarget.addEventListener('pageshow', onPageShow);\n this._pageEvents = { target: eventTarget, onPageHide, onPageShow };\n }\n // Removed once the client is disconnected, like the network listeners.\n _clearPageEvents() {\n if (this._pageEvents === null) {\n return;\n }\n const { target, onPageHide, onPageShow } = this._pageEvents;\n if (!isFunction(target.removeEventListener)) {\n this._debug('page event target has no removeEventListener, listeners kept');\n return;\n }\n target.removeEventListener('pagehide', onPageHide);\n target.removeEventListener('pageshow', onPageShow);\n this._pageEvents = null;\n }\n _getReconnectDelay() {\n const delay = backoff(this._reconnectAttempts, this._config.minReconnectDelay, this._config.maxReconnectDelay);\n this._reconnectAttempts += 1;\n return delay;\n }\n // See _connectResponse: an emulation connection resets the backoff once it\n // proved usable.\n _resetReconnectAttemptsIfPending() {\n if (this._reconnectAttemptsResetPending) {\n this._reconnectAttemptsResetPending = false;\n this._reconnectAttempts = 0;\n }\n }\n _clearOutgoingRequests() {\n // fire errbacks of registered outgoing calls.\n for (const id in this._callbacks) {\n if (this._callbacks.hasOwnProperty(id)) {\n const callbacks = this._callbacks[id];\n clearTimeout(callbacks.timeout);\n const errback = callbacks.errback;\n if (!errback) {\n continue;\n }\n errback({ error: this._createErrorObject(errorCodes.connectionClosed, 'connection closed') });\n }\n }\n this._callbacks = {};\n }\n _clearConnectedState() {\n this._client = null;\n this._clearServerPingTimeout();\n this._clearRefreshTimeout();\n // fire events for client-side subscriptions.\n for (const channel in this._subs) {\n if (!this._subs.hasOwnProperty(channel)) {\n continue;\n }\n const sub = this._subs[channel];\n if (sub.state === SubscriptionState.Subscribed) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n sub._setSubscribing(subscribingCodes.transportClosed, 'transport closed');\n }\n }\n // fire events for server-side subscriptions, once per subscribed period.\n for (const channel in this._serverSubs) {\n if (this._serverSubs.hasOwnProperty(channel) && this._serverSubs[channel].subscribed) {\n this._serverSubs[channel].subscribed = false;\n this.emit('subscribing', { channel: channel });\n }\n }\n }\n _handleWriteError(commands) {\n for (const command of commands) {\n const id = command.id;\n if (!(id in this._callbacks)) {\n continue;\n }\n const callbacks = this._callbacks[id];\n clearTimeout(this._callbacks[id].timeout);\n delete this._callbacks[id];\n const errback = callbacks.errback;\n errback({ error: this._createErrorObject(errorCodes.transportWriteError, 'transport write error') });\n }\n }\n _transportSendCommands(commands) {\n if (!commands.length) {\n return true;\n }\n if (!this._transport) {\n return false;\n }\n try {\n this._transport.send(this._codec.encodeCommands(commands), this._session, this._node);\n }\n catch (e) {\n this._debug('error writing commands', e);\n this._handleWriteError(commands);\n return false;\n }\n return true;\n }\n _advanceTransportIndex() {\n this._currentTransportIndex++;\n if (this._currentTransportIndex >= this._transports.length) {\n this._triedAllTransports = true;\n this._currentTransportIndex = 0;\n }\n }\n // Transport dependencies from the config, or else from globals. An absent one\n // stays null, not undefined: supported() of sockjs, sse and http_stream only\n // checks `!== null`.\n _resolveTransportDeps() {\n let websocket;\n if (this._config.websocket !== null) {\n websocket = this._config.websocket;\n }\n else {\n if (!(typeof globalThis.WebSocket !== 'function' && typeof globalThis.WebSocket !== 'object')) {\n websocket = globalThis.WebSocket;\n }\n }\n let sockjs = null;\n if (this._config.sockjs !== null) {\n sockjs = this._config.sockjs;\n }\n else {\n if (typeof globalThis.SockJS !== 'undefined') {\n sockjs = globalThis.SockJS;\n }\n }\n let eventsource = null;\n if (this._config.eventsource !== null) {\n eventsource = this._config.eventsource;\n }\n else {\n if (typeof globalThis.EventSource !== 'undefined') {\n eventsource = globalThis.EventSource;\n }\n }\n let fetchFunc = null;\n if (this._config.fetch !== null) {\n fetchFunc = this._config.fetch;\n }\n else {\n if (typeof globalThis.fetch !== 'undefined') {\n fetchFunc = globalThis.fetch;\n }\n }\n let readableStream = null;\n if (this._config.readableStream !== null) {\n readableStream = this._config.readableStream;\n }\n else {\n if (typeof globalThis.ReadableStream !== 'undefined') {\n readableStream = globalThis.ReadableStream;\n }\n }\n return { websocket, sockjs, eventsource, fetchFunc, readableStream };\n }\n // Constructs a transport, without checking that it is supported.\n _createTransport(transportName, endpoint, deps) {\n switch (transportName) {\n case 'websocket':\n return new WebsocketTransport(endpoint, {\n websocket: deps.websocket\n });\n case 'webtransport':\n return new WebtransportTransport(endpoint, {\n webtransport: globalThis.WebTransport,\n decoder: this._codec,\n encoder: this._codec\n });\n case 'http_stream':\n return new HttpStreamTransport(endpoint, {\n fetch: deps.fetchFunc,\n readableStream: deps.readableStream,\n emulationEndpoint: this._config.emulationEndpoint,\n decoder: this._codec,\n encoder: this._codec\n });\n case 'sse':\n return new SseTransport(endpoint, {\n eventsource: deps.eventsource,\n fetch: deps.fetchFunc,\n emulationEndpoint: this._config.emulationEndpoint,\n });\n case 'sockjs':\n return new SockjsTransport(endpoint, {\n sockjs: deps.sockjs,\n sockjsOptions: this._config.sockjsOptions\n });\n default:\n throw new Error('unknown transport ' + transportName);\n }\n }\n // Throws for a configuration no retry can fix. Called from connect() before\n // the state changes, so the client stays disconnected, and before a token or\n // data is loaded, so it fails the same way with getToken or getData.\n _validateTransportConfig() {\n const deps = this._resolveTransportDeps();\n if (!this._emulation) {\n if (startsWith(this._endpoint, 'http')) {\n throw new Error('Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport');\n }\n if (!this._createTransport('websocket', this._endpoint, deps).supported()) {\n throw new Error(websocketNotFound);\n }\n return;\n }\n for (const transportConfig of this._transports) {\n if (this._createTransport(transportConfig.transport, transportConfig.endpoint, deps).supported()) {\n return;\n }\n }\n throw new Error('no supported transport found');\n }\n _initializeTransport() {\n const deps = this._resolveTransportDeps();\n let selected = null;\n if (!this._emulation) {\n this._debug('client will use websocket');\n const candidate = this._createTransport('websocket', this._endpoint, deps);\n if (candidate.supported()) {\n selected = candidate;\n }\n }\n else {\n if (this._currentTransportIndex >= this._transports.length) {\n this._triedAllTransports = true;\n this._currentTransportIndex = 0;\n }\n for (let count = 0; count < this._transports.length; count++) {\n const transportConfig = this._transports[this._currentTransportIndex];\n this._debug('trying ' + transportConfig.transport + ' transport');\n const candidate = this._createTransport(transportConfig.transport, transportConfig.endpoint, deps);\n if (candidate.supported()) {\n selected = candidate;\n break;\n }\n this._debug(transportConfig.transport + ' transport not available');\n this._advanceTransportIndex();\n }\n }\n if (selected === null) {\n // connect() checked that a transport can be used, so a dependency went away\n // under a running client. A reconnect timer has no caller to throw to:\n // report it as a transport failure and retry.\n const message = this._emulation ? 'no supported transport found' : websocketNotFound;\n this._debug(message);\n this._disconnect(connectingCodes.transportClosed, 'transport closed', true);\n this.emit('error', {\n type: 'transport',\n error: {\n code: errorCodes.transportClosed,\n message: message\n }\n });\n return;\n }\n this._transport = selected;\n const self = this;\n const transport = this._transport;\n const transportId = this._nextTransportId();\n self._debug(\"id of transport\", transportId);\n let wasOpen = false;\n const initialCommands = [];\n if (this._transport.emulation()) {\n const connectCommand = self._sendConnect(true);\n initialCommands.push(connectCommand);\n }\n this._transportClosed = false;\n // Fails an attempt that did not open in time or could not be initialized. It\n // does not wait for the transport's close callback: a transport may never\n // issue one, e.g. a replaced WebSocket whose close() does nothing.\n const failTransport = function (reason) {\n if (self._transportId != transportId) {\n self._debug('failure of non-actual transport', reason);\n return;\n }\n self._debug(transport.name(), 'transport failed:', reason);\n if (self._emulation && !self._transportWasOpen) {\n self._advanceTransportIndex();\n }\n // The teardown rejects a connect command pending on it: the transport error\n // below reports the failure, not a connect error too.\n self._abortedTransportId = transportId;\n // Closes the transport and clears the connect timeout.\n self._disconnect(connectingCodes.transportClosed, 'transport closed', true);\n self.emit('error', {\n type: 'transport',\n error: {\n code: errorCodes.transportClosed,\n message: reason\n },\n transport: transport.name()\n });\n };\n this._clearConnectTimeout();\n const connectDue = Date.now() + this._config.timeout;\n this._connectTimeout = setTimeout(function () {\n // The transport may have opened already, its open callback not run yet, e.g.\n // when a suspended process resumes: let it run first, as for a call (see\n // _registerCall). The open callback clears this timeout.\n const late = Date.now() - connectDue >= lateCallTimer;\n self._connectTimeout = setTimeout(function () {\n self._connectTimeout = null;\n failTransport('connect timeout');\n }, late ? lateCallGrace : 0);\n }, this._config.timeout);\n const callbacks = {\n onOpen: function () {\n if (self._transportId != transportId) {\n self._debug('open callback from non-actual transport');\n try {\n transport.close();\n }\n catch (e) {\n // E.g. a replaced WebSocket without a working close().\n self._debug('error closing transport', e);\n }\n return;\n }\n // Only after the check: the connect timeout belongs to the current attempt.\n self._clearConnectTimeout();\n wasOpen = true;\n self._debug(transport.subName(), 'transport open');\n if (transport.emulation()) {\n return;\n }\n self._transportIsOpen = true;\n // A socket that opened keeps its transport, as in 5.7.4: a slow first connect\n // reply must not move the client to a fallback transport for good.\n self._transportWasOpen = true;\n self.startBatching();\n try {\n self._sendConnect(false);\n self._sendSubscribeCommands();\n }\n catch (e) {\n // E.g. thrown by an app callback of a subscription: the commands collected\n // still go out, instead of staying batched for the next transport.\n self._reportDispatchError(e);\n }\n finally {\n self.stopBatching();\n }\n //@ts-ignore must be used only for debug and test purposes. Exposed only for non-emulation transport.\n self.emit('__centrifuge_debug:connect_frame_sent', {});\n },\n onError: function (e) {\n if (self._transportId != transportId) {\n self._debug('error callback from non-actual transport');\n return;\n }\n self._debug('transport level error', e);\n },\n onClose: function handleClose(closeEvent, dispatched) {\n if (self._transportId != transportId) {\n self._debug('close callback from non-actual transport');\n return;\n }\n if (!dispatched && (transport.emulation() || transport.name() === 'webtransport')) {\n // A stream may end in the same task as the data read before it, e.g. the\n // server's disconnect push written before it closes the connection: that\n // data is dispatched first, as a websocket's messages are before its close\n // event. A disconnect push ends this transport, and this callback with it.\n self._dispatchPromise.then(() => handleClose(closeEvent, true));\n return;\n }\n self._clearConnectTimeout();\n self._debug(transport.subName(), 'transport closed');\n self._transportClosed = true;\n self._transportIsOpen = false;\n let reason = 'connection closed';\n let needReconnect = true;\n let code = 0;\n if (closeEvent && 'code' in closeEvent && closeEvent.code) {\n code = closeEvent.code;\n }\n if (closeEvent && closeEvent.reason) {\n try {\n const advice = JSON.parse(closeEvent.reason);\n reason = advice.reason;\n needReconnect = advice.reconnect;\n }\n catch (e) {\n reason = closeEvent.reason;\n if ((code >= 3500 && code < 4000) || (code >= 4500 && code < 5000)) {\n needReconnect = false;\n }\n }\n }\n if (code < 3000) {\n if (code === 1009) {\n code = disconnectedCodes.messageSizeLimit;\n reason = 'message size limit exceeded';\n needReconnect = false;\n }\n else {\n code = connectingCodes.transportClosed;\n reason = 'transport closed';\n }\n if (self._emulation && !self._transportWasOpen) {\n self._advanceTransportIndex();\n }\n }\n else {\n // Codes >= 3000 are sent from a server application level.\n self._transportWasOpen = true;\n }\n const teardown = function () {\n self._reconnecting = false;\n self._disconnect(code, reason, needReconnect);\n };\n if (self._isConnecting() && !wasOpen) {\n // The teardown rejects a connect command pending on it (emulation): this\n // transport error reports the failure, not a connect error too.\n self._abortedTransportId = transportId;\n self._emitError({\n type: 'transport',\n error: {\n code: errorCodes.transportClosed,\n message: 'transport closed'\n },\n transport: transport.name()\n }, teardown);\n }\n else {\n teardown();\n }\n },\n onMessage: function (data) {\n if (self._transportId != transportId) {\n // A frame from a transport that was already closed or replaced.\n self._debug('message from non-actual transport');\n return;\n }\n self._dataReceived(data, transportId);\n }\n };\n // A transport that fails to initialize, e.g. a socket constructor throwing on\n // a malformed URL or on an insecure one from a secure page, issues no close\n // callback either.\n const onInitializeError = function (e) {\n self._debug('error initializing transport', e);\n failTransport(e instanceof Error ? e.message : String(e));\n };\n let initialized;\n try {\n // Encoded here: commands the codec can't encode, e.g. connect data with a BigInt,\n // fail the attempt as a transport failing to initialize, not connect().\n initialized = transport.initialize(this._codecName(), callbacks, this._codec.encodeCommands(initialCommands));\n }\n catch (e) {\n onInitializeError(e);\n return;\n }\n if (initialized && isFunction(initialized.then)) {\n // WebTransport initializes asynchronously.\n initialized.then(null, onInitializeError);\n }\n //@ts-ignore must be used only for debug and test purposes.\n self.emit('__centrifuge_debug:transport_initialized', {});\n }\n _sendConnect(skipSending) {\n const connectCommand = this._constructConnectCommand();\n const self = this;\n // A teardown rejects the pending command, and the rejection is processed after\n // it: a newer attempt may have started by then, which must not be torn down.\n const transportId = this._transportId;\n const token = this._token;\n // An exception while handling the reply stops the client (see _dispatchFailed).\n // next() is still called, so replies of a later connection aren't blocked.\n this._call(connectCommand, skipSending).then(resolveCtx => {\n try {\n self._connectResponse(resolveCtx.reply.connect);\n }\n catch (err) {\n self._dispatchFailed(err);\n }\n finally {\n if (resolveCtx.next) {\n resolveCtx.next();\n }\n }\n }, rejectCtx => {\n try {\n if (transportId === self._abortedTransportId) {\n self._debug('connect command of a transport aborted by the client rejected');\n }\n else {\n // An error in a reply comes with next(): a rejection by a timeout, a write\n // error or a teardown doesn't.\n self._connectError(rejectCtx.error, self._transportId !== transportId, rejectCtx.next !== undefined, token);\n }\n }\n catch (err) {\n self._rejectionFailed(err, rejectCtx);\n }\n finally {\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n }\n });\n return connectCommand;\n }\n _startReconnecting() {\n this._debug('start reconnecting');\n if (!this._isConnecting()) {\n this._debug('stop reconnecting: client not in connecting state');\n return;\n }\n if (this._reconnecting) {\n this._debug('reconnect already in progress, return from reconnect routine');\n return;\n }\n if (this._transportClosed === false) {\n this._debug('waiting for transport close');\n return;\n }\n this._reconnecting = true;\n // A disconnect while the token/data is loading aborts this attempt (a new one\n // is scheduled by the disconnect), so the continuations below must not act on\n // it. Not the transport id: _initializeTransport changes it too, and its\n // exceptions must still reach the error handlers below.\n const disconnects = this._disconnects;\n const emptyToken = this._token === '';\n const needTokenRefresh = this._refreshRequired || (emptyToken && this._config.getToken !== null);\n // Whether the token or data promise resolved: an error caught after that was thrown\n // by the continuation, e.g. by an event handler, and must not be lost.\n let tokenResolved = false;\n let dataResolved = false;\n if (!needTokenRefresh) {\n if (this._config.getData) {\n this._getData().then(data => {\n dataResolved = true;\n if (this._attemptAborted(disconnects)) {\n return;\n }\n this._data = data;\n this._initializeTransport();\n })\n .catch(e => this._handleGetDataError(e, disconnects, dataResolved));\n }\n else {\n this._initializeTransport();\n }\n return;\n }\n const self = this;\n this._getToken().then(function (token) {\n tokenResolved = true;\n if (self._attemptAborted(disconnects)) {\n return;\n }\n if (token == null || token == undefined) {\n self._failUnauthorized();\n return;\n }\n self._token = token;\n self._debug('connection token refreshed');\n if (self._config.getData) {\n self._getData().then(function (data) {\n dataResolved = true;\n if (self._attemptAborted(disconnects)) {\n return;\n }\n self._data = data;\n self._initializeTransport();\n })\n .catch(e => self._handleGetDataError(e, disconnects, dataResolved));\n }\n else {\n self._initializeTransport();\n }\n }).catch(function (e) {\n if (self._attemptAborted(disconnects)) {\n if (tokenResolved) {\n self._reportDispatchError(e);\n }\n return;\n }\n if (e instanceof UnauthorizedError) {\n self._failUnauthorized();\n return;\n }\n self._emitError({\n 'type': 'connectToken',\n 'error': {\n code: errorCodes.clientConnectToken,\n message: e !== undefined ? e.toString() : ''\n }\n }, () => {\n const delay = self._getReconnectDelay();\n self._debug('error on getting connection token, reconnect after ' + delay + ' milliseconds', e);\n self._reconnecting = false;\n self._reconnectTimeout = setTimeout(() => {\n self._startReconnecting();\n }, delay);\n });\n });\n }\n // Emits an error event, then runs the continuation: not when a handler disconnected\n // the client (or threw, which disconnects it), maybe to connect again, whose new\n // attempt the continuation must not touch.\n _emitError(ctx, continuation) {\n const disconnects = this._disconnects;\n try {\n this.emit('error', ctx);\n }\n finally {\n if (this._disconnects === disconnects) {\n continuation();\n }\n }\n }\n _attemptAborted(disconnects) {\n return !this._isConnecting() || this._disconnects !== disconnects;\n }\n // resolved: the data promise resolved, so the error was thrown by its continuation.\n _handleGetDataError(e, disconnects, resolved) {\n if (this._attemptAborted(disconnects)) {\n if (resolved) {\n // E.g. by an event handler of the teardown that ended the attempt.\n this._reportDispatchError(e);\n }\n return;\n }\n if (e instanceof UnauthorizedError) {\n this._failUnauthorized();\n return;\n }\n this._emitError({\n type: 'connectData',\n error: {\n code: errorCodes.badConfiguration,\n message: (e === null || e === void 0 ? void 0 : e.toString()) || ''\n }\n }, () => {\n const delay = this._getReconnectDelay();\n this._debug('error on getting connect data, reconnect after ' + delay + ' milliseconds', e);\n this._reconnecting = false;\n this._reconnectTimeout = setTimeout(() => {\n this._startReconnecting();\n }, delay);\n });\n }\n // stale: the error belongs to a transport that was already closed. It is still\n // reported, but must not tear down the current connection attempt.\n // replied: the server returned the error in a reply, so the transport works.\n // token: the token the connect command carried.\n _connectError(err, stale, replied, token) {\n if (this.state !== State.Connecting) {\n return;\n }\n // Token expired: the next attempt gets a new one, unless the app set a new one\n // meanwhile (see setToken).\n if (err.code === 109 && token === this._token) {\n this._refreshRequired = true;\n }\n if (err.code < 100 || err.temporary === true || err.code === 109) {\n this._emitError({\n 'type': 'connect',\n 'error': err\n }, () => {\n if (stale) {\n return;\n }\n if (replied) {\n // The transport reached the server: retry it after the reconnect delay, not\n // at once with the next transport as for one that failed to open. An\n // emulation transport is otherwise marked open only by a connect reply.\n this._transportWasOpen = true;\n }\n if (!replied && this._emulation && !this._transportWasOpen) {\n // A handshake the server never answered, e.g. timed out, moves on to the next\n // transport before any reply, but not after a socket opened (see onOpen). For\n // other failures the transport's close callback does that, but it is ignored\n // after the teardown below.\n this._advanceTransportIndex();\n }\n this._debug('closing transport due to connect error');\n this._disconnect(err.code, err.message, true);\n });\n }\n else if (!stale) {\n this._disconnect(err.code, err.message, false);\n }\n }\n _scheduleReconnect() {\n if (!this._isConnecting()) {\n return;\n }\n let isInitialHandshake = false;\n if (this._emulation && !this._transportWasOpen && !this._triedAllTransports) {\n isInitialHandshake = true;\n }\n // The first round over the transports doesn't count towards the backoff.\n const delay = isInitialHandshake ? 0 : this._getReconnectDelay();\n this._debug('reconnect after ' + delay + ' milliseconds');\n this._clearReconnectTimeout();\n this._reconnectTimeout = setTimeout(() => {\n this._startReconnecting();\n }, delay);\n }\n _constructConnectCommand() {\n const req = {};\n if (this._token) {\n req.token = this._token;\n }\n if (this._data) {\n req.data = this._data;\n }\n if (this._config.name) {\n req.name = this._config.name;\n }\n if (this._config.version) {\n req.version = this._config.version;\n }\n if (Object.keys(this._config.headers).length > 0) {\n req.headers = this._config.headers;\n }\n const subs = {};\n let hasSubs = false;\n for (const channel in this._serverSubs) {\n if (this._serverSubs.hasOwnProperty(channel) && this._serverSubs[channel].recoverable) {\n hasSubs = true;\n const sub = {\n 'recover': true\n };\n // A publication being dispatched counts as delivered: a connect command built\n // from its handler recovers after it, while the stored position still holds\n // the previous one until that handler returned (see _handlePublication).\n const pending = this._pendingServerSubOffsets[channel];\n const offset = pending !== undefined && pending !== null ? pending : this._serverSubs[channel].offset;\n if (offset) {\n sub['offset'] = offset;\n }\n if (this._serverSubs[channel].epoch) {\n sub['epoch'] = this._serverSubs[channel].epoch;\n }\n subs[channel] = sub;\n }\n }\n if (hasSubs) {\n req.subs = subs;\n }\n return {\n connect: req\n };\n }\n _getHistoryRequest(channel, options) {\n const req = {\n channel: channel\n };\n if (options !== undefined) {\n if (options.since) {\n req.since = {\n offset: options.since.offset\n };\n if (options.since.epoch) {\n req.since.epoch = options.since.epoch;\n }\n }\n if (options.limit !== undefined) {\n req.limit = options.limit;\n }\n if (options.reverse === true) {\n req.reverse = true;\n }\n }\n return req;\n }\n _methodCall() {\n if (this._isConnected()) {\n return Promise.resolve();\n }\n return new Promise((res, rej) => {\n const id = this._nextPromiseId();\n const timeout = setTimeout(() => {\n delete this._promises[id];\n rej({ code: errorCodes.timeout, message: 'timeout' });\n }, this._config.timeout);\n this._promises[id] = {\n timeout: timeout,\n resolve: res,\n reject: rej\n };\n });\n }\n _callPromise(cmd, resultCB) {\n return new Promise((resolve, reject) => {\n this._call(cmd, false).then((resolveCtx) => {\n var _a;\n try {\n resolve(resultCB(resolveCtx.reply));\n }\n catch (e) {\n reject(e);\n }\n finally {\n (_a = resolveCtx.next) === null || _a === void 0 ? void 0 : _a.call(resolveCtx);\n }\n }, (rejectCtx) => {\n var _a;\n reject(rejectCtx.error);\n (_a = rejectCtx.next) === null || _a === void 0 ? void 0 : _a.call(rejectCtx);\n });\n });\n }\n _dataReceived(data, transportId = this._transportId) {\n let replies;\n try {\n replies = this._codec.decodeReplies(data);\n }\n catch (e) {\n // Not Centrifugo data, e.g. an HTML page from a captive portal or a\n // misconfigured proxy. Close the transport so the client reconnects,\n // instead of throwing from the transport callback.\n this._debug('error decoding received data', e);\n // Tear the connection down at once, as the close callback of the transport\n // would: the data read with this, e.g. the next lines of an http_stream chunk,\n // must not be dispatched, and the close callback comes later, or never for a\n // transport whose close() throws.\n if (this._emulation && !this._transportWasOpen) {\n this._advanceTransportIndex();\n }\n this._disconnect(connectingCodes.transportClosed, 'transport closed', true);\n return;\n }\n // Only data from the server proves the connection alive: not e.g. blank keep-alive\n // lines an intermediary writes.\n if (this._serverPing > 0 && replies.length > 0) {\n this._waitServerPing();\n }\n // We have to guarantee order of events in replies processing - i.e. start processing\n // next reply only when we finished processing of current one. Without syncing things in\n // this way we could get wrong publication events order as reply promises resolve\n // on next loop tick so for loop continues before we finished emitting all reply events.\n this._dispatchPromise = this._dispatchPromise.then(() => new Promise(resolve => {\n this._dispatchSynchronized(replies, resolve, transportId);\n }));\n }\n _dispatchSynchronized(replies, finishDispatch, transportId) {\n let p = Promise.resolve();\n for (const i in replies) {\n if (replies.hasOwnProperty(i)) {\n p = p.then(() => {\n // The transport was closed or replaced while this frame waited or was\n // being dispatched (e.g. disconnect() called from an event handler):\n // its remaining replies are outdated.\n if (this._transportId !== transportId) {\n return;\n }\n return this._dispatchReply(replies[i]);\n }).catch(err => {\n // The exception stops the client, which skips the remaining replies. The\n // chain still settles: frames of a later connection wait for this one.\n this._dispatchFailed(err);\n });\n }\n }\n p.then(() => {\n finishDispatch();\n });\n }\n /** @internal Every event reaches the application's handlers through here. */\n emit(event, ...args) {\n try {\n return EventEmitter.prototype.emit.call(this, event, ...args);\n }\n catch (e) {\n this._handlerFailed(e);\n return true;\n }\n }\n // An exception escaping an application event handler. The SDK can't know what the\n // handler left undone, so it fails loudly instead of going on as if nothing\n // happened: the client disconnects without reconnecting, and the exception is\n // re-raised as an unhandled rejection. The SDK's own work continues as if the\n // handler had returned, as for a handler calling disconnect(), so no state change\n // is left half done.\n /** @internal */\n _handlerFailed(err) {\n this._handlerFailures++;\n this._reportDispatchError(err);\n this._disconnect(disconnectedCodes.badProtocol, `exception in event handler: ${errorMessage(err)}`, false);\n }\n // An exception while handling a reply, other than one of an event handler (see\n // _handlerFailed), may have left the client's state inconsistent. The client stops\n // in a state the application can see: it disconnects without reconnecting, so no\n // later reply is processed.\n _dispatchFailed(err) {\n this._reportDispatchError(err);\n this._disconnect(disconnectedCodes.badProtocol, `exception during message handling: ${errorMessage(err)}`, false);\n }\n // The exception is surfaced as an unhandled rejection, as before.\n _reportDispatchError(err) {\n this._debug('error dispatching reply', err);\n Promise.reject(err);\n }\n // An exception, other than one of an event handler, while handling a rejected\n // command. A rejection with next() carries a reply, and is handled as any reply\n // (see _dispatchFailed). A timeout or a teardown doesn't: stopping the client would\n // cancel the reconnect or retry the handling scheduled, so the exception is only\n // reported.\n _rejectionFailed(err, rejectCtx) {\n if (rejectCtx.next !== undefined) {\n this._dispatchFailed(err);\n }\n else {\n this._reportDispatchError(err);\n }\n }\n _dispatchReply(reply) {\n let next;\n const p = new Promise(resolve => {\n next = resolve;\n });\n if (reply === undefined || reply === null) {\n this._debug('dispatch: got undefined or null reply');\n next();\n return p;\n }\n const id = reply.id;\n if (id && id > 0) {\n this._handleReply(reply, next);\n }\n else {\n if (!reply.push) {\n this._handleServerPing(next);\n }\n else {\n this._handlePush(reply.push, next);\n }\n }\n return p;\n }\n _call(cmd, skipSending) {\n return new Promise((resolve, reject) => {\n cmd.id = this._nextCommandId();\n this._registerCall(cmd.id, resolve, reject);\n if (!skipSending) {\n this._addCommand(cmd);\n }\n });\n }\n _startConnecting() {\n this._debug('start connecting');\n // The attempt starts unless a handler of the events disconnected the client (or\n // threw, which disconnects it). So the number of the transition is taken before\n // its state event.\n const transition = this.state !== State.Connecting ? this._stateTransitions + 1 : 0;\n try {\n this._setState(State.Connecting);\n // A 'state' handler may have called disconnect() already.\n if (transition && !this._transitionSuperseded(transition)) {\n this.emit('connecting', { code: connectingCodes.connectCalled, reason: 'connect called' });\n }\n }\n finally {\n if (!this._transitionSuperseded(transition)) {\n this._client = null;\n this._startReconnecting();\n }\n }\n }\n _disconnect(code, reason, reconnect) {\n if (code === disconnectedCodes.stateInvalidated) {\n // State invalidated: clear connection token (forcing a fresh one via\n // getToken on reconnect) and invalidate all subscription state. Done here\n // (the shared funnel) so it fires whether it arrives as a Disconnect push\n // or as a raw WebSocket close code \u2014 and before _clearConnectedState below\n // moves subscriptions to subscribing for the resubscribe. Runs ahead of the\n // isDisconnected guard so the invalidation is unconditional.\n // Without getToken there is no new token to get: keep the token the\n // client has (or none) and reconnect with it. The server rejects it if\n // it's no longer valid, instead of the client stopping on a local\n // configuration error.\n if (this._config.getToken !== null) {\n this._token = '';\n this._refreshRequired = true;\n }\n for (const channel in this._subs) {\n if (this._subs.hasOwnProperty(channel)) {\n // @ts-ignore \u2013 _invalidateState is internal.\n this._subs[channel]._invalidateState();\n }\n }\n // Server-side subscriptions carry their own cached recovery position,\n // separate from the client-side subscriptions above \u2014 reset it to the\n // same unrecoverable sentinel so the next connect can't recover from\n // now-invalidated state. \"_\" is a sentinel, not an epoch the server can\n // produce: the recovery of the next connect is meant to fail. It has to be\n // non-empty \u2014 an empty epoch means \"any epoch\" to the server (see\n // _invalidateState of a subscription).\n for (const channel in this._serverSubs) {\n if (this._serverSubs.hasOwnProperty(channel)) {\n this._serverSubs[channel].offset = 0;\n this._serverSubs[channel].epoch = '_';\n }\n }\n }\n if (this._isDisconnected()) {\n if (!reconnect) {\n // Calls made while disconnected wait for a connection: disconnect() ends\n // that wait too.\n this._rejectPromises({ code: errorCodes.clientDisconnected, message: 'disconnected' });\n }\n return;\n }\n const previousState = this.state;\n const newState = reconnect ? State.Connecting : State.Disconnected;\n // Tear everything down before emitting any event: handlers may call connect()\n // or disconnect() synchronously, and nothing below must undo what they start.\n this._transportIsOpen = false;\n this._reconnecting = false;\n if (previousState === State.Connecting) {\n this._clearReconnectTimeout();\n }\n this._clearConnectTimeout();\n // Invalidates callbacks of the transport closed below (SSE issues its close\n // callback synchronously).\n this._nextTransportId();\n // Aborts token/data continuations of an attempt that had not created a\n // transport yet.\n this._disconnects++;\n if (this._transport) {\n this._debug(\"closing existing transport\");\n const transport = this._transport;\n this._transport = null;\n try {\n transport.close();\n }\n catch (e) {\n // E.g. a transport whose socket constructor threw: the teardown must complete.\n this._debug('error closing transport', e);\n }\n // Its close callback is ignored, so a new attempt must not wait for it.\n this._transportClosed = true;\n }\n else {\n this._debug(\"no transport to close\");\n }\n // A connection that ends before it proved usable keeps the backoff growing.\n this._reconnectAttemptsResetPending = false;\n // Commands collected for the closed transport must not go out on the next one.\n this._commands = [];\n this._clearOutgoingRequests();\n if (!reconnect) {\n this._rejectPromises({ code: errorCodes.clientDisconnected, message: 'disconnected' });\n // Network listeners are removed with the state change below, so no online\n // event can reset it.\n this._deviceWentOffline = false;\n this._pageCached = false;\n }\n const ctx = {\n code: code,\n reason: reason\n };\n // The rest runs whatever the handlers of the events do: subscriptions must move to\n // subscribing and a reconnect must be scheduled, or the client is left stuck. So\n // the number of the transition is taken before its state event.\n const transition = this.state !== newState ? this._stateTransitions + 1 : 0;\n try {\n try {\n this._setState(newState);\n }\n finally {\n if (!reconnect && !this._transitionSuperseded(transition)) {\n // Client methods called from a 'state' handler must fail now too, not wait\n // for a connection.\n this._rejectPromises({ code: errorCodes.clientDisconnected, message: 'disconnected' });\n }\n if (previousState === State.Connected) {\n this._clearConnectedState();\n }\n }\n // A handler of the events above may have changed the state again: this\n // transition is outdated then, and its event would arrive out of order.\n if (transition && !this._transitionSuperseded(transition)) {\n if (reconnect) {\n this.emit('connecting', ctx);\n }\n else {\n this.emit('disconnected', ctx);\n }\n }\n }\n finally {\n // Unless a handler has already started a new attempt.\n if (reconnect && !this._transitionSuperseded(transition)) {\n this._scheduleReconnect();\n }\n }\n }\n _failUnauthorized() {\n this._disconnect(disconnectedCodes.unauthorized, 'unauthorized', false);\n }\n _getToken() {\n this._debug('get connection token');\n if (!this._config.getToken) {\n try {\n this.emit('error', {\n type: 'configuration',\n error: {\n code: errorCodes.badConfiguration,\n message: 'token expired but no getToken function set in the configuration'\n }\n });\n }\n catch (e) {\n // The attempt must fail as unauthorized all the same, not stay in progress.\n this._reportDispatchError(e);\n }\n return Promise.reject(new UnauthorizedError(''));\n }\n // A callback throwing instead of returning a rejected promise fails the same way,\n // not by throwing out of the attempt.\n try {\n return Promise.resolve(this._config.getToken({}));\n }\n catch (e) {\n return Promise.reject(e);\n }\n }\n // See _getToken.\n _getData() {\n try {\n return Promise.resolve(this._config.getData());\n }\n catch (e) {\n return Promise.reject(e);\n }\n }\n _refresh() {\n const clientId = this._client;\n const self = this;\n // See _startReconnecting.\n let tokenResolved = false;\n this._getToken().then(function (token) {\n tokenResolved = true;\n if (clientId !== self._client) {\n return;\n }\n if (!token) {\n self._failUnauthorized();\n return;\n }\n self._token = token;\n self._debug('connection token refreshed');\n if (!self._isConnected()) {\n return;\n }\n const cmd = {\n refresh: { token: self._token }\n };\n self._call(cmd, false).then(resolveCtx => {\n try {\n self._refreshResponse(resolveCtx.reply.refresh);\n }\n catch (err) {\n self._dispatchFailed(err);\n }\n finally {\n if (resolveCtx.next) {\n resolveCtx.next();\n }\n }\n }, rejectCtx => {\n try {\n // A disconnect rejects the pending command too: nothing to retry then,\n // the connection this refresh was for is gone.\n if (clientId === self._client) {\n self._refreshError(rejectCtx.error);\n }\n }\n catch (err) {\n self._rejectionFailed(err, rejectCtx);\n }\n finally {\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n }\n });\n }).catch(function (e) {\n if (clientId !== self._client || !self._isConnected()) {\n if (tokenResolved) {\n self._reportDispatchError(e);\n }\n return;\n }\n if (e instanceof UnauthorizedError) {\n self._failUnauthorized();\n return;\n }\n self._emitError({\n type: 'refreshToken',\n error: {\n code: errorCodes.clientRefreshToken,\n message: e !== undefined ? e.toString() : ''\n }\n }, () => {\n self._refreshTimeout = setTimeout(() => self._refresh(), self._getRefreshRetryDelay());\n });\n });\n }\n _refreshError(err) {\n if (err.code < 100 || err.temporary === true) {\n this._emitError({\n type: 'refresh',\n error: err\n }, () => {\n this._refreshTimeout = setTimeout(() => this._refresh(), this._getRefreshRetryDelay());\n });\n }\n else {\n this._disconnect(err.code, err.message, false);\n }\n }\n _getRefreshRetryDelay() {\n return backoff(0, 5000, 10000);\n }\n _refreshResponse(result) {\n if (this._refreshTimeout) {\n clearTimeout(this._refreshTimeout);\n this._refreshTimeout = null;\n }\n if (result.expires) {\n // The client id of the connection only changes if the reply carries one \u2014 and\n // Centrifugo never sets that field of a refresh reply. Taking an absent one\n // leaves the client without an id, and the checks comparing against it stop\n // recognising a token fetch, or a reply, of a connection that is gone.\n if (result.client) {\n this._client = result.client;\n }\n this._refreshTimeout = setTimeout(() => this._refresh(), ttlMilliseconds(result.ttl));\n }\n }\n // A new subscription of the channel waits for the unsubscribe of a removed one, and\n // of those removed before it still unsubscribing (see _setSubscribing of a\n // subscription): a subscription removed without sending an unsubscribe doesn't\n // drop one still pending.\n _recordRemovedUnsubscribe(sub) {\n const channel = sub.channel;\n const previous = this._removedUnsubscribes[channel];\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n const own = sub._unsubPromise;\n const unsubscribed = previous ? Promise.all([previous, own]).then(() => undefined) : own;\n this._removedUnsubscribes[channel] = unsubscribed;\n unsubscribed.then(() => {\n if (this._removedUnsubscribes[channel] === unsubscribed) {\n delete this._removedUnsubscribes[channel];\n }\n });\n }\n // Resolves once a subscription of the channel removed from the client has\n // unsubscribed (see BaseSubscription._setSubscribing).\n // @ts-ignore \u2013 this is used by a subscription in subscription.ts.\n _removedSubscriptionUnsubscribed(channel) {\n return this._removedUnsubscribes[channel] || Promise.resolve();\n }\n _unsubscribe(sub) {\n if (!this._transportIsOpen) {\n return Promise.resolve();\n }\n const req = {\n channel: sub.channel\n };\n const cmd = { unsubscribe: req };\n const self = this;\n // A teardown rejects the pending command, and the rejection is processed after\n // it: a newer attempt may have started by then, which must not be torn down.\n const transportId = this._transportId;\n const unsubscribePromise = new Promise((resolve, _) => {\n this._call(cmd, false).then(resolveCtx => {\n resolve();\n if (resolveCtx.next) {\n resolveCtx.next();\n }\n }, rejectCtx => {\n resolve();\n if (rejectCtx.next) {\n rejectCtx.next();\n }\n if (self._transportId !== transportId) {\n self._debug('unsubscribe command of a closed transport rejected');\n return;\n }\n try {\n self._disconnect(connectingCodes.unsubscribeError, 'unsubscribe error', true);\n }\n catch (err) {\n self._rejectionFailed(err, rejectCtx);\n }\n });\n });\n return unsubscribePromise;\n }\n _getSub(channel, id) {\n if (id && id > 0) {\n for (const ch in this._subs) {\n if (this._subs.hasOwnProperty(ch)) {\n const sub = this._subs[ch];\n // @ts-ignore \u2013 we are accessing private property for internal use\n if (sub._id === id) {\n return sub;\n }\n }\n }\n return null;\n }\n const sub = this._subs[channel];\n if (!sub) {\n return null;\n }\n return sub;\n }\n _isServerSub(channel) {\n return this._serverSubs[channel] !== undefined;\n }\n // The client-side subscription a push is for. The server allows one subscription\n // per channel: while a server-side subscription has the channel, its pushes\n // belong to it unless the client-side subscription is subscribed, e.g. when the\n // app kept an unsubscribed subscription object of that channel.\n _getSubForPush(channel, id) {\n const sub = this._getSub(channel, id);\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n if (sub && channel && this._isServerSub(channel) && !sub._isSubscribed()) {\n return null;\n }\n return sub;\n }\n _sendSubscribeCommands() {\n const commands = [];\n for (const channel in this._subs) {\n if (!this._subs.hasOwnProperty(channel)) {\n continue;\n }\n const sub = this._subs[channel];\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n if (sub._inflight === true) {\n continue;\n }\n // A subscribe error is retried after its backoff, also across a reconnect.\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n if (sub._resubscribeTimeout !== null) {\n continue;\n }\n if (sub.state === SubscriptionState.Subscribing) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n const cmd = sub._subscribe();\n if (cmd) {\n commands.push(cmd);\n }\n }\n }\n return commands;\n }\n _connectResponse(result) {\n this._transportIsOpen = true;\n this._transportWasOpen = true;\n if (this._transport !== null && this._transport.emulation()) {\n // A connect reply over an emulation transport proves only the stream. Commands\n // go through the emulation endpoint, which may keep failing and close the\n // transport after every connect: reset the backoff once the server replied to\n // a command or pinged, or such a client reconnects at the minimum delay forever.\n this._reconnectAttemptsResetPending = true;\n }\n else {\n this._reconnectAttempts = 0;\n }\n this._refreshRequired = false;\n // Connected again: a later online event must not take the device for having been\n // offline and abort a transport that works.\n this._deviceWentOffline = false;\n // Reconnected by the timer, in a page that was not frozen.\n this._pageCached = false;\n if (this._isConnected()) {\n return;\n }\n this._client = result.client;\n const transition = this._setState(State.Connected);\n // A 'state' handler may have called disconnect(), which already tore the\n // connection down.\n if (this._transitionSuperseded(transition)) {\n return;\n }\n if (this._refreshTimeout) {\n clearTimeout(this._refreshTimeout);\n }\n if (result.expires) {\n this._refreshTimeout = setTimeout(() => this._refresh(), ttlMilliseconds(result.ttl));\n }\n this._session = result.session;\n this._node = result.node;\n this.startBatching();\n this._sendSubscribeCommands();\n this.stopBatching();\n const ctx = {\n client: result.client,\n transport: this._transport.subName()\n };\n if (result.data) {\n ctx.data = result.data;\n }\n this.emit('connected', ctx);\n // Same for a 'connected' handler.\n if (this._transitionSuperseded(transition)) {\n return;\n }\n this._resolvePromises();\n this._processServerSubs(result.subs || {}, transition);\n if (result.ping && result.ping > 0) {\n this._serverPing = result.ping * 1000;\n this._sendPong = result.pong === true;\n this._waitServerPing();\n }\n else {\n this._serverPing = 0;\n }\n }\n _processServerSubs(subs, transition) {\n // A 'subscribed' or 'publication' handler may call disconnect(). Removed\n // channels are still reported, but no more subscribed or publication events\n // of this connection are emitted, and no more positions stored: a position\n // whose subscribed event the app didn't get would hide a gap from it (the\n // next connect recovering from a position after it, recovered=true).\n for (const channel in subs) {\n if (!subs.hasOwnProperty(channel)) {\n continue;\n }\n if (this._transitionSuperseded(transition)) {\n continue;\n }\n const sub = subs[channel];\n this._serverSubs[channel] = {\n 'offset': toOffset(sub.offset),\n 'epoch': sub.epoch,\n 'recoverable': sub.recoverable || false,\n 'subscribed': true\n };\n const subCtx = this._getSubscribeContext(channel, sub);\n this.emit('subscribed', subCtx);\n }\n for (const channel in subs) {\n if (!subs.hasOwnProperty(channel)) {\n continue;\n }\n const sub = subs[channel];\n if (sub.recovered) {\n const pubs = sub.publications || [];\n for (let i = 0; i < pubs.length && !this._transitionSuperseded(transition); i++) {\n this._handlePublication(channel, pubs[i]);\n }\n }\n }\n for (const channel in this._serverSubs) {\n if (!this._serverSubs.hasOwnProperty(channel)) {\n continue;\n }\n if (!subs[channel]) {\n this.emit('unsubscribed', { channel: channel });\n delete this._serverSubs[channel];\n }\n }\n }\n _clearRefreshTimeout() {\n if (this._refreshTimeout !== null) {\n clearTimeout(this._refreshTimeout);\n this._refreshTimeout = null;\n }\n }\n _clearReconnectTimeout() {\n if (this._reconnectTimeout !== null) {\n clearTimeout(this._reconnectTimeout);\n this._reconnectTimeout = null;\n }\n }\n _clearConnectTimeout() {\n if (this._connectTimeout !== null) {\n clearTimeout(this._connectTimeout);\n this._connectTimeout = null;\n }\n }\n _clearServerPingTimeout() {\n if (this._serverPingTimeout !== null) {\n clearTimeout(this._serverPingTimeout);\n this._serverPingTimeout = null;\n }\n }\n _waitServerPing() {\n if (this._config.maxServerPingDelay === 0) {\n return;\n }\n if (!this._isConnected()) {\n return;\n }\n this._clearServerPingTimeout();\n const delay = this._serverPing + this._config.maxServerPingDelay;\n const due = Date.now() + delay;\n this._serverPingTimeout = setTimeout(() => {\n if (!this._isConnected()) {\n return;\n }\n // A ping may have been received already but not processed yet, e.g. when a\n // suspended process resumes: let that data be processed first, as for a call\n // (see _registerCall). Any data received re-arms this timer.\n const late = Date.now() - due >= lateCallTimer;\n this._serverPingTimeout = setTimeout(() => {\n if (!this._isConnected()) {\n return;\n }\n this._disconnect(connectingCodes.noPing, 'no ping', true);\n }, late ? lateCallGrace : 0);\n }, delay);\n }\n _getSubscribeContext(channel, result) {\n const ctx = {\n channel: channel,\n positioned: false,\n recoverable: false,\n wasRecovering: false,\n recovered: false,\n hasRecoveredPublications: false,\n };\n if (result.recovered) {\n ctx.recovered = true;\n }\n if (result.positioned) {\n ctx.positioned = true;\n }\n if (result.recoverable) {\n ctx.recoverable = true;\n }\n if (result.was_recovering) {\n ctx.wasRecovering = true;\n }\n let epoch = '';\n if ('epoch' in result) {\n epoch = result.epoch;\n }\n let offset = 0;\n if ('offset' in result) {\n offset = toOffset(result.offset);\n }\n if (ctx.positioned || ctx.recoverable) {\n ctx.streamPosition = {\n 'offset': offset,\n 'epoch': epoch\n };\n }\n if (Array.isArray(result.publications) && result.publications.length > 0) {\n ctx.hasRecoveredPublications = true;\n }\n if (result.data) {\n ctx.data = result.data;\n }\n return ctx;\n }\n _handleReply(reply, next) {\n this._resetReconnectAttemptsIfPending();\n const id = reply.id;\n if (!(id in this._callbacks)) {\n next();\n return;\n }\n const callbacks = this._callbacks[id];\n clearTimeout(this._callbacks[id].timeout);\n delete this._callbacks[id];\n if (!errorExists(reply)) {\n const callback = callbacks.callback;\n if (!callback) {\n return;\n }\n callback({ reply, next });\n }\n else {\n const errback = callbacks.errback;\n if (!errback) {\n next();\n return;\n }\n const error = { code: reply.error.code, message: reply.error.message || '', temporary: reply.error.temporary || false };\n errback({ error, next });\n }\n }\n _handleJoin(channel, join, id) {\n const sub = this._getSubForPush(channel, id);\n if (!sub) {\n // See _handlePublication: a compacted push with an unknown id has an empty\n // channel and no matching subscription \u2014 drop instead of crashing.\n if (channel && this._isServerSub(channel)) {\n const ctx = { channel: channel, info: this._getJoinLeaveContext(join.info) };\n this.emit('join', ctx);\n }\n return;\n }\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n if (!sub._isSubscribed()) {\n this._debug('join for a subscription that is not subscribed', channel);\n return;\n }\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n sub._handleJoin(join);\n }\n _handleLeave(channel, leave, id) {\n const sub = this._getSubForPush(channel, id);\n if (!sub) {\n // See _handlePublication: a compacted push with an unknown id has an empty\n // channel and no matching subscription \u2014 drop instead of crashing.\n if (channel && this._isServerSub(channel)) {\n const ctx = { channel: channel, info: this._getJoinLeaveContext(leave.info) };\n this.emit('leave', ctx);\n }\n return;\n }\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n if (!sub._isSubscribed()) {\n this._debug('leave for a subscription that is not subscribed', channel);\n return;\n }\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n sub._handleLeave(leave);\n }\n _handleUnsubscribe(channel, unsubscribe) {\n const sub = this._getSubForPush(channel, 0);\n if (!sub) {\n if (channel && this._isServerSub(channel)) {\n delete this._serverSubs[channel];\n this.emit('unsubscribed', { channel: channel });\n }\n return;\n }\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n if (!sub._isSubscribed()) {\n // It ends a previous subscription: one the app unsubscribed, or one that raced\n // unsubscribe() and subscribe() of the app. The server unsubscribes a\n // subscription in progress only after replying to its subscribe, and it sends\n // the push also when the subscription is already gone. A resubscribe code must\n // not subscribe again, nor invalidate the state of a subscribe in progress.\n this._debug('unsubscribe push for a previous subscription', channel);\n return;\n }\n if (unsubscribe.code < 2500) {\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n sub._setUnsubscribed(unsubscribe.code, unsubscribe.reason, false);\n }\n else {\n if (unsubscribe.code === unsubscribedCodes.stateInvalidated) {\n // State invalidated: clear subscription token and cached state so the\n // resubscribe gets a fresh token and re-syncs.\n // @ts-ignore \u2013 _invalidateState is internal.\n sub._invalidateState();\n }\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n sub._setSubscribing(unsubscribe.code, unsubscribe.reason);\n }\n }\n _handleSubscribe(channel, sub) {\n this._serverSubs[channel] = {\n 'offset': toOffset(sub.offset),\n 'epoch': sub.epoch,\n 'recoverable': sub.recoverable || false,\n 'subscribed': true\n };\n this.emit('subscribed', this._getSubscribeContext(channel, sub));\n }\n _handleDisconnect(disconnect) {\n // The server pushed it over the transport, so the transport works: reconnect\n // after the reconnect delay, as after a close code from the server, not at once\n // with the next transport as for one that failed to open. An emulation transport\n // is otherwise marked open only by a connect reply.\n this._transportWasOpen = true;\n const code = disconnect.code;\n let reconnect = true;\n if ((code >= 3500 && code < 4000) || (code >= 4500 && code < 5000)) {\n reconnect = false;\n }\n // State invalidation (code 3014) is handled centrally in _disconnect so it\n // covers both delivery paths: a Disconnect push (this method) and a raw\n // WebSocket close code (transport onClose \u2192 _disconnect directly).\n this._disconnect(code, disconnect.reason, reconnect);\n }\n _getPublicationContext(channel, pub) {\n const ctx = {\n channel: channel,\n data: pub.data\n };\n if (hasOffset(pub.offset)) {\n ctx.offset = toOffset(pub.offset);\n }\n if (pub.info) {\n ctx.info = this._getJoinLeaveContext(pub.info);\n }\n if (pub.tags) {\n ctx.tags = pub.tags;\n }\n return ctx;\n }\n _getJoinLeaveContext(clientInfo) {\n const info = {\n client: clientInfo.client,\n user: clientInfo.user\n };\n const connInfo = clientInfo['conn_info'];\n if (connInfo) {\n info.connInfo = connInfo;\n }\n const chanInfo = clientInfo['chan_info'];\n if (chanInfo) {\n info.chanInfo = chanInfo;\n }\n return info;\n }\n _handlePublication(channel, pub, id) {\n const sub = this._getSubForPush(channel, id);\n if (!sub) {\n // No client-side subscription. With channel compaction the push carries a\n // numeric id and no channel, so an unknown id (e.g. a publication for a\n // subscription already unsubscribed) has an empty channel here \u2014 it must\n // be dropped, not fall through to sub._handlePublication on null.\n if (channel && this._isServerSub(channel)) {\n const ctx = this._getPublicationContext(channel, pub);\n // The position moves after the app has the publication, so the position it can\n // observe never runs ahead of what it received (see\n // BaseSubscription._handlePublication). A connect command built while a handler\n // runs takes the offset of the publication being dispatched (see the subs of\n // _constructConnectCommand), so a connect() from that handler still recovers\n // after it instead of receiving it again.\n this._pendingServerSubOffsets[channel] = hasOffset(pub.offset) ? toOffset(pub.offset) : null;\n const failures = this._handlerFailures;\n try {\n this.emit('publication', ctx);\n }\n finally {\n delete this._pendingServerSubOffsets[channel];\n }\n // A publication whose handler threw isn't delivered: the position stays before\n // it, so the next recovery delivers it again.\n if (this._handlerFailures !== failures) {\n return;\n }\n if (hasOffset(pub.offset)) {\n this._serverSubs[channel].offset = toOffset(pub.offset);\n }\n // The epoch of a channel that had no stream at subscribe time comes with\n // its first publication (see BaseSubscription._setPublicationPosition).\n if (pub.epoch) {\n this._serverSubs[channel].epoch = pub.epoch;\n }\n }\n return;\n }\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n if (!sub._isSubscribed()) {\n // E.g. a publication already on its way when the app called unsubscribe().\n this._debug('publication for a subscription that is not subscribed', channel);\n return;\n }\n // @ts-ignore \u2013 we are hiding some symbols from public API autocompletion.\n sub._handlePublication(pub);\n }\n _handleMessage(message) {\n this.emit('message', { data: message.data });\n }\n _handleServerPing(next) {\n this._resetReconnectAttemptsIfPending();\n if (this._sendPong) {\n const cmd = {};\n this._transportSendCommands([cmd]);\n }\n next();\n }\n _handlePush(data, next) {\n const channel = data.channel;\n const id = data.id;\n if (data.pub) {\n this._handlePublication(channel, data.pub, id);\n }\n else if (data.message) {\n this._handleMessage(data.message);\n }\n else if (data.join) {\n this._handleJoin(channel, data.join, id);\n }\n else if (data.leave) {\n this._handleLeave(channel, data.leave, id);\n }\n else if (data.unsubscribe) {\n this._handleUnsubscribe(channel, data.unsubscribe);\n }\n else if (data.subscribe) {\n this._handleSubscribe(channel, data.subscribe);\n }\n else if (data.disconnect) {\n this._handleDisconnect(data.disconnect);\n }\n next();\n }\n _flush() {\n const commands = this._commands.slice(0);\n this._commands = [];\n this._transportSendCommands(commands);\n }\n _createErrorObject(code, message, temporary) {\n const errObject = {\n code: code,\n message: message\n };\n if (temporary) {\n errObject.temporary = true;\n }\n return errObject;\n }\n _registerCall(id, callback, errback) {\n this._callbacks[id] = {\n callback: callback,\n errback: errback,\n timeout: null\n };\n const due = Date.now() + this._config.timeout;\n this._callbacks[id].timeout = setTimeout(() => {\n // The reply may have been received already but not processed yet, e.g. when\n // a suspended process resumes and this overdue timer runs before the data\n // waiting in the socket. Let that data be processed first: one event loop\n // turn is enough in Node. A timer running far too late means the process was\n // suspended or blocked, and browsers don't promise to run the socket events\n // before it: the reply gets a grace period then.\n const late = Date.now() - due >= lateCallTimer;\n this._callbacks[id].timeout = setTimeout(() => {\n delete this._callbacks[id];\n if (isFunction(errback)) {\n errback({ error: this._createErrorObject(errorCodes.timeout, 'timeout') });\n }\n }, late ? lateCallGrace : 0);\n }, this._config.timeout);\n }\n _addCommand(command) {\n if (this._batching) {\n this._commands.push(command);\n }\n else {\n this._transportSendCommands([command]);\n }\n }\n _nextPromiseId() {\n return ++this._promiseId;\n }\n _nextTransportId() {\n return ++this._transportId;\n }\n _resolvePromises() {\n for (const id in this._promises) {\n if (!this._promises.hasOwnProperty(id)) {\n continue;\n }\n if (this._promises[id].timeout) {\n clearTimeout(this._promises[id].timeout);\n }\n this._promises[id].resolve();\n delete this._promises[id];\n }\n }\n _rejectPromises(err) {\n for (const id in this._promises) {\n if (!this._promises.hasOwnProperty(id)) {\n continue;\n }\n if (this._promises[id].timeout) {\n clearTimeout(this._promises[id].timeout);\n }\n this._promises[id].reject(err);\n delete this._promises[id];\n }\n }\n}\nCentrifuge.SubscriptionState = SubscriptionState;\nCentrifuge.State = State;\nCentrifuge.UnauthorizedError = UnauthorizedError;\n\nexport { Centrifuge, State, Subscription, SubscriptionState, UnauthorizedError, connectingCodes, disconnectedCodes, errorCodes, subscribingCodes, subscriptionFlags, unsubscribedCodes };\n", "import type { DataBusPublication } from './types';\n\n/**\n * Normalize legacy flat publications, metadata payload envelopes, and the\n * canonical `{ op: 'publication', publication: ... }` shape.\n *\n * `fallbackTopic` is used by transports such as Centrifuge where the channel\n * is supplied out-of-band by the client library rather than inside the data.\n */\nexport function parseDataBusPublication<TData = unknown>(\n value: unknown,\n fallbackTopic?: string\n): DataBusPublication<TData> | null {\n if (!value || typeof value !== 'object') {\n return fallbackTopic ? { topic: fallbackTopic, data: value as TData } : null;\n }\n const frame = value as Record<string, unknown>;\n const nested = frame.publication && typeof frame.publication === 'object'\n ? frame.publication as Record<string, unknown>\n : null;\n const publication = nested ?? frame;\n const topic = typeof publication.topic === 'string' ? publication.topic : fallbackTopic;\n if (!topic) return null;\n\n // Centrifuge's legacy metadata envelope carries `{ data, messageId }`\n // without a topic because the channel is provided by PublicationContext.\n const hasMetadataEnvelope = fallbackTopic !== undefined\n && Object.prototype.hasOwnProperty.call(publication, 'data')\n && (typeof publication.messageId === 'string' || typeof publication.timestamp === 'number');\n const data = nested || fallbackTopic === undefined || hasMetadataEnvelope\n ? publication.data\n : value;\n const messageId = typeof publication.messageId === 'string' && publication.messageId.length > 0\n ? publication.messageId\n : undefined;\n const timestamp = typeof publication.timestamp === 'number' && Number.isFinite(publication.timestamp)\n ? publication.timestamp\n : undefined;\n return {\n topic,\n data: data as TData,\n ...(messageId === undefined ? {} : { messageId }),\n ...(timestamp === undefined ? {} : { timestamp })\n };\n}\n", "/**\n * \u516C\u5171\u5B57\u7B26\u4E32\u5E38\u91CF \u2014\u2014 \u751F\u547D\u5468\u671F\u72B6\u6001\u3001\u89D2\u8272\u3001\u63A7\u5236\u52A8\u4F5C\u3001\u534F\u8BAE\u6D88\u606F\u7C7B\u578B\u3001\u679A\u4E3E\u4E0E\n * \u547D\u540D\u7A7A\u95F4\u524D\u7F00\u3002\n *\n * \u6240\u6709\u8FD0\u884C\u65F6\u4F7F\u7528\u7684\u5B57\u7B26\u4E32\u5B57\u9762\u91CF\u96C6\u4E2D\u5728\u6B64\u4E00\u4EFD\u503C\uFF0C\u7C7B\u578B\u5B9A\u4E49\uFF08src/core/types.ts\n * \u7B49\uFF09\u901A\u8FC7 `(typeof X)[keyof typeof X]` \u4ECE\u8FD9\u4E9B\u5E38\u91CF\u6D3E\u751F\uFF0C\u6BD4\u8F83/switch \u5904\u5F15\u7528\n * \u540C\u4E00\u5BF9\u8C61\u6210\u5458\u3002\u8FD9\u6837\u65E2\u80FD\u6D88\u9664\u6563\u843D\u5728\u5404\u6587\u4EF6\u91CC\u7684\u91CD\u590D\u5B57\u7B26\u4E32\uFF08\u907F\u514D\u5927\u5C0F\u5199\u4E0D\u7EDF\u4E00\n * \u6216\u7B14\u8BEF\uFF09\uFF0C\u53C8\u4FDD\u8BC1\u7C7B\u578B\u4E0E\u503C\u6C38\u4E0D\u9519\u4F4D\u3002\n *\n * ## \u4F7F\u7528\u7EA6\u5B9A\n *\n * - **\u65B0\u589E\u6216\u4FEE\u6539\u5B57\u7B26\u4E32\u5B57\u9762\u91CF\u65F6\uFF0C\u5148\u5230\u8FD9\u91CC\u67E5\u627E/\u589E\u8865\uFF0C\u4E0D\u8981\u5728\u4E1A\u52A1\u6587\u4EF6\u91CC\u76F4\u63A5\u5199\n * \u9B54\u6CD5\u5B57\u7B26\u4E32\u3002** \u626B\u63CF\u6B8B\u7559\u5B57\u9762\u91CF\uFF1A`rg \"'(['a-z]+)'\" src/`\u3002\n * - **\u53EA\u7528\u4E8E\u7C7B\u578B\u4F4D\u7F6E\u7684\u5E38\u91CF**\uFF08\u5373\u53EA\u51FA\u73B0\u5728 `typeof X[keyof typeof X]` \u8FD9\u7C7B\u6D3E\u751F\u91CC\u3001\n * \u4ECE\u4E0D\u53C2\u4E0E\u8FD0\u884C\u65F6\u6BD4\u8F83\u7684\uFF09\u5728\u8C03\u7528\u65B9\u7528 `import type`\uFF1B**\u5728\u8FD0\u884C\u65F6\u6BD4\u8F83/\u6784\u9020\u4E2D\u4F7F\u7528\u7684**\n * \uFF08\u5982 `WORKER_STATUS.ERROR`\u3001`TRACE_EVENT_TYPE.LIFECYCLE`\u3001\n * `PERSISTENCE_OPERATION.APPEND`\uFF09\u5FC5\u987B\u7528\u503C\u5BFC\u5165\uFF0C\u5426\u5219\u4F1A\u62A5 \"cannot be used as\n * a value because it was imported using 'import type'\"\u3002`PERSISTENCE_OPERATION`\n * \u5C5E\u4E8E\u540E\u8005\u800C\u4E0D\u662F\u7C7B\u578B\u4FA7\u7684\u4F8B\u5B50\uFF1A`replay-manager.ts` \u4EE5\u503C\u5BFC\u5165\u5B83\uFF0C\u5E76\u628A\u5B83\u7684\u6210\u5458\u4F5C\u4E3A\n * `withPersistenceRetry` \u7684\u7B2C\u4E00\u4E2A\u5B9E\u53C2\u4F20\u8FDB\u53BB\u3002\n * - **\u503C\u6D3E\u751F\u7C7B\u578B**\uFF1A`export type WorkerStatus = (typeof WORKER_STATUS)[keyof\n * typeof WORKER_STATUS]`\u3002\u8FD9\u6837\u65B0\u589E\u679A\u4E3E\u5206\u652F\u65F6\u7C7B\u578B\u81EA\u52A8\u6536\u7A84\uFF0C\u7F16\u8BD1\u5668\u4F1A\u6307\u51FA\n * \u6BCF\u4E2A\u9057\u6F0F\u7684 switch \u5206\u652F\u3002\n * - \u5206\u7EC4\u7684\u987A\u5E8F\uFF08\u72B6\u6001 / \u89D2\u8272 / \u540E\u7AEF / \u6D88\u606F\u7C7B\u578B / \u679A\u4E3E / \u524D\u7F00\uFF09\u4FDD\u6301\u7A33\u5B9A\uFF0C\u65B9\u4FBF\n * \u7EF4\u62A4\u8005\u4E00\u773C\u5B9A\u4F4D\u3002\n */\n\n// ---- \u751F\u547D\u5468\u671F\u72B6\u6001 / \u89D2\u8272 / \u53EF\u89C1\u6027 ----\nexport const WORKER_STATUS = {\n CONNECTING: 'connecting',\n CONNECTED: 'connected',\n DISCONNECTED: 'disconnected',\n ERROR: 'error',\n} as const;\n\nexport const WORKER_ROLE = {\n ACTIVE: 'active',\n STANDBY: 'standby',\n} as const;\n\nexport const TAB_VISIBILITY = {\n VISIBLE: 'visible',\n HIDDEN: 'hidden',\n} as const;\n\n// ---- Worker \u540E\u7AEF\u6A21\u5F0F\u4E0E\u89E3\u6790\u7ED3\u679C\uFF08WorkerMode / WorkerBackend\uFF09----\nexport const WORKER_MODE = {\n DEDICATED: 'dedicated',\n SHARED: 'shared',\n AUTO: 'auto',\n} as const;\n\nexport const WORKER_BACKEND = {\n DEDICATED: 'dedicated',\n SHARED: 'shared',\n LOCAL: 'local',\n} as const;\n\n// ---- \u5B58\u50A8\u4E8B\u4EF6\u901A\u9053\u56DE\u9000 ----\nexport const CHANNEL_FALLBACK = {\n NONE: 'none',\n STORAGE_EVENT: 'storage-event',\n} as const;\n\n// ---- Worker / MessagePort / BroadcastChannel \u7684 EventTarget \u4E8B\u4EF6\u540D\u5224\u522B ----\n// MessageEvent.type\uFF08'message' / 'messageerror'\uFF09\u4E0E Worker \u4E0A\u7684 'error' \u4E8B\u4EF6\u540D\uFF0C\n// \u7528\u4E8E\u73AF\u5883\u9002\u914D\u5668\u63A5\u53E3\u7B7E\u540D\u4E0E\u6D4B\u8BD5\u66FF\u8EAB\u7684 addEventListener \u771F\u5047\u5206\u652F\u3002\nexport const EVENT_TYPE = {\n MESSAGE: 'message',\n MESSAGEERROR: 'messageerror',\n ERROR: 'error',\n} as const;\n\n// ---- \u63A7\u5236\u5E73\u9762\u52A8\u4F5C\uFF08WorkerControlAction\uFF09----\nexport const CONTROL_ACTION = {\n SUBSCRIBE: 'SUBSCRIBE',\n UNSUBSCRIBE: 'UNSUBSCRIBE',\n PUBLISH: 'PUBLISH',\n} as const;\n\n// ---- BroadcastChannel \u96C6\u7FA4\u6D88\u606F\u7C7B\u578B ----\nexport const CLUSTER_MESSAGE_TYPE = {\n CONTROL: 'CONTROL',\n EVENT: 'EVENT',\n REGISTRY: 'REGISTRY',\n ROUTE_RELEASED: 'ROUTE_RELEASED',\n} as const;\n\n// ---- \u547D\u540D\u7A7A\u95F4\u524D\u7F00\u4E0E\u4E8B\u4EF6\u540D ----\nexport const DEFAULT_STORAGE_PREFIX = 'cross-tab-worker-databus';\nexport const STORAGE_CHANNEL_PREFIX = `${DEFAULT_STORAGE_PREFIX}:channel:`;\nexport const TAB_ID_STORAGE_KEY = `${DEFAULT_STORAGE_PREFIX}:tab-id`;\nexport const PUBLICATION_EVENT = 'DATABUS_PUBLICATION';\n\n// ---- \u89C4\u8303 JSON \u4FE1\u5C01\u64CD\u4F5C\u7801 ----\nexport const PUBLICATION_ENVELOPE_OP = 'publication';\n\n// ---- trace \u4E8B\u4EF6\u7C7B\u578B ----\nexport const TRACE_EVENT_TYPE = {\n LIFECYCLE: 'lifecycle',\n STATUS: 'status',\n SUBSCRIPTION: 'subscription',\n COORDINATION: 'coordination',\n ERROR: 'error',\n RELIABILITY: 'reliability',\n MESSAGE_METRICS: 'message_metrics',\n} as const;\n\n// ---- trace \u751F\u547D\u5468\u671F\u52A8\u4F5C ----\nexport const TRACE_LIFECYCLE_ACTION = {\n START: 'start',\n STOP: 'stop',\n SUSPEND: 'suspend',\n RESUME: 'resume',\n} as const;\n\n// ---- \u5185\u90E8 handler \u8C03\u7528\u6807\u7B7E\uFF08\u9694\u79BB\u5F02\u5E38\u65F6\u7684\u5206\u7C7B\u6765\u6E90\uFF09----\nexport const INVOKE_LABEL = {\n DISPATCH: 'dispatch',\n STATUS: 'status',\n ERROR_HANDLER: 'error handler',\n} as const;\n\n// ---- trace \u6A21\u5F0F\uFF08DataBusTraceMode\uFF09----\nexport const TRACE_MODE = {\n EVENTS: 'events',\n METRICS: 'metrics',\n ALL: 'all',\n} as const;\n\n// ---- trace \u9519\u8BEF\u6765\u6E90 ----\nexport const TRACE_ERROR_SOURCE = {\n TRANSPORT: 'transport',\n OPERATION: 'operation',\n} as const;\n\n// ---- reliability \u8BCA\u65AD\u64CD\u4F5C ----\nexport const RELIABILITY_OPERATION = {\n TRANSPORT_RECOVERY: 'transport_recovery',\n ROUTE_ACK: 'route_ack',\n ROUTE_MIGRATION: 'route_migration',\n // A re-election that recovered a stranded unconfirmed handoff (previous\n // owner gone, ACK never arrived). Distinct from ROUTE_MIGRATION so trace\n // consumers can tell recoveries apart from routine graceful handoffs.\n ROUTE_MIGRATION_RECOVERY: 'route_migration_recovery',\n PERSISTENCE_CLEANUP: 'persistence_cleanup',\n PERSISTENCE_RETRY: 'persistence_retry',\n DEDUP_SUPPRESSED: 'dedup_suppressed',\n} as const;\n\n// ---- \u81EA\u52A8\u6062\u590D\u5C1D\u8BD5\u7ED3\u679C ----\nexport const RECOVERY_OUTCOME = {\n SCHEDULED: 'scheduled',\n SUCCEEDED: 'succeeded',\n FAILED: 'failed',\n EXHAUSTED: 'exhausted',\n} as const;\n\n// ---- \u8BA2\u9605\u52A8\u4F5C ----\nexport const SUBSCRIPTION_ACTION = {\n SUBSCRIBE: 'subscribe',\n UNSUBSCRIBE: 'unsubscribe',\n} as const;\n\n// ---- \u56DE\u653E\u4FEE\u526A\u7B56\u7565 ----\nexport const PRUNE_STRATEGY = {\n COUNT: 'count',\n AGE: 'age',\n BOTH: 'both',\n} as const;\n\n// ---- \u6301\u4E45\u5316\u64CD\u4F5C ----\nexport const PERSISTENCE_OPERATION = {\n LOAD: 'load',\n APPEND: 'append',\n CLEAR: 'clear',\n CLEAR_TOPIC: 'clearTopic',\n CLEAR_BEFORE: 'clearBefore',\n} as const;\n\n// ---- \u6545\u969C\u6765\u6E90\uFF08DataBusFailureSource\uFF09----\nexport const FAILURE_SOURCE = {\n TRANSPORT: 'transport',\n PERSISTENCE: 'persistence',\n DISPATCH: 'dispatch',\n} as const;\n\n// ---- \u5065\u5EB7\u5224\u5B9A\u72B6\u6001\uFF08DataBusHealthSummary['state']\uFF09----\nexport const HEALTH_STATE = {\n STOPPED: 'stopped',\n STARTING: 'starting',\n HEALTHY: 'healthy',\n RECOVERING: 'recovering',\n SUSPENDED: 'suspended',\n DEGRADED: 'degraded',\n} as const;\n\n// ---- WebSocket wire \u534F\u8BAE\u64CD\u4F5C\u7801 ----\nexport const WS_OP = {\n SUBSCRIBE: 'subscribe',\n UNSUBSCRIBE: 'unsubscribe',\n PUBLISH: 'publish',\n PUBLISH_BATCH: 'publishBatch',\n} as const;\n\n// ---- Centrifuge Worker \u8F93\u5165\u6D88\u606F\u7C7B\u578B ----\nexport const CENTRIFUGE_INPUT_TYPE = {\n INIT: 'INIT',\n SUBSCRIBE: 'SUBSCRIBE',\n UNSUBSCRIBE: 'UNSUBSCRIBE',\n PUBLISH: 'PUBLISH',\n PUBLISH_BIN: 'PUBLISH_BIN',\n PING: 'PING',\n STOP: 'STOP',\n TOKEN_RESPONSE: 'TOKEN_RESPONSE',\n TOKEN_ERROR: 'TOKEN_ERROR',\n} as const;\n\n// ---- Centrifuge Worker \u8F93\u51FA\u6D88\u606F\u7C7B\u578B ----\nexport const CENTRIFUGE_OUTPUT_TYPE = {\n STATUS: 'STATUS',\n MESSAGE: 'MESSAGE',\n MESSAGE_BIN: 'MESSAGE_BIN',\n ERROR: 'ERROR',\n TOKEN_REQUEST: 'TOKEN_REQUEST',\n SESSION_REAPED: 'SESSION_REAPED',\n} as const;\n", "/**\n * \u53D1\u5E03\u5143\u6570\u636E\u5DE5\u5177 \u2014\u2014 \u6784\u9020 { messageId?, timestamp? }\uFF0C\u4EC5\u5728\u5B57\u6BB5\u5DF2\u5B9A\u4E49\u65F6\u5199\u5165\uFF0C\n * \u907F\u514D\u5F80 wire \u5E27/\u63A7\u5236\u6D88\u606F\u91CC\u585E\u7A7A\u679A\u4E3E\u5B57\u6BB5\u3002\n *\n * \u6B64\u524D cluster.ts\u3001data-bus.ts\u3001centrifuge.ts\u3001centrifuge-session.ts \u5404\u81EA\u5185\u8054\n * \u5B9E\u73B0\u4E86\u4E00\u904D `...(x === undefined ? {} : { x })` \u5C55\u5F00\uFF0C\u884C\u4E3A\u5BB9\u6613\u6F02\u79FB\uFF1B\u7EDF\u4E00\u5230\u6B64\n * \u4E00\u5904\u540E\u6240\u6709\u8C03\u7528\u65B9\u5171\u4EAB\u540C\u4E00\u8BED\u4E49\u3002\n */\nimport type { DataBusPublicationMetadata } from '../core/types';\n\n/**\n * Copy defined publication metadata without adding empty enumerable fields.\n * Returns `undefined` when neither field is set, so callers can preserve a\n * legacy \"no metadata\" argument shape (e.g. `onControl(..., undefined)`).\n */\nexport function publicationMetadata(\n messageId?: string,\n timestamp?: number\n): DataBusPublicationMetadata | undefined {\n if (messageId === undefined && timestamp === undefined) return undefined;\n return {\n ...(messageId === undefined ? {} : { messageId }),\n ...(timestamp === undefined ? {} : { timestamp })\n };\n}\n", "/**\n * \u9519\u8BEF\u5E8F\u5217\u5316\u5DE5\u5177 \u2014\u2014 \u5728 Worker \u8FB9\u754C\u5F80\u8FD4\u4F20\u8F93 Error\u3002\n *\n * Error \u5B9E\u4F8B\u65E0\u6CD5\u901A\u8FC7 postMessage \u7ED3\u6784\u5316\u514B\u9686\uFF0C\u6240\u4EE5 CentrifugeSession \u4FA7\u7528\n * serializeError \u628A\u5B83\u538B\u6210 plain object\uFF0C\u4E3B\u7EBF\u7A0B\u4FA7\u7528 deserializeWorkerError\n * \u8FD8\u539F\u6210\u771F Error\uFF08\u5E26 name/stack\uFF09\u3002\u6B64\u524D\u4E24\u4E2A\u51FD\u6570\u5206\u522B\u5185\u8054\u5728 centrifuge-session.ts\n * \u4E0E centrifuge.ts\uFF0C\u6B64\u5904\u7EDF\u4E00\u5B9A\u4E49\u5E76\u4ECE\u4E24\u5904\u5F15\u7528\u3002\n */\n\n/** Error object serialized for cross-thread transfer. */\nexport interface SerializedWorkerError {\n /** The Error's `name` (e.g. 'TypeError', 'CentrifugeError'). */\n name: string;\n /** The Error's `message`. */\n message: string;\n /** The Error's `stack` if available (for debugging). */\n stack?: string;\n /** Arbitrary context attached by the Worker (e.g. the failing operation). */\n context?: unknown;\n}\n\n/** Convert an arbitrary error into a structured-cloneable form for postMessage.\n * A non-Error value is attached as `context`, but only when it is itself\n * structured-cloneable: a function, symbol, or an object/map holding one would\n * otherwise make the serialised error unserializable, so `postMessage` would\n * throw `DataCloneError` while reporting the original failure. */\nexport function serializeError(error: unknown): SerializedWorkerError {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n ...(error.stack ? { stack: error.stack } : {})\n };\n }\n const context = error === undefined ? undefined : error;\n return {\n name: 'CentrifugeError',\n message: typeof error === 'string' ? error : 'Centrifuge worker operation failed.',\n ...(context === undefined || !isStructuredCloneable(context) ? {} : { context })\n };\n}\n\n/** True when `value` survives a structured clone. When the runtime has no\n * `structuredClone`, cloneability cannot be checked and the value is kept\n * (best effort); the eventual postMessage would fail either way. */\nfunction isStructuredCloneable(value: unknown): boolean {\n if (typeof structuredClone !== 'function') return true;\n try {\n structuredClone(value);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Reconstruct an Error instance from its serialised form. */\nexport function deserializeWorkerError(error: SerializedWorkerError): Error {\n const result = new Error(error.message);\n result.name = error.name;\n if (error.stack) result.stack = error.stack;\n if (error.context !== undefined) Object.assign(result, { context: error.context });\n return result;\n}\n\n/** Render an arbitrary rejection reason as a message, guaranteed not to throw.\n *\n * `String(value)` is *not* total: a null-prototype object has no primitive\n * conversion at all (`TypeError: Cannot convert object to primitive value`), and\n * any object can carry a `toString` that throws. Both are inside the public\n * contract, which lets a transport reject with any value \u2014 so the coercion runs\n * on the path that reports a failure, where throwing is worse than the failure\n * itself: it replaces the real reason with a message about the formatter's\n * limits, and it turns a chain ending in `.catch(error => reportError(error))`\n * from a resolved promise into a rejected one. The whole `try` covers the\n * `Error` branch too, because `instanceof` and a `.message` getter can each be\n * made to throw by the value being recorded. */\nexport function describeFailure(error: unknown): string {\n try {\n if (error instanceof Error) return error.message;\n return String(error);\n } catch {\n return `[unstringifiable ${typeof error}]`;\n }\n}\n", "/**\n * CentrifugeSession \u2014 a reusable wrapper around a single Centrifuge client.\n *\n * Provides a structured-clone-safe message protocol (INIT/SUBSCRIBE/UNSUBSCRIBE/\n * PUBLISH/STOP) so the same session class can run inside a Dedicated Worker,\n * a SharedWorker port, or directly on the main thread as a local fallback.\n */\nimport { Centrifuge } from 'centrifuge';\nimport { parseDataBusPublication } from './core/publication';\nimport type {\n PublicationContext,\n StateContext,\n Subscription,\n SubscriptionErrorContext\n} from 'centrifuge';\nimport type {\n CentrifugeWorkerConfig,\n CentrifugeWorkerInput,\n CentrifugeWorkerOutput\n} from './centrifuge-protocol';\nimport { CENTRIFUGE_INPUT_TYPE, CENTRIFUGE_OUTPUT_TYPE, WORKER_STATUS } from './utils/constants';\nimport { publicationMetadata } from './utils/metadata';\nimport { deserializeWorkerError, serializeError } from './utils/error-utils';\n\n/** Callback interface for posting messages back to the transport layer. */\nexport interface CentrifugeSessionSink<TData = unknown> {\n post(message: CentrifugeWorkerOutput<TData>, transfer?: ArrayBuffer[]): void;\n}\n\n/** A pending getToken/getChannelToken request awaiting a main-thread response. */\ninterface PendingTokenRequest {\n resolve: (token: string) => void;\n reject: (error: unknown) => void;\n}\n\n/** Centrifuge client options for token-bridge mode: the structured-clone-safe\n * subset plus the function-valued credential hooks this session installs.\n * Against the pinned SDK (5.8.0) `getToken` is the only one that is a real\n * client option (the constructor of `centrifuge.js` copies it off the config \u2014 the\n * assignment is greppable in the shipped bundle as\n * `e.getToken&&(this._getToken=e.getToken)`, and the same hook serves renewal) \u2014\n * cited by that substring rather than a file and\n * line: the installed package ships no `.d.ts` at all and the string\n * `build/types.d.ts` appears nowhere inside it, so a generated-file line number could\n * not be checked by a reader here at all;\n * `getChannelToken` appears nowhere in the package's types or build, and\n * subscriptions are created with `newSubscription(topic)` and no per-\n * subscription options \u2014 so that hook is never invoked, and the `'channelToken'`\n * request kind is produced only by the test fake. It stays because the Worker\n * protocol carries the kind: an SDK that later names it would need no change on\n * this side. Used only inside the session, never across the Worker boundary. */\ntype CentrifugeBridgedOptions = Omit<CentrifugeWorkerConfig, 'getToken' | 'getChannelToken'> & {\n getToken: () => Promise<string>;\n getChannelToken: (channel: string) => Promise<string>;\n};\n\n/**\n * Stateful Centrifuge client wrapper shared by Dedicated Worker, SharedWorker\n * ports and the main-thread local fallback. Each session owns one connection.\n */\nexport class CentrifugeSession<TData = unknown> {\n private client: Centrifuge | null = null;\n private readonly subscriptions = new Map<string, Subscription>();\n private transferable = false;\n private tokenBridge = false;\n private nextRequestId = 1;\n // Bumped on every initialize/stop. Async client callbacks capture the value\n // from the connection that created them so a stopped client cannot emit into\n // a later session instance (including the main-thread local fallback).\n private lifecycle = 0;\n private readonly pendingTokenRequests = new Map<number, PendingTokenRequest>();\n\n constructor(private readonly sink: CentrifugeSessionSink<TData>) {}\n\n /** Dispatch an incoming Worker message to the matching operation.\n * Unknown message types are ignored rather than thrown, so a future protocol\n * extension adding a new variant cannot crash an older session. */\n handle(message: CentrifugeWorkerInput): void {\n switch (message.type) {\n case CENTRIFUGE_INPUT_TYPE.INIT:\n this.initialize(message.url, message.config, message.transferable === true, message.tokenBridge === true);\n return;\n case CENTRIFUGE_INPUT_TYPE.SUBSCRIBE:\n this.subscribe(message.topic);\n return;\n case CENTRIFUGE_INPUT_TYPE.UNSUBSCRIBE:\n this.unsubscribe(message.topic);\n return;\n case CENTRIFUGE_INPUT_TYPE.PUBLISH:\n case CENTRIFUGE_INPUT_TYPE.PUBLISH_BIN:\n // Binary and JSON publish share the same Centrifuge client call; the\n // transport layer decides whether to transfer the ArrayBuffer.\n this.publish(message.topic, message.data, message.messageId, message.timestamp);\n return;\n case CENTRIFUGE_INPUT_TYPE.STOP:\n this.stop();\n return;\n case CENTRIFUGE_INPUT_TYPE.TOKEN_RESPONSE:\n this.resolveToken(message.requestId, message.token);\n return;\n case CENTRIFUGE_INPUT_TYPE.TOKEN_ERROR:\n this.rejectToken(message.requestId, deserializeWorkerError(message.error));\n return;\n default:\n return;\n }\n }\n\n /** Create the Centrifuge client, wire up lifecycle listeners, and connect. */\n private initialize(url: string, config: CentrifugeWorkerConfig, transferable: boolean, tokenBridge: boolean): void {\n if (this.client) return;\n const lifecycle = ++this.lifecycle;\n this.transferable = transferable;\n this.tokenBridge = tokenBridge;\n const clientOptions: CentrifugeWorkerConfig | CentrifugeBridgedOptions = tokenBridge\n ? {\n ...config,\n // Route credential fetches back to the main thread, where the\n // application's credentialProvider lives (config must stay\n // structured-cloneable, so functions cannot cross the boundary).\n getToken: () => this.requestToken('token', lifecycle),\n getChannelToken: (channel: string) => this.requestToken('channelToken', lifecycle, channel)\n }\n : config;\n const client = new Centrifuge(url, clientOptions);\n this.client = client;\n client.on('state', (context: StateContext) => {\n if (this.lifecycle !== lifecycle) return;\n this.post({ type: CENTRIFUGE_OUTPUT_TYPE.STATUS, status: normalizeStatus(context.newState) });\n });\n client.on('connected', () => {\n if (this.lifecycle !== lifecycle) return;\n this.post({ type: CENTRIFUGE_OUTPUT_TYPE.STATUS, status: WORKER_STATUS.CONNECTED });\n });\n client.on('disconnected', () => {\n if (this.lifecycle !== lifecycle) return;\n this.post({ type: CENTRIFUGE_OUTPUT_TYPE.STATUS, status: WORKER_STATUS.DISCONNECTED });\n });\n client.on('error', context => {\n if (this.lifecycle !== lifecycle) return;\n this.postError(context);\n });\n // Client-level publications are only for server-side subscriptions (where\n // no client Subscription object exists). For topics we have an active\n // subscription for, the subscription-level 'publication' listener handles\n // dispatch \u2014 skip here to avoid delivering the same message twice.\n client.on('publication', (context: PublicationContext) => {\n if (this.lifecycle !== lifecycle) return;\n const topic = context.channel || getPayloadTopic(context.data);\n if (!topic || this.subscriptions.has(topic)) return;\n this.postPublication(topic, context.data);\n });\n client.connect();\n }\n\n /** Subscribe to a Centrifuge channel. Reuses an existing subscription if one exists.\n * Listeners are only registered once per subscription object \u2014 a repeated\n * SUBSCRIBE for an already-tracked topic skips the listener wiring entirely,\n * avoiding the removeAllListeners + re-on churn on every duplicate message. */\n private subscribe(topic: string): void {\n if (!this.client) return this.postError(new Error('Centrifuge client is not initialized.'));\n const lifecycle = this.lifecycle;\n // If we already track this subscription, it already has our listeners \u2014\n // a duplicate SUBSCRIBE is a no-op (idempotent), matching the transport\n // contract. Only a fresh subscription needs listener wiring.\n const existing = this.subscriptions.get(topic);\n if (existing) {\n existing.subscribe();\n return;\n }\n let subscription = this.client.getSubscription(topic);\n if (!subscription) subscription = this.client.newSubscription(topic);\n // Scoped to the three events this method wires, so the client's own `state`\n // wiring is untouched \u2014 but `error` is NOT internal-listener-free: a no-op\n // `error` listener is installed on every subscription precisely\n // \"Avoid unhandled exception in EventEmitter for non-set error handler.\",\n // and not by `Subscription` itself \u2014 that class body contains no `on('error')`\n // call at all (measured on the pinned copy), so the guard runs in the\n // `BaseSubscription` constructor every subscription reaches through `super`.\n // (centrifuge 5.8.0. Line numbers here are read off the ORIGINAL source the\n // package now ships: `node_modules/centrifuge/dist/centrifuge.js.map`'s\n // `sourcesContent` carries `../src/subscription.ts` verbatim, so a reader can\n // open it \u2014 the built `dist/centrifuge.js` is mangled, and 5.7.4 shipped no\n // sources at all, which is why the previous copy quoted build substrings.)\n // `BaseSubscription`'s body is lines 25\u20132858 of that file and holds **eight**\n // `emit('error')` sites (5.7.4 had twelve): `_emitError` (1314), which every\n // guarded caller reaches through; `_subscribeError`'s expired-token emit (1330),\n // behind the `_isSubscribing()` test that opens the method; `_getSubscriptionToken`'s\n // `getToken === null` emit (1491), the one site with no state test of its own; and\n // five `untrack`-failure emits (1799, 1933, 2019, 2156, 2193) sitting in `.catch()`\n // continuations of `_sendUntrackRequest` \u2014 a shared-poll feature path this session\n // never enables, because `newSubscription(topic)` constructs a plain `Subscription`\n // with no options. A second change matters for what a listener-less emit costs:\n // `Subscription.emit` (1002) now wraps the emitter in try/catch and routes an\n // escaping throw to `this._centrifuge._handlerFailed(e)` \u2014 \"An exception escaping a\n // handler stops the client\", its own doc comment says \u2014 so the failure mode is no\n // longer an unhandled exception but a client-stopping handler failure. The\n // re-installation below puts a listener back for as long as this session holds the\n // subscription \u2014 three statements later (the `unsubscribed` removal, the\n // `subscriptions` set, the `publication` wiring), all inside this same synchronous\n // task, so no emit can land in between.\n // `unsubscribe()` removes both \u2014 this handler and the constructor's no-op \u2014 and\n // adds nothing back, which is settled rather than open. After `_setUnsubscribed`\n // has moved `state` to `Unsubscribed` no path re-enters the token-null emit: the\n // resubscribe timer's callback re-tests `_isSubscribing()` before it does anything\n // (1302), the client's reconnect pass drives only subscriptions whose state is\n // already `Subscribing` (`src/centrifuge.ts` in the same sourcemap, 2298), and\n // `_refresh()` is reachable only through `_refreshTimeout`, which\n // `_setUnsubscribed` clears via `_clearSubscribedState()` (1066 \u2192 472).\n // The 1491 exclusion still runs through the token, not the state: the three\n // `_getSubscriptionToken()` call sites that have no state test above them\n // (`_subscribe()`, `_loadStreamState()`'s `_getState().then(\u2026)` continuation and\n // `_mapSubscribe()`) reach their calls as the `else` of\n // `_canSubscribeWithoutGettingToken()` (741), which reads `!_usesToken() || !!_token`,\n // so entering the else needs `_usesToken()` true with a falsy `_token`; every falsy\n // value the class itself writes there is `''` (its option handling is\n // `if (options.token)`, 1391), and for `''` the `_usesToken()` half is exactly\n // `_getToken !== null`, which the emit's own `if (getToken === null)` refutes. So\n // the exclusion runs through the token, not the state \u2014 and through one of the\n // token's writers: `_refresh` assigns `self._token = token` (1523) whatever an\n // application `getToken` resolved with, so a falsy value that is not `''` would put\n // a wrapped call back in reach of the emit. A throw still needs the listeners gone\n // while the object is still live, and `unsubscribe()` does not leave it live.\n // `MapSubscription` and\n // `SharedPollSubscription` have their own emit sites but never carry this\n // session's listeners \u2014 `newSubscription` constructs a plain `Subscription`.\n subscription.removeAllListeners('publication');\n subscription.removeAllListeners('error');\n subscription.removeAllListeners('unsubscribed');\n this.subscriptions.set(topic, subscription);\n subscription.on('publication', context => {\n if (this.lifecycle !== lifecycle) return;\n this.postPublication(topic, context.data);\n });\n subscription.on('error', (context: SubscriptionErrorContext) => {\n if (this.lifecycle !== lifecycle) return;\n this.postError(context);\n });\n subscription.on('unsubscribed', () => {\n if (this.lifecycle === lifecycle) this.subscriptions.delete(topic);\n });\n subscription.subscribe();\n }\n\n /** Unsubscribe from a Centrifuge channel and clean up the local reference.\n * Listeners are removed before unsubscribing so a late `unsubscribed` event\n * cannot delete a subscription that a subsequent `subscribe()` re-added. */\n private unsubscribe(topic: string): void {\n const subscription = this.subscriptions.get(topic) ?? this.client?.getSubscription(topic);\n if (!subscription) return;\n subscription.removeAllListeners('publication');\n subscription.removeAllListeners('error');\n subscription.removeAllListeners('unsubscribed');\n this.subscriptions.delete(topic);\n subscription.unsubscribe();\n }\n\n /** Publish a message to the Centrifuge channel. */\n private publish(topic: string, data: unknown, messageId?: string, timestamp?: number): void {\n if (!this.client) return this.postError(new Error('Centrifuge client is not initialized.'));\n const lifecycle = this.lifecycle;\n // Centrifuge's payload is application-defined. Preserve legacy payloads;\n // when an ID is requested, send a small metadata envelope that compatible\n // servers can echo back for end-to-end deduplication.\n const hasMetadata = messageId !== undefined || timestamp !== undefined;\n const payload = hasMetadata\n ? {\n data,\n ...(messageId === undefined ? {} : { messageId }),\n ...(timestamp === undefined ? {} : { timestamp })\n }\n : data;\n void this.client.publish(topic, payload).catch(error => {\n if (this.lifecycle === lifecycle) this.postError(error);\n });\n }\n\n /** Forward a publication to the transport. Binary payloads take the\n * zero-copy `MESSAGE_BIN` path when `transferable` is enabled; everything\n * else is structured-cloned via `MESSAGE`. An empty topic means the\n * publication carried no channel info and is silently dropped.\n *\n * That drop is uncovered and dominated: the connection-level caller tests the\n * same emptiness before calling, and the subscription-level caller reads the\n * topic out of a key this session only ever populates from a SUBSCRIBE frame.\n * Measured \u2014 deleting this line leaves the whole suite green, and the frame\n * it withholds has nowhere to land anyway: the only handler registry is the\n * DataBus's `topicHandlers`, and every write to it sits behind\n * `assertPublicTopic` (at the head of `data-bus.ts`'s `subscribe()`, `publish()`\n * and `publishBatch()`), so no `''` key can\n * exist \u2014 while `topicMatchesPattern` answers false for an empty topic against\n * both `*` and `prefix.*`, so a wildcard handler cannot see it either. Neither\n * of those is a reason to delete this guard: it is the only one *at this layer*,\n * because neither the session nor the transport calls `assertPublicTopic` \u2014 a\n * SUBSCRIBE frame naming `''` creates a real Centrifuge subscription\n * (`newSubscription` does not validate a channel), so the undeliverable\n * publication would otherwise be posted back to the main thread. Kept as the\n * boundary statement, not counted as a closed leg. */\n private postPublication(topic: string, data: unknown): void {\n if (!topic) return;\n if (this.transferable && data instanceof ArrayBuffer) {\n this.post({ type: CENTRIFUGE_OUTPUT_TYPE.MESSAGE_BIN, topic, data }, [data]);\n return;\n }\n const publication = parseDataBusPublication<TData>(data, topic);\n if (!publication) return;\n this.post({\n type: CENTRIFUGE_OUTPUT_TYPE.MESSAGE,\n topic: publication.topic,\n data: publication.data,\n ...publicationMetadata(publication.messageId, publication.timestamp)\n });\n }\n\n /** Disconnect the client and clear all subscriptions. */\n private stop(): void {\n // Invalidate callbacks from the connection being stopped before disconnect\n // so its synchronous or queued events cannot leak into a later session.\n this.lifecycle += 1;\n // Settle every in-flight credential request so a stop cannot leave the\n // Worker awaiting a main-thread response forever.\n for (const [, pending] of this.pendingTokenRequests) {\n pending.reject(new Error('Centrifuge session stopped before the credential was resolved.'));\n }\n this.pendingTokenRequests.clear();\n this.client?.disconnect();\n this.subscriptions.clear();\n this.client = null;\n this.post({ type: CENTRIFUGE_OUTPUT_TYPE.STATUS, status: WORKER_STATUS.DISCONNECTED });\n }\n\n /** Issue a credential request to the main thread and await the response.\n * Used as Centrifuge's `getToken` / `getChannelToken` when token bridging is\n * enabled; resolved or rejected by a matching TOKEN_RESPONSE / TOKEN_ERROR. */\n private requestToken(kind: 'token' | 'channelToken', lifecycle: number, channel?: string): Promise<string> {\n // The provider is installed on a specific Centrifuge client. An old client\n // must not be able to route a late credential request into a replacement\n // session merely because it retained the callback closure.\n if (this.lifecycle !== lifecycle) {\n return Promise.reject(new Error('Centrifuge client lifecycle has ended before the credential was requested.'));\n }\n const requestId = this.nextRequestId;\n this.nextRequestId += 1;\n return new Promise<string>((resolve, reject) => {\n this.pendingTokenRequests.set(requestId, { resolve, reject });\n this.post({\n type: CENTRIFUGE_OUTPUT_TYPE.TOKEN_REQUEST,\n requestId,\n kind,\n ...(channel === undefined ? {} : { channel })\n });\n });\n }\n\n private resolveToken(requestId: number, token: string): void {\n const pending = this.pendingTokenRequests.get(requestId);\n if (!pending) return;\n this.pendingTokenRequests.delete(requestId);\n pending.resolve(token);\n }\n\n private rejectToken(requestId: number, error: unknown): void {\n const pending = this.pendingTokenRequests.get(requestId);\n if (!pending) return;\n this.pendingTokenRequests.delete(requestId);\n pending.reject(error);\n }\n\n /** Forward a message to the sink (the transport layer). */\n private post(message: CentrifugeWorkerOutput<TData>, transfer?: ArrayBuffer[]): void {\n this.sink.post(message, transfer);\n }\n\n /** Serialise and report an error. The Centrifuge client handles reconnection\n * internally, so a transient error should not trigger a `STATUS: error` that\n * would cause `selectActiveWorkers()` to exclude this worker from routing.\n * Fatal errors are distinguished by the client eventually emitting\n * `disconnected` without a subsequent `connected`. */\n private postError(error: unknown): void {\n this.post({ type: CENTRIFUGE_OUTPUT_TYPE.ERROR, error: serializeError(error) });\n }\n}\n\n/** Extract a topic from a Centrifuge publication payload if one is present.\n * Handles both direct `channel` fields and the nested `push.channel` shape\n * that Centrifugo uses for some server-side push types. */\nfunction getPayloadTopic(data: unknown): string {\n if (!data || typeof data !== 'object') return '';\n const payload = data as Record<string, unknown>;\n // Prefer nested push.channel (server-side push) then fall back to top-level channel.\n const push = payload.push;\n const nested = typeof push === 'object' && push !== null ? (push as Record<string, unknown>).channel : undefined;\n const topic = nested ?? payload.channel;\n return typeof topic === 'string' ? topic : '';\n}\n\n/** Map a Centrifuge state string to the DataBus's status vocabulary.\n * 'connecting' and 'connected' pass through; anything else (e.g. 'reconnecting',\n * 'disconnected') maps to 'disconnected'. */\nconst LIVE_STATES = new Set<string>([WORKER_STATUS.CONNECTING, WORKER_STATUS.CONNECTED]);\nfunction normalizeStatus(status: string): 'connecting' | 'connected' | 'disconnected' {\n return LIVE_STATES.has(status) ? (status as 'connecting' | 'connected') : 'disconnected';\n}\n", "/**\n * Worker-thread protocol for Centrifuge WebSocket transport.\n *\n * Defines the message types exchanged between the main thread and a Web Worker\n * (dedicated or shared) that runs a centrifuge client. The worker is isolated\n * from the main thread so that WebSocket lifecycle, token refresh, and binary\n * data handling never block the UI.\n *\n * The message `type` discriminant values are derived from the constants in\n * `utils/constants.ts` so main-thread and Worker sides reference the same\n * values and can never drift apart.\n */\nimport type { Options } from 'centrifuge';\nimport type { CENTRIFUGE_INPUT_TYPE, CENTRIFUGE_OUTPUT_TYPE } from './utils/constants';\nimport type { WorkerStatus } from './core/types';\nimport type { SerializedWorkerError } from './utils/error-utils';\n\nexport type { SerializedWorkerError } from './utils/error-utils';\n\n/**\n * Default interval between main-thread PING heartbeats to a SharedWorker. The\n * SharedWorker reaps a silent port after `SESSION_TIMEOUT_MULTIPLIER` intervals.\n * Shared here so the main thread (heartbeat sender) and the SharedWorker (reaper)\n * always agree on the cadence.\n */\nexport const DEFAULT_HEARTBEAT_INTERVAL_MS = 10_000;\n/** SharedWorker per-port session timeout, expressed as a multiple of that port's\n * heartbeat interval. A live port PINGs every heartbeat interval, so a timeout of\n * several intervals tolerates throttled tabs without reaping healthy sessions. */\nexport const DEFAULT_SESSION_TIMEOUT_MULTIPLIER = 3;\n/** Default per-port session timeout in ms, derived from the heartbeat interval\n * and the multiplier. Used as the fallback when a port sends no INIT config. */\nexport const DEFAULT_SESSION_TIMEOUT_MS =\n DEFAULT_HEARTBEAT_INTERVAL_MS * DEFAULT_SESSION_TIMEOUT_MULTIPLIER;\n\n// These options reference browser APIs (WebSocket, EventSource, fetch, \u2026) that\n// do not exist inside a Worker \u2014 the worker imports its own WebSocket. Nothing\n// strips them at runtime: `buildInitInput` forwards `config.options` verbatim,\n// so this exclusion is compile-time only. A value forced through with a cast is\n// caught by the runtime gate that does exist, `assertStructuredCloneable` on the\n// same options, which throws a TypeError from the transport before any backend\n// is created \u2014 a function-valued option would otherwise die at the structured-\n// clone boundary with a DataCloneError instead.\ntype WorkerUnsafeOption =\n | 'eventsource'\n | 'fetch'\n | 'getData'\n | 'getToken'\n | 'networkEventTarget'\n | 'readableStream'\n | 'sockjs'\n | 'websocket';\n\n/** Centrifuge options safe to pass into a Worker; unsafe options are explicitly\n * excluded and set to `never` so the compiler rejects them at the call site. */\nexport type CentrifugeWorkerConfig = Omit<Partial<Options>, WorkerUnsafeOption> & {\n [Key in WorkerUnsafeOption]?: never;\n};\n\n/**\n * Async credential provider run on the main thread. Centrifuge client options\n * are structured-cloned into the Worker, so function-valued `getToken` /\n * `getChannelToken` cannot travel with the config. When a provider is set, the\n * Worker asks the main thread for each fresh token over a TOKEN_REQUEST /\n * TOKEN_RESPONSE exchange and this provider supplies it from application\n * context (async token endpoints, SecureStorage, etc.).\n */\nexport interface CentrifugeCredentialProvider {\n /** Return a fresh top-level connection token. Called on connect and refresh. */\n getToken: () => MaybePromise<string | null | undefined>;\n /** Return a channel token for a channel. Centrifuge falls back to `getToken`\n * when channel tokens are not configured by the server. */\n getChannelToken?: (channel: string) => MaybePromise<string | null | undefined>;\n}\n\n/** A value or a promise of a value. */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/** Messages sent from the main thread to the Worker. All variants are\n * structured-cloneable; `PUBLISH_BIN` carries an ArrayBuffer (transferable). */\nexport type CentrifugeWorkerInput =\n /** Initial connection: URL + config. Sent once per backend creation.\n * `transferable` enables ArrayBuffer zero-copy for subsequent PUBLISH_BIN.\n * `heartbeatIntervalMs` overrides the SharedWorker PING cadence.\n * `tokenBridge` asks the Worker to route getToken/getChannelToken back to\n * the main thread instead of holding function-valued config. */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.INIT; url: string; config: CentrifugeWorkerConfig; transferable?: boolean; heartbeatIntervalMs?: number; tokenBridge?: boolean }\n /** Subscribe to a channel. Idempotent \u2014 re-subscribing is a no-op. */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.SUBSCRIBE; topic: string }\n /** Unsubscribe from a channel. Idempotent. */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.UNSUBSCRIBE; topic: string }\n /** Publish a structured-cloneable payload to a channel. */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.PUBLISH; topic: string; data: unknown; messageId?: string; timestamp?: number }\n /** Publish an ArrayBuffer via Transferable (zero-copy when `transferable` is on). */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.PUBLISH_BIN; topic: string; data: ArrayBuffer; messageId?: string; timestamp?: number }\n /** Heartbeat from the main thread; the SharedWorker reaps silent ports. */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.PING }\n /** Disconnect the client and clear all subscriptions. */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.STOP }\n /** Fresh credential for an earlier TOKEN_REQUEST, resolved by requestId. */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.TOKEN_RESPONSE; requestId: number; token: string }\n /** A credential request failed (provider rejected or returned no token). */\n | { type: typeof CENTRIFUGE_INPUT_TYPE.TOKEN_ERROR; requestId: number; error: SerializedWorkerError };\n\n/** Messages sent from the Worker back to the main thread. The main thread\n * routes these to the DataBusTransportHandlers via handleOutput(). */\nexport type CentrifugeWorkerOutput<TData = unknown> =\n /** Connection status changed. Maps Centrifuge states to the DataBus vocabulary. */\n | { type: typeof CENTRIFUGE_OUTPUT_TYPE.STATUS; status: WorkerStatus }\n /** A JSON publication arrived. Routed to onMessage via handleOutput. */\n | { type: typeof CENTRIFUGE_OUTPUT_TYPE.MESSAGE; topic: string; data: TData; messageId?: string; timestamp?: number }\n /** A binary publication arrived (Transferable). Routed to onMessage with the ArrayBuffer. */\n | { type: typeof CENTRIFUGE_OUTPUT_TYPE.MESSAGE_BIN; topic: string; data: ArrayBuffer; messageId?: string; timestamp?: number }\n /** A non-fatal error occurred. Does not imply disconnection (the client retries internally). */\n | { type: typeof CENTRIFUGE_OUTPUT_TYPE.ERROR; error: SerializedWorkerError }\n /** The Worker needs a fresh credential. The main thread resolves it via a\n * matching TOKEN_RESPONSE / TOKEN_ERROR carrying the same `requestId`. */\n | { type: typeof CENTRIFUGE_OUTPUT_TYPE.TOKEN_REQUEST; requestId: number; kind: 'token' | 'channelToken'; channel?: string }\n /** The SharedWorker's reaper is about to close this port, so its session and\n * WebSocket are going away with it. Sent as the last message on the port: a tab\n * whose heartbeat was merely starved (a long task, background throttling) is\n * alive and can rebuild, but only if it learns that its backend is gone. */\n | { type: typeof CENTRIFUGE_OUTPUT_TYPE.SESSION_REAPED };\n", "/**\n * Reaper for SharedWorker ports.\n *\n * A `MessagePort` has no `close` event, so the SharedWorker cannot tell whether\n * a tab died without sending STOP. The main thread therefore sends periodic\n * PING messages, and this reaper closes any session whose port has been silent\n * longer than its timeout.\n *\n * The cadence is adaptive: the reaper runs at the smallest configured heartbeat\n * interval across active ports, and stops entirely when the last port is\n * removed, so a long-lived SharedWorker does not run a perpetual no-op interval\n * between connect bursts.\n *\n * The timers and clock are injected so the reaper can be unit-tested without a\n * real worker or DOM.\n */\n\nimport {\n DEFAULT_HEARTBEAT_INTERVAL_MS,\n DEFAULT_SESSION_TIMEOUT_MS,\n DEFAULT_SESSION_TIMEOUT_MULTIPLIER\n} from '../centrifuge-protocol';\n\n/** The three teardown steps `reap()` runs on a silent port, in that order:\n * `notify` posts the loss to the main thread, `close` withdraws the port, `stop`\n * ends its session. `notify` has to go first because a closed port discards\n * anything posted after it, so this is its owner's only notice of why the\n * session ended. The three share one `try`/`catch`: a target that throws in\n * `notify` also skips `close` and `stop` for itself, which `reap()` accepts\n * rather than working around. */\nexport interface ReapTarget {\n notify(): void;\n close(): void;\n stop(): void;\n}\n\ntype SetTimer = (callback: () => void, ms: number) => number;\ntype ClearTimer = (handle: number) => void;\n\nexport class PortReaper {\n private readonly targets = new Map<MessagePort, ReapTarget>();\n private readonly lastSeenAt = new Map<MessagePort, number>();\n private readonly sessionTimeoutMs = new Map<MessagePort, number>();\n private handle: number | null = null;\n private intervalMs = DEFAULT_HEARTBEAT_INTERVAL_MS;\n\n constructor(\n private readonly now: () => number = Date.now,\n setTimer: SetTimer = (callback, ms) => setInterval(callback, ms) as unknown as number,\n clearTimer: ClearTimer = handle => clearInterval(handle)\n ) {\n this.setTimer = setTimer;\n this.clearTimer = clearTimer;\n }\n\n private readonly setTimer: SetTimer;\n private readonly clearTimer: ClearTimer;\n\n /** Track a newly connected port and its session. The default timeout applies\n * until the port sends an INIT with its own heartbeat config, at which point\n * setTimeout() overrides it. register() always calls schedule() so the\n * reaper interval starts as soon as the first port connects. */\n register(port: MessagePort, target: ReapTarget): void {\n this.targets.set(port, target);\n this.lastSeenAt.set(port, this.now());\n this.sessionTimeoutMs.set(port, DEFAULT_SESSION_TIMEOUT_MS);\n this.schedule();\n }\n\n /** Record activity on a port (any incoming message). The early return is what\n * keeps a late PING from a removed port out of `lastSeenAt`: `reap()` iterates\n * `targets`, so a row here would be unreachable rather than dangerous \u2014 measured,\n * deleting the guard passes every test in the suite, because the only difference is\n * one stale map entry per dead port. It stays as the cheap invariant that the three\n * maps hold exactly the tracked ports, which is what `reap()`'s `??` fallbacks and\n * this file's tracking contract both lean on. */\n touch(port: MessagePort): void {\n if (!this.targets.has(port)) return;\n this.lastSeenAt.set(port, this.now());\n }\n\n /** Override a port's session timeout from its INIT heartbeat config.\n * `Infinity` is the documented way to disable the PING heartbeat, and it means\n * this port can never be judged silent: `startHeartbeat()` sends nothing at all\n * once configured that way, so a timeout would be a death sentence with no\n * possible appeal. A non-finite-or-non-positive *other* value falls back to\n * the default, which keeps the timeout comparison from degenerating into\n * \"always expired\" \u2014 a NaN timeout reaps every port on the first tick. Read\n * that narrowly, because it is not a busy-loop guard: the busy-loop vector is\n * a tiny *positive* interval, which the ternary passes through untouched\n * (0.0001 \u2192 a 0.0003 ms timeout \u2192 every tick reaps everything), and the\n * reaper's own cadence is bounded elsewhere \u2014 `computeMinHeartbeat` starts\n * from DEFAULT_HEARTBEAT_INTERVAL_MS and only takes a minimum, so a payload\n * can shorten the sweep but never stretch it past 10 s. The three values\n * rejected here (NaN, 0, negative) are also rejected by\n * `assertHeartbeatInterval` at the transport constructor and so can only\n * arrive from a main thread that is not this library. No-op for untracked\n * ports (e.g. setTimeout arrives after remove/STOP). */\n setTimeout(port: MessagePort, heartbeatIntervalMs: number): void {\n if (!this.targets.has(port)) return;\n const safe = heartbeatIntervalMs === Infinity\n ? Infinity\n : Number.isFinite(heartbeatIntervalMs) && heartbeatIntervalMs > 0\n ? heartbeatIntervalMs\n : DEFAULT_HEARTBEAT_INTERVAL_MS;\n this.sessionTimeoutMs.set(port, safe * DEFAULT_SESSION_TIMEOUT_MULTIPLIER);\n this.schedule();\n }\n\n /** Remove a port (STOP message). The caller is responsible for closing the\n * port and stopping the session. No-op for untracked ports so a duplicate\n * STOP or a STOP-after-reap cannot corrupt the reaper's bookkeeping. */\n remove(port: MessagePort): void {\n if (!this.targets.has(port)) return;\n this.targets.delete(port);\n this.lastSeenAt.delete(port);\n this.sessionTimeoutMs.delete(port);\n this.schedule();\n }\n\n /** Clear all state and stop the reaper. Closes and stops every tracked\n * session so the SharedWorker does not leak WebSockets on shutdown. */\n dispose(): void {\n if (this.handle !== null) this.clearTimer(this.handle);\n this.handle = null;\n for (const target of this.targets.values()) {\n try {\n target.close();\n target.stop();\n } catch {\n // A failing target must not prevent the rest from being cleaned up.\n }\n }\n this.targets.clear();\n this.lastSeenAt.clear();\n this.sessionTimeoutMs.clear();\n }\n\n /** Recompute the reaper cadence, or stop it entirely when no ports remain.\n * Idempotent: if the interval is already running at the correct cadence,\n * no new timer is created. This guards against register/remove/setTimeout\n * each spawning redundant timers when the cadence hasn't changed. */\n private schedule(): void {\n if (this.sessionTimeoutMs.size === 0) {\n // Zero counts on the guard's false arm: reaching this line with `handle`\n // already null needs a `schedule()` call made while all three maps are empty,\n // and every caller is gated on a tracked port \u2014 `remove()` and `setTimeout()`\n // behind `targets.has(port)`, `register()` having just added one, and the reap\n // pass only after it reaped something. The two statements that null `handle`\n // are this branch itself, which requires the empty map it implies, and\n // `dispose()`, which clears all three maps and therefore takes every caller's\n // guard with it. `dispose()` also has no Worker-side caller at all \u2014 recorded\n // in configuration.md \u2014 so in the shipped SharedWorker this arm is\n // unreachable rather than merely unreached. It stays as the file's statement\n // that a null handle is never handed to `clearTimer`.\n // The null assignment is what keeps this terminating, and that is a stronger\n // statement than \"correctness\": measured, replacing it with *any* re-arm \u2014\n // including a 0 ms one \u2014 produces a mutant that **never terminates**, because\n // `setTimer(() => this.reap(), 0)` re-enters `reap()`, which reaches this\n // branch again with the maps still empty, forever. It cost a thirty-minute\n // harness run and a mutated working tree before the mutant was bounded, so the\n // measurement is recorded here: a null handle is not merely tidy here, it is\n // the only thing standing between this branch and an unbounded timer loop.\n if (this.handle !== null) this.clearTimer(this.handle);\n this.handle = null;\n return;\n }\n const minHeartbeat = this.computeMinHeartbeat();\n if (this.handle !== null && this.intervalMs === minHeartbeat) return;\n if (this.handle !== null) this.clearTimer(this.handle);\n this.intervalMs = minHeartbeat;\n this.handle = this.setTimer(() => this.reap(), minHeartbeat);\n }\n\n /** Smallest heartbeat interval among active ports, derived from each port's\n * configured session timeout. Extracted because `schedule()` derives its delay\n * from it on every re-arm. Not a test seam: nothing in `tests/` calls it\n * (grep: zero hits), and the cadence is asserted through the injected\n * `setTimer` \u2014 i.e. through the same plumbing this note used to claim it was\n * isolated from. */\n private computeMinHeartbeat(): number {\n let minHeartbeat = DEFAULT_HEARTBEAT_INTERVAL_MS;\n for (const timeout of this.sessionTimeoutMs.values()) {\n minHeartbeat = Math.min(minHeartbeat, timeout / DEFAULT_SESSION_TIMEOUT_MULTIPLIER);\n }\n return minHeartbeat;\n }\n\n /** Close sessions whose port has been silent longer than its timeout.\n * Iterates a snapshot. That is defensive rather than load-bearing: `Map`\n * iteration in JS is deletion-safe, so removing the current entry cannot skip the\n * next one, and the only case a snapshot changes is a re-entrant `register()` from\n * inside a target's own teardown \u2014 which a fresh port would survive anyway, because\n * `register()` stamps `lastSeenAt` with the current time and a zero-age port is\n * never past its timeout. Measured: iterating the live map instead passes every\n * test, so do not read this line as pinned. */\n private reap(): void {\n const now = this.now();\n let reapedAny = false;\n for (const [port, target] of Array.from(this.targets)) {\n // Both `??` arms are uncovered and dominated, and the enumeration is the\n // tracking contract above: `targets` gains a port only in `register()`,\n // which writes all three maps, and loses one only in `remove()` and in the\n // loop below, and in the whole-map `clear()`s of dispose(): a port in\n // `targets` is therefore in the other two as well. Measured \u2014 replacing the\n // first fallback with a non-null assertion leaves the whole suite green.\n // It stays because of what a half-registered port would cost: `lastSeen` 0\n // reads as silent-since-epoch, so the next tick closes a session that was\n // never late, which is a worse failure than the undefined it stands in for.\n const lastSeen = this.lastSeenAt.get(port) ?? 0;\n const timeout = this.sessionTimeoutMs.get(port) ?? DEFAULT_SESSION_TIMEOUT_MS;\n if (now - lastSeen <= timeout) continue;\n this.targets.delete(port);\n this.lastSeenAt.delete(port);\n this.sessionTimeoutMs.delete(port);\n // Announce before withdrawing, then close the port and stop the session.\n // The order matters in both directions:\n // - `notify` is the last thing this port ever delivers, and it has to\n // precede `close()`, because a closed port discards everything posted to\n // it \u2014 including the session's own `disconnected` status post. A tab whose\n // heartbeat was merely starved (a long task, the throttling a backgrounded\n // tab gets) rather than gone is alive and can rebuild its backend, but only\n // if it learns the session left. Measured in a real browser before this\n // existed: a 34 s stall got a shared-mode tab's port reaped while the bus\n // kept `state: healthy` / `status: connected` and its routes, and every\n // publication it posted went into the closed port and vanished.\n // - `close` still precedes `stop`: the STOP handler posts that\n // `disconnected` status back to the port, which must not reach the main\n // thread after it has been told outright, and a closed port can never\n // deliver a later message that would resurrect the session outside the\n // reaper's tracking.\n // All three share the existing try/catch, which isolates a failing target\n // from the *other* ports in the pass. That is the same guarantee `close`\n // already had: a step that throws also skips the steps after it for this one\n // target, which is accepted here rather than newly introduced.\n try {\n target.notify();\n target.close();\n target.stop();\n } catch {\n // A failing target must not prevent the rest from being reaped or\n // leave the reaper in a broken state for subsequent ticks.\n }\n reapedAny = true;\n }\n // Recompute the cadence (and clear the interval if the last port was reaped).\n //\n // `if (reapedAny)` is **dominated**, and the proof is a pair rather than an\n // argument: deleting it alone leaves the suite green, because `schedule()` opens\n // with its own idempotency guard, so a call at an unchanged cadence is a no-op.\n // Deleting *both* \u2014 this condition and that guard \u2014 kills three cases. So the\n // reschedule is redundant with the idempotency check a few lines above it, and\n // this reads as a leg about avoiding pointless work rather than about\n // correctness. Kept: it says the intent (recompute only when the sweep did\n // something) at the point where the sweep happened, where the next reader is\n // looking.\n if (reapedAny) this.schedule();\n }\n}", "/// <reference lib=\"webworker\" />\n\n/**\n * SharedWorker hosting one independent Centrifuge WebSocket client per tab.\n *\n * Each connecting tab receives its own MessagePort with an independent\n * CentrifugeSession and its own WebSocket connection. When a tab sends STOP,\n * its port is unregistered from the reaper and closed while the remaining tabs\n * continue to operate. There is no session map to remove it from: each\n * connection's session is a closure variable in the connect handler, and the\n * only per-port indexed state is the reaper's own maps.\n *\n * A periodic reaper (PortReaper) closes sessions for ports that have stopped\n * sending messages (e.g. crashed tabs). The reaper cadence is adaptive: it runs\n * at the smallest configured heartbeat interval across active ports, derived\n * from the `heartbeatIntervalMs` the main thread sends in the INIT message.\n * The interval is cleared when the last port is disconnected.\n */\n\nimport type { CentrifugeWorkerInput } from '../centrifuge-protocol';\nimport { CentrifugeSession } from '../centrifuge-session';\nimport { PortReaper } from './port-reaper';\nimport { CENTRIFUGE_INPUT_TYPE, CENTRIFUGE_OUTPUT_TYPE } from '../utils/constants';\n\nconst sharedWorkerScope = self as unknown as SharedWorkerGlobalScope;\n// One session per connecting port \u2014 each tab gets its own subscription scope.\nconst reaper = new PortReaper();\n\nsharedWorkerScope.addEventListener('connect', event => {\n const port = event.ports[0];\n if (!port) return;\n const session = new CentrifugeSession({\n post: (message, transfer) => {\n // Transferable buffers are forwarded when present (zero-copy ArrayBuffer);\n // otherwise the message is structured-cloned normally.\n if (transfer) port.postMessage(message, transfer as Transferable[]);\n else port.postMessage(message);\n }\n });\n reaper.register(port, {\n // Last message this port will ever deliver. The main thread's transport turns\n // it into a backend failure, which is what lets a tab whose heartbeat was\n // merely starved (long task, background throttling) recover instead of going\n // on owning routes that post into a closed port.\n notify: () => port.postMessage({ type: CENTRIFUGE_OUTPUT_TYPE.SESSION_REAPED }),\n close: () => port.close(),\n stop: () => session.handle({ type: CENTRIFUGE_INPUT_TYPE.STOP })\n });\n port.addEventListener('message', event => {\n const message = event.data as CentrifugeWorkerInput;\n reaper.touch(port);\n if (message.type === CENTRIFUGE_INPUT_TYPE.PING) return;\n if (message.type === CENTRIFUGE_INPUT_TYPE.STOP) {\n // Remove from reaper tracking first, then close the port so the\n // session's disconnected status post is discarded, then stop the\n // session to cleanly disconnect its WebSocket.\n reaper.remove(port);\n port.close();\n session.handle({ type: CENTRIFUGE_INPUT_TYPE.STOP });\n return;\n }\n // Capture the heartbeat config from the first (INIT) message so the\n // reaper uses the correct per-port timeout.\n if (message.type === CENTRIFUGE_INPUT_TYPE.INIT && typeof message.heartbeatIntervalMs === 'number') {\n reaper.setTimeout(port, message.heartbeatIntervalMs);\n }\n session.handle(message);\n });\n port.start();\n});"],
|
|
5
|
+
"mappings": ";AAiBA,SAAS,UAAU,SAAS,YAAY,GAAG,WAAW;AAClD,WAAS,MAAM,OAAO;AAAE,WAAO,iBAAiB,IAAI,QAAQ,IAAI,EAAE,SAAU,SAAS;AAAE,cAAQ,KAAK;AAAA,IAAG,CAAC;AAAA,EAAG;AAC3G,SAAO,KAAK,MAAM,IAAI,UAAU,SAAU,SAAS,QAAQ;AACvD,aAAS,UAAU,OAAO;AAAE,UAAI;AAAE,aAAK,UAAU,KAAK,KAA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,MAAM,QAAQ,OAAO,EAAE,MAAM,sBAAsB,KAAK,CAAC;AAAA,EACjE,CAAC;AACD,OAAK,iBAAiB,WAAW,CAAAC,WAAS;AACxC,UAAM,UAAUA,OAAM;AACtB,WAAO,MAAM,IAAI;AACjB,QAAI,QAAQ,SAAS,sBAAsB,KAAM;AACjD,QAAI,QAAQ,SAAS,sBAAsB,MAAM;AAI/C,aAAO,OAAO,IAAI;AAClB,WAAK,MAAM;AACX,cAAQ,OAAO,EAAE,MAAM,sBAAsB,KAAK,CAAC;AACnD;AAAA,IACF;AAGA,QAAI,QAAQ,SAAS,sBAAsB,QAAQ,OAAO,QAAQ,wBAAwB,UAAU;AAClG,aAAO,WAAW,MAAM,QAAQ,mBAAmB;AAAA,IACrD;AACA,YAAQ,OAAO,OAAO;AAAA,EACxB,CAAC;AACD,OAAK,MAAM;AACb,CAAC;",
|
|
6
6
|
"names": ["ReflectApply", "ReflectOwnKeys", "NumberIsNaN", "EventEmitter", "events", "once", "errorCodes", "connectingCodes", "disconnectedCodes", "subscribingCodes", "unsubscribedCodes", "subscriptionFlags", "State", "SubscriptionState", "MapPhase", "sendFn", "self", "keys", "sub", "event"]
|
|
7
7
|
}
|