centrifuge
Version:
JavaScript client SDK for bidirectional communication with Centrifugo and Centrifuge-based server from browser, NodeJS and React Native
20,016 lines • 905 kB
JavaScript
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var events = {exports: {}};
var hasRequiredEvents;
function requireEvents () {
if (hasRequiredEvents) return events.exports;
hasRequiredEvents = 1;
var R = typeof Reflect === 'object' ? Reflect : null;
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
};
var ReflectOwnKeys;
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys;
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
};
function EventEmitter() {
EventEmitter.init.call(this);
}
events.exports = EventEmitter;
events.exports.once = once;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err; // Unhandled 'error' event
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
// not listening for removeListener, no need to emit
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function (resolve, reject) {
function errorListener(err) {
emitter.removeListener(name, resolver);
reject(err);
}
function resolver() {
if (typeof emitter.removeListener === 'function') {
emitter.removeListener('error', errorListener);
}
resolve([].slice.call(arguments));
}
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
if (name !== 'error') {
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
}
});
}
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
if (typeof emitter.on === 'function') {
eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
}
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
if (typeof emitter.on === 'function') {
if (flags.once) {
emitter.once(name, listener);
} else {
emitter.on(name, listener);
}
} else if (typeof emitter.addEventListener === 'function') {
// EventTarget does not have `error` event semantics like Node
// EventEmitters, we do not listen for `error` events here.
emitter.addEventListener(name, function wrapListener(arg) {
// IE does not have builtin `{ once: true }` support so we
// have to do it manually.
if (flags.once) {
emitter.removeEventListener(name, wrapListener);
}
listener(arg);
});
} else {
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
}
}
return events.exports;
}
var eventsExports = requireEvents();
var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventsExports);
var errorCodes;
(function (errorCodes) {
errorCodes[errorCodes["timeout"] = 1] = "timeout";
errorCodes[errorCodes["transportClosed"] = 2] = "transportClosed";
errorCodes[errorCodes["clientDisconnected"] = 3] = "clientDisconnected";
errorCodes[errorCodes["clientClosed"] = 4] = "clientClosed";
errorCodes[errorCodes["clientConnectToken"] = 5] = "clientConnectToken";
errorCodes[errorCodes["clientRefreshToken"] = 6] = "clientRefreshToken";
errorCodes[errorCodes["subscriptionUnsubscribed"] = 7] = "subscriptionUnsubscribed";
errorCodes[errorCodes["subscriptionSubscribeToken"] = 8] = "subscriptionSubscribeToken";
errorCodes[errorCodes["subscriptionRefreshToken"] = 9] = "subscriptionRefreshToken";
errorCodes[errorCodes["transportWriteError"] = 10] = "transportWriteError";
errorCodes[errorCodes["connectionClosed"] = 11] = "connectionClosed";
errorCodes[errorCodes["badConfiguration"] = 12] = "badConfiguration";
errorCodes[errorCodes["subscriptionGetState"] = 13] = "subscriptionGetState";
errorCodes[errorCodes["sharedPollGetSignature"] = 14] = "sharedPollGetSignature";
})(errorCodes || (errorCodes = {}));
var connectingCodes;
(function (connectingCodes) {
connectingCodes[connectingCodes["connectCalled"] = 0] = "connectCalled";
connectingCodes[connectingCodes["transportClosed"] = 1] = "transportClosed";
connectingCodes[connectingCodes["noPing"] = 2] = "noPing";
connectingCodes[connectingCodes["subscribeTimeout"] = 3] = "subscribeTimeout";
connectingCodes[connectingCodes["unsubscribeError"] = 4] = "unsubscribeError";
})(connectingCodes || (connectingCodes = {}));
var disconnectedCodes;
(function (disconnectedCodes) {
disconnectedCodes[disconnectedCodes["disconnectCalled"] = 0] = "disconnectCalled";
disconnectedCodes[disconnectedCodes["unauthorized"] = 1] = "unauthorized";
disconnectedCodes[disconnectedCodes["badProtocol"] = 2] = "badProtocol";
disconnectedCodes[disconnectedCodes["messageSizeLimit"] = 3] = "messageSizeLimit";
// Server-sent: the connection's cached state and/or token are no longer valid.
// The client clears the connection token (to force getToken), invalidates all
// subscription state, and reconnects. Delivered as a Disconnect push or a raw
// WebSocket close code.
disconnectedCodes[disconnectedCodes["stateInvalidated"] = 3014] = "stateInvalidated";
})(disconnectedCodes || (disconnectedCodes = {}));
var subscribingCodes;
(function (subscribingCodes) {
subscribingCodes[subscribingCodes["subscribeCalled"] = 0] = "subscribeCalled";
subscribingCodes[subscribingCodes["transportClosed"] = 1] = "transportClosed";
})(subscribingCodes || (subscribingCodes = {}));
var unsubscribedCodes;
(function (unsubscribedCodes) {
unsubscribedCodes[unsubscribedCodes["unsubscribeCalled"] = 0] = "unsubscribeCalled";
unsubscribedCodes[unsubscribedCodes["unauthorized"] = 1] = "unauthorized";
unsubscribedCodes[unsubscribedCodes["clientClosed"] = 2] = "clientClosed";
// Server-sent (in an Unsubscribe push): this subscription's cached state
// and/or token are no longer valid. The client clears the subscription state
// and resubscribes (this is a temporary unsubscribe, code >= 2500).
unsubscribedCodes[unsubscribedCodes["stateInvalidated"] = 2502] = "stateInvalidated";
})(unsubscribedCodes || (unsubscribedCodes = {}));
var subscriptionFlags;
(function (subscriptionFlags) {
subscriptionFlags[subscriptionFlags["channelCompaction"] = 1] = "channelCompaction";
subscriptionFlags[subscriptionFlags["rejectUnrecovered"] = 2] = "rejectUnrecovered";
})(subscriptionFlags || (subscriptionFlags = {}));
/** State of client. */
var State;
(function (State) {
State["Disconnected"] = "disconnected";
State["Connecting"] = "connecting";
State["Connected"] = "connected";
})(State || (State = {}));
/** State of Subscription */
var SubscriptionState;
(function (SubscriptionState) {
SubscriptionState["Unsubscribed"] = "unsubscribed";
SubscriptionState["Subscribing"] = "subscribing";
SubscriptionState["Subscribed"] = "subscribed";
})(SubscriptionState || (SubscriptionState = {}));
/** @internal */
function startsWith(value, prefix) {
return value.lastIndexOf(prefix, 0) === 0;
}
/** @internal */
function isFunction(value) {
if (value === undefined || value === null) {
return false;
}
return typeof value === 'function';
}
/** @internal */
function log(level, args) {
if (globalThis.console) {
const logger = globalThis.console[level];
if (isFunction(logger)) {
logger.apply(globalThis.console, args);
}
}
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
/** @internal */
function backoff(step, min, max) {
// Full jitter technique, see:
// https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
if (step > 31) {
step = 31;
}
const interval = randomInt(0, Math.min(max, min * Math.pow(2, step)));
return Math.min(max, min + interval);
}
/** @internal */
function errorExists(data) {
return 'error' in data && data.error !== null;
}
/** @internal */
function ttlMilliseconds(ttl) {
// https://stackoverflow.com/questions/12633405/what-is-the-maximum-delay-for-setinterval
return Math.min(ttl * 1000, 2147483647);
}
/** @internal */
function localStorageItem(key) {
// Accessing localStorage is not always safe: it may be null (Safari in
// private browsing mode), or even throw on property access (when access to
// storage is denied by the browser settings).
try {
if (typeof localStorage === 'undefined' || localStorage === null || !isFunction(localStorage.getItem)) {
return null;
}
return localStorage.getItem(key);
}
catch (e) {
return null;
}
}
/** @internal Reports whether a publication carries an offset. Protobuf decodes a
* missing offset as 0 (a Long where long.js is available), which must not replace
* a stored position. */
function hasOffset(offset) {
return offset !== undefined && offset !== null && Number(offset) > 0;
}
/** @internal Converts an offset of a reply or a publication to a number.
* Over the protobuf protocol a uint64 decodes to a Long object where long.js is
* available (it comes with protobufjs), and such an object must reach neither the
* app — the public types declare a number, and an app storing the position gets
* `{low, high, unsigned}` back, which compares and adds as NaN — nor the position
* the library keeps. A position an app stored with an earlier version, and passes
* back through `since`, has the same shape without the methods, so it is converted
* here too. Offsets above 2^53 lose exactness, as the public type implies. */
function toOffset(offset) {
if (offset === undefined || offset === null) {
return 0;
}
if (typeof offset === 'object') {
const low = offset.low;
const high = offset.high;
if (typeof low === 'number' && typeof high === 'number') {
return (high >>> 0) * 4294967296 + (low >>> 0);
}
}
const value = Number(offset);
return isNaN(value) ? 0 : value;
}
// Internal-only — phases the SDK walks through during a map subscribe.
// Not exposed on the public surface; kept here so it doesn't leak via
// `export * from "./types"` in index.ts.
var MapPhase;
(function (MapPhase) {
MapPhase[MapPhase["Live"] = 0] = "Live";
MapPhase[MapPhase["Stream"] = 1] = "Stream";
MapPhase[MapPhase["State"] = 2] = "State";
})(MapPhase || (MapPhase = {}));
/** Base subscription to a channel — all subscription logic lives here. */
class BaseSubscription extends EventEmitter {
/** Subscription constructor should not be used directly, create subscriptions using Client method. */
constructor(centrifuge, channel, options) {
super();
this._resubscribeTimeout = null;
this._refreshTimeout = null;
/** The offset of the publication being dispatched, until its handler returned. See _getOffset. */
this._pendingOffset = null;
// @ts-ignore – this is set by a client in centrifuge.ts.
this._removed = false;
// Stream getState callback (external state for stream subscriptions)
this._getState = null;
// Map subscription state
this._map = false;
this._mapPresenceType = 1; // 1=MAP, 2=MAP_CLIENTS, 3=MAP_USERS
// @ts-ignore – this is used for tracking map subscription phase state.
this._mapPhase = null;
// Publications of state and stream pages, decoded once the live reply tells
// whether delta is on (see _handleMapLiveResponse).
this._mapStateBuffer = [];
this._mapStreamBuffer = [];
this._mapCursor = ''; // Pagination cursor
this._mapPageSize = 0; // Page size (0 = use server default)
this._mapUnrecoverableStrategy = 'from_scratch';
// Incremented when the map position is reset (setTagsFilter, state invalidation),
// so a subscribe that completes meanwhile doesn't store its position over that.
this._mapPositionResets = 0;
// The subscribe flow in progress: replies and continuations of an earlier flow are
// ignored. Every map flow and every unsubscribe starts a new one, so a subscribe
// reply still in flight when the app calls unsubscribe() and subscribe() doesn't
// complete the new subscribe. A map flow pages from its own stream offset and
// epoch; the subscription position (_offset/_epoch) moves only with what the app
// received.
this._subscribeFlow = 0;
// Incremented whenever the subscription stops being subscribed: a token or signature
// obtained for an earlier subscribed period is outdated (see _refresh).
this._refreshGeneration = 0;
// Set while a shared poll subscription completes its subscribe: tracking changes of
// handlers of its events go out with the replay that follows, not before it too.
this._sharedPollReplayPending = false;
// Incremented by every state change: an event of a change a 'state' handler
// followed with another one is outdated, even when that one came back to the
// same state.
this._stateTransitions = 0;
// Over emulation, the shared poll track / untrack requests of the channel, one
// at a time (see _sharedPollSerial).
this._sharedPollQueue = Promise.resolve();
// The flow of the subscribe command (or map page) waiting for its reply.
this._subscribeCallFlow = null;
// Over emulation, the unsubscribe of a subscribe in flight: sent once the
// subscribe's reply comes (see _setUnsubscribed).
this._deferredUnsubscribe = null;
this._mapFlowRecovering = false;
this._mapFlowOffset = 0;
this._mapFlowEpoch = null;
this._mapFlowPositionResets = 0;
// Publish debounce state (protocol-level, controlled by server)
this._debounceMs = 0;
this._debouncePending = new Map();
// Shared poll subscription state
this._sharedPoll = false;
this._sharedPollEpoch = '';
this._sharedPollTrackedItems = new Map(); // key → version
this._sharedPollGetSignature = null;
// TTL-driven and 109-driven consolidating refresh (one call to getSignature
// covering all tracked keys, replaces the library with one entry).
this._sharedPollSignatureRefreshTimeout = null;
this._sharedPollSignatureRefreshAttempts = 0;
// Per-track-command transient retry (track call failed with temporary error).
this._sharedPollTrackRetryTimeout = null;
this._sharedPollTrackRetryAttempts = 0;
// Replay-getSignature retry (Phase 2 of _sharedPollReplayTrack failed). Held
// separately so it can't clobber the refresh timer or accumulate backoff
// attempts onto refresh failures.
this._sharedPollReplayRetryTimeout = null;
this._sharedPollReplayRetryAttempts = 0;
// Library of HMAC signatures previously obtained for track() calls.
// Each entry covers the exact key set originally signed; reused on reconnect
// so we don't hit the application's getSignature endpoint for every client
// during mass reconnect storms. Periodic refresh consolidates entries into
// one combined signature covering all currently tracked keys.
this._sharedPollSignatures = [];
// Earliest scheduled refresh time (unix milliseconds) across all received
// track responses. Server returns MIN ttl per response; SDK keeps the
// single earliest deadline as the refresh target. Cleared on consolidation
// refresh and on explicit unsubscribe.
this._sharedPollSignatureRefreshTargetMs = null;
// Guard against concurrent refresh calls — multiple 109 errors during
// reconnect replay could otherwise trigger overlapping getSignature calls.
this._sharedPollSignatureRefreshInFlight = false;
// A refresh asked for while one was in flight for keys it doesn't cover (e.g.
// a 109 of a key tracked since it started): run after it.
this._sharedPollSignatureRefreshAgain = false;
// The keys of the refresh in flight.
this._sharedPollSignatureRefreshKeys = new Set();
this.channel = channel;
this.state = SubscriptionState.Unsubscribed;
this._centrifuge = centrifuge;
this._token = '';
this._getToken = null;
this._data = null;
this._getData = null;
this._recover = false;
this._offset = null;
this._epoch = null;
this._id = 0;
this._recoverable = false;
this._positioned = false;
this._joinLeave = false;
this._minResubscribeDelay = 500;
this._maxResubscribeDelay = 20000;
this._resubscribeTimeout = null;
this._resubscribeAttempts = 0;
this._promises = {};
this._promiseId = 0;
this._inflight = false;
this._refreshTimeout = null;
this._delta = '';
this._delta_negotiated = false;
this._tagsFilter = null;
this._prevValueMap = new Map();
this._unsubPromise = Promise.resolve();
this._deltaNumPubs = 0;
this._deltaNumFull = 0;
this._deltaNumDelta = 0;
this._deltaBytesReceived = 0;
this._deltaBytesDecoded = 0;
this._setOptions(options);
this.type = this._sharedPoll ? 'shared_poll' : this._map ? 'map' : 'stream';
// @ts-ignore – we are hiding some symbols from public API autocompletion.
if (this._centrifuge._debugEnabled) {
this.on('state', (ctx) => {
this._debug('subscription state', channel, ctx.oldState, '->', ctx.newState);
});
this.on('error', (ctx) => {
this._debug('subscription error', channel, ctx);
});
}
else {
// Avoid unhandled exception in EventEmitter for non-set error handler.
this.on('error', function () { Function.prototype(); });
}
}
/** ready returns a Promise which resolves upon subscription goes to Subscribed
* state and rejects in case of subscription goes to Unsubscribed state.
* Optional timeout can be passed.*/
ready(timeout) {
if (this.state === SubscriptionState.Unsubscribed) {
return Promise.reject({ code: errorCodes.subscriptionUnsubscribed, message: this.state });
}
if (this.state === SubscriptionState.Subscribed) {
return Promise.resolve();
}
return new Promise((res, rej) => {
const id = this._nextPromiseId();
const ctx = {
resolve: res,
reject: rej
};
if (timeout) {
ctx.timeout = setTimeout(() => {
// A call that gave up waiting leaves no waiter behind.
delete this._promises[id];
rej({ code: errorCodes.timeout, message: 'timeout' });
}, timeout);
}
this._promises[id] = ctx;
});
}
/** subscribe to a channel.*/
subscribe() {
if (this._removed) {
// The client no longer tracks it: the server would keep a subscription whose
// publications are dropped, and which is never subscribed again on reconnect.
throw new Error('Subscription to the channel ' + this.channel + ' was removed from the client');
}
if (this._isSubscribed()) {
return;
}
if (this._isUnsubscribed()) {
// A subscribe in progress keeps its backoff.
this._resubscribeAttempts = 0;
}
this._setSubscribing(subscribingCodes.subscribeCalled, 'subscribe called');
}
/** unsubscribe from a channel, keeping position state.*/
unsubscribe() {
this._setUnsubscribed(unsubscribedCodes.unsubscribeCalled, 'unsubscribe called', true);
}
_debouncedPublish(key, data, isMap) {
const existing = this._debouncePending.get(key);
if (existing) {
// Update pending value, mark as dirty, keep existing timer.
existing.data = data;
existing.dirty = true;
return Promise.resolve({});
}
// First publish for this key — send immediately, start debounce timer.
const entry = { data, dirty: false, timer: null };
entry.timer = setTimeout(() => {
const pending = this._debouncePending.get(key);
if (!pending || !pending.dirty) {
// No new data since last send — just clean up.
this._debouncePending.delete(key);
return;
}
// Send the latest pending value, reset dirty flag, restart timer.
pending.dirty = false;
const sendData = pending.data;
const sendFn = isMap
? this._centrifuge.mapPublish(this.channel, key, sendData)
: this._centrifuge.publish(this.channel, sendData);
sendFn.catch(() => { });
// Restart timer for next window.
pending.timer = setTimeout(() => {
const p = this._debouncePending.get(key);
if (!p || !p.dirty) {
this._debouncePending.delete(key);
return;
}
// Recursive — but in practice debounce windows are short. Nobody awaits
// this send, so swallow errors like the timer-driven send above does.
this._debouncePending.delete(key);
this._debouncedPublish(key, p.data, isMap).catch(() => { });
}, this._debounceMs);
}, this._debounceMs);
this._debouncePending.set(key, entry);
// Send first publish immediately.
const sendFn = isMap
? this._centrifuge.mapPublish(this.channel, key, data)
: this._centrifuge.publish(this.channel, data);
return sendFn;
}
_cancelDebounce(key) {
const existing = this._debouncePending.get(key);
if (existing) {
clearTimeout(existing.timer);
this._debouncePending.delete(key);
}
}
_cancelAllDebounce() {
for (const [, entry] of this._debouncePending) {
clearTimeout(entry.timer);
}
this._debouncePending.clear();
}
/** get online presence for a channel.*/
presence() {
return __awaiter(this, void 0, void 0, function* () {
yield this._methodCall();
return this._centrifuge.presence(this.channel);
});
}
/** presence stats for a channel (num clients and unique users).*/
presenceStats() {
return __awaiter(this, void 0, void 0, function* () {
yield this._methodCall();
return this._centrifuge.presenceStats(this.channel);
});
}
/**
* Sets server-side tags filter for the subscription.
* This only applies on the next subscription attempt, not the current one.
* Cannot be used together with delta option.
*
* @param tagsFilter - Filter configuration object or null to remove filter
* @throws {Error} If both delta and tagsFilter are configured
*
* @example
* ```typescript
* // Simple equality filter
* sub.setTagsFilter({
* key: 'ticker',
* cmp: 'eq',
* val: 'BTC'
* });
* ```
*
* @example
* ```typescript
* // Complex filter with logical operators
* sub.setTagsFilter({
* op: 'and',
* nodes: [
* { key: 'ticker', cmp: 'eq', val: 'BTC' },
* { key: 'price', cmp: 'gt', val: '50000' }
* ]
* });
* ```
*
* @example
* ```typescript
* // Filter with IN operator
* sub.setTagsFilter({
* key: 'ticker',
* cmp: 'in',
* vals: ['BTC', 'ETH', 'SOL']
* });
* ```
*/
setTagsFilter(tagsFilter) {
if (tagsFilter && this._delta) {
throw new Error('cannot use delta and tagsFilter together');
}
this._tagsFilter = tagsFilter;
// For map subscriptions, changing the filter invalidates the local state —
// the next subscribe must go through full STATE phase, not stream recovery.
if (this._map) {
this._recover = false;
this._offset = null;
this._epoch = null;
this._mapPositionResets++;
}
}
/** setData allows setting subscription data. This only applied on the next subscription attempt,
* Note that if getData callback is configured, it will override this value during resubscriptions. */
setData(data) {
this._data = data;
}
/** deltaStats returns delta compression statistics for this subscription.
* Only meaningful when delta compression is enabled (delta: 'fossil'). */
deltaStats() {
const bytesDecoded = this._deltaBytesDecoded;
return {
numPublications: this._deltaNumPubs,
numFullPayloads: this._deltaNumFull,
numDeltaPayloads: this._deltaNumDelta,
bytesReceived: this._deltaBytesReceived,
bytesDecoded: bytesDecoded,
compressionRatio: bytesDecoded > 0 ? 1 - this._deltaBytesReceived / bytesDecoded : 0,
};
}
_methodCall() {
if (this._isSubscribed()) {
return Promise.resolve();
}
if (this._isUnsubscribed()) {
return Promise.reject({
code: errorCodes.subscriptionUnsubscribed,
message: this.state
});
}
return new Promise((resolve, reject) => {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
const timeoutDuration = this._centrifuge._config.timeout;
const id = this._nextPromiseId();
const timeout = setTimeout(() => {
delete this._promises[id];
reject({ code: errorCodes.timeout, message: 'timeout' });
}, timeoutDuration);
this._promises[id] = {
timeout,
resolve,
reject
};
});
}
_nextPromiseId() {
return ++this._promiseId;
}
_needRecover() {
return this._recover === true;
}
_isUnsubscribed() {
return this.state === SubscriptionState.Unsubscribed;
}
_isSubscribing() {
return this.state === SubscriptionState.Subscribing;
}
_isSubscribed() {
return this.state === SubscriptionState.Subscribed;
}
_setState(newState) {
if (this.state !== newState) {
const oldState = this.state;
this.state = newState;
this._stateTransitions++;
this.emit('state', { newState, oldState, channel: this.channel });
return true;
}
return false;
}
_usesToken() {
return this._token !== '' || this._getToken !== null;
}
_clearSubscribingState() {
this._resubscribeAttempts = 0;
this._clearResubscribeTimeout();
}
_clearSubscribedState() {
this._clearRefreshTimeout();
// A token refresh in progress belongs to the subscription that ends here.
this._refreshGeneration++;
this._cancelAllDebounce();
this._clearSharedPollSignatureRefresh();
this._clearSharedPollTrackRetry();
this._clearSharedPollReplayRetry();
// Drop the stale refresh target — the replay after reconnect will set a
// fresh one from the next batch of track responses.
this._sharedPollSignatureRefreshTargetMs = null;
// Reset the in-flight guard so refresh can run again after reconnect.
this._sharedPollSignatureRefreshInFlight = false;
this._sharedPollSignatureRefreshAgain = false;
// NOTE: do NOT clear _sharedPollSignatures or _sharedPollTrackedItems.
// They persist across reconnects so _sharedPollReplayTrack can re-send
// tracks using the cached signatures — avoids hitting getSignature for
// every client during mass reconnect storms. Cleared only on explicit
// unsubscribe via _setUnsubscribed.
}
/** Called on "state invalidated" — unsubscribe code 2502 for this channel,
* or connection disconnect code 3014. Clears the token when getToken is set
* (next subscribe fetches a fresh one) and the fossil delta base (every
* subscription type uses _prevValueMap; a stale base would corrupt decoding
* of the first publication after re-subscribe).
*
* Without getToken there is no new token to get: the subscription keeps the
* token it has (or none) and resubscribes with it. The server rejects it if
* it's no longer valid.
*
* Map subscriptions restart from scratch: their recovery position and
* materialized-state buffers are dropped so the next subscribe does a full
* STATE re-sync.
*
* Stream/shared-poll subscriptions instead reset the recovery position to a
* sentinel epoch ("_") the server can never match (offset 0), leaving
* _recover untouched: a recoverable subscription then resubscribes with
* was_recovering=true, recovered=false (so the app reloads via its existing
* recovery-failure path rather than treating it as a brand-new first
* subscribe), while a non-recoverable one simply resubscribes. The real
* epoch/offset are adopted from the subscribe reply. */
_invalidateState() {
if (this._getToken !== null) {
this._token = '';
}
this._prevValueMap = new Map();
if (this._map) {
this._offset = null;
this._epoch = null;
this._recover = false;
this._mapPositionResets++;
this._mapStateBuffer = [];
this._mapStreamBuffer = [];
this._mapCursor = '';
this._mapPhase = null;
}
else if (this._offset !== null) {
// Only a position that exists: without one, e.g. before getState was called,
// the next subscribe must still load the state.
// "_" is a sentinel, not an epoch the server can produce: the recovery of the
// next subscribe is meant to fail, so the app reloads through its
// recovery-failure path instead of taking the resubscribe for a first one.
// It has to be non-empty — an empty epoch means "any epoch" to the server,
// which would let the recovery succeed from now-invalidated state.
this._offset = 0;
this._epoch = '_';
}
}
_setSubscribed(result) {
if (!this._isSubscribing()) {
return;
}
this._clearSubscribingState();
if (result.id) {
this._id = result.id;
}
if (result.recoverable) {
this._recover = true;
// After a recovery the server replies with the position recovered from: each
// recovered publication delivered below moves it. A map subscription differs:
// its live reply carries the top of the stream (see _handleMapLiveResponse).
this._offset = toOffset(result.offset);
this._epoch = result.epoch || '';
}
else {
// A channel the server doesn't recover is no channel to recover from. Without
// this, a subscription given a position by `since` or getState keeps asking to
// recover on every resubscribe, and the app is told a recovery failed
// (wasRecovering true, recovered false) every time, though nothing was lost.
// The flag comes from every reply, so recovery enabled later is picked up.
this._recover = false;
}
if (result.delta) {
this._delta_negotiated = true;
}
else {
this._delta_negotiated = false;
}
if (result.publish_debounce) {
this._debounceMs = result.publish_debounce;
}
if (this._sharedPoll) {
const newEpoch = result.epoch || '';
if (this._sharedPollEpoch !== '' && this._sharedPollEpoch !== newEpoch) {
// Epoch changed (server restart, mode change, node switch) —
// stored synthetic versions are invalid, reset to 0.
for (const key of this._sharedPollTrackedItems.keys()) {
this._sharedPollTrackedItems.set(key, 0);
}
}
this._sharedPollEpoch = newEpoch;
}
this._setState(SubscriptionState.Subscribed);
// A 'state' handler may have unsubscribed already: no subscribed event then.
if (!this._isSubscribed()) {
return;
}
// @ts-ignore – we are hiding some methods from public API autocompletion.
const ctx = this._centrifuge._getSubscribeContext(this.channel, result);
this.emit('subscribed', ctx);
// A 'subscribed' handler may have unsubscribed, and subscribed again: promises
// made since then wait for that subscribe.
if (!this._isSubscribed()) {
return;
}
this._resolvePromises();
// A 'publication' handler may have unsubscribed: the rest of the recovered
// publications must not be delivered or move the position.
const pubs = result.publications || [];
for (let i = 0; i < pubs.length && this._isSubscribed(); i++) {
this._handlePublication(pubs[i]);
}
if (result.expires === true && this._isSubscribed()) {
this._refreshTimeout = setTimeout(() => this._refresh(), ttlMilliseconds(result.ttl));
}
}
_setSubscribing(code, reason) {
return __awaiter(this, void 0, void 0, function* () {
if (this._isSubscribing()) {
return;
}
if (this._isSubscribed()) {
this._clearSubscribedState();
}
// Channel compaction: the numeric channel id is scoped to the connected
// session — drop it when moving back to subscribing (e.g. on reconnect). The
// next subscribe reply re-establishes it (the server may reuse the same id).
this._id = 0;
// Not when a 'state' handler changed the state again: the event would come after
// that change's own events, out of order.
const transition = this._stateTransitions + 1;
if (this._setState(SubscriptionState.Subscribing) && this._stateTransitions === transition) {
this.emit('subscribing', { channel: this.channel, code: code, reason: reason });
}
// @ts-ignore – for performance reasons only await _unsubPromise for emulution case where it's required.
if (this._centrifuge._transport && this._centrifuge._transport.emulation()) {
yield this._unsubPromise;
// Also for a subscription of this channel removed from the client: the server
// may otherwise handle this subscribe before its unsubscribe.
// @ts-ignore – we are hiding some symbols from public API autocompletion.
yield this._centrifuge._removedSubscriptionUnsubscribed(this.channel);
// And for the shared poll requests of an earlier subscription: the server
// may otherwise apply them to this one.
yield this._sharedPollQueue;
}
if (!this._isSubscribing()) {
return;
}
this._subscribe();
});
}
_subscribe() {
this._debug('subscribing on', this.channel);
if (!this._isTransportOpen()) {
this._debug('delay subscribe on', this.channel, 'till connected');
return null;
}
if (this._inflight) {
return null;
}
this._inflight = true;
// Route to map subscribe flow if map mode is enabled
if (this._map) {
this._mapSubscribe();
return null;
}
// Stream getState: call app's callback to load state + get position.
// Only called when we don't have a saved position (first subscribe or after
// position reset due to failed recovery). On normal reconnects with a valid
// saved position, we skip getState and let the server try recovery — getState
// is only called again if recovery fails (see _setSubscribed).
// Continuations of this flow (getState, getToken, getData) do nothing once
// it is outdated: after unsubscribe(), maybe followed by subscribe() and a
// flow of its own.
const flow = this._subscribeFlow;
if (this._getState && this._offset === null) {
this._loadStreamState(flow);
return null;
}
if (this._canSubscribeWithoutGettingToken()) {
return this._subscribeWithoutToken(flow);
}
this._getSubscriptionToken()
.then(token => this._handleTokenResponse(token, flow))
.catch(e => this._handleTokenError(e, flow));
return null;
}
_flowOutdated(flow) {
return flow !== this._subscribeFlow;
}
// Over emulation commands go in separate requests the server may handle in any
// order: an unsubscribe of a subscribe in flight could overtake it, and the
// server would keep the subscription. The unsubscribe waits for the
// subscribe's reply then.
_mustDeferUnsubscribe() {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
const transport = this._centrifuge._transport;
return this._subscribeCallFlow === this._subscribeFlow && !!transport && transport.emulation();
}
// Called first by the reply handlers of a subscribe command or map page. True
// when the reply belongs to a subscribe whose unsubscribe was deferred, which is
// handled here: the unsubscribe goes out if the subscribe succeeded. A timeout
// leaves unknown whether the server subscribed: the client reconnects.
_settleSubscribeCall(flow, ok, error) {
if (this._subscribeCallFlow === flow) {
this._subscribeCallFlow = null;
}
const deferred = this._deferredUnsubscribe;
if (deferred === null || deferred.flow !== flow) {
return false;
}
this._deferredUnsubscribe = null;
if (ok) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._unsubscribe(this).then(deferred.resolve);
return true;
}
deferred.resolve();
if (error && error.code === errorCodes.timeout) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._disconnect(connectingCodes.subscribeTimeout, 'subscribe timeout', true);
}
return true;
}
_isTransportOpen() {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
return this._centrifuge._transportIsOpen;
}
_canSubscribeWithoutGettingToken() {
return !this._usesToken() || !!this._token;
}
_subscribeWithoutToken(flow) {
if (this._getData) {
this._getDataAndSubscribe(this._token, flow);
return null;
}
else {
return this._sendSubscribe(this._token);
}
}
/** Load stream position from app via getState callback, then proceed to subscribe
* with recovery from that position. Called only when _offset is null:
* - Initial subscribe (no saved position)
* - After position reset due to failed recovery (see _setSubscribed)
*
* NOT called on normal reconnects where the SDK has a saved position — in that
* case recovery is attempted first, and getState is only invoked if recovery fails.
*
* The app's getState callback should:
* 1. Read cf_stream_top_position (or equivalent) FIRST to capture the stream position
* 2. Then read its own data from the database/API
* 3. Render/update the UI
* 4. Return the captured stream position
*
* This order is critical: reading position first ensures it's a lower bound.
* Recovered publications may overlap with data the app already loaded — this
* requires idempotent updates or offset-based dedup. */
_loadStreamState(flow) {
if (!this._isSubscribing()) {
this._inflight = false;
return;
}
this._callAsync(() => this._getState()).then(result => {
if (this._flowOutdated(flow)) {
return;
}
if (!this._isSubscribing()) {
this._inflight = false;
return;
}
// Store stream position from app's source of truth.
this._offset = toOffset(result.offset);
this._epoch = result.epoch;
this._recover = true;
// Proceed with normal subscribe flow (token → sendSubscribe).
if (this._canSubscribeWithoutGettingToken()) {
this._subscribeWithoutToken(flow);
}
else {
this._getSubscriptionToken()
.then(token => this._handleTokenResponse(token, flow))
.catch(e => this._handleTokenError(e, flow));
}
}).catch(e => {
if (this._flowOutdated(flow)) {
return;
}
if (!this._isSubscribing()) {
this._inflight = false;
return;
}
// Match map subscription error handling: route through _subscribeError
// which emits error event and schedules resubscribe for temporary errors
// (code < 100), matching the map's _handleMapSubscribeError pattern.
this._inflight = false;
this._subscribeError({
code: errorCodes.subscriptionGetState,
message: (e === null || e === void 0 ? void 0 : e.toString()) || 'getState failed',
temporary: true,
});
});
}
_getDataAndSubscribe(token, flow) {
if (!this._getData) {
this._inflight = false;
return;
}
this._callAsync(() => this._getData({ channel: this.channel }))
.then(data => {
if (this._flowOutdated(flow)) {
return;
}
if (!this._isSubscribing()) {
this._inflight = false;
return;
}
this._data = data;
this._sendSubscribe(token);
})
.catch(e => this._handleGetDataError(e, flow));
}
_handleGetDataError(error, flow) {
if (this._flowOutdated(flow)) {
return;
}
if (!this._isSubscribing()) {
this._inflight = false;
return;
}
if (error instanceof UnauthorizedError) {
this._inflight = false;
this._failUnauthorized();
return;
}
this._emitError({
type: 'subscribeData',
channel: this.channel,
error: {
code: errorCodes.badConfiguration,
message: (error === null || error === void 0 ? void 0 : error.toString()) || ''
}
}, () => {
this._inflight = false;
this._scheduleResubscribe();
});
}
_handleTokenResponse(token, flow) {
if (this._flowOutdated(flow)) {
return;
}
if (!this._isSubscribing()) {
this._inflight = false;
return;
}
if (!token) {
this._inflight = false;
this._failUnauthorized();
return;
}
this._token = token;
if (this._getData) {
this._getDataAndSubscribe(token, flow);
}
else {
this._sendSubscribe(token);
}
}
_handleTokenError(error, flow) {
if (this._flowOutdated(flow)) {
return;
}
if (!this._isSubscribing()) {
this._inflight = false;
return;
}
if (error instanceof UnauthorizedError) {
this._inflight = false;
this._failUnauthorized();
return;
}
this._emitError({
type: 'subscribeToken',
channel: this.channel,
error: {
code: errorCodes.subscriptionSubscribeToken,
message: (error === null || error === void 0 ? void 0 : error.toString()) || ''
}
}, () => {
this._inflight = false;
this._scheduleResubscribe();
});
}
_sendSubscribe(token) {
if (!this._isTransportOpen()) {
this._inflight = false;
return null;
}
const cmd = this._buildSubscribeCommand(token);
const flow = this._subscribeFlow;
this._subscribeCallFlow = flow;
// @ts-ignore – we are hiding some symbols from public API autocompletion.
// An exception while handling the reply stops the client (see _dispatchFailed).
// next() is still called, so replies of a later connection aren't blocked.
this._centrifuge._call(cmd).then(resolveCtx => {
try {
if (this._settleSubscribeCall(flow, true)) {
return;
}
if (flow !== this._subscribeFlow) {
// The app unsubscribed meanwhile, maybe to subscribe again.
return;
}
this._inflight = false;
this._handleSubscribeResponse(resolveCtx.reply.subscribe);
}
catch (err) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._dispatchFailed(err);
}
finally {
if (resolveCtx.next) {
resolveCtx.next();
}
}
}, rejectCtx => {
try {
if (this._settleSubscribeCall(flow, false, rejectCtx.error)) {
return;
}
if (flow !== this._subscribeFlow) {
return;
}
this._inflight = false;
this._handleSubscribeError(rejectCtx.error);
}
catch (err) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._rejectionFailed(err, rejectCtx);
}
finally {
if (rejectCtx.next) {
rejectCtx.next();
}
}
});
return cmd;
}
_buildSubscribeCommand(token) {
const req = { channel: this.channel };
if (token)
req.token = token;
if (this._data)
req.data = this._data;
// Shared poll: simple subscribe with type=4, no positioning/recovery fields.
if (this._sharedPoll) {
req.type = 4;
if (this._delta)
req.delta = this._delta;
return { subscribe: req };
}
if (this._positioned)
req.positioned = true;
if (this._recoverable)
req.recoverable = true;
if (this._joinLeave)
req.join_leave = true;
req.flag = subscriptionFlags.channelCompaction;
if (this._getState) {
req.flag |= subscriptionFlags.rejectUnrecovered;
}
if (this._needRecover()) {
req.recover = true;
const offset = this._getOffset();
if (offset)
req.offset = offset;
const epoch = this._getEpoch();
if (epoch)
req.epoch = epoch;
}
if (this._delta)
req.delta = this._delta;
if (this._tagsFilter)
req.tf = this._tagsFilter;
return { subscribe: req };
}
_debug(...args) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._debug(...args);
}
/** @internal An exception escaping a handler stops the client: see Centrifuge._handlerFailed. */
emit(event, ...args) {
try {
return EventEmitter.prototype.emit.call(this, event, ...args);
}
catch (e) {
this._centrifuge._handlerFailed(e);
return true;
}
}
_handleSubscribeError(error) {
if (!this._isSubscribing()) {
return;
}
if (error.code === errorCodes.connectionClosed) {
// The transport closed with the subscribe in flight: no error of the
// subscribe, the next connection subscribes again without a backoff.
return;
}
if (error.code === errorCodes.timeout) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._disconnect(connectingCodes.subscribeTimeout, 'subscribe timeout', true);
return;
}
if (error.code === 112 && this._getState) {
// Unrecoverable position with getState: reset position so next
// subscribe attempt calls getState() to reload app state from scratch.
this._offset = null;
this._epoch = null;
this._recover = false;
this._prevValueMap = new Map();
this._scheduleResubscribe();
return;
}
this._subscribeError(error);
}
_handleSubscribeResponse(result) {
if (!this._isSubscribing()) {
return;
}
this._sharedPollReplayPending = this._sharedPoll;
try {
this._setSubscribed(result);
}
finally {
this._sharedPollReplayPending = false;
}
// After shared poll subscribe, replay tracked items if any.
if (this._sharedPoll) {
this._sharedPollReplayTrack();
}
}
_setUnsubscribed(code, reason, sendUnsubscribe) {
if (this._isUnsubscribed()) {
return Promise.resolve();
}
// Set before the unsubscribed event: a subscribe() from its handler waits for
// the unsubscribe reply over emulation (see _setSubscribing).
let promise = Promise.resolve();
if (this._isSubscribed()) {
if (sendUnsubscribe) {
// @ts-ignore – we are hiding some methods from public API autocompletion.
promise = this._unsubPromise = this._centrifuge._unsubscribe(this);
}
this._clearSubscribedState();
}
else if (this._isSubscribing()) {
if (this._inflight && sendUnsubscribe) {
if (this._mustDeferUnsubscribe()) {
const flow = this._subscribeFlow;
promise = this._unsubPromise = new Promise(resolve => {
this._deferredUnsubscribe = { flow, resolve };
});
}
else {
// @ts-ignore – we are hiding some methods from public API autocompletion.
promise = this._unsubPromise = this._centrifuge._unsubscribe(this);
}
}
this._clearSubscribingState();
}
this._inflight = false;
// Replies and continuations of a subscribe in progress must not complete a later one.
this._subscribeFlow++;
// Channel compaction: the numeric channel id is scoped to the active
// subscription. Drop it so a push for the old id (e.g. one in flight when we
// unsubscribe) is no longer routed to this subscription.
this._id = 0;
this._sharedPollEpoch = '';
// Explicit unsubscribe — drop all shared-poll state so a subsequent
// subscribe starts cold. Reconnects use _clearSubscribedState (above)
// which preserves the signature library and tracked items.
this._sharedPollSignatures = [];
this._sharedPollTrackedItems.clear();
this._sharedPollSignatureRefreshInFlight = false;
this._sharedPollSignatureRefreshAgain = false;
this._sharedPollSignatureRefreshTargetMs = null;
this._cancelAllDebounce();
// Waiters fail before the events: a handler subscribing again makes waiters of
// the new subscribe, which must not fail with this one.
this._rejectPromises({ code: errorCodes.subscriptionUnsubscribed, message: SubscriptionState.Unsubscribed });
// Not when a 'state' handler changed the state again (see _setSubscribing).
const transition = this._stateTransitions + 1;
if (this._setState(SubscriptionState.Unsubscribed) && this._stateTransitions === transition) {
this.emit('unsubscribed', { channel: this.channel, code: code, reason: reason });
}
return promise;
}
_handlePublication(pub) {
if (this._sharedPoll && pub.key && !pub.removed && hasOffset(pub.version)) {
// Versions dedupe: one not newer than the version held for the key is a
// duplicate (e.g. the reply of a second track request of the key) or
// older. Dropped before delta decoding, which would move the key's base.
const known = this._sharedPollTrackedItems.get(pub.key);
if (known !== undefined && known > 0 && toOffset(pub.version) <= known) {
return;
}
}
if (this._delta && this._delta_negotiated) {
// For map and shared poll subs, delta is per-key.
// For non-map subs, delta is a single chain regardless of pub.key.
const deltaKey = (this._map || this._sharedPoll) ? (pub.key || '') : '';
if (pub.removed) {
// A removal carries no payload to decode, and ends the key's delta chain.
this._prevValueMap.delete(deltaKey);
}
else {
// @ts-ignore – we are hiding some methods from public API autocompletion.
const { newData, newPrevValue, isDelta, wireBytes, fullBytes } = this._centrifuge._codec.applyDeltaIfNeeded(pub, this._prevValueMap.get(deltaKey));
pub.data = newData;
this._deltaNumPubs++;
this._deltaBytesReceived += wireBytes;
this._deltaBytesDecoded += fullBytes;
if (isDelta) {
this._deltaNumDelta++;
}
else {
this._deltaNumFull++;
}
this._prevValueMap.set(deltaKey, newPrevValue);
}
}
let ctx;
if (this._sharedPoll) {
// Ignore publications for keys the user is no longer tracking.
// Common race: SDK replays a cached signature batch on reconnect with
// some keys the user untracked locally; the chained untrack hasn't
// reached the server yet, so the server may push updates for those
// keys in the meantime. Without this guard those updates would
// re-insert the keys into _sharedPollTrackedItems and emit 'update'
// events the user already opted out of.
if (pub.key && !this._sharedPollTrackedItems.has(pub.key)) {
return;
}
// The tracked version is the key's position: it moves with the position below.
ctx = this._getSharedPollUpdateContext(pub);
}
else if (this._map) {
ctx = this._getMapUpdateContext(pub);
}
else {
// @ts-ignore – we are hiding some methods from public API autocompletion.
ctx = this._centrifuge._getPublicationContext(this.channel, pub);
}
// The position moves after the app has the publication, so the position it can
// observe never runs ahead of what it received: a handler that throws (which
// stops the client), or that unsubscribes before the last event, doesn't skip it. A subscribe command built
// while a handler runs still recovers after this publication, because _getOffset
// prefers the pending offset — a resubscribe from the handler gets no duplicate.
if (this._map || this._sharedPoll) {
this.emit('publication', ctx);
if (!this._isSubscribed()) {
return;
}
this._setPublicationPosition(pub);
this.emit('update', ctx);
}
else {
this._pendingOffset = hasOffset(pub.offset) ? toOffset(pub.offset) : null;
const failures = this._centrifuge._handlerFailures;
try {
this.emit('publication', ctx);
}
finally {
this._pendingOffset = null;
}
// A publication whose handler threw isn't delivered: the position stays before
// it, so the next recovery delivers it again.
if (this._centrifuge._handlerFailures !== failures) {
return;
}
this._setPublicationPosition(pub);
}
}
_setPublicationPosition(pub) {
// Shared poll: the version of a key still tracked, which a replay of the tracked
// keys asks from. A publication handler may have untracked it.
if (this._sharedPoll && pub.key && this._sharedPollTrackedItems.has(pub.key)) {
if (pub.removed) {
this._sharedPollTrackedItems.delete(pub.key);
}
else if (pub.version) {
this._sharedPollTrackedItems.set(pub.key, toOffset(pub.version));
}
}
if (hasOffset(pub.offset)) {
this._offset = toOffset(pub.offset);
}
if (pub.epoch) {
this._epoch = pub.epoch;
}
}
/** Seed per-key delta tracking from state/stream entries.
* Handles JSON-escaped data (server-side delta escaping) and protobuf data.
* Decodes escaped data back to original format for user consumption.
* Values are escaped only when delta is negotiated: otherwise they come as
* they are, and a string value must not be parsed. */
_seedDeltaTracking(pub, deltaNegotiated) {
if (!this._delta || !pub.key)
return;
if (pub.removed) {
// A removal carries no payload to decode, and ends the key's delta chain.
this._prevValueMap.delete(pub.key);
return;
}
if (!deltaNegotiated) {
this._prevValueMap.set(pub.key, pub.data);
return;
}
if (typeof pub.data === 'string') {
// JSON transport with server-side delta escaping.
// Store raw bytes for delta, decode for user.
const rawBytes = pub.data;
const encoded = new TextEncoder().encode(rawBytes);
this._prevValueMap.set(pub.key, encoded);
// Count as full payload in delta stats. Use the UTF-8 byte length, not
// rawBytes.length (JS string length counts UTF-16 code units, which
// undercounts any non-ASCII content).
const byteLen = encoded.length;
this._deltaNumPubs++;
this._deltaNumFull++;
this._deltaBytesReceived += byteLen;
this._deltaBytesDecoded += byteLen;
pub.data = JSON.parse(rawBytes);
}
else if (pub.data instanceof Uint8Array) {
// Protobuf transport.
this._prevValueMap.set(pub.key, pub.data);
// Count as full payload in delta stats.
const byteLen = pub.data.length;
this._deltaNumPubs++;
this._deltaNumFull++;
this._deltaBytesReceived += byteLen;
this._deltaBytesDecoded += byteLen;
}
}
_handleJoin(join) {
// @ts-ignore – we are hiding some methods from public API autocompletion.
const info = this._centrifuge._getJoinLeaveContext(join.info);
this.emit('join', { channel: this.channel, info: info });
}
_handleLeave(leave) {
// @ts-ignore – we are hiding some methods from public API autocompletion.
const info = this._centrifuge._getJoinLeaveContext(leave.info);
this.emit('leave', { channel: this.channel, info: info });
}
_resolvePromises() {
for (const id in this._promises) {
if (!this._promises.hasOwnProperty(id)) {
continue;
}
if (this._promises[id].timeout) {
clearTimeout(this._promises[id].timeout);
}
this._promises[id].resolve();
delete this._promises[id];
}
}
_rejectPromises(err) {
for (const id in this._promises) {
if (!this._promises.hasOwnProperty(id)) {
continue;
}
if (this._promises[id].timeout) {
clearTimeout(this._promises[id].timeout);
}
this._promises[id].reject(err);
delete this._promises[id];
}
}
_scheduleResubscribe() {
if (!this._isSubscribing()) {
this._debug('not in subscribing state, skip resubscribe scheduling', this.channel);
return;
}
const self = this;
const delay = this._getResubscribeDelay();
// One timer at a time: a timer left armed would fire later, out of the
// backoff, and send a subscribe the emulation waits don't cover.
this._clearResubscribeTimeout();
this._resubscribeTimeout = setTimeout(function () {
self._resubscribeTimeout = null;
if (self._isSubscribing()) {
self._subscribe();
}
}, delay);
this._debug('resubscribe scheduled after ' + delay, this.channel);
}
// Emits an error event, then runs the continuation: not when a handler unsubscribed,
// maybe to subscribe again, whose new subscribe the continuation must not touch.
_emitError(ctx, continuation) {
const flow = this._subscribeFlow;
try {
this.emit('error', ctx);
}
finally {
if (flow === this._subscribeFlow) {
continuation();
}
}
}
_subscribeError(err) {
if (!this._isSubscribing()) {
return;
}
if (err.code === 109 && this._getToken === null) {
// The token expired and there is no getToken to get another one: like a
// connection, unauthorized (instead of subscribing again without a token).
try {
this.emit('error', {
type: 'configuration',
channel: this.channel,
error: {
code: errorCodes.badConfiguration,
message: 'subscription token expired but no getToken function set'
}
});
}
catch (e) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._reportDispatchError(e);
}
this._setUnsubscribed(unsubscribedCodes.unauthorized, 'unauthorized', false);
return;
}
if (err.code < 100 || err.code === 109 || err.temporary === true) {
if (err.code === 109) { // Token expired error.
this._token = '';
}
const errContext = {
channel: this.channel,
type: 'subscribe',
error: err
};
if (this._centrifuge.state === State.Connected) {
this._emitError(errContext, () => this._scheduleResubscribe());
}
else {
this._scheduleResubscribe();
}
}
else {
this._setUnsubscribed(err.code, err.message, false);
}
}
_getResubscribeDelay() {
const delay = backoff(this._resubscribeAttempts, this._minResubscribeDelay, this._maxResubscribeDelay);
this._resubscribeAttempts++;
return delay;
}
_setOptions(options) {
if (!options) {
return;
}
if (options.since) {
this._offset = toOffset(options.since.offset);
this._epoch = options.since.epoch || '';
this._recover = true;
}
if (options.data) {
this._data = options.data;
}
if (options.getData) {
this._getData = options.getData;
}
if (options.minResubscribeDelay !== undefined) {
this._minResubscribeDelay = options.minResubscribeDelay;
}
if (options.maxResubscribeDelay !== undefined) {
this._maxResubscribeDelay = options.maxResubscribeDelay;
}
if (options.token) {
this._token = options.token;
}
if (options.getToken) {
this._getToken = options.getToken;
}
if (options.positioned === true) {
this._positioned = true;
}
if (options.recoverable === true) {
this._recoverable = true;
}
if (options.joinLeave === true) {
this._joinLeave = true;
}
if (options.delta) {
if (options.delta !== 'fossil') {
throw new Error('unsupported delta format');
}
this._delta = options.delta;
}
if (options.tagsFilter) {
this._tagsFilter = options.tagsFilter;
}
if (this._tagsFilter && this._delta) {
throw new Error('cannot use delta and tagsFilter together');
}
// Stream getState option
if (options.getState) {
this._getState = options.getState;
this._recover = true; // getState implies recovery
}
// Map subscription options
if (options.map === true) {
this._map = true;
}
if (options.mapPageSize !== undefined) {
this._mapPageSize = options.mapPageSize;
}
// Presence type for presence subscriptions (2=clients, 3=users)
if (options.mapPresenceType !== undefined) {
this._mapPresenceType = options.mapPresenceType;
this._map = true; // Presence subscriptions are always map subscriptions
}
if (options.mapUnrecoverableStrategy) {
this._mapUnrecoverableStrategy = options.mapUnrecoverableStrategy;
}
// Shared poll subscription options
if (options.sharedPoll === true) {
this._sharedPoll = true;
}
if (options.sharedPollGetSignature) {
this._sharedPollGetSignature = options.sharedPollGetSignature;
}
}
_getOffset() {
// A publication being dispatched counts as delivered: a subscribe command built
// from its handler recovers after it, while the stored position still holds the
// previous one until that handler returned (see _handlePublication).
if (this._pendingOffset !== null) {
return this._pendingOffset;
}
const offset = this._offset;
if (offset !== null) {
return offset;
}
return 0;
}
_getEpoch() {
const epoch = this._epoch;
if (epoch !== null) {
return epoch;
}
return '';
}
_clearRefreshTimeout() {
if (this._refreshTimeout !== null) {
clearTimeout(this._refreshTimeout);
this._refreshTimeout = null;
}
}
_clearResubscribeTimeout() {
if (this._resubscribeTimeout !== null) {
clearTimeout(this._resubscribeTimeout);
this._resubscribeTimeout = null;
}
}
_getSubscriptionToken() {
this._debug('get subscription token for channel', this.channel);
const ctx = {
channel: this.channel
};
const getToken = this._getToken;
if (getToken === null) {
try {
this.emit('error', {
type: 'configuration',
channel: this.channel,
error: {
code: errorCodes.badConfiguration,
message: 'provide a function to get channel subscription token'
}
});
}
catch (e) {
// The subscribe must fail as unauthorized all the same, not stay in progress.
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._reportDispatchError(e);
}
return Promise.reject(new UnauthorizedError(''));
}
return this._callAsync(() => getToken(ctx));
}
_refresh() {
this._clearRefreshTimeout();
const self = this;
// The subscription may end while the token is loading, and a new one start, e.g.
// after unsubscribe() or a reconnect: this refresh is outdated then.
const generation = this._refreshGeneration;
this._getSubscriptionToken().then(function (token) {
if (generation !== self._refreshGeneration || !self._isSubscribed()) {
return;
}
if (!token) {
self._failUnauthorized();
return;
}
self._token = token;
const req = {
channel: self.channel,
token: token
};
const msg = {
'sub_refresh': req
};
// @ts-ignore – we are hiding some symbols from public API autocompletion.
self._centrifuge._call(msg).then(resolveCtx => {
try {
self._refreshResponse(resolveCtx.reply.sub_refresh);
}
catch (err) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
self._centrifuge._dispatchFailed(err);
}
finally {
if (resolveCtx.next) {
resolveCtx.next();
}
}
}, rejectCtx => {
try {
self._refreshError(rejectCtx.error);
}
catch (err) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
self._centrifuge._rejectionFailed(err, rejectCtx);
}
finally {
if (rejectCtx.next) {
rejectCtx.next();
}
}
});
}).catch(function (e) {
if (generation !== self._refreshGeneration || !self._isSubscribed()) {
return;
}
if (e instanceof UnauthorizedError) {
self._failUnauthorized();
return;
}
self._emitError({
type: 'refreshToken',
channel: self.channel,
error: {
code: errorCodes.subscriptionRefreshToken,
message: e !== undefined ? e.toString() : ''
}
}, () => {
// A handler may have ended the subscription, e.g. by disconnecting the client.
if (generation !== self._refreshGeneration || !self._isSubscribed()) {
return;
}
self._refreshTimeout = setTimeout(() => self._refresh(), self._getRefreshRetryDelay());
});
});
}
_refreshResponse(result) {
if (!this._isSubscribed()) {
return;
}
this._debug('subscription token refreshed, channel', this.channel);
this._clearRefreshTimeout();
if (result.expires === true) {
this._refreshTimeout = setTimeout(() => this._refresh(), ttlMilliseconds(result.ttl));
}
}
_refreshError(err) {
if (!this._isSubscribed()) {
return;
}
if (err.code < 100 || err.temporary === true) {
this._emitError({
type: 'refresh',
channel: this.channel,
error: err
}, () => {
// A handler may have ended the subscription, e.g. by disconnecting the client.
if (!this._isSubscribed()) {
return;
}
this._refreshTimeout = setTimeout(() => this._refresh(), this._getRefreshRetryDelay());
});
}
else {
this._setUnsubscribed(err.code, err.message, true);
}
}
_getRefreshRetryDelay() {
return backoff(0, 10000, 20000);
}
// Calls an app callback expected to return a promise: one throwing instead of
// returning a rejected promise fails the same way, not by throwing out of the
// subscribe or refresh in progress.
_callAsync(callback) {
try {
return Promise.resolve(callback());
}
catch (e) {
return Promise.reject(e);
}
}
_failUnauthorized() {
this._setUnsubscribed(unsubscribedCodes.unauthorized, 'unauthorized', true);
}
// ============ Shared Poll Internal Helpers ============
// Send ONE or MORE signature batches in a single sub_refresh frame.
// Splits across frames when the estimated payload exceeds the wire frame
// budget — keeps each request well under the 64k Centrifugo frame limit.
_sendTrackRequest(batches, untrackKeys) {
if (batches.length === 0)
return Promise.resolve();
// Estimate ~80 bytes per signature + ~40 bytes per item (key + varint + framing).
// ~60KB budget leaves headroom for envelope, channel name, and reply.
const maxBytes = 60000;
const frames = [];
let current = [];
// Reserve space for inline untrack keys in the first frame.
let currentBytes = 100; // envelope baseline
if (untrackKeys && untrackKeys.length > 0) {
for (const key of untrackKeys)
currentBytes += key.length + 4;
}
for (const b of batches) {
let cost = 100;
for (const it of b.items)
cost += it.key.length + 16;
if (current.length > 0 && currentBytes + cost > maxBytes) {
frames.push(current);
current = [];
currentBytes = 100;
}
current.push(b);
currentBytes += cost;
}
if (current.length > 0)
frames.push(current);
// A failing frame stops the frames after it: a permanent error untracks the
// keys of all of them.
const keysFrom = (idx) => frames.slice(idx).flatMap(f => f.flatMap(b => b.items.map(i => i.key)));
const send = (frame, idx, frameUntrackKeys) => new Promise((resolve, reject) => {
const req = {
channel: this.channel,
type: 1,
track: frame.map(b => ({
signature: b.signature,
items: b.items.map(i => i.version > 0 ? i : { key: i.key }),
})),
};
if (frameUntrackKeys && frameUntrackKeys.length > 0) {
req.untrack = frameUntrackKeys;
}
const msg = { 'sub_refresh': req };
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._call(msg).then(resolveCtx => {
try {
this._handleTrackResponse(resolveCtx.reply.sub_refresh, frame.flatMap(b => b.items.map(i => i.key)), frameUntrackKeys);
}
catch (err) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._dispatchFailed(err);
}
finally {
if (resolveCtx.next)
resolveCtx.next();
}
resolve();
}, rejectCtx => {
if (rejectCtx.next)
rejectCtx.next();
this._sharedPollRequestFailed(rejectCtx.error);
// With the keys of the request, which a permanent error untracks.
reject({ error: rejectCtx.error, keys: keysFrom(idx) });
});
});
// Sequential dispatch: a frame failure stops further frames so the SDK
// doesn't end up with some frames committed server-side and others not
// — which would otherwise lead to retry-with-duplicate-publications.
// Inline untrack keys go only in the first frame.
return this._sharedPollSerial(() => frames.reduce((chain, frame, idx) => chain.then(() => send(frame, idx, idx === 0 ? untrackKeys : undefined)), Promise.resolve()));
}
_isEmulation() {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
const transport = this._centrifuge._transport;
return !!transport && transport.emulation();
}
// Over emulation each request is a separate HTTP request the server may handle
// in any order: a track and an untrack of a key could overtake each other. The
// channel's requests go one at a time then, in the order made; one made for a
// subscription that has ended by its turn is dropped.
_sharedPollSerial(send) {
if (!this._isEmulation()) {
return send();
}
const generation = this._refreshGeneration;
const run = this._sharedPollQueue.then(() => {
if (generation !== this._refreshGeneration || !this._isSubscribed()) {
return;
}
return send();
});
this._sharedPollQueue = run.then(() => undefined, () => undefined);
return run;
}
// A timed-out request over emulation may still reach the server after later
// ones: whether the keys are tracked is unknown, the client reconnects.
_sharedPollRequestFailed(error) {
if (error && error.code === errorCodes.timeout && this._isEmulation()) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._disconnect(connectingCodes.subscribeTimeout, 'shared poll request timeout', true);
}
}
_sendUntrackRequest(keys) {
return this._sharedPollSerial(() => new Promise((resolve, reject) => {
const req = {
channel: this.channel,
type: 2,
untrack: keys,
};
const msg = { 'sub_refresh': req };
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._call(msg).then(resolveCtx => {
if (resolveCtx.next) {
resolveCtx.next();
}
resolve();
}, rejectCtx => {
if (rejectCtx.next) {
rejectCtx.next();
}
this._sharedPollRequestFailed(rejectCtx.error);
reject(rejectCtx.error);
});
}));
}
_handleTrackResponse(result, keys, untrackKeys) {
// The reply to a track sent before unsubscribe() belongs to that subscription:
// its items and versions must not reach the next one.
if (!this._isSubscribed()) {
return;
}
// Track succeeded — reset retry state.
this._clearSharedPollTrackRetry();
// Process cached items from server (publications across all batches in the request).
if (result && result.items && result.items.length > 0) {
for (const pub of result.items) {
// A handler may have unsubscribed or disconnected: the rest must neither be
// delivered nor move the tracked versions.
if (!this._isSubscribed()) {
return;
}
this._handlePublication(pub);
}
}
if (!this._isSubscribed()) {
return;
}
// Keys the request tracked at the server which the client no longer tracks,
// e.g. removed by the server while the request was in flight: the server
// would keep tracking them, untracked there too.
const untracked = new Set(untrackKeys || []);
const stale = keys.filter(key => !untracked.has(key) && !this._sharedPollTrackedItems.has(key));
if (stale.length > 0) {
this._sendUntrackRequest(stale).catch(err => {
this.emit('error', { type: 'untrack', channel: this.channel, error: err });
});
}
// Server returns MIN ttl across all batches in this request. Keep the
// EARLIEST deadline received across all responses as the refresh target.
// Refreshing too early is harmless (cheap getSignature call); refreshing
// too late risks 109 errors mid-replay, so we err earlier.
if (result && result.expires === true) {
// Without a positive ttl a signature has expired already, still accepted within
// the server's grace period: refresh it soon, or the server drops the keys
// silently. Not at once, in case the backend keeps returning expired ones.
const targetMs = Date.now() + (result.ttl > 0 ? result.ttl * 1000 : 1000);
this._maybeScheduleSharedPollSignatureRefresh(targetMs);
}
}
// Reschedule the consolidating refresh timer if `targetMs` is earlier than
// the currently scheduled target. No-op when a sooner refresh is already
// pending. Pass null to clear and reset (e.g. after consolidation succeeded).
_maybeScheduleSharedPollSignatureRefresh(targetMs) {
if (targetMs === null) {
this._sharedPollSignatureRefreshTargetMs = null;
this._clearSharedPollSignatureRefresh();
return;
}
if (!this._isSubscribed())
return;
if (this._sharedPollSignatureRefreshTargetMs !== null &&
targetMs >= this._sharedPollSignatureRefreshTargetMs) {
return; // existing timer fires sooner
}
this._sharedPollSignatureRefreshTargetMs = targetMs;
this._clearSharedPollSignatureRefresh();
this._sharedPollSignatureRefreshTimeout = setTimeout(() => this._sharedPollRefreshSignature(), Math.max(0, targetMs - Date.now()));
}
_clearSharedPollSignatureRefresh() {
if (this._sharedPollSignatureRefreshTimeout !== null) {
clearTimeout(this._sharedPollSignatureRefreshTimeout);
this._sharedPollSignatureRefreshTimeout = null;
}
this._sharedPollSignatureRefreshAttempts = 0;
// Do not clear the target here — _maybeScheduleSharedPollSignatureRefresh
// owns target lifecycle. This helper only stops the timer and resets
// backoff so the next reschedule starts fresh.
}
_clearSharedPollTrackRetry() {
if (this._sharedPollTrackRetryTimeout !== null) {
clearTimeout(this._sharedPollTrackRetryTimeout);
this._sharedPollTrackRetryTimeout = null;
}
this._sharedPollTrackRetryAttempts = 0;
}
_scheduleSharedPollReplayRetry() {
if (this._sharedPollReplayRetryTimeout !== null) {
clearTimeout(this._sharedPollReplayRetryTimeout);
}
this._sharedPollReplayRetryTimeout = setTimeout(() => this._sharedPollReplayTrack(), backoff(this._sharedPollReplayRetryAttempts++, 5000, 30000));
}
_clearSharedPollReplayRetry() {
if (this._sharedPollReplayRetryTimeout !== null) {
clearTimeout(this._sharedPollReplayRetryTimeout);
this._sharedPollReplayRetryTimeout = null;
}
this._sharedPollReplayRetryAttempts = 0;
}
// Adds a signature to the library, dropping the entries whose keys it covers
// entirely: they may have expired, and a replay sends every entry in one request,
// which a single expired signature fails as a whole.
_addSharedPollSignature(keys, signature) {
const covered = new Set(keys);
this._sharedPollSignatures = this._sharedPollSignatures.filter(entry => !entry.keys.every(key => covered.has(key)));
this._sharedPollSignatures.push({ keys, signature });
}
_handleTrackError(err, keys) {
if (!this._isSubscribed()) {
return;
}
this._emitError({
type: 'track',
channel: this.channel,
error: err,
}, () => {
// A handler may have ended the subscription, e.g. by disconnecting the client.
if (!this._isSubscribed()) {
return;
}
// Error 109 (token expired) on a track command means the signature has
// expired past the server's grace period. Trigger a refresh — getSignature
// will issue a fresh consolidated signature that replaces stale ones.
// The in-flight guard inside _sharedPollRefreshSignature prevents
// duplicate refresh calls when multiple track retries all hit 109.
if (err.code === 109) {
this._sharedPollRefreshSignature();
return;
}
if (err.code < 100 || err.temporary === true) {
// Temporary error — retry full track replay with backoff.
this._sharedPollTrackRetryTimeout = setTimeout(() => this._sharedPollReplayTrack(), backoff(this._sharedPollTrackRetryAttempts++, 1000, 15000));
return;
}
// A permanent error, e.g. limit exceeded or permission denied: retrying
// fails the same way. The keys are untracked like revoked ones, also at
// the server: an earlier request (e.g. one that timed out) may have
// tracked them.
this._untrackFailedKeys(keys);
});
}
_untrackFailedKeys(keys) {
const failed = keys.filter(key => this._sharedPollTrackedItems.has(key));
if (failed.length === 0) {
return;
}
for (const key of failed) {
this._sharedPollTrackedItems.delete(key);
}
this._sharedPollSignatures = this._sharedPollSignatures.filter(entry => entry.keys.some(k => this._sharedPollTrackedItems.has(k)));
this._sendUntrackRequest(failed).catch(err => {
this.emit('error', { type: 'untrack', channel: this.channel, error: err });
});
for (const key of failed) {
// A handler of an earlier removal may have ended the subscription.
if (!this._isSubscribed()) {
return;
}
this.emit('update', {
channel: this.channel,
key: key,
data: null,
removed: true,
});
}
}
// _sharedPollRefreshSignature obtains a fresh consolidated signature
// covering all currently tracked keys, then replaces the library with the
// single new entry. Triggered by the TTL timer (server's `expires/ttl`
// response) and by 109 errors on track commands. The in-flight guard
// collapses concurrent refresh attempts into one.
_sharedPollRefreshSignature() {
this._clearSharedPollSignatureRefresh();
if (!this._isSubscribed())
return;
if (!this._sharedPollGetSignature)
return;
if (this._sharedPollTrackedItems.size === 0)
return;
if (this._sharedPollSignatureRefreshInFlight) {
for (const key of this._sharedPollTrackedItems.keys()) {
if (!this._sharedPollSignatureRefreshKeys.has(key)) {
this._sharedPollSignatureRefreshAgain = true;
break;
}
}
return;
}
// Reset the global refresh target — the timer that pointed at this
// moment has already fired, and the in-flight refresh will publish a
// fresh deadline via the consolidated track response. Resetting here
// (not after consolidation success) lets any concurrent track() call
// that lands during getSignature still set a tighter target if its
// signature is shorter-lived than the consolidated one.
this._sharedPollSignatureRefreshTargetMs = null;
this._sharedPollSignatureRefreshInFlight = true;
const keys = Array.from(this._sharedPollTrackedItems.keys());
this._sharedPollSignatureRefreshKeys = new Set(keys);
const self = this;
// A subscription ending meanwhile resets the in-flight guard for its next period.
const generation = this._refreshGeneration;
this._callAsync(() => this._sharedPollGetSignature({ keys })).then(result => {
if (generation !== self._refreshGeneration)
return;
self._sharedPollSignatureRefreshInFlight = false;
if (!self._isSubscribed())
return;
self._sharedPollSignatureRefreshAttempts = 0;
if (self._sharedPollSignatureRefreshAgain) {
self._sharedPollSignatureRefreshAgain = false;
// After this refresh's track request is sent below.
Promise.resolve().then(() => self._sharedPollRefreshSignature());
}
// Handle revoked keys (keys not in the returned set).
const returnedKeys = new Set(result.keys);
const revokedKeys = [];
for (const key of keys) {
if (!returnedKeys.has(key) && this._sharedPollTrackedItems.has(key)) {
self._sharedPollTrackedItems.delete(key);
revokedKeys.push(key);
// A handler of an earlier removal may have ended the subscription: the
// keys are still untracked below, but nothing more is delivered.
if (!self._isSubscribed()) {
continue;
}
self.emit('update', {
channel: self.channel,
key: key,
data: null,
removed: true,
});
}
}
// Tell the server to stop tracking revoked keys — otherwise the server
// keeps broadcasting them and the SDK silently drops the publications.
if (revokedKeys.length > 0) {
self._sendUntrackRequest(revokedKeys).catch(err => {
self.emit('error', { type: 'untrack', channel: self.channel, error: err });
});
}
// Re-track only keys covered by the returned signature.
const items = [];
for (const key of result.keys) {
const version = self._sharedPollTrackedItems.get(key);
if (version !== undefined) {
items.push({ key, version });
}
}
// Replace the signature library with the consolidated entry. Keep
// any entries that cover keys NOT in the consolidation — those keys
// may have been added via a concurrent track() while getSignature was
// in flight and their signatures must remain available for reconnect.
const consolidatedKeySet = new Set(result.keys);
const uncovered = self._sharedPollSignatures.filter(entry => entry.keys.some(k => self._sharedPollTrackedItems.has(k) && !consolidatedKeySet.has(k)));
// Target was already reset at refresh start; any concurrent track()
// during getSignature has set its own target if its TTL was tighter.
// The consolidated track response below will set a target unless
// something earlier is already in place.
self._sharedPollSignatures = items.length > 0
? [{ keys: result.keys, signature: result.signature }, ...uncovered]
: uncovered;
if (items.length === 0)
return;
self._sendTrackRequest([{ items, signature: result.signature }]).catch(e => {
self._handleTrackError(e.error, e.keys);
});
}).catch(e => {
if (generation !== self._refreshGeneration)
return;
self._sharedPollSignatureRefreshInFlight = false;
// The retry below covers it.
self._sharedPollSignatureRefreshAgain = false;
self._emitError({
type: 'signatureRefresh',
channel: self.channel,
error: {
code: errorCodes.sharedPollGetSignature,
message: e !== undefined ? e.toString() : ''
}
}, () => {
// A handler may have ended the subscription, e.g. by disconnecting the client.
if (generation !== self._refreshGeneration || !self._isSubscribed()) {
return;
}
// Retry after delay with exponential backoff.
self._sharedPollSignatureRefreshTimeout = setTimeout(() => self._sharedPollRefreshSignature(), backoff(self._sharedPollSignatureRefreshAttempts++, 5000, 30000));
});
});
}
// _sharedPollReplayTrack runs after subscribe completes — on initial
// subscribe AND after every reconnect. It reuses every cached signature
// in _sharedPollSignatures so that mass reconnects don't trigger mass
// getSignature calls on the application backend.
//
// For each cached batch:
// - Build a track command with the batch's ORIGINAL key set (HMAC was
// signed over those keys, so the full set must be sent). Versions are
// CURRENT per-connection versions, so the server pushes only what's
// changed.
// - Any keys in the batch that were locally untracked() since the original
// track() are sent in the same frame's `untrack` field — the server
// validates the full HMAC then removes them immediately, avoiding a
// separate round-trip.
//
// getSignature is invoked only when there are no cached signatures (e.g.
// initial subscribe where track(keys) was called without explicit sig).
// Once a signature is expired beyond the server's grace period, the next
// track command returns error 109 — _handleTrackError then triggers
// _sharedPollRefreshSignature for a fresh consolidated signature.
_sharedPollReplayTrack() {
if (!this._isSubscribed())
return;
if (this._sharedPollTrackedItems.size === 0 && this._sharedPollSignatures.length === 0)
return;
// Phase 1: replay every cached signature batch in a SINGLE sub_refresh
// frame (multi-batch wire format). The server validates each batch's
// HMAC independently and merges the response. All-or-nothing semantics:
// one failed signature → the whole replay fails and _handleTrackError
// drives a consolidating refresh.
//
// After this block `coveredKeys` is the set of currently-tracked keys
// that already have a signature in the library — any tracked key not
// in this set needs a fresh getSignature in Phase 2.
const coveredKeys = new Set();
const replayBatches = [];
const allUntrackedInReplay = [];
for (const entry of this._sharedPollSignatures) {
// Items: ORIGINAL key set + current per-connection versions. Keys that
// were untracked locally still go in items (HMAC needs the full batch);
// a single chained untrack runs after the multi-batch track resolves
// to converge server-side state.
const items = entry.keys.map(key => {
var _a;
return ({
key,
version: (_a = this._sharedPollTrackedItems.get(key)) !== null && _a !== void 0 ? _a : 0,
});
});
replayBatches.push({ items, signature: entry.signature });
for (const k of entry.keys) {
if (this._sharedPollTrackedItems.has(k)) {
coveredKeys.add(k);
}
else {
allUntrackedInReplay.push(k);
}
}
}
if (replayBatches.length > 0) {
// Pass untracked keys inline — server validates HMAC over the full batch
// then immediately removes the stale keys in the same handler, eliminating
// the previous two-round-trip track→untrack sequence.
this._sendTrackRequest(replayBatches, allUntrackedInReplay).catch(e => {
this._handleTrackError(e.error, e.keys);
});
}
// Phase 2: any tracked items NOT covered by a cached signature need
// a fresh getSignature. This handles two cases:
// - initial subscribe where track(keys) was called without explicit
// sig (library starts empty, all keys uncovered);
// - mixed track(keys) + track(items, sig) before subscribe — the
// explicit batch sits in the library, but auto-tracked keys still
// need a signature.
const uncoveredKeys = [];
for (const key of this._sharedPollTrackedItems.keys()) {
if (!coveredKeys.has(key))
uncoveredKeys.push(key);
}
if (uncoveredKeys.length === 0)
return;
if (!this._sharedPollGetSignature) {
this.emit('error', {
type: 'track',
channel: this.channel,
error: { code: errorCodes.sharedPollGetSignature, message: 'getSignature callback required for tracked keys without an explicit signature' },
});
return;
}
const self = this;
const generation = this._refreshGeneration;
this._callAsync(() => this._sharedPollGetSignature({ keys: uncoveredKeys })).then(result => {
// The subscription ended meanwhile, e.g. by a reconnect: its replay asks again.
if (generation !== self._refreshGeneration || !self._isSubscribed())
return;
self._clearSharedPollReplayRetry();
// Handle revoked keys (keys we asked about that the backend didn't authorize).
const returnedKeys = new Set(result.keys);
const revokedKeys = [];
for (const key of uncoveredKeys) {
if (!returnedKeys.has(key) && this._sharedPollTrackedItems.has(key)) {
self._sharedPollTrackedItems.delete(key);
revokedKeys.push(key);
// A handler of an earlier removal may have ended the subscription: the
// keys are still untracked below, but nothing more is delivered.
if (!self._isSubscribed()) {
continue;
}
self.emit('update', {
channel: self.channel,
key: key,
data: null,
removed: true,
});
}
}
if (revokedKeys.length > 0) {
self._sendUntrackRequest(revokedKeys).catch(err => {
self.emit('error', { type: 'untrack', channel: self.channel, error: err });
});
}
const items = [];
for (const key of result.keys) {
const version = self._sharedPollTrackedItems.get(key);
if (version !== undefined) {
items.push({ key, version });
}
}
if (items.length === 0)
return;
// Cache the obtained signature for subsequent reconnect replays.
self._addSharedPollSignature(result.keys, result.signature);
self._sendTrackRequest([{ items, signature: result.signature }]).catch(e => {
self._handleTrackError(e.error, e.keys);
});
}).catch(e => {
if (generation !== self._refreshGeneration || !self._isSubscribed())
return;
self._emitError({
type: 'signatureRefresh',
channel: self.channel,
error: {
code: errorCodes.sharedPollGetSignature,
message: e !== undefined ? e.toString() : ''
}
}, () => {
// A handler may have ended the subscription, e.g. by disconnecting the client.
if (generation !== self._refreshGeneration || !self._isSubscribed())
return;
// Replay-getSignature retry uses its OWN backoff state — separate from
// the refresh timer so a stuck replay can't delay the next TTL refresh.
self._sharedPollReplayRetryTimeout = setTimeout(() => self._sharedPollReplayTrack(), backoff(self._sharedPollReplayRetryAttempts++, 5000, 30000));
});
});
}
// ============ Keyed Subscription Methods ============
/** Entry point for map subscriptions */
_mapSubscribe() {
this._debug('starting map subscribe on', this.channel);
const flow = ++this._subscribeFlow;
// Decided when the first request goes, after the token if one is needed: the
// position may be reset meanwhile (state invalidation, setTagsFilter).
const start = () => {
// Initialize buffers and phase
this._mapStateBuffer = [];
this._mapStreamBuffer = [];
this._mapCursor = '';
// If we have a position from `since`, we may skip snapshot and go to stream
const recovering = this._recover && this._offset !== null && this._epoch !== null;
// Preserve _prevValueMap when recovering — the server will send deltas
// against the values the client already has from the previous session.
// Only clear when starting from scratch (no recovery position).
if (!recovering) {
this._prevValueMap = new Map();
}
this._mapFlowRecovering = recovering;
this._mapFlowOffset = recovering ? this._offset : 0;
this._mapFlowEpoch = recovering ? this._epoch : null;
this._mapFlowPositionResets = this._mapPositionResets;
this._mapPhase = MapPhase.State;
if (recovering) {
this._debug('map subscribe: recovering from position, skipping to stream phase');
this._mapPhase = MapPhase.Stream;
this._fetchStream(flow);
}
else {
this._fetchSnapshot(flow);
}
};
// Get token if needed, then start fetching. Also when recovering: the token
// may have been cleared, e.g. after it expired.
if (this._canSubscribeWithoutGettingToken()) {
start();
}
else {
this._getSubscriptionToken()
.then(token => {
// A later flow owns the subscription now.
if (flow !== this._subscribeFlow) {
return;
}
if (!this._isSubscribing()) {
this._inflight = false;
return;
}
if (!token) {
this._inflight = false;
this._failUnauthorized();
return;
}
this._token = token;
start();
})
.catch(e => {
this._handleTokenError(e, flow);
});
}
}
/** Fetch a page of snapshot data */
_fetchSnapshot(flow, cursor) {
if (!this._isSubscribing() || !this._isTransportOpen()) {
this._inflight = false;
return;
}
const cmd = this._buildMapSubscribeCommand(MapPhase.State, cursor);
this._debug('map subscribe: fetching snapshot page', cursor ? `cursor=${cursor}` : 'initial');
this._subscribeCallFlow = flow;
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._call(cmd).then(resolveCtx => {
try {
if (this._settleSubscribeCall(flow, true)) {
return;
}
// The reply to a page of an earlier flow is outdated.
if (flow === this._subscribeFlow) {
this._handleMapStateResponse(flow, resolveCtx.reply.subscribe);
}
}
catch (err) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._dispatchFailed(err);
}
finally {
if (resolveCtx.next) {
resolveCtx.next();
}
}
}, rejectCtx => {
try {
if (this._settleSubscribeCall(flow, false, rejectCtx.error)) {
return;
}
if (flow === this._subscribeFlow) {
this._handleMapSubscribeError(rejectCtx.error);
}
}
catch (err) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._rejectionFailed(err, rejectCtx);
}
finally {
if (rejectCtx.next) {
rejectCtx.next();
}
}
});
}
/** Process snapshot response */
_handleMapStateResponse(flow, result) {
if (!this._isSubscribing()) {
this._inflight = false;
return;
}
// Check if server forced LIVE transition during STATE phase.
// This happens on the last state page when server decides to skip STREAM phase
// (streamless mode, or positioned mode with stream close enough).
// Note: phase=0 may be omitted by JSON serializer, so !result.phase handles both 0 and undefined.
if (!result.phase) {
this._debug('map subscribe: server forced LIVE transition during state pagination');
// _handleMapLiveResponse will process result.state and result.publications.
this._handleMapLiveResponse(flow, result);
return;
}
// Store epoch/offset from first response. Both are frozen for the duration
// of state pagination to maintain consistency: the stream catch-up must start
// from where the first state page was captured, not from a later stream.Top().
if (!this._mapFlowEpoch && result.epoch) {
this._mapFlowEpoch = result.epoch;
this._mapFlowOffset = toOffset(result.offset);
}
// Validate epoch on subsequent pages - if epoch changed, restart
if (this._mapFlowEpoch && result.epoch && this._mapFlowEpoch !== result.epoch) {
this._debug('map subscribe: epoch changed during snapshot pagination, restarting');
this._restartMapFlow();
this._fetchSnapshot(flow);
return;
}
// Append state entries to snapshot buffer (state field, not publications).
if (result.state && result.state.length > 0) {
this._mapStateBuffer.push(...result.state);
}
// Check if there's more data to fetch
if (result.cursor) {
this._mapCursor = result.cursor;
this._fetchSnapshot(flow, this._mapCursor);
return;
}
// No more snapshot pages, transition to next phase
this._transitionFromSnapshot(flow);
}
// The stream epoch changed during the flow: what it collected and the stored
// position are outdated. The flow continues from a snapshot.
_restartMapFlow() {
this._mapStateBuffer = [];
this._mapStreamBuffer = [];
this._mapCursor = '';
this._mapFlowRecovering = false;
this._mapFlowOffset = 0;
this._mapFlowEpoch = null;
this._epoch = null;
this._offset = null;
this._recover = false;
this._prevValueMap = new Map();
this._mapPhase = MapPhase.State;
}
/** Transition from STATE to STREAM phase after snapshot pagination completes */
_transitionFromSnapshot(flow) {
this._debug('map subscribe: snapshot complete, transitioning to stream phase');
// After STATE pagination, move to STREAM phase.
// Client sends phase=1 requests, server decides when to go LIVE
// by responding with phase=0.
this._mapPhase = MapPhase.Stream;
this._fetchStream(flow);
}
/** Fetch stream data (offset-based catch-up) */
_fetchStream(flow) {
if (!this._isSubscribing() || !this._isTransportOpen()) {
this._inflight = false;
return;
}
const cmd = this._buildMapSubscribeCommand(MapPhase.Stream);
this._debug('map subscribe: fetching stream from offset', this._mapFlowOffset);
this._subscribeCallFlow = flow;
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._call(cmd).then(resolveCtx => {
try {
if (this._settleSubscribeCall(flow, true)) {
return;
}
// The reply to a page of an earlier flow is outdated.
if (flow === this._subscribeFlow) {
this._handleMapStreamResponse(flow, resolveCtx.reply.subscribe);
}
}
catch (err) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._dispatchFailed(err);
}
finally {
if (resolveCtx.next) {
resolveCtx.next();
}
}
}, rejectCtx => {
try {
if (this._settleSubscribeCall(flow, false, rejectCtx.error)) {
return;
}
if (flow === this._subscribeFlow) {
this._handleMapSubscribeError(rejectCtx.error);
}
}
catch (err) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._rejectionFailed(err, rejectCtx);
}
finally {
if (rejectCtx.next) {
rejectCtx.next();
}
}
});
}
/** Process stream response */
_handleMapStreamResponse(flow, result) {
if (!this._isSubscribing()) {
this._inflight = false;
return;
}
// Check if server forced LIVE transition (server-controlled).
// When server decides client is close enough, it returns phase=0 (LIVE).
// Note: phase=0 may be omitted by JSON serializer, so !result.phase handles both 0 and undefined.
if (!result.phase) {
this._debug('map subscribe: server forced LIVE transition during stream');
this._handleMapLiveResponse(flow, result);
return;
}
// Validate epoch - if changed, we need to restart
if (this._mapFlowEpoch && result.epoch && this._mapFlowEpoch !== result.epoch) {
this._debug('map subscribe: epoch changed during stream, restarting');
this._restartMapFlow();
this._fetchSnapshot(flow);
return;
}
// Append publications to stream buffer
if (result.publications && result.publications.length > 0) {
this._mapStreamBuffer.push(...result.publications);
}
// Page from the offset in the result. Server returns the last publication's
// actual offset for intermediate STREAM pages (not stream.Top()). The stored
// position doesn't move: these entries only reach the app with the live reply.
if (result.offset !== undefined) {
this._mapFlowOffset = toOffset(result.offset);
}
// Server controls LIVE transition. If server responded with phase=1,
// we continue STREAM pagination. Server will respond with phase=0 when ready.
this._fetchStream(flow);
}
/** Process live response - complete the map subscription */
_handleMapLiveResponse(flow, result) {
if (!this._isSubscribing()) {
this._inflight = false;
return;
}
this._inflight = false;
// Validate epoch one more time
if (this._mapFlowEpoch && result.epoch && this._mapFlowEpoch !== result.epoch) {
this._debug('map subscribe: epoch changed during live transition, restarting');
this._restartMapFlow();
this._inflight = true;
this._fetchSnapshot(flow);
return;
}
// Values of state and stream pages are escaped only when delta is negotiated,
// which only the live reply tells: decode the buffered pages now. State entries
// (including those of this reply) first, then the stream catch-up, whose delta
// bases the live publications below may build on.
const deltaNegotiated = !!(this._delta && result.delta);
const statePubs = result.state && result.state.length > 0 ? this._mapStateBuffer.concat(result.state) : this._mapStateBuffer;
this._mapStateBuffer = statePubs.map(pub => {
this._seedDeltaTracking(pub, deltaNegotiated);
return this._getMapUpdateContext(pub);
});
this._mapStreamBuffer = this._mapStreamBuffer.map(pub => {
this._seedDeltaTracking(pub, deltaNegotiated);
return this._getMapUpdateContext(pub);
});
// Append any remaining publications from the live response to stream buffer.
// Recovery publications may be delta-encoded — decode before buffering.
// Use result.delta (not this._delta_negotiated which is set later).
if (result.publications && result.publications.length > 0) {
for (const pub of result.publications) {
if (deltaNegotiated) {
// Delta negotiated: decode and update tracking in one block. A removal
// carries no payload to decode, and ends the key's delta chain.
const deltaKey = pub.key || '';
if (pub.removed) {
this._prevValueMap.delete(deltaKey);
}
else {
// @ts-ignore – we are hiding some methods from public API autocompletion.
const { newData, newPrevValue, isDelta, wireBytes, fullBytes } = this._centrifuge._codec.applyDeltaIfNeeded(pub, this._prevValueMap.get(deltaKey));
pub.data = newData;
this._deltaNumPubs++;
this._deltaBytesReceived += wireBytes;
this._deltaBytesDecoded += fullBytes;
if (isDelta) {
this._deltaNumDelta++;
}
else {
this._deltaNumFull++;
}
this._prevValueMap.set(deltaKey, newPrevValue);
}
}
else if (this._delta && pub.key) {
// Delta requested but not negotiated: seed tracking with raw data.
if (pub.removed) {
this._prevValueMap.delete(pub.key);
}
else {
this._prevValueMap.set(pub.key, pub.data);
}
}
this._mapStreamBuffer.push(this._getMapUpdateContext(pub));
}
}
// Final offset/epoch — use || 0/'' to handle zero values omitted by JSON/protobuf.
const offset = toOffset(result.offset);
const epoch = result.epoch || '';
// Clear subscribing state
this._clearSubscribingState();
// Store subscription ID if provided
if (result.id) {
this._id = result.id;
}
// Recoverable state - enable recovery for reconnects.
// In streamless mode server omits recoverable (JSON: undefined, protobuf: false).
const recover = result.recoverable === true;
// Handle delta negotiation
if (result.delta) {
this._delta_negotiated = true;
}
else {
this._delta_negotiated = false;
}
// Set publish debounce from subscribe result.
if (result.publish_debounce) {
this._debounceMs = result.publish_debounce;
}
// Take the buffers: a handler below may unsubscribe and subscribe again,
// which starts a new flow using them.
let stateEntries = this._mapStateBuffer;
let streamEntries = this._mapStreamBuffer;
this._mapStateBuffer = [];
this._mapStreamBuffer = [];
this._mapPhase = null;
// Build subscribed context with state entries
// @ts-ignore – we are hiding some methods from public API autocompletion.
const ctx = this._centrifuge._getSubscribeContext(this.channel, result);
ctx.state = stateEntries;
// The reply's offset is the top of the stream, also after a recovery. This
// differs from a stream subscription, whose reply after a recovery carries the
// position recovered from (see _setSubscribed). Nor would that position cover
// the whole catch-up here: its entries can come from several stream pages,
// buffered until now. Until the events below reached the app, the stored
// position must not skip what they carry: a handler, from the state event on,
// may unsubscribe, or subscribe again, in between.
// The position may also be reset (setTagsFilter()) since this flow started, or by
// a handler below: it's kept then, and the next subscribe starts from scratch.
const positionResets = this._mapFlowPositionResets;
if (this._mapPositionResets === positionResets) {
this._recover = recover;
this._epoch = epoch;
if (!ctx.recovered) {
// Until sync, the app doesn't have the complete state: start from scratch.
this._recover = false;
this._offset = null;
this._epoch = null;
}
else if (streamEntries.length > 0 && streamEntries[0].offset !== undefined) {
// Before the recovered catch-up.
this._offset = streamEntries[0].offset - 1;
}
else {
this._offset = offset;
}
}
// Transition to subscribed state. A 'state' handler may have unsubscribed
// already: no subscribed event then.
this._setState(SubscriptionState.Subscribed);
if (!this._isSubscribed()) {
return;
}
// Emit subscribed event
this.emit('subscribed', ctx);
// A 'subscribed', 'sync', 'publication' or 'update' handler may have
// unsubscribed: the rest of this flow must not reach the app. If it subscribed
// again, promises made since then wait for that subscribe.
if (!this._isSubscribed()) {
return;
}
this._resolvePromises();
// Emit sync event — complete state for simplified state management.
// Skipped on successful recovery (app already has rendered state; stream
// catch-up is emitted as individual update events).
if (!ctx.recovered) {
if (streamEntries.length > 0) {
// Apply stream catch-up buffer to state by key (last value wins, removed deletes).
// Produces a single sync snapshot that reflects state as of LIVE transition.
const stateMap = new Map();
for (const entry of stateEntries) {
stateMap.set(entry.key, entry);
}
for (const entry of streamEntries) {
if (entry.removed) {
stateMap.delete(entry.key);
}
else {
stateMap.set(entry.key, entry);
}
}
stateEntries = Array.from(stateMap.values());
streamEntries = []; // Already applied — don't emit as updates.
}
if (this._mapPositionResets === positionResets) {
this._recover = recover;
this._offset = offset;
this._epoch = epoch;
}
this.emit('sync', { entries: stateEntries });
}
// Flush remaining stream buffer as publication and update events.
// On recovery (sync skipped above) — app already has state and just needs
// incremental changes. An entry counts as delivered from its update event on,
// as a live publication (see _handlePublication).
for (const entry of streamEntries) {
if (!this._isSubscribed()) {
return;
}
this.emit('publication', entry);
if (!this._isSubscribed()) {
return;
}
if (entry.offset !== undefined && this._mapPositionResets === positionResets) {
this._offset = entry.offset;
}
this.emit('update', entry);
}
if (!this._isSubscribed()) {
return;
}
if (this._mapPositionResets === positionResets) {
this._offset = offset;
}
// Handle token expiry
if (result.expires === true) {
this._refreshTimeout = setTimeout(() => this._refresh(), ttlMilliseconds(result.ttl));
}
}
/** Handle errors during map subscription process */
_handleMapSubscribeError(error) {
this._inflight = false;
if (!this._isSubscribing()) {
return;
}
if (error.code === errorCodes.connectionClosed) {
// See _handleSubscribeError.
return;
}
if (error.code === errorCodes.timeout) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
this._centrifuge._disconnect(connectingCodes.subscribeTimeout, 'subscribe timeout', true);
return;
}
// Clear map state on error. The delta bases stay with the position: a
// recovery from it gets deltas of the values the client has.
this._mapStateBuffer = [];
this._mapStreamBuffer = [];
this._mapPhase = null;
// Handle unrecoverable position error (code 112) based on strategy
if (error.code === 112) {
if (this._mapUnrecoverableStrategy === 'from_scratch') {
// Reset position and resubscribe from snapshot
this._debug('map subscribe: unrecoverable position, restarting from scratch');
this._prevValueMap = new Map();
this._offset = null;
this._epoch = null;
this._recover = false;
this._scheduleResubscribe();
return;
}
// 'fatal' strategy: fall through to _subscribeError which will unsubscribe
}
this._subscribeError(error);
}
/** Build map subscribe command for a specific phase */
_buildMapSubscribeCommand(phase, cursor) {
const req = {
channel: this.channel,
type: this._mapPresenceType || 1, // 1=MAP, 2=MAP_CLIENTS, 3=MAP_USERS
phase: phase,
};
if (this._token)
req.token = this._token;
if (this._tagsFilter)
req.tf = this._tagsFilter;
if (this._delta)
req.delta = this._delta;
req.flag = subscriptionFlags.channelCompaction;
// STATE phase
if (phase === MapPhase.State) {
if (this._mapPageSize > 0)
req.limit = this._mapPageSize;
if (cursor)
req.cursor = cursor;
// Epoch validation after first page
if (this._mapFlowEpoch) {
req.offset = this._mapFlowOffset;
req.epoch = this._mapFlowEpoch;
}
else {
// First request of the flow — include custom data.
if (this._data)
req.data = this._data;
}
}
// STREAM phase
if (phase === MapPhase.Stream) {
if (this._mapPageSize > 0)
req.limit = this._mapPageSize;
req.offset = this._mapFlowOffset;
req.epoch = this._mapFlowEpoch;
if (this._mapFlowRecovering) {
req.recover = true;
// First request of the flow (skipped STATE) — include custom data for authorization.
if (this._mapStreamBuffer.length === 0) {
if (this._data)
req.data = this._data;
}
}
}
return { subscribe: req };
}
/** Convert raw publication to MapUpdateContext */
_getMapUpdateContext(pub) {
const ctx = {
channel: this.channel,
data: pub.data,
key: pub.key || '',
};
if (pub.removed === true) {
ctx.removed = true;
}
if (pub.offset !== undefined) {
ctx.offset = toOffset(pub.offset);
}
if (pub.info) {
// @ts-ignore – we are hiding some methods from public API autocompletion.
ctx.info = this._centrifuge._getJoinLeaveContext(pub.info);
}
if (pub.tags) {
ctx.tags = pub.tags;
}
return ctx;
}
/** Convert raw publication to SharedPollUpdateContext */
_getSharedPollUpdateContext(pub) {
const ctx = {
channel: this.channel,
key: pub.key || '',
data: pub.data,
};
if (pub.removed === true) {
ctx.removed = true;
}
if (pub.version !== undefined) {
ctx.version = toOffset(pub.version);
}
return ctx;
}
}
/** Stream subscription with publish/history methods. */
class Subscription extends BaseSubscription {
/** Publish data to the channel. */
publish(data) {
return __awaiter(this, void 0, void 0, function* () {
yield this._methodCall();
// Debounce per channel (key = "" for stream publishes).
if (this._debounceMs > 0) {
return this._debouncedPublish('', data, false);
}
return this._centrifuge.publish(this.channel, data);
});
}
/** history for a channel. By default it does not return publications (only current
* StreamPosition data) – provide an explicit limit > 0 to load publications.*/
history(opts) {
return __awaiter(this, void 0, void 0, function* () {
yield this._methodCall();
return this._centrifuge.history(this.channel, opts);
});
}
}
/** Map subscription with publish/remove methods. */
class MapSubscription extends BaseSubscription {
/** Publish data to a key. */
publish(key, data) {
return __awaiter(this, void 0, void 0, function* () {
yield this._methodCall();
if (this._debounceMs > 0) {
return this._debouncedPublish(key, data, true);
}
return this._centrifuge.mapPublish(this.channel, key, data);
});
}
/** Remove a key. */
remove(key) {
return __awaiter(this, void 0, void 0, function* () {
yield this._methodCall();
// Cancel any pending debounced publish for this key.
this._cancelDebounce(key);
return this._centrifuge.mapRemove(this.channel, key);
});
}
}
/** Shared poll subscription with track/untrack/trackedKeys. */
class SharedPollSubscription extends BaseSubscription {
/** Track items in a shared poll subscription.
*
* Overloads:
* - `track(keys: string[])` — pass key names only (version defaults to 0).
* Requires `getSignature` callback in subscription options. The SDK
* automatically obtains a signature before sending the track request.
* - `track(items: SharedPollTrackItem[], signature: string)` — pass items
* with explicit versions and a pre-computed HMAC signature.
*
* Items are stored in local state immediately. If subscribed, the track request
* is sent right away. If not yet subscribed, items will be sent via replay
* (with a fresh signature from getSignature) after subscribe completes.
*
* **Fire-and-forget** (similar to subscribe/unsubscribe): returns void and never
* throws for in-flight failures. Subscribe to the `error` event to observe
* failures: `type: 'track'` covers both the server-side track request and
* the `getSignature` callback when using `track(keys)`. Server-revoked keys
* arrive as synthetic `update` events with `removed: true`. */
track(keysOrItems, signature) {
if (keysOrItems.length === 0) {
return; // Nothing to track — avoid wasteful getSignature call.
}
let items;
const sig = signature;
if (typeof keysOrItems[0] === 'string') {
const keys = keysOrItems;
items = keys.map(k => ({ key: k, version: 0 }));
}
else {
items = keysOrItems;
}
// Update per-connection tracked items (use max(existing, new) so a stale
// page load can't downgrade a version already advanced by a publication).
for (const item of items) {
// A version an app stored and restored comes back as an object, see toOffset.
const version = toOffset(item.version);
const existing = this._sharedPollTrackedItems.get(item.key);
if (existing === undefined || version > existing) {
this._sharedPollTrackedItems.set(item.key, version);
}
}
if (sig !== undefined) {
// Explicit signature path — append to library and (if subscribed) send.
this._addSharedPollSignature(items.map(i => i.key), sig);
if (this._isSubscribed() && !this._sharedPollReplayPending) {
this._sendTrackRequest([{ items, signature: sig }]).catch(e => {
this._handleTrackError(e.error, e.keys);
});
}
// If not subscribed yet, or completing the subscribe, _sharedPollReplayTrack
// sends it after subscribe.
return;
}
// Auto-obtain signature via getSignature callback.
if (!this._sharedPollGetSignature) {
this.emit('error', {
type: 'track',
channel: this.channel,
error: { code: errorCodes.sharedPollGetSignature, message: 'getSignature callback required for track(keys)' },
});
return;
}
if (!this._isSubscribed() || this._sharedPollReplayPending) {
// Defer the getSignature call until after subscribe — _sharedPollReplayTrack
// will obtain a signature covering all tracked keys at once.
return;
}
const keys = items.map(i => i.key);
const generation = this._refreshGeneration;
this._callAsync(() => this._sharedPollGetSignature({ keys })).then(result => {
// The subscription ended meanwhile, e.g. by a reconnect: its replay asks again.
if (generation !== this._refreshGeneration || !this._isSubscribed())
return;
// Handle revoked keys.
const returnedKeys = new Set(result.keys);
const revokedKeys = [];
for (const key of keys) {
if (!returnedKeys.has(key) && this._sharedPollTrackedItems.has(key)) {
this._sharedPollTrackedItems.delete(key);
revokedKeys.push(key);
// A handler of an earlier removal may have ended the subscription: the
// keys are still untracked below, but nothing more is delivered.
if (!this._isSubscribed()) {
continue;
}
this.emit('update', {
channel: this.channel,
key: key,
data: null,
removed: true,
});
}
}
// Server may already be tracking some of these from a prior track() with
// a different signature — send untrack so it stops broadcasting them.
if (revokedKeys.length > 0) {
this._sendUntrackRequest(revokedKeys).catch(err => {
this.emit('error', { type: 'untrack', channel: this.channel, error: err });
});
}
// A getSignature that works again: the next failure starts the backoff over.
this._sharedPollReplayRetryAttempts = 0;
// Track authorized keys.
const authorizedItems = [];
for (const key of result.keys) {
const version = this._sharedPollTrackedItems.get(key);
if (version !== undefined) {
authorizedItems.push({ key, version });
}
}
if (authorizedItems.length === 0)
return;
// Cache the obtained signature for reconnect replay.
this._addSharedPollSignature(result.keys, result.signature);
this._sendTrackRequest([{ items: authorizedItems, signature: result.signature }]).catch(e => {
this._handleTrackError(e.error, e.keys);
});
}).catch(e => {
if (generation !== this._refreshGeneration || !this._isSubscribed())
return;
this._emitError({
type: 'track',
channel: this.channel,
error: { code: errorCodes.sharedPollGetSignature, message: e !== undefined ? e.toString() : 'getSignature failed' },
}, () => {
if (generation !== this._refreshGeneration || !this._isSubscribed())
return;
// Retried by the replay, which gets a signature for the keys without one.
this._scheduleSharedPollReplayRetry();
});
});
}
/** Stop tracking specific keys in a shared poll subscription.
* Keys are removed from local state immediately. If subscribed, the untrack
* request is sent right away. If not yet subscribed, the keys simply won't
* be included in the replay after subscribe completes.
*
* **Fire-and-forget** (similar to subscribe/unsubscribe): returns void and never
* throws for in-flight failures. Subscribe to the `error` event with
* `type: 'untrack'` to observe failures of the untrack request. */
untrack(keys) {
for (const key of keys) {
this._sharedPollTrackedItems.delete(key);
}
// Drop any signature entries whose ENTIRE key set is now untracked —
// they contribute nothing to reconnect replays and would grow unboundedly
// in long-running sessions with many track/untrack cycles. Entries where
// at least one key is still tracked are kept intact: pruning them would
// cause those live keys to lose their signature on the next reconnect.
this._sharedPollSignatures = this._sharedPollSignatures.filter(entry => entry.keys.some(k => this._sharedPollTrackedItems.has(k)));
if (this._isSubscribed()) {
this._sendUntrackRequest(keys).catch(err => {
this.emit('error', {
type: 'untrack',
channel: this.channel,
error: err,
});
});
}
}
/** Returns the set of currently tracked keys in a shared poll subscription. */
trackedKeys() {
return new Set(this._sharedPollTrackedItems.keys());
}
}
/** @internal */
class SockjsTransport {
constructor(endpoint, options) {
this.endpoint = endpoint;
this.options = options;
this._transport = null;
}
name() {
return 'sockjs';
}
subName() {
return 'sockjs-' + this._transport.transport;
}
emulation() {
return false;
}
supported() {
return this.options.sockjs !== null;
}
initialize(_protocol, callbacks) {
this._transport = new this.options.sockjs(this.endpoint, null, this.options.sockjsOptions);
this._transport.onopen = () => {
callbacks.onOpen();
};
this._transport.onerror = e => {
callbacks.onError(e);
};
this._transport.onclose = closeEvent => {
callbacks.onClose(closeEvent);
};
this._transport.onmessage = event => {
callbacks.onMessage(event.data);
};
}
close() {
// No socket if its constructor threw in initialize().
if (this._transport !== null) {
this._transport.close();
}
}
send(data) {
this._transport.send(data);
}
}
/** @internal */
class WebsocketTransport {
constructor(endpoint, options) {
this.endpoint = endpoint;
this.options = options;
this._transport = null;
}
name() {
return 'websocket';
}
subName() {
return 'websocket';
}
emulation() {
return false;
}
supported() {
return this.options.websocket !== undefined && this.options.websocket !== null;
}
initialize(protocol, callbacks) {
let subProtocol = '';
if (protocol === 'protobuf') {
subProtocol = 'centrifuge-protobuf';
}
if (subProtocol !== '') {
this._transport = new this.options.websocket(this.endpoint, subProtocol);
}
else {
this._transport = new this.options.websocket(this.endpoint);
}
if (protocol === 'protobuf') {
this._transport.binaryType = 'arraybuffer';
}
this._transport.onopen = () => {
callbacks.onOpen();
};
this._transport.onerror = e => {
callbacks.onError(e);
};
this._transport.onclose = closeEvent => {
callbacks.onClose(closeEvent);
};
this._transport.onmessage = event => {
callbacks.onMessage(event.data);
};
}
close() {
// No socket if its constructor threw in initialize().
if (this._transport !== null) {
this._transport.close();
}
}
send(data) {
this._transport.send(data);
}
}
// A buffer grown beyond this for a large reply is released once the reply is cut out.
const maxRetainedSize = 64 * 1024;
/** @internal Collects the chunks of a binary stream and cuts complete replies out
* of them. Appending a chunk and cutting a reply cost their own size only, not the
* size of what is buffered: a large reply arriving in many small chunks is not
* copied again for every chunk. */
class ReplyStreamBuffer {
constructor() {
this._buf = new Uint8Array(0);
this._start = 0;
this._end = 0;
}
push(chunk) {
const size = this._end - this._start;
if (this._end + chunk.length > this._buf.length) {
if (size + chunk.length <= this._buf.length / 2) {
// Enough room once the data already cut out is dropped.
this._buf.copyWithin(0, this._start, this._end);
}
else {
const buf = new Uint8Array(Math.max(this._buf.length * 2, size + chunk.length));
buf.set(this._buf.subarray(this._start, this._end));
this._buf = buf;
}
this._start = 0;
this._end = size;
}
this._buf.set(chunk, this._end);
this._end += chunk.length;
}
// Calls onReply with a copy of each complete reply buffered, in order.
// decodeReply tells whether the data starts with a complete reply, and where it ends.
drain(decodeReply, onReply) {
while (this._start < this._end) {
const result = decodeReply(this._buf.subarray(this._start, this._end));
if (!result.ok) {
break;
}
const end = this._start + result.pos;
const reply = this._buf.slice(this._start, end);
this._start = end;
onReply(reply);
}
const size = this._end - this._start;
if (this._buf.length > maxRetainedSize && size <= this._buf.length / 4) {
// Don't keep the memory of a large reply for the rest of the connection. The
// copy costs at most a quarter of what growing the buffer did.
this._buf = this._buf.slice(this._start, this._end);
this._start = 0;
this._end = size;
}
else if (size === 0) {
this._start = 0;
this._end = 0;
}
}
}
/** @internal Collects the chunks of a stream of newline-delimited text replies and
* cuts complete lines out of them. Each chunk is scanned once, and the parts of a
* line arriving in many chunks are joined once: a large reply doesn't make every
* chunk cost more. */
class LineStreamBuffer {
constructor() {
this._decoder = new TextDecoder();
this._parts = [];
}
// Calls onLine with each complete line, in order, without its '\n'.
push(chunk, onLine) {
// stream: true keeps decoder state across reads so a multi-byte UTF-8 character
// split across two chunks is not corrupted into replacement characters.
const text = this._decoder.decode(chunk, { stream: true });
let start = 0;
let end = text.indexOf('\n');
while (end !== -1) {
this._parts.push(text.substring(start, end));
const line = this._parts.join('');
this._parts = [];
start = end + 1;
onLine(line);
end = text.indexOf('\n', start);
}
if (start < text.length) {
this._parts.push(text.substring(start));
}
}
}
/** @internal */
class HttpStreamTransport {
constructor(endpoint, options) {
this.endpoint = endpoint;
this.options = options;
this._abortController = null;
this._protocol = 'json';
}
name() {
return 'http_stream';
}
subName() {
return 'http_stream';
}
emulation() {
return true;
}
_handleErrors(response) {
if (!response.ok)
throw new Error(response.status);
return response;
}
_fetchEventTarget(self, endpoint, options) {
const eventTarget = new EventTarget();
// fetch with connection timeout maybe? https://github.com/github/fetch/issues/175
const fetchFunc = self.options.fetch;
fetchFunc(endpoint, options)
.then(self._handleErrors)
.then(response => {
eventTarget.dispatchEvent(new Event('open'));
const jsonStreamBuf = new LineStreamBuffer();
const protoStreamBuf = new ReplyStreamBuffer();
const reader = response.body.getReader();
return new self.options.readableStream({
start(controller) {
function pump() {
return reader.read().then(({ done, value }) => {
// When no more data needs to be consumed, close the stream
if (done) {
eventTarget.dispatchEvent(new Event('close'));
controller.close();
return;
}
try {
if (self._protocol === 'json') {
jsonStreamBuf.push(value, line => eventTarget.dispatchEvent(new MessageEvent('message', { data: line })));
}
else {
protoStreamBuf.push(value);
protoStreamBuf.drain(data => self.options.decoder.decodeReply(data), reply => eventTarget.dispatchEvent(new MessageEvent('message', { data: reply })));
}
}
catch (error) {
// @ts-ignore - improve later.
eventTarget.dispatchEvent(new Event('error', { detail: error }));
eventTarget.dispatchEvent(new Event('close'));
controller.close();
return;
}
pump();
}).catch(function (e) {
// @ts-ignore - improve later.
eventTarget.dispatchEvent(new Event('error', { detail: e }));
eventTarget.dispatchEvent(new Event('close'));
controller.close();
return;
});
}
return pump();
}
});
})
.catch(error => {
// @ts-ignore - improve later.
eventTarget.dispatchEvent(new Event('error', { detail: error }));
eventTarget.dispatchEvent(new Event('close'));
});
return eventTarget;
}
supported() {
return this.options.fetch !== null &&
this.options.readableStream !== null &&
typeof TextDecoder !== 'undefined' &&
typeof AbortController !== 'undefined' &&
typeof EventTarget !== 'undefined' &&
typeof Event !== 'undefined' &&
typeof MessageEvent !== 'undefined' &&
typeof Error !== 'undefined';
}
initialize(protocol, callbacks, initialData) {
this._protocol = protocol;
this._abortController = new AbortController();
let headers;
let body;
if (protocol === 'json') {
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
body = initialData;
}
else {
headers = {
'Accept': 'application/octet-stream',
'Content-Type': 'application/octet-stream'
};
body = initialData;
}
const fetchOptions = {
method: 'POST',
headers: headers,
body: body,
mode: 'cors',
credentials: 'same-origin',
signal: this._abortController.signal
};
const eventTarget = this._fetchEventTarget(this, this.endpoint, fetchOptions);
eventTarget.addEventListener('open', () => {
callbacks.onOpen();
});
eventTarget.addEventListener('error', (e) => {
this._abortController.abort();
callbacks.onError(e);
});
eventTarget.addEventListener('close', () => {
this._abortController.abort();
callbacks.onClose({
code: 4,
reason: 'connection closed'
});
});
eventTarget.addEventListener('message', (e) => {
callbacks.onMessage(e.data);
});
}
close() {
// Not created if initialize() threw before creating it.
if (this._abortController !== null) {
this._abortController.abort();
}
}
send(data, session, node) {
let headers;
let body;
const req = {
session: session,
node: node,
data: data
};
if (this._protocol === 'json') {
headers = {
'Content-Type': 'application/json'
};
body = JSON.stringify(req);
}
else {
headers = {
'Content-Type': 'application/octet-stream'
};
body = this.options.encoder.encodeEmulationRequest(req);
}
const fetchFunc = this.options.fetch;
const fetchOptions = {
method: 'POST',
headers: headers,
body: body,
mode: 'cors',
credentials: 'same-origin',
// Closing the transport aborts requests still pending, e.g. hung in an
// intermediary, which would otherwise keep connections of the per-host pool.
signal: this._abortController.signal
};
fetchFunc(this.options.emulationEndpoint, fetchOptions).then(response => {
// The server has no node of the session (404), e.g. the node was restarted, or
// the server or an intermediary failed. Other statuses, e.g. a too large request
// body, reject only this command. A session gone from a running node is answered
// with 204: its stream ends then.
if (response && (response.status === 404 || response.status >= 500)) {
this.close();
}
}, () => {
// The command was not delivered. Close the transport so the client
// reconnects instead of waiting for the command timeout.
this.close();
});
}
}
/** @internal */
class SseTransport {
constructor(endpoint, options) {
this.endpoint = endpoint;
this.options = options;
this._protocol = 'json';
this._transport = null;
this._onClose = null;
this._abortController = null;
}
name() {
return 'sse';
}
subName() {
return 'sse';
}
emulation() {
return true;
}
supported() {
return this.options.eventsource !== null && this.options.fetch !== null;
}
initialize(_protocol, callbacks, initialData) {
// Aborts pending emulation requests on close.
if (typeof AbortController !== 'undefined') {
this._abortController = new AbortController();
}
let url;
if (globalThis && globalThis.document && globalThis.document.baseURI) {
// Handle case when endpoint is relative, like //example.com/connection/sse
url = new URL(this.endpoint, globalThis.document.baseURI);
}
else {
url = new URL(this.endpoint);
}
url.searchParams.append('cf_connect', initialData);
const eventsourceOptions = {};
const eventSource = new this.options.eventsource(url.toString(), eventsourceOptions);
this._transport = eventSource;
const self = this;
eventSource.onopen = function () {
callbacks.onOpen();
};
eventSource.onerror = function (e) {
eventSource.close();
callbacks.onError(e);
callbacks.onClose({
code: 4,
reason: 'connection closed'
});
};
eventSource.onmessage = function (e) {
callbacks.onMessage(e.data);
};
self._onClose = function () {
callbacks.onClose({
code: 4,
reason: 'connection closed'
});
};
}
close() {
if (this._abortController !== null) {
this._abortController.abort();
}
// No event source if its constructor threw in initialize().
if (this._transport !== null) {
this._transport.close();
}
if (this._onClose !== null) {
this._onClose();
}
}
send(data, session, node) {
const req = {
session: session,
node: node,
data: data
};
const headers = {
'Content-Type': 'application/json'
};
const body = JSON.stringify(req);
const fetchFunc = this.options.fetch;
// Closing the transport aborts requests still pending, e.g. hung in an
// intermediary, which would otherwise keep connections of the per-host pool.
const signal = this._abortController !== null ? this._abortController.signal : undefined;
const fetchOptions = {
method: 'POST',
headers: headers,
body: body,
mode: 'cors',
credentials: 'same-origin',
signal: signal
};
fetchFunc(this.options.emulationEndpoint, fetchOptions).then(response => {
// The server has no node of the session (404), e.g. the node was restarted, or
// the server or an intermediary failed. Other statuses, e.g. a too large request
// body, reject only this command. A session gone from a running node is answered
// with 204: its stream ends then.
if (response && (response.status === 404 || response.status >= 500)) {
this.close();
}
}, () => {
// Aborted because the transport was closed already.
if (signal && signal.aborted) {
return;
}
// The command was not delivered. Close the transport so the client
// reconnects instead of waiting for the command timeout.
this.close();
});
}
}
/** @internal */
class WebtransportTransport {
constructor(endpoint, options) {
this.endpoint = endpoint;
this.options = options;
this._transport = null;
this._stream = null;
this._writer = null;
this._protocol = 'json';
}
name() {
return 'webtransport';
}
subName() {
return 'webtransport';
}
emulation() {
return false;
}
supported() {
return this.options.webtransport !== undefined && this.options.webtransport !== null;
}
initialize(protocol, callbacks) {
return __awaiter(this, void 0, void 0, function* () {
let url;
if (globalThis && globalThis.document && globalThis.document.baseURI) {
// Handle case when endpoint is relative, like //example.com/connection/webtransport
url = new URL(this.endpoint, globalThis.document.baseURI);
}
else {
url = new URL(this.endpoint);
}
if (protocol === 'protobuf') {
url.searchParams.append('cf_protocol', 'protobuf');
}
this._protocol = protocol;
const eventTarget = new EventTarget();
this._transport = new this.options.webtransport(url.toString());
this._transport.closed.then(() => {
callbacks.onClose({
code: 4,
reason: 'connection closed'
});
}).catch(() => {
callbacks.onClose({
code: 4,
reason: 'connection closed'
});
});
try {
yield this._transport.ready;
}
catch (_a) {
this.close();
return;
}
let stream;
try {
stream = yield this._transport.createBidirectionalStream();
}
catch (_b) {
this.close();
return;
}
this._stream = stream;
this._writer = this._stream.writable.getWriter();
eventTarget.addEventListener('close', () => {
callbacks.onClose({
code: 4,
reason: 'connection closed'
});
});
eventTarget.addEventListener('message', (e) => {
callbacks.onMessage(e.data);
});
this._startReading(eventTarget);
callbacks.onOpen();
});
}
_startReading(eventTarget) {
return __awaiter(this, void 0, void 0, function* () {
const reader = this._stream.readable.getReader();
const jsonStreamBuf = new LineStreamBuffer();
const protoStreamBuf = new ReplyStreamBuffer();
try {
while (true) {
const { done, value } = yield reader.read();
if (value && value.length > 0) {
if (this._protocol === 'json') {
jsonStreamBuf.push(value, line => eventTarget.dispatchEvent(new MessageEvent('message', { data: line })));
}
else {
protoStreamBuf.push(value);
protoStreamBuf.drain(data => this.options.decoder.decodeReply(data), reply => eventTarget.dispatchEvent(new MessageEvent('message', { data: reply })));
}
}
if (done) {
break;
}
}
}
catch (_a) {
eventTarget.dispatchEvent(new Event('close'));
}
});
}
close() {
return __awaiter(this, void 0, void 0, function* () {
try {
if (this._writer) {
yield this._writer.close();
}
this._transport.close();
}
catch (e) {
// already closed.
}
});
}
send(data) {
return __awaiter(this, void 0, void 0, function* () {
let binary;
if (this._protocol === 'json') {
// Need extra \n since WT is non-frame protocol.
binary = new TextEncoder().encode(data + '\n');
}
else {
binary = data;
}
try {
yield this._writer.write(binary);
}
catch (e) {
this.close();
}
});
}
}
/*
Copyright 2014-2024 Dmitry Chestnykh (JavaScript port)
Copyright 2007 D. Richard Hipp (original C version)
Fossil SCM delta compression algorithm, this is only the applyDelta part extracted
from https://github.com/dchest/fossil-delta-js. The code was slightly modified
to strip unnecessary parts. The copyright on top of this file is from the original
repo on Github licensed under Simplified BSD License.
*/
const zValue = [
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1,
-1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36, -1, 37,
38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
];
// Reader reads bytes, chars, ints from array.
class Reader {
constructor(array) {
this.a = array; // source array
this.pos = 0; // current position in array
}
haveBytes() {
return this.pos < this.a.length;
}
getByte() {
const b = this.a[this.pos];
this.pos++;
if (this.pos > this.a.length)
throw new RangeError("out of bounds");
return b;
}
getChar() {
return String.fromCharCode(this.getByte());
}
// Read base64-encoded unsigned integer.
getInt() {
let v = 0;
let c;
while (this.haveBytes() && (c = zValue[0x7f & this.getByte()]) >= 0) {
v = (v << 6) + c;
}
this.pos--;
return v >>> 0;
}
}
// Write writes an array.
class Writer {
constructor() {
this.a = [];
}
toByteArray(sourceType) {
if (Array.isArray(sourceType)) {
return this.a;
}
return new Uint8Array(this.a);
}
// Copy from array at start to end.
putArray(a, start, end) {
// TODO: optimize.
for (let i = start; i < end; i++)
this.a.push(a[i]);
}
}
// Return a 32-bit checksum of the array.
function checksum(arr) {
let sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0, z = 0, N = arr.length;
//TODO measure if this unrolling is helpful.
while (N >= 16) {
sum0 = (sum0 + arr[z + 0]) | 0;
sum1 = (sum1 + arr[z + 1]) | 0;
sum2 = (sum2 + arr[z + 2]) | 0;
sum3 = (sum3 + arr[z + 3]) | 0;
sum0 = (sum0 + arr[z + 4]) | 0;
sum1 = (sum1 + arr[z + 5]) | 0;
sum2 = (sum2 + arr[z + 6]) | 0;
sum3 = (sum3 + arr[z + 7]) | 0;
sum0 = (sum0 + arr[z + 8]) | 0;
sum1 = (sum1 + arr[z + 9]) | 0;
sum2 = (sum2 + arr[z + 10]) | 0;
sum3 = (sum3 + arr[z + 11]) | 0;
sum0 = (sum0 + arr[z + 12]) | 0;
sum1 = (sum1 + arr[z + 13]) | 0;
sum2 = (sum2 + arr[z + 14]) | 0;
sum3 = (sum3 + arr[z + 15]) | 0;
z += 16;
N -= 16;
}
while (N >= 4) {
sum0 = (sum0 + arr[z + 0]) | 0;
sum1 = (sum1 + arr[z + 1]) | 0;
sum2 = (sum2 + arr[z + 2]) | 0;
sum3 = (sum3 + arr[z + 3]) | 0;
z += 4;
N -= 4;
}
sum3 = (((((sum3 + (sum2 << 8)) | 0) + (sum1 << 16)) | 0) + (sum0 << 24)) | 0;
switch (N) {
//@ts-ignore fallthrough is needed.
case 3:
sum3 = (sum3 + (arr[z + 2] << 8)) | 0; /* falls through */
//@ts-ignore fallthrough is needed.
case 2:
sum3 = (sum3 + (arr[z + 1] << 16)) | 0; /* falls through */
case 1:
sum3 = (sum3 + (arr[z + 0] << 24)) | 0; /* falls through */
}
return sum3 >>> 0;
}
/**
* Apply a delta byte array to a source byte array, returning the target byte array.
*/
function applyDelta(source, delta) {
let total = 0;
const zDelta = new Reader(delta);
const lenSrc = source.length;
const lenDelta = delta.length;
const limit = zDelta.getInt();
if (zDelta.getChar() !== "\n")
throw new Error("size integer not terminated by '\\n'");
const zOut = new Writer();
while (zDelta.haveBytes()) {
const cnt = zDelta.getInt();
let ofst;
switch (zDelta.getChar()) {
case "@":
ofst = zDelta.getInt();
if (zDelta.haveBytes() && zDelta.getChar() !== ",")
throw new Error("copy command not terminated by ','");
total += cnt;
if (total > limit)
throw new Error("copy exceeds output file size");
if (ofst + cnt > lenSrc)
throw new Error("copy extends past end of input");
zOut.putArray(source, ofst, ofst + cnt);
break;
case ":":
total += cnt;
if (total > limit)
throw new Error("insert command gives an output larger than predicted");
if (cnt > lenDelta)
throw new Error("insert count exceeds size of delta");
zOut.putArray(zDelta.a, zDelta.pos, zDelta.pos + cnt);
zDelta.pos += cnt;
break;
case ";":
{
const out = zOut.toByteArray(source);
if (cnt !== checksum(out))
throw new Error("bad checksum");
if (total !== limit)
throw new Error("generated size does not match predicted size");
return out;
}
default:
throw new Error("unknown delta operator");
}
}
throw new Error("unterminated delta");
}
/** @internal */
class JsonCodec {
name() {
return 'json';
}
encodeCommands(commands) {
return commands.map(c => JSON.stringify(c)).join('\n');
}
decodeReplies(data) {
// Empty lines carry nothing, e.g. newlines an intermediary sends to keep a
// stream alive: they are skipped instead of failing to parse.
return data.split('\n').filter(r => r.trim() !== '').map(r => JSON.parse(r));
}
applyDeltaIfNeeded(pub, prevValue) {
let newData, newPrevValue, wireBytes;
let isDelta;
if (pub.delta) {
isDelta = true;
// JSON string delta.
const deltaBytes = new TextEncoder().encode(pub.data);
const valueArray = applyDelta(prevValue, deltaBytes);
newData = JSON.parse(new TextDecoder().decode(valueArray));
newPrevValue = valueArray;
wireBytes = deltaBytes.length;
}
else {
isDelta = false;
// Full data as JSON string.
newData = JSON.parse(pub.data);
newPrevValue = new TextEncoder().encode(pub.data);
wireBytes = newPrevValue.length;
}
// wireBytes is the UTF-8 byte length of pub.data, not its JS string length
// (.length counts UTF-16 code units, which undercounts any non-ASCII content).
return { newData, newPrevValue, isDelta, wireBytes, fullBytes: newPrevValue.length };
}
}
const defaults = {
headers: {},
token: '',
getToken: null,
data: null,
getData: null,
debug: false,
name: 'js',
version: '',
fetch: null,
readableStream: null,
websocket: null,
eventsource: null,
sockjs: null,
sockjsOptions: {},
emulationEndpoint: '/emulation',
minReconnectDelay: 500,
maxReconnectDelay: 20000,
timeout: 5000,
maxServerPingDelay: 10000,
networkEventTarget: null,
pageEventTarget: null,
};
const websocketNotFound = 'WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options';
// A call or no-ping timer running at least this late means the event loop didn't
// run meanwhile: the process was suspended or blocked (see _registerCall).
const lateCallTimer = 1000;
// How long such a call still waits for its reply, or the connection for a ping,
// before failing.
const lateCallGrace = 1000;
function errorMessage(err) {
try {
return err instanceof Error ? err.message : String(err);
}
catch (e) {
// E.g. a thrown Object.create(null): it has no string form.
return 'value without a string form';
}
}
class UnauthorizedError extends Error {
constructor(message) {
super(message);
this.name = this.constructor.name;
}
}
/** Centrifuge is a Centrifuge/Centrifugo bidirectional client. */
class Centrifuge extends EventEmitter {
/** Constructs Centrifuge client. Call connect() method to start connecting. */
constructor(endpoint, options) {
super();
this._reconnectTimeout = null;
this._connectTimeout = null;
// Unsubscribes still in progress of subscriptions removed from the client, per channel.
this._removedUnsubscribes = {};
// The offset of the publication being dispatched, per server-side channel, until its
// handler returned. See _handlePublication and the subs of _constructConnectCommand.
this._pendingServerSubOffsets = {};
this._refreshTimeout = null;
this._serverPingTimeout = null;
/** @internal The number of exceptions escaped from event handlers (see _handlerFailed). */
this._handlerFailures = 0;
this.state = State.Disconnected;
this._transportIsOpen = false;
this._endpoint = endpoint;
this._emulation = false;
this._transports = [];
this._currentTransportIndex = 0;
this._triedAllTransports = false;
this._transportWasOpen = false;
this._transport = null;
this._transportId = 0;
this._deviceWentOffline = false;
this._transportClosed = true;
this._codec = new JsonCodec();
this._reconnecting = false;
this._reconnectTimeout = null;
this._connectTimeout = null;
this._reconnectAttempts = 0;
this._client = null;
this._session = '';
this._node = '';
this._subs = {};
this._serverSubs = {};
this._commandId = 0;
this._commands = [];
this._batching = false;
this._refreshRequired = false;
this._refreshTimeout = null;
this._callbacks = {};
this._token = '';
this._data = null;
this._dispatchPromise = Promise.resolve();
this._serverPing = 0;
this._serverPingTimeout = null;
this._sendPong = false;
this._promises = {};
this._promiseId = 0;
this._debugEnabled = false;
this._networkEvents = null;
this._pageEvents = null;
this._pageCached = false;
this._stateTransitions = 0;
this._disconnects = 0;
this._abortedTransportId = 0;
this._reconnectAttemptsResetPending = false;
this._config = Object.assign(Object.assign({}, defaults), options);
this._configure();
if (this._debugEnabled) {
this.on('state', (ctx) => {
this._debug('client state', ctx.oldState, '->', ctx.newState);
});
this.on('error', (ctx) => {
this._debug('client error', ctx);
});
}
else {
// Avoid unhandled exception in EventEmitter for non-set error handler.
this.on('error', function () { Function.prototype(); });
}
}
/** newSubscription allocates new Subscription to a channel. Since server only allows
* one subscription per channel per client this method throws if client already has
* channel subscription in internal registry.
* */
newSubscription(channel, options) {
if (this.getSubscription(channel) !== null) {
throw new Error('Subscription to the channel ' + channel + ' already exists');
}
const sub = new Subscription(this, channel, options);
this._subs[channel] = sub;
return sub;
}
/** newMapSubscription allocates new map Subscription to a channel. Since server only allows
* one subscription per channel per client this method throws if client already has
* channel subscription in internal registry.
*
* Experimental. Requires Centrifugo >= v6.8.0. API may change in a backwards-incompatible
* way in subsequent minor releases. */
newMapSubscription(channel, options) {
if (this.getSubscription(channel) !== null) {
throw new Error('Subscription to the channel ' + channel + ' already exists');
}
const sub = new MapSubscription(this, channel, {
token: options === null || options === void 0 ? void 0 : options.token,
getToken: options === null || options === void 0 ? void 0 : options.getToken,
data: options === null || options === void 0 ? void 0 : options.data,
minResubscribeDelay: options === null || options === void 0 ? void 0 : options.minResubscribeDelay,
maxResubscribeDelay: options === null || options === void 0 ? void 0 : options.maxResubscribeDelay,
delta: options === null || options === void 0 ? void 0 : options.delta,
tagsFilter: options === null || options === void 0 ? void 0 : options.tagsFilter,
map: true,
mapPageSize: options === null || options === void 0 ? void 0 : options.pageSize,
mapUnrecoverableStrategy: options === null || options === void 0 ? void 0 : options.unrecoverableStrategy,
});
this._subs[channel] = sub;
return sub;
}
/** Create a map subscription for observing individual connections (clients presence).
* Each entry has key=clientId and contains full ClientInfo.
* Use this to track connections per channel.
* The channel should be the full presence channel name (e.g., "$clients:games").
*
* Experimental. Requires Centrifugo >= v6.8.0. API may change in a backwards-incompatible
* way in subsequent minor releases. */
newMapClientsSubscription(channel, options) {
if (this.getSubscription(channel) !== null) {
throw new Error('Subscription to the channel ' + channel + ' already exists');
}
const sub = new MapSubscription(this, channel, {
token: options === null || options === void 0 ? void 0 : options.token,
getToken: options === null || options === void 0 ? void 0 : options.getToken,
data: options === null || options === void 0 ? void 0 : options.data,
minResubscribeDelay: options === null || options === void 0 ? void 0 : options.minResubscribeDelay,
maxResubscribeDelay: options === null || options === void 0 ? void 0 : options.maxResubscribeDelay,
delta: options === null || options === void 0 ? void 0 : options.delta,
tagsFilter: options === null || options === void 0 ? void 0 : options.tagsFilter,
map: true,
mapPresenceType: 2, // MAP_CLIENTS_PRESENCE
mapPageSize: options === null || options === void 0 ? void 0 : options.pageSize,
mapUnrecoverableStrategy: options === null || options === void 0 ? void 0 : options.unrecoverableStrategy,
});
this._subs[channel] = sub;
return sub;
}
/** Create a map subscription for observing unique users (users presence).
* Each entry has key=userId (no ClientInfo stored).
* User entries expire via TTL, providing debounce for quick reconnects.
* The channel should be the full presence channel name (e.g., "$users:games").
*
* Experimental. Requires Centrifugo >= v6.8.0. API may change in a backwards-incompatible
* way in subsequent minor releases. */
newMapUsersSubscription(channel, options) {
if (this.getSubscription(channel) !== null) {
throw new Error('Subscription to the channel ' + channel + ' already exists');
}
const sub = new MapSubscription(this, channel, {
token: options === null || options === void 0 ? void 0 : options.token,
getToken: options === null || options === void 0 ? void 0 : options.getToken,
data: options === null || options === void 0 ? void 0 : options.data,
minResubscribeDelay: options === null || options === void 0 ? void 0 : options.minResubscribeDelay,
maxResubscribeDelay: options === null || options === void 0 ? void 0 : options.maxResubscribeDelay,
delta: options === null || options === void 0 ? void 0 : options.delta,
tagsFilter: options === null || options === void 0 ? void 0 : options.tagsFilter,
map: true,
mapPresenceType: 3, // MAP_USERS_PRESENCE
mapPageSize: options === null || options === void 0 ? void 0 : options.pageSize,
mapUnrecoverableStrategy: options === null || options === void 0 ? void 0 : options.unrecoverableStrategy,
});
this._subs[channel] = sub;
return sub;
}
/** newSharedPollSubscription allocates a new shared poll Subscription to a channel.
* Shared poll subscriptions use server-side polling to aggregate interest sets
* and deliver periodic updates with version tracking. Track items after subscribing
* using the track() method on the returned Subscription.
*
* Experimental. Requires Centrifugo >= v6.8.0. API may change in a backwards-incompatible
* way in subsequent minor releases. */
newSharedPollSubscription(channel, options) {
if (this.getSubscription(channel) !== null) {
throw new Error('Subscription to the channel ' + channel + ' already exists');
}
const sub = new SharedPollSubscription(this, channel, {
token: options === null || options === void 0 ? void 0 : options.token,
getToken: options === null || options === void 0 ? void 0 : options.getToken,
data: options === null || options === void 0 ? void 0 : options.data,
minResubscribeDelay: options === null || options === void 0 ? void 0 : options.minResubscribeDelay,
maxResubscribeDelay: options === null || options === void 0 ? void 0 : options.maxResubscribeDelay,
delta: options === null || options === void 0 ? void 0 : options.delta,
sharedPoll: true,
sharedPollGetSignature: options === null || options === void 0 ? void 0 : options.getSignature,
});
this._subs[channel] = sub;
return sub;
}
/** getSubscription returns Subscription if it's registered in the internal
* registry or null. */
getSubscription(channel) {
return this._getSub(channel);
}
/** Get a map subscription by channel. */
getMapSubscription(channel) {
return this._getSub(channel);
}
/** Get a shared poll subscription by channel. */
getSharedPollSubscription(channel) {
return this._getSub(channel);
}
/** removeSubscription allows removing Subcription from the internal registry. */
removeSubscription(sub) {
if (!sub) {
return;
}
// A subscription removed before must not remove a newer one of its channel.
if (this._subs[sub.channel] !== sub) {
return;
}
// Removed before its unsubscribed event: a handler of it may create a new
// subscription of the channel, and must not subscribe this one again.
delete this._subs[sub.channel];
// @ts-ignore – we are hiding some symbols from public API autocompletion.
sub._removed = true;
if (sub.state !== SubscriptionState.Unsubscribed) {
sub.unsubscribe();
}
this._recordRemovedUnsubscribe(sub);
}
/** Remove a map subscription. */
removeMapSubscription(sub) {
this.removeSubscription(sub);
}
/** Remove a shared poll subscription. */
removeSharedPollSubscription(sub) {
this.removeSubscription(sub);
}
/** Get a map with all current client-side subscriptions. */
subscriptions() {
return this._subs;
}
/** Get all map subscriptions. */
mapSubscriptions() {
const result = {};
for (const [ch, sub] of Object.entries(this._subs)) {
if (sub.type === 'map')
result[ch] = sub;
}
return result;
}
/** Get all shared poll subscriptions. */
sharedPollSubscriptions() {
const result = {};
for (const [ch, sub] of Object.entries(this._subs)) {
if (sub.type === 'shared_poll')
result[ch] = sub;
}
return result;
}
/** ready returns a Promise which resolves upon client goes to Connected
* state and rejects in case of client goes to Disconnected or Failed state.
* Users can provide optional timeout in milliseconds. */
ready(timeout) {
return __awaiter(this, void 0, void 0, function* () {
switch (this.state) {
case State.Disconnected:
throw { code: errorCodes.clientDisconnected, message: 'client disconnected' };
case State.Connected:
return;
default:
return new Promise((resolve, reject) => {
const id = this._nextPromiseId();
const ctx = { resolve, reject };
if (timeout) {
ctx.timeout = setTimeout(() => {
// A call that gave up waiting leaves no waiter behind.
delete this._promises[id];
reject({ code: errorCodes.timeout, message: 'timeout' });
}, timeout);
}
this._promises[id] = ctx;
});
}
});
}
/** connect to a server. */
connect() {
if (this._isConnected()) {
this._debug('connect called when already connected');
return;
}
if (this._isConnecting()) {
this._debug('connect called when already connecting');
return;
}
this._debug('connect called');
// Throws for a configuration no retry can fix, before the state changes.
this._validateTransportConfig();
this._reconnectAttempts = 0;
this._startConnecting();
}
/** disconnect from a server. */
disconnect() {
this._disconnect(disconnectedCodes.disconnectCalled, 'disconnect called', false);
}
/** setToken allows setting connection token. Or resetting used token to be empty. */
setToken(token) {
this._token = token;
if (this._config.getToken === null) {
// The token expired, and the app set a new one: without getToken there is no
// other way to get it, so the next attempt uses it instead of failing on a
// configuration error. With getToken, the next attempt still gets a new token:
// the one set meanwhile may be the expired one.
this._refreshRequired = false;
}
}
/** setData allows setting connection data. This only affects the next connection attempt,
* not the current one. Note that if getData callback is configured, it will override
* this value during reconnects. */
setData(data) {
this._data = data;
}
/** setHeaders allows setting connection emulated headers. */
setHeaders(headers) {
this._config.headers = headers;
}
/** send asynchronous data to a server (without any response from a server
* expected, see rpc method if you need response). */
send(data) {
return __awaiter(this, void 0, void 0, function* () {
const cmd = {
send: {
data
}
};
yield this._methodCall();
const sent = this._transportSendCommands([cmd]); // can send message to server without id set
if (!sent) {
throw this._createErrorObject(errorCodes.transportWriteError, 'transport write error');
}
});
}
/** rpc to a server - i.e. a call which waits for a response with data. */
rpc(method, data) {
return __awaiter(this, void 0, void 0, function* () {
const cmd = {
rpc: {
method,
data
}
};
yield this._methodCall();
const result = yield this._callPromise(cmd, (reply) => reply.rpc);
return {
data: result.data
};
});
}
/** publish data to a channel. */
publish(channel, data) {
return __awaiter(this, void 0, void 0, function* () {
const cmd = {
publish: {
channel,
data
}
};
yield this._methodCall();
yield this._callPromise(cmd, () => ({}));
return {};
});
}
/** Publish data to a key in a map channel without holding a MapSubscription.
* Use this when you need to write to a map channel from outside a subscription
* context (e.g. a standalone publisher). When you already hold a MapSubscription,
* prefer `sub.publish(key, data)` instead — it enforces the method-call guard and
* applies debounce configuration. */
mapPublish(channel, key, data) {
return __awaiter(this, void 0, void 0, function* () {
const cmd = {
publish: { channel, type: 1, key, data }
};
yield this._methodCall();
yield this._callPromise(cmd, () => ({}));
return {};
});
}
/** Remove a key from a map channel without holding a MapSubscription.
* Use this when you need to remove a key from outside a subscription context.
* When you already hold a MapSubscription, prefer `sub.remove(key)` instead —
* it enforces the method-call guard and cancels any pending debounced publish. */
mapRemove(channel, key) {
return __awaiter(this, void 0, void 0, function* () {
const cmd = {
publish: { channel, type: 1, key, removed: true }
};
yield this._methodCall();
yield this._callPromise(cmd, () => ({}));
return {};
});
}
/** history for a channel. By default it does not return publications (only current
* StreamPosition data) – provide an explicit limit > 0 to load publications.*/
history(channel, options) {
return __awaiter(this, void 0, void 0, function* () {
const cmd = {
history: this._getHistoryRequest(channel, options)
};
yield this._methodCall();
const result = yield this._callPromise(cmd, (reply) => reply.history);
const publications = [];
if (result.publications) {
for (let i = 0; i < result.publications.length; i++) {
publications.push(this._getPublicationContext(channel, result.publications[i]));
}
}
return {
publications,
epoch: result.epoch || '',
offset: toOffset(result.offset)
};
});
}
/** presence for a channel. */
presence(channel) {
return __awaiter(this, void 0, void 0, function* () {
const cmd = {
presence: {
channel
}
};
yield this._methodCall();
const result = yield this._callPromise(cmd, (reply) => reply.presence);
const clients = result.presence;
for (const clientId in clients) {
if (Object.prototype.hasOwnProperty.call(clients, clientId)) {
const rawClient = clients[clientId];
const connInfo = rawClient['conn_info'];
const chanInfo = rawClient['chan_info'];
if (connInfo) {
rawClient.connInfo = connInfo;
}
if (chanInfo) {
rawClient.chanInfo = chanInfo;
}
}
}
return { clients };
});
}
presenceStats(channel) {
return __awaiter(this, void 0, void 0, function* () {
const cmd = {
'presence_stats': {
channel
}
};
yield this._methodCall();
const result = yield this._callPromise(cmd, (reply) => {
return reply.presence_stats;
});
return {
numUsers: result.num_users,
numClients: result.num_clients
};
});
}
/** start command batching (collect into temporary buffer without sending to a server)
* until stopBatching called.*/
startBatching() {
// start collecting messages without sending them to Centrifuge until flush
// method called
this._batching = true;
}
/** stop batching commands and flush collected commands to the
* network (all in one request/frame).*/
stopBatching() {
const self = this;
// Why so nested? Two levels here requred to deal with promise resolving queue.
// In Subscription case we wait 2 futures before sending data to connection.
// Otherwise _batching becomes false before batching decision has a chance to be executed.
Promise.resolve().then(function () {
Promise.resolve().then(function () {
self._batching = false;
self._flush();
});
});
}
_debug(...args) {
if (!this._debugEnabled) {
return;
}
log('debug', args);
}
_codecName() {
return this._codec.name();
}
/** @internal */
_formatOverride() {
return;
}
_configure() {
if (!('Promise' in globalThis)) {
throw new Error('Promise polyfill required');
}
if (!this._endpoint) {
throw new Error('endpoint configuration required');
}
if (this._config.token !== null) {
this._token = this._config.token;
}
if (this._config.data !== null) {
this._data = this._config.data;
}
this._codec = new JsonCodec();
this._formatOverride();
if (this._config.debug === true || localStorageItem('centrifuge.debug')) {
this._debugEnabled = true;
}
this._debug('config', this._config);
if (typeof this._endpoint === 'string') ;
else if (Array.isArray(this._endpoint)) {
this._transports = this._endpoint;
this._emulation = true;
for (const i in this._transports) {
if (this._transports.hasOwnProperty(i)) {
const transportConfig = this._transports[i];
if (!transportConfig.endpoint || !transportConfig.transport) {
throw new Error('malformed transport configuration');
}
const transportName = transportConfig.transport;
if (['websocket', 'http_stream', 'sse', 'sockjs', 'webtransport'].indexOf(transportName) < 0) {
throw new Error('unsupported transport name: ' + transportName);
}
}
}
}
else {
throw new Error('unsupported url configuration type: only string or array of objects are supported');
}
}
// Returns the number of the transition made, or 0 if the client already was in newState.
_setState(newState) {
if (this.state !== newState) {
this._reconnecting = false;
const oldState = this.state;
this.state = newState;
const transition = ++this._stateTransitions;
// Keep network listeners in sync with the state before emitting: a 'state'
// handler may call connect() or disconnect() synchronously.
if (newState === State.Connecting) {
this._setNetworkEvents();
this._setPageEvents();
}
else if (newState === State.Disconnected) {
this._clearNetworkEvents();
this._clearPageEvents();
}
this.emit('state', { newState, oldState });
return transition;
}
return 0;
}
// Whether an event handler made another state transition after the given one
// (as returned by _setState), so that the given one is outdated.
_transitionSuperseded(transition) {
return transition !== 0 && this._stateTransitions !== transition;
}
_isDisconnected() {
return this.state === State.Disconnected;
}
_isConnecting() {
return this.state === State.Connecting;
}
_isConnected() {
return this.state === State.Connected;
}
_nextCommandId() {
return ++this._commandId;
}
_setNetworkEvents() {
if (this._networkEvents !== null) {
return;
}
let eventTarget = null;
if (this._config.networkEventTarget !== null) {
eventTarget = this._config.networkEventTarget;
}
else if (typeof globalThis.addEventListener !== 'undefined') {
eventTarget = globalThis;
}
if (eventTarget) {
const onOffline = () => {
this._debug('offline event triggered');
if (this.state === State.Connected || this.state === State.Connecting) {
// Set first: a handler of the events emitted by the disconnect may call
// disconnect(), which resets it.
this._deviceWentOffline = true;
this._disconnect(connectingCodes.transportClosed, 'transport closed', true);
}
};
const onOnline = () => {
this._debug('online event triggered');
const wentOffline = this._deviceWentOffline;
this._deviceWentOffline = false;
if (this.state !== State.Connecting) {
return;
}
if (wentOffline && !this._transportClosed) {
// A reconnect attempt opened a transport while the device was offline.
// Mobile Safari may never issue the close callback for it, so abort it
// explicitly and start over. The transport ID changes, so a close
// callback issued later is ignored. The rejection of a connect command
// still pending on it is not an error to report (see _sendConnect).
this._abortedTransportId = this._transportId;
this._disconnect(connectingCodes.transportClosed, 'transport closed', true);
}
this._clearReconnectTimeout();
this._startReconnecting();
};
eventTarget.addEventListener('offline', onOffline);
eventTarget.addEventListener('online', onOnline);
this._networkEvents = { target: eventTarget, onOffline, onOnline };
}
}
// The online listener drives reconnect, so listeners stay until the client is
// disconnected; removing them then lets a disconnected client be garbage-collected.
_clearNetworkEvents() {
if (this._networkEvents === null) {
return;
}
const { target, onOffline, onOnline } = this._networkEvents;
if (!isFunction(target.removeEventListener)) {
this._debug('network event target has no removeEventListener, listeners kept');
return;
}
target.removeEventListener('offline', onOffline);
target.removeEventListener('online', onOnline);
this._networkEvents = null;
}
// A page entering the back/forward cache is frozen, but the browser may keep its
// socket open: the server then sees a client that stopped answering pings. So the
// transport is closed when the page is hidden into the cache, and the client
// reconnects as soon as the page is restored from it. The reconnect is scheduled
// as usual too: its timer does not run in a frozen page, and it still reconnects
// a page which was not frozen, or was restored without a pageshow event.
_setPageEvents() {
if (this._pageEvents !== null) {
return;
}
let eventTarget = null;
if (this._config.pageEventTarget !== null) {
eventTarget = this._config.pageEventTarget;
}
else if (typeof globalThis.addEventListener !== 'undefined') {
eventTarget = globalThis;
}
if (!eventTarget) {
return;
}
const onPageHide = (e) => {
if (!e.persisted) {
return;
}
this._debug('page entered back/forward cache');
if (this.state === State.Connected || this.state === State.Connecting) {
// Set first: a handler of the events emitted by the disconnect may call
// disconnect(), which resets it.
this._pageCached = true;
this._disconnect(connectingCodes.transportClosed, 'page entered back/forward cache', true);
}
};
const onPageShow = (e) => {
if (!e.persisted) {
return;
}
this._debug('page restored from back/forward cache');
const cached = this._pageCached;
this._pageCached = false;
if (!cached || this.state !== State.Connecting) {
return;
}
this._clearReconnectTimeout();
this._startReconnecting();
};
eventTarget.addEventListener('pagehide', onPageHide);
eventTarget.addEventListener('pageshow', onPageShow);
this._pageEvents = { target: eventTarget, onPageHide, onPageShow };
}
// Removed once the client is disconnected, like the network listeners.
_clearPageEvents() {
if (this._pageEvents === null) {
return;
}
const { target, onPageHide, onPageShow } = this._pageEvents;
if (!isFunction(target.removeEventListener)) {
this._debug('page event target has no removeEventListener, listeners kept');
return;
}
target.removeEventListener('pagehide', onPageHide);
target.removeEventListener('pageshow', onPageShow);
this._pageEvents = null;
}
_getReconnectDelay() {
const delay = backoff(this._reconnectAttempts, this._config.minReconnectDelay, this._config.maxReconnectDelay);
this._reconnectAttempts += 1;
return delay;
}
// See _connectResponse: an emulation connection resets the backoff once it
// proved usable.
_resetReconnectAttemptsIfPending() {
if (this._reconnectAttemptsResetPending) {
this._reconnectAttemptsResetPending = false;
this._reconnectAttempts = 0;
}
}
_clearOutgoingRequests() {
// fire errbacks of registered outgoing calls.
for (const id in this._callbacks) {
if (this._callbacks.hasOwnProperty(id)) {
const callbacks = this._callbacks[id];
clearTimeout(callbacks.timeout);
const errback = callbacks.errback;
if (!errback) {
continue;
}
errback({ error: this._createErrorObject(errorCodes.connectionClosed, 'connection closed') });
}
}
this._callbacks = {};
}
_clearConnectedState() {
this._client = null;
this._clearServerPingTimeout();
this._clearRefreshTimeout();
// fire events for client-side subscriptions.
for (const channel in this._subs) {
if (!this._subs.hasOwnProperty(channel)) {
continue;
}
const sub = this._subs[channel];
if (sub.state === SubscriptionState.Subscribed) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
sub._setSubscribing(subscribingCodes.transportClosed, 'transport closed');
}
}
// fire events for server-side subscriptions, once per subscribed period.
for (const channel in this._serverSubs) {
if (this._serverSubs.hasOwnProperty(channel) && this._serverSubs[channel].subscribed) {
this._serverSubs[channel].subscribed = false;
this.emit('subscribing', { channel: channel });
}
}
}
_handleWriteError(commands) {
for (const command of commands) {
const id = command.id;
if (!(id in this._callbacks)) {
continue;
}
const callbacks = this._callbacks[id];
clearTimeout(this._callbacks[id].timeout);
delete this._callbacks[id];
const errback = callbacks.errback;
errback({ error: this._createErrorObject(errorCodes.transportWriteError, 'transport write error') });
}
}
_transportSendCommands(commands) {
if (!commands.length) {
return true;
}
if (!this._transport) {
return false;
}
try {
this._transport.send(this._codec.encodeCommands(commands), this._session, this._node);
}
catch (e) {
this._debug('error writing commands', e);
this._handleWriteError(commands);
return false;
}
return true;
}
_advanceTransportIndex() {
this._currentTransportIndex++;
if (this._currentTransportIndex >= this._transports.length) {
this._triedAllTransports = true;
this._currentTransportIndex = 0;
}
}
// Transport dependencies from the config, or else from globals. An absent one
// stays null, not undefined: supported() of sockjs, sse and http_stream only
// checks `!== null`.
_resolveTransportDeps() {
let websocket;
if (this._config.websocket !== null) {
websocket = this._config.websocket;
}
else {
if (!(typeof globalThis.WebSocket !== 'function' && typeof globalThis.WebSocket !== 'object')) {
websocket = globalThis.WebSocket;
}
}
let sockjs = null;
if (this._config.sockjs !== null) {
sockjs = this._config.sockjs;
}
else {
if (typeof globalThis.SockJS !== 'undefined') {
sockjs = globalThis.SockJS;
}
}
let eventsource = null;
if (this._config.eventsource !== null) {
eventsource = this._config.eventsource;
}
else {
if (typeof globalThis.EventSource !== 'undefined') {
eventsource = globalThis.EventSource;
}
}
let fetchFunc = null;
if (this._config.fetch !== null) {
fetchFunc = this._config.fetch;
}
else {
if (typeof globalThis.fetch !== 'undefined') {
fetchFunc = globalThis.fetch;
}
}
let readableStream = null;
if (this._config.readableStream !== null) {
readableStream = this._config.readableStream;
}
else {
if (typeof globalThis.ReadableStream !== 'undefined') {
readableStream = globalThis.ReadableStream;
}
}
return { websocket, sockjs, eventsource, fetchFunc, readableStream };
}
// Constructs a transport, without checking that it is supported.
_createTransport(transportName, endpoint, deps) {
switch (transportName) {
case 'websocket':
return new WebsocketTransport(endpoint, {
websocket: deps.websocket
});
case 'webtransport':
return new WebtransportTransport(endpoint, {
webtransport: globalThis.WebTransport,
decoder: this._codec,
encoder: this._codec
});
case 'http_stream':
return new HttpStreamTransport(endpoint, {
fetch: deps.fetchFunc,
readableStream: deps.readableStream,
emulationEndpoint: this._config.emulationEndpoint,
decoder: this._codec,
encoder: this._codec
});
case 'sse':
return new SseTransport(endpoint, {
eventsource: deps.eventsource,
fetch: deps.fetchFunc,
emulationEndpoint: this._config.emulationEndpoint,
});
case 'sockjs':
return new SockjsTransport(endpoint, {
sockjs: deps.sockjs,
sockjsOptions: this._config.sockjsOptions
});
default:
throw new Error('unknown transport ' + transportName);
}
}
// Throws for a configuration no retry can fix. Called from connect() before
// the state changes, so the client stays disconnected, and before a token or
// data is loaded, so it fails the same way with getToken or getData.
_validateTransportConfig() {
const deps = this._resolveTransportDeps();
if (!this._emulation) {
if (startsWith(this._endpoint, 'http')) {
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');
}
if (!this._createTransport('websocket', this._endpoint, deps).supported()) {
throw new Error(websocketNotFound);
}
return;
}
for (const transportConfig of this._transports) {
if (this._createTransport(transportConfig.transport, transportConfig.endpoint, deps).supported()) {
return;
}
}
throw new Error('no supported transport found');
}
_initializeTransport() {
const deps = this._resolveTransportDeps();
let selected = null;
if (!this._emulation) {
this._debug('client will use websocket');
const candidate = this._createTransport('websocket', this._endpoint, deps);
if (candidate.supported()) {
selected = candidate;
}
}
else {
if (this._currentTransportIndex >= this._transports.length) {
this._triedAllTransports = true;
this._currentTransportIndex = 0;
}
for (let count = 0; count < this._transports.length; count++) {
const transportConfig = this._transports[this._currentTransportIndex];
this._debug('trying ' + transportConfig.transport + ' transport');
const candidate = this._createTransport(transportConfig.transport, transportConfig.endpoint, deps);
if (candidate.supported()) {
selected = candidate;
break;
}
this._debug(transportConfig.transport + ' transport not available');
this._advanceTransportIndex();
}
}
if (selected === null) {
// connect() checked that a transport can be used, so a dependency went away
// under a running client. A reconnect timer has no caller to throw to:
// report it as a transport failure and retry.
const message = this._emulation ? 'no supported transport found' : websocketNotFound;
this._debug(message);
this._disconnect(connectingCodes.transportClosed, 'transport closed', true);
this.emit('error', {
type: 'transport',
error: {
code: errorCodes.transportClosed,
message: message
}
});
return;
}
this._transport = selected;
const self = this;
const transport = this._transport;
const transportId = this._nextTransportId();
self._debug("id of transport", transportId);
let wasOpen = false;
const initialCommands = [];
if (this._transport.emulation()) {
const connectCommand = self._sendConnect(true);
initialCommands.push(connectCommand);
}
this._transportClosed = false;
// Fails an attempt that did not open in time or could not be initialized. It
// does not wait for the transport's close callback: a transport may never
// issue one, e.g. a replaced WebSocket whose close() does nothing.
const failTransport = function (reason) {
if (self._transportId != transportId) {
self._debug('failure of non-actual transport', reason);
return;
}
self._debug(transport.name(), 'transport failed:', reason);
if (self._emulation && !self._transportWasOpen) {
self._advanceTransportIndex();
}
// The teardown rejects a connect command pending on it: the transport error
// below reports the failure, not a connect error too.
self._abortedTransportId = transportId;
// Closes the transport and clears the connect timeout.
self._disconnect(connectingCodes.transportClosed, 'transport closed', true);
self.emit('error', {
type: 'transport',
error: {
code: errorCodes.transportClosed,
message: reason
},
transport: transport.name()
});
};
this._clearConnectTimeout();
const connectDue = Date.now() + this._config.timeout;
this._connectTimeout = setTimeout(function () {
// The transport may have opened already, its open callback not run yet, e.g.
// when a suspended process resumes: let it run first, as for a call (see
// _registerCall). The open callback clears this timeout.
const late = Date.now() - connectDue >= lateCallTimer;
self._connectTimeout = setTimeout(function () {
self._connectTimeout = null;
failTransport('connect timeout');
}, late ? lateCallGrace : 0);
}, this._config.timeout);
const callbacks = {
onOpen: function () {
if (self._transportId != transportId) {
self._debug('open callback from non-actual transport');
try {
transport.close();
}
catch (e) {
// E.g. a replaced WebSocket without a working close().
self._debug('error closing transport', e);
}
return;
}
// Only after the check: the connect timeout belongs to the current attempt.
self._clearConnectTimeout();
wasOpen = true;
self._debug(transport.subName(), 'transport open');
if (transport.emulation()) {
return;
}
self._transportIsOpen = true;
// A socket that opened keeps its transport, as in 5.7.4: a slow first connect
// reply must not move the client to a fallback transport for good.
self._transportWasOpen = true;
self.startBatching();
try {
self._sendConnect(false);
self._sendSubscribeCommands();
}
catch (e) {
// E.g. thrown by an app callback of a subscription: the commands collected
// still go out, instead of staying batched for the next transport.
self._reportDispatchError(e);
}
finally {
self.stopBatching();
}
//@ts-ignore must be used only for debug and test purposes. Exposed only for non-emulation transport.
self.emit('__centrifuge_debug:connect_frame_sent', {});
},
onError: function (e) {
if (self._transportId != transportId) {
self._debug('error callback from non-actual transport');
return;
}
self._debug('transport level error', e);
},
onClose: function handleClose(closeEvent, dispatched) {
if (self._transportId != transportId) {
self._debug('close callback from non-actual transport');
return;
}
if (!dispatched && (transport.emulation() || transport.name() === 'webtransport')) {
// A stream may end in the same task as the data read before it, e.g. the
// server's disconnect push written before it closes the connection: that
// data is dispatched first, as a websocket's messages are before its close
// event. A disconnect push ends this transport, and this callback with it.
self._dispatchPromise.then(() => handleClose(closeEvent, true));
return;
}
self._clearConnectTimeout();
self._debug(transport.subName(), 'transport closed');
self._transportClosed = true;
self._transportIsOpen = false;
let reason = 'connection closed';
let needReconnect = true;
let code = 0;
if (closeEvent && 'code' in closeEvent && closeEvent.code) {
code = closeEvent.code;
}
if (closeEvent && closeEvent.reason) {
try {
const advice = JSON.parse(closeEvent.reason);
reason = advice.reason;
needReconnect = advice.reconnect;
}
catch (e) {
reason = closeEvent.reason;
if ((code >= 3500 && code < 4000) || (code >= 4500 && code < 5000)) {
needReconnect = false;
}
}
}
if (code < 3000) {
if (code === 1009) {
code = disconnectedCodes.messageSizeLimit;
reason = 'message size limit exceeded';
needReconnect = false;
}
else {
code = connectingCodes.transportClosed;
reason = 'transport closed';
}
if (self._emulation && !self._transportWasOpen) {
self._advanceTransportIndex();
}
}
else {
// Codes >= 3000 are sent from a server application level.
self._transportWasOpen = true;
}
const teardown = function () {
self._reconnecting = false;
self._disconnect(code, reason, needReconnect);
};
if (self._isConnecting() && !wasOpen) {
// The teardown rejects a connect command pending on it (emulation): this
// transport error reports the failure, not a connect error too.
self._abortedTransportId = transportId;
self._emitError({
type: 'transport',
error: {
code: errorCodes.transportClosed,
message: 'transport closed'
},
transport: transport.name()
}, teardown);
}
else {
teardown();
}
},
onMessage: function (data) {
if (self._transportId != transportId) {
// A frame from a transport that was already closed or replaced.
self._debug('message from non-actual transport');
return;
}
self._dataReceived(data, transportId);
}
};
// A transport that fails to initialize, e.g. a socket constructor throwing on
// a malformed URL or on an insecure one from a secure page, issues no close
// callback either.
const onInitializeError = function (e) {
self._debug('error initializing transport', e);
failTransport(e instanceof Error ? e.message : String(e));
};
let initialized;
try {
// Encoded here: commands the codec can't encode, e.g. connect data with a BigInt,
// fail the attempt as a transport failing to initialize, not connect().
initialized = transport.initialize(this._codecName(), callbacks, this._codec.encodeCommands(initialCommands));
}
catch (e) {
onInitializeError(e);
return;
}
if (initialized && isFunction(initialized.then)) {
// WebTransport initializes asynchronously.
initialized.then(null, onInitializeError);
}
//@ts-ignore must be used only for debug and test purposes.
self.emit('__centrifuge_debug:transport_initialized', {});
}
_sendConnect(skipSending) {
const connectCommand = this._constructConnectCommand();
const self = this;
// A teardown rejects the pending command, and the rejection is processed after
// it: a newer attempt may have started by then, which must not be torn down.
const transportId = this._transportId;
const token = this._token;
// An exception while handling the reply stops the client (see _dispatchFailed).
// next() is still called, so replies of a later connection aren't blocked.
this._call(connectCommand, skipSending).then(resolveCtx => {
try {
self._connectResponse(resolveCtx.reply.connect);
}
catch (err) {
self._dispatchFailed(err);
}
finally {
if (resolveCtx.next) {
resolveCtx.next();
}
}
}, rejectCtx => {
try {
if (transportId === self._abortedTransportId) {
self._debug('connect command of a transport aborted by the client rejected');
}
else {
// An error in a reply comes with next(): a rejection by a timeout, a write
// error or a teardown doesn't.
self._connectError(rejectCtx.error, self._transportId !== transportId, rejectCtx.next !== undefined, token);
}
}
catch (err) {
self._rejectionFailed(err, rejectCtx);
}
finally {
if (rejectCtx.next) {
rejectCtx.next();
}
}
});
return connectCommand;
}
_startReconnecting() {
this._debug('start reconnecting');
if (!this._isConnecting()) {
this._debug('stop reconnecting: client not in connecting state');
return;
}
if (this._reconnecting) {
this._debug('reconnect already in progress, return from reconnect routine');
return;
}
if (this._transportClosed === false) {
this._debug('waiting for transport close');
return;
}
this._reconnecting = true;
// A disconnect while the token/data is loading aborts this attempt (a new one
// is scheduled by the disconnect), so the continuations below must not act on
// it. Not the transport id: _initializeTransport changes it too, and its
// exceptions must still reach the error handlers below.
const disconnects = this._disconnects;
const emptyToken = this._token === '';
const needTokenRefresh = this._refreshRequired || (emptyToken && this._config.getToken !== null);
// Whether the token or data promise resolved: an error caught after that was thrown
// by the continuation, e.g. by an event handler, and must not be lost.
let tokenResolved = false;
let dataResolved = false;
if (!needTokenRefresh) {
if (this._config.getData) {
this._getData().then(data => {
dataResolved = true;
if (this._attemptAborted(disconnects)) {
return;
}
this._data = data;
this._initializeTransport();
})
.catch(e => this._handleGetDataError(e, disconnects, dataResolved));
}
else {
this._initializeTransport();
}
return;
}
const self = this;
this._getToken().then(function (token) {
tokenResolved = true;
if (self._attemptAborted(disconnects)) {
return;
}
if (token == null || token == undefined) {
self._failUnauthorized();
return;
}
self._token = token;
self._debug('connection token refreshed');
if (self._config.getData) {
self._getData().then(function (data) {
dataResolved = true;
if (self._attemptAborted(disconnects)) {
return;
}
self._data = data;
self._initializeTransport();
})
.catch(e => self._handleGetDataError(e, disconnects, dataResolved));
}
else {
self._initializeTransport();
}
}).catch(function (e) {
if (self._attemptAborted(disconnects)) {
if (tokenResolved) {
self._reportDispatchError(e);
}
return;
}
if (e instanceof UnauthorizedError) {
self._failUnauthorized();
return;
}
self._emitError({
'type': 'connectToken',
'error': {
code: errorCodes.clientConnectToken,
message: e !== undefined ? e.toString() : ''
}
}, () => {
const delay = self._getReconnectDelay();
self._debug('error on getting connection token, reconnect after ' + delay + ' milliseconds', e);
self._reconnecting = false;
self._reconnectTimeout = setTimeout(() => {
self._startReconnecting();
}, delay);
});
});
}
// Emits an error event, then runs the continuation: not when a handler disconnected
// the client (or threw, which disconnects it), maybe to connect again, whose new
// attempt the continuation must not touch.
_emitError(ctx, continuation) {
const disconnects = this._disconnects;
try {
this.emit('error', ctx);
}
finally {
if (this._disconnects === disconnects) {
continuation();
}
}
}
_attemptAborted(disconnects) {
return !this._isConnecting() || this._disconnects !== disconnects;
}
// resolved: the data promise resolved, so the error was thrown by its continuation.
_handleGetDataError(e, disconnects, resolved) {
if (this._attemptAborted(disconnects)) {
if (resolved) {
// E.g. by an event handler of the teardown that ended the attempt.
this._reportDispatchError(e);
}
return;
}
if (e instanceof UnauthorizedError) {
this._failUnauthorized();
return;
}
this._emitError({
type: 'connectData',
error: {
code: errorCodes.badConfiguration,
message: (e === null || e === void 0 ? void 0 : e.toString()) || ''
}
}, () => {
const delay = this._getReconnectDelay();
this._debug('error on getting connect data, reconnect after ' + delay + ' milliseconds', e);
this._reconnecting = false;
this._reconnectTimeout = setTimeout(() => {
this._startReconnecting();
}, delay);
});
}
// stale: the error belongs to a transport that was already closed. It is still
// reported, but must not tear down the current connection attempt.
// replied: the server returned the error in a reply, so the transport works.
// token: the token the connect command carried.
_connectError(err, stale, replied, token) {
if (this.state !== State.Connecting) {
return;
}
// Token expired: the next attempt gets a new one, unless the app set a new one
// meanwhile (see setToken).
if (err.code === 109 && token === this._token) {
this._refreshRequired = true;
}
if (err.code < 100 || err.temporary === true || err.code === 109) {
this._emitError({
'type': 'connect',
'error': err
}, () => {
if (stale) {
return;
}
if (replied) {
// The transport reached the server: retry it after the reconnect delay, not
// at once with the next transport as for one that failed to open. An
// emulation transport is otherwise marked open only by a connect reply.
this._transportWasOpen = true;
}
if (!replied && this._emulation && !this._transportWasOpen) {
// A handshake the server never answered, e.g. timed out, moves on to the next
// transport before any reply, but not after a socket opened (see onOpen). For
// other failures the transport's close callback does that, but it is ignored
// after the teardown below.
this._advanceTransportIndex();
}
this._debug('closing transport due to connect error');
this._disconnect(err.code, err.message, true);
});
}
else if (!stale) {
this._disconnect(err.code, err.message, false);
}
}
_scheduleReconnect() {
if (!this._isConnecting()) {
return;
}
let isInitialHandshake = false;
if (this._emulation && !this._transportWasOpen && !this._triedAllTransports) {
isInitialHandshake = true;
}
// The first round over the transports doesn't count towards the backoff.
const delay = isInitialHandshake ? 0 : this._getReconnectDelay();
this._debug('reconnect after ' + delay + ' milliseconds');
this._clearReconnectTimeout();
this._reconnectTimeout = setTimeout(() => {
this._startReconnecting();
}, delay);
}
_constructConnectCommand() {
const req = {};
if (this._token) {
req.token = this._token;
}
if (this._data) {
req.data = this._data;
}
if (this._config.name) {
req.name = this._config.name;
}
if (this._config.version) {
req.version = this._config.version;
}
if (Object.keys(this._config.headers).length > 0) {
req.headers = this._config.headers;
}
const subs = {};
let hasSubs = false;
for (const channel in this._serverSubs) {
if (this._serverSubs.hasOwnProperty(channel) && this._serverSubs[channel].recoverable) {
hasSubs = true;
const sub = {
'recover': true
};
// A publication being dispatched counts as delivered: a connect command built
// from its handler recovers after it, while the stored position still holds
// the previous one until that handler returned (see _handlePublication).
const pending = this._pendingServerSubOffsets[channel];
const offset = pending !== undefined && pending !== null ? pending : this._serverSubs[channel].offset;
if (offset) {
sub['offset'] = offset;
}
if (this._serverSubs[channel].epoch) {
sub['epoch'] = this._serverSubs[channel].epoch;
}
subs[channel] = sub;
}
}
if (hasSubs) {
req.subs = subs;
}
return {
connect: req
};
}
_getHistoryRequest(channel, options) {
const req = {
channel: channel
};
if (options !== undefined) {
if (options.since) {
req.since = {
offset: options.since.offset
};
if (options.since.epoch) {
req.since.epoch = options.since.epoch;
}
}
if (options.limit !== undefined) {
req.limit = options.limit;
}
if (options.reverse === true) {
req.reverse = true;
}
}
return req;
}
_methodCall() {
if (this._isConnected()) {
return Promise.resolve();
}
return new Promise((res, rej) => {
const id = this._nextPromiseId();
const timeout = setTimeout(() => {
delete this._promises[id];
rej({ code: errorCodes.timeout, message: 'timeout' });
}, this._config.timeout);
this._promises[id] = {
timeout: timeout,
resolve: res,
reject: rej
};
});
}
_callPromise(cmd, resultCB) {
return new Promise((resolve, reject) => {
this._call(cmd, false).then((resolveCtx) => {
var _a;
try {
resolve(resultCB(resolveCtx.reply));
}
catch (e) {
reject(e);
}
finally {
(_a = resolveCtx.next) === null || _a === void 0 ? void 0 : _a.call(resolveCtx);
}
}, (rejectCtx) => {
var _a;
reject(rejectCtx.error);
(_a = rejectCtx.next) === null || _a === void 0 ? void 0 : _a.call(rejectCtx);
});
});
}
_dataReceived(data, transportId = this._transportId) {
let replies;
try {
replies = this._codec.decodeReplies(data);
}
catch (e) {
// Not Centrifugo data, e.g. an HTML page from a captive portal or a
// misconfigured proxy. Close the transport so the client reconnects,
// instead of throwing from the transport callback.
this._debug('error decoding received data', e);
// Tear the connection down at once, as the close callback of the transport
// would: the data read with this, e.g. the next lines of an http_stream chunk,
// must not be dispatched, and the close callback comes later, or never for a
// transport whose close() throws.
if (this._emulation && !this._transportWasOpen) {
this._advanceTransportIndex();
}
this._disconnect(connectingCodes.transportClosed, 'transport closed', true);
return;
}
// Only data from the server proves the connection alive: not e.g. blank keep-alive
// lines an intermediary writes.
if (this._serverPing > 0 && replies.length > 0) {
this._waitServerPing();
}
// We have to guarantee order of events in replies processing - i.e. start processing
// next reply only when we finished processing of current one. Without syncing things in
// this way we could get wrong publication events order as reply promises resolve
// on next loop tick so for loop continues before we finished emitting all reply events.
this._dispatchPromise = this._dispatchPromise.then(() => new Promise(resolve => {
this._dispatchSynchronized(replies, resolve, transportId);
}));
}
_dispatchSynchronized(replies, finishDispatch, transportId) {
let p = Promise.resolve();
for (const i in replies) {
if (replies.hasOwnProperty(i)) {
p = p.then(() => {
// The transport was closed or replaced while this frame waited or was
// being dispatched (e.g. disconnect() called from an event handler):
// its remaining replies are outdated.
if (this._transportId !== transportId) {
return;
}
return this._dispatchReply(replies[i]);
}).catch(err => {
// The exception stops the client, which skips the remaining replies. The
// chain still settles: frames of a later connection wait for this one.
this._dispatchFailed(err);
});
}
}
p.then(() => {
finishDispatch();
});
}
/** @internal Every event reaches the application's handlers through here. */
emit(event, ...args) {
try {
return EventEmitter.prototype.emit.call(this, event, ...args);
}
catch (e) {
this._handlerFailed(e);
return true;
}
}
// An exception escaping an application event handler. The SDK can't know what the
// handler left undone, so it fails loudly instead of going on as if nothing
// happened: the client disconnects without reconnecting, and the exception is
// re-raised as an unhandled rejection. The SDK's own work continues as if the
// handler had returned, as for a handler calling disconnect(), so no state change
// is left half done.
/** @internal */
_handlerFailed(err) {
this._handlerFailures++;
this._reportDispatchError(err);
this._disconnect(disconnectedCodes.badProtocol, `exception in event handler: ${errorMessage(err)}`, false);
}
// An exception while handling a reply, other than one of an event handler (see
// _handlerFailed), may have left the client's state inconsistent. The client stops
// in a state the application can see: it disconnects without reconnecting, so no
// later reply is processed.
_dispatchFailed(err) {
this._reportDispatchError(err);
this._disconnect(disconnectedCodes.badProtocol, `exception during message handling: ${errorMessage(err)}`, false);
}
// The exception is surfaced as an unhandled rejection, as before.
_reportDispatchError(err) {
this._debug('error dispatching reply', err);
Promise.reject(err);
}
// An exception, other than one of an event handler, while handling a rejected
// command. A rejection with next() carries a reply, and is handled as any reply
// (see _dispatchFailed). A timeout or a teardown doesn't: stopping the client would
// cancel the reconnect or retry the handling scheduled, so the exception is only
// reported.
_rejectionFailed(err, rejectCtx) {
if (rejectCtx.next !== undefined) {
this._dispatchFailed(err);
}
else {
this._reportDispatchError(err);
}
}
_dispatchReply(reply) {
let next;
const p = new Promise(resolve => {
next = resolve;
});
if (reply === undefined || reply === null) {
this._debug('dispatch: got undefined or null reply');
next();
return p;
}
const id = reply.id;
if (id && id > 0) {
this._handleReply(reply, next);
}
else {
if (!reply.push) {
this._handleServerPing(next);
}
else {
this._handlePush(reply.push, next);
}
}
return p;
}
_call(cmd, skipSending) {
return new Promise((resolve, reject) => {
cmd.id = this._nextCommandId();
this._registerCall(cmd.id, resolve, reject);
if (!skipSending) {
this._addCommand(cmd);
}
});
}
_startConnecting() {
this._debug('start connecting');
// The attempt starts unless a handler of the events disconnected the client (or
// threw, which disconnects it). So the number of the transition is taken before
// its state event.
const transition = this.state !== State.Connecting ? this._stateTransitions + 1 : 0;
try {
this._setState(State.Connecting);
// A 'state' handler may have called disconnect() already.
if (transition && !this._transitionSuperseded(transition)) {
this.emit('connecting', { code: connectingCodes.connectCalled, reason: 'connect called' });
}
}
finally {
if (!this._transitionSuperseded(transition)) {
this._client = null;
this._startReconnecting();
}
}
}
_disconnect(code, reason, reconnect) {
if (code === disconnectedCodes.stateInvalidated) {
// State invalidated: clear connection token (forcing a fresh one via
// getToken on reconnect) and invalidate all subscription state. Done here
// (the shared funnel) so it fires whether it arrives as a Disconnect push
// or as a raw WebSocket close code — and before _clearConnectedState below
// moves subscriptions to subscribing for the resubscribe. Runs ahead of the
// isDisconnected guard so the invalidation is unconditional.
// Without getToken there is no new token to get: keep the token the
// client has (or none) and reconnect with it. The server rejects it if
// it's no longer valid, instead of the client stopping on a local
// configuration error.
if (this._config.getToken !== null) {
this._token = '';
this._refreshRequired = true;
}
for (const channel in this._subs) {
if (this._subs.hasOwnProperty(channel)) {
// @ts-ignore – _invalidateState is internal.
this._subs[channel]._invalidateState();
}
}
// Server-side subscriptions carry their own cached recovery position,
// separate from the client-side subscriptions above — reset it to the
// same unrecoverable sentinel so the next connect can't recover from
// now-invalidated state. "_" is a sentinel, not an epoch the server can
// produce: the recovery of the next connect is meant to fail. It has to be
// non-empty — an empty epoch means "any epoch" to the server (see
// _invalidateState of a subscription).
for (const channel in this._serverSubs) {
if (this._serverSubs.hasOwnProperty(channel)) {
this._serverSubs[channel].offset = 0;
this._serverSubs[channel].epoch = '_';
}
}
}
if (this._isDisconnected()) {
if (!reconnect) {
// Calls made while disconnected wait for a connection: disconnect() ends
// that wait too.
this._rejectPromises({ code: errorCodes.clientDisconnected, message: 'disconnected' });
}
return;
}
const previousState = this.state;
const newState = reconnect ? State.Connecting : State.Disconnected;
// Tear everything down before emitting any event: handlers may call connect()
// or disconnect() synchronously, and nothing below must undo what they start.
this._transportIsOpen = false;
this._reconnecting = false;
if (previousState === State.Connecting) {
this._clearReconnectTimeout();
}
this._clearConnectTimeout();
// Invalidates callbacks of the transport closed below (SSE issues its close
// callback synchronously).
this._nextTransportId();
// Aborts token/data continuations of an attempt that had not created a
// transport yet.
this._disconnects++;
if (this._transport) {
this._debug("closing existing transport");
const transport = this._transport;
this._transport = null;
try {
transport.close();
}
catch (e) {
// E.g. a transport whose socket constructor threw: the teardown must complete.
this._debug('error closing transport', e);
}
// Its close callback is ignored, so a new attempt must not wait for it.
this._transportClosed = true;
}
else {
this._debug("no transport to close");
}
// A connection that ends before it proved usable keeps the backoff growing.
this._reconnectAttemptsResetPending = false;
// Commands collected for the closed transport must not go out on the next one.
this._commands = [];
this._clearOutgoingRequests();
if (!reconnect) {
this._rejectPromises({ code: errorCodes.clientDisconnected, message: 'disconnected' });
// Network listeners are removed with the state change below, so no online
// event can reset it.
this._deviceWentOffline = false;
this._pageCached = false;
}
const ctx = {
code: code,
reason: reason
};
// The rest runs whatever the handlers of the events do: subscriptions must move to
// subscribing and a reconnect must be scheduled, or the client is left stuck. So
// the number of the transition is taken before its state event.
const transition = this.state !== newState ? this._stateTransitions + 1 : 0;
try {
try {
this._setState(newState);
}
finally {
if (!reconnect && !this._transitionSuperseded(transition)) {
// Client methods called from a 'state' handler must fail now too, not wait
// for a connection.
this._rejectPromises({ code: errorCodes.clientDisconnected, message: 'disconnected' });
}
if (previousState === State.Connected) {
this._clearConnectedState();
}
}
// A handler of the events above may have changed the state again: this
// transition is outdated then, and its event would arrive out of order.
if (transition && !this._transitionSuperseded(transition)) {
if (reconnect) {
this.emit('connecting', ctx);
}
else {
this.emit('disconnected', ctx);
}
}
}
finally {
// Unless a handler has already started a new attempt.
if (reconnect && !this._transitionSuperseded(transition)) {
this._scheduleReconnect();
}
}
}
_failUnauthorized() {
this._disconnect(disconnectedCodes.unauthorized, 'unauthorized', false);
}
_getToken() {
this._debug('get connection token');
if (!this._config.getToken) {
try {
this.emit('error', {
type: 'configuration',
error: {
code: errorCodes.badConfiguration,
message: 'token expired but no getToken function set in the configuration'
}
});
}
catch (e) {
// The attempt must fail as unauthorized all the same, not stay in progress.
this._reportDispatchError(e);
}
return Promise.reject(new UnauthorizedError(''));
}
// A callback throwing instead of returning a rejected promise fails the same way,
// not by throwing out of the attempt.
try {
return Promise.resolve(this._config.getToken({}));
}
catch (e) {
return Promise.reject(e);
}
}
// See _getToken.
_getData() {
try {
return Promise.resolve(this._config.getData());
}
catch (e) {
return Promise.reject(e);
}
}
_refresh() {
const clientId = this._client;
const self = this;
// See _startReconnecting.
let tokenResolved = false;
this._getToken().then(function (token) {
tokenResolved = true;
if (clientId !== self._client) {
return;
}
if (!token) {
self._failUnauthorized();
return;
}
self._token = token;
self._debug('connection token refreshed');
if (!self._isConnected()) {
return;
}
const cmd = {
refresh: { token: self._token }
};
self._call(cmd, false).then(resolveCtx => {
try {
self._refreshResponse(resolveCtx.reply.refresh);
}
catch (err) {
self._dispatchFailed(err);
}
finally {
if (resolveCtx.next) {
resolveCtx.next();
}
}
}, rejectCtx => {
try {
// A disconnect rejects the pending command too: nothing to retry then,
// the connection this refresh was for is gone.
if (clientId === self._client) {
self._refreshError(rejectCtx.error);
}
}
catch (err) {
self._rejectionFailed(err, rejectCtx);
}
finally {
if (rejectCtx.next) {
rejectCtx.next();
}
}
});
}).catch(function (e) {
if (clientId !== self._client || !self._isConnected()) {
if (tokenResolved) {
self._reportDispatchError(e);
}
return;
}
if (e instanceof UnauthorizedError) {
self._failUnauthorized();
return;
}
self._emitError({
type: 'refreshToken',
error: {
code: errorCodes.clientRefreshToken,
message: e !== undefined ? e.toString() : ''
}
}, () => {
self._refreshTimeout = setTimeout(() => self._refresh(), self._getRefreshRetryDelay());
});
});
}
_refreshError(err) {
if (err.code < 100 || err.temporary === true) {
this._emitError({
type: 'refresh',
error: err
}, () => {
this._refreshTimeout = setTimeout(() => this._refresh(), this._getRefreshRetryDelay());
});
}
else {
this._disconnect(err.code, err.message, false);
}
}
_getRefreshRetryDelay() {
return backoff(0, 5000, 10000);
}
_refreshResponse(result) {
if (this._refreshTimeout) {
clearTimeout(this._refreshTimeout);
this._refreshTimeout = null;
}
if (result.expires) {
// The client id of the connection only changes if the reply carries one — and
// Centrifugo never sets that field of a refresh reply. Taking an absent one
// leaves the client without an id, and the checks comparing against it stop
// recognising a token fetch, or a reply, of a connection that is gone.
if (result.client) {
this._client = result.client;
}
this._refreshTimeout = setTimeout(() => this._refresh(), ttlMilliseconds(result.ttl));
}
}
// A new subscription of the channel waits for the unsubscribe of a removed one, and
// of those removed before it still unsubscribing (see _setSubscribing of a
// subscription): a subscription removed without sending an unsubscribe doesn't
// drop one still pending.
_recordRemovedUnsubscribe(sub) {
const channel = sub.channel;
const previous = this._removedUnsubscribes[channel];
// @ts-ignore – we are hiding some symbols from public API autocompletion.
const own = sub._unsubPromise;
const unsubscribed = previous ? Promise.all([previous, own]).then(() => undefined) : own;
this._removedUnsubscribes[channel] = unsubscribed;
unsubscribed.then(() => {
if (this._removedUnsubscribes[channel] === unsubscribed) {
delete this._removedUnsubscribes[channel];
}
});
}
// Resolves once a subscription of the channel removed from the client has
// unsubscribed (see BaseSubscription._setSubscribing).
// @ts-ignore – this is used by a subscription in subscription.ts.
_removedSubscriptionUnsubscribed(channel) {
return this._removedUnsubscribes[channel] || Promise.resolve();
}
_unsubscribe(sub) {
if (!this._transportIsOpen) {
return Promise.resolve();
}
const req = {
channel: sub.channel
};
const cmd = { unsubscribe: req };
const self = this;
// A teardown rejects the pending command, and the rejection is processed after
// it: a newer attempt may have started by then, which must not be torn down.
const transportId = this._transportId;
const unsubscribePromise = new Promise((resolve, _) => {
this._call(cmd, false).then(resolveCtx => {
resolve();
if (resolveCtx.next) {
resolveCtx.next();
}
}, rejectCtx => {
resolve();
if (rejectCtx.next) {
rejectCtx.next();
}
if (self._transportId !== transportId) {
self._debug('unsubscribe command of a closed transport rejected');
return;
}
try {
self._disconnect(connectingCodes.unsubscribeError, 'unsubscribe error', true);
}
catch (err) {
self._rejectionFailed(err, rejectCtx);
}
});
});
return unsubscribePromise;
}
_getSub(channel, id) {
if (id && id > 0) {
for (const ch in this._subs) {
if (this._subs.hasOwnProperty(ch)) {
const sub = this._subs[ch];
// @ts-ignore – we are accessing private property for internal use
if (sub._id === id) {
return sub;
}
}
}
return null;
}
const sub = this._subs[channel];
if (!sub) {
return null;
}
return sub;
}
_isServerSub(channel) {
return this._serverSubs[channel] !== undefined;
}
// The client-side subscription a push is for. The server allows one subscription
// per channel: while a server-side subscription has the channel, its pushes
// belong to it unless the client-side subscription is subscribed, e.g. when the
// app kept an unsubscribed subscription object of that channel.
_getSubForPush(channel, id) {
const sub = this._getSub(channel, id);
// @ts-ignore – we are hiding some symbols from public API autocompletion.
if (sub && channel && this._isServerSub(channel) && !sub._isSubscribed()) {
return null;
}
return sub;
}
_sendSubscribeCommands() {
const commands = [];
for (const channel in this._subs) {
if (!this._subs.hasOwnProperty(channel)) {
continue;
}
const sub = this._subs[channel];
// @ts-ignore – we are hiding some symbols from public API autocompletion.
if (sub._inflight === true) {
continue;
}
// A subscribe error is retried after its backoff, also across a reconnect.
// @ts-ignore – we are hiding some symbols from public API autocompletion.
if (sub._resubscribeTimeout !== null) {
continue;
}
if (sub.state === SubscriptionState.Subscribing) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
const cmd = sub._subscribe();
if (cmd) {
commands.push(cmd);
}
}
}
return commands;
}
_connectResponse(result) {
this._transportIsOpen = true;
this._transportWasOpen = true;
if (this._transport !== null && this._transport.emulation()) {
// A connect reply over an emulation transport proves only the stream. Commands
// go through the emulation endpoint, which may keep failing and close the
// transport after every connect: reset the backoff once the server replied to
// a command or pinged, or such a client reconnects at the minimum delay forever.
this._reconnectAttemptsResetPending = true;
}
else {
this._reconnectAttempts = 0;
}
this._refreshRequired = false;
// Connected again: a later online event must not take the device for having been
// offline and abort a transport that works.
this._deviceWentOffline = false;
// Reconnected by the timer, in a page that was not frozen.
this._pageCached = false;
if (this._isConnected()) {
return;
}
this._client = result.client;
const transition = this._setState(State.Connected);
// A 'state' handler may have called disconnect(), which already tore the
// connection down.
if (this._transitionSuperseded(transition)) {
return;
}
if (this._refreshTimeout) {
clearTimeout(this._refreshTimeout);
}
if (result.expires) {
this._refreshTimeout = setTimeout(() => this._refresh(), ttlMilliseconds(result.ttl));
}
this._session = result.session;
this._node = result.node;
this.startBatching();
this._sendSubscribeCommands();
this.stopBatching();
const ctx = {
client: result.client,
transport: this._transport.subName()
};
if (result.data) {
ctx.data = result.data;
}
this.emit('connected', ctx);
// Same for a 'connected' handler.
if (this._transitionSuperseded(transition)) {
return;
}
this._resolvePromises();
this._processServerSubs(result.subs || {}, transition);
if (result.ping && result.ping > 0) {
this._serverPing = result.ping * 1000;
this._sendPong = result.pong === true;
this._waitServerPing();
}
else {
this._serverPing = 0;
}
}
_processServerSubs(subs, transition) {
// A 'subscribed' or 'publication' handler may call disconnect(). Removed
// channels are still reported, but no more subscribed or publication events
// of this connection are emitted, and no more positions stored: a position
// whose subscribed event the app didn't get would hide a gap from it (the
// next connect recovering from a position after it, recovered=true).
for (const channel in subs) {
if (!subs.hasOwnProperty(channel)) {
continue;
}
if (this._transitionSuperseded(transition)) {
continue;
}
const sub = subs[channel];
this._serverSubs[channel] = {
'offset': toOffset(sub.offset),
'epoch': sub.epoch,
'recoverable': sub.recoverable || false,
'subscribed': true
};
const subCtx = this._getSubscribeContext(channel, sub);
this.emit('subscribed', subCtx);
}
for (const channel in subs) {
if (!subs.hasOwnProperty(channel)) {
continue;
}
const sub = subs[channel];
if (sub.recovered) {
const pubs = sub.publications || [];
for (let i = 0; i < pubs.length && !this._transitionSuperseded(transition); i++) {
this._handlePublication(channel, pubs[i]);
}
}
}
for (const channel in this._serverSubs) {
if (!this._serverSubs.hasOwnProperty(channel)) {
continue;
}
if (!subs[channel]) {
this.emit('unsubscribed', { channel: channel });
delete this._serverSubs[channel];
}
}
}
_clearRefreshTimeout() {
if (this._refreshTimeout !== null) {
clearTimeout(this._refreshTimeout);
this._refreshTimeout = null;
}
}
_clearReconnectTimeout() {
if (this._reconnectTimeout !== null) {
clearTimeout(this._reconnectTimeout);
this._reconnectTimeout = null;
}
}
_clearConnectTimeout() {
if (this._connectTimeout !== null) {
clearTimeout(this._connectTimeout);
this._connectTimeout = null;
}
}
_clearServerPingTimeout() {
if (this._serverPingTimeout !== null) {
clearTimeout(this._serverPingTimeout);
this._serverPingTimeout = null;
}
}
_waitServerPing() {
if (this._config.maxServerPingDelay === 0) {
return;
}
if (!this._isConnected()) {
return;
}
this._clearServerPingTimeout();
const delay = this._serverPing + this._config.maxServerPingDelay;
const due = Date.now() + delay;
this._serverPingTimeout = setTimeout(() => {
if (!this._isConnected()) {
return;
}
// A ping may have been received already but not processed yet, e.g. when a
// suspended process resumes: let that data be processed first, as for a call
// (see _registerCall). Any data received re-arms this timer.
const late = Date.now() - due >= lateCallTimer;
this._serverPingTimeout = setTimeout(() => {
if (!this._isConnected()) {
return;
}
this._disconnect(connectingCodes.noPing, 'no ping', true);
}, late ? lateCallGrace : 0);
}, delay);
}
_getSubscribeContext(channel, result) {
const ctx = {
channel: channel,
positioned: false,
recoverable: false,
wasRecovering: false,
recovered: false,
hasRecoveredPublications: false,
};
if (result.recovered) {
ctx.recovered = true;
}
if (result.positioned) {
ctx.positioned = true;
}
if (result.recoverable) {
ctx.recoverable = true;
}
if (result.was_recovering) {
ctx.wasRecovering = true;
}
let epoch = '';
if ('epoch' in result) {
epoch = result.epoch;
}
let offset = 0;
if ('offset' in result) {
offset = toOffset(result.offset);
}
if (ctx.positioned || ctx.recoverable) {
ctx.streamPosition = {
'offset': offset,
'epoch': epoch
};
}
if (Array.isArray(result.publications) && result.publications.length > 0) {
ctx.hasRecoveredPublications = true;
}
if (result.data) {
ctx.data = result.data;
}
return ctx;
}
_handleReply(reply, next) {
this._resetReconnectAttemptsIfPending();
const id = reply.id;
if (!(id in this._callbacks)) {
next();
return;
}
const callbacks = this._callbacks[id];
clearTimeout(this._callbacks[id].timeout);
delete this._callbacks[id];
if (!errorExists(reply)) {
const callback = callbacks.callback;
if (!callback) {
return;
}
callback({ reply, next });
}
else {
const errback = callbacks.errback;
if (!errback) {
next();
return;
}
const error = { code: reply.error.code, message: reply.error.message || '', temporary: reply.error.temporary || false };
errback({ error, next });
}
}
_handleJoin(channel, join, id) {
const sub = this._getSubForPush(channel, id);
if (!sub) {
// See _handlePublication: a compacted push with an unknown id has an empty
// channel and no matching subscription — drop instead of crashing.
if (channel && this._isServerSub(channel)) {
const ctx = { channel: channel, info: this._getJoinLeaveContext(join.info) };
this.emit('join', ctx);
}
return;
}
// @ts-ignore – we are hiding some symbols from public API autocompletion.
if (!sub._isSubscribed()) {
this._debug('join for a subscription that is not subscribed', channel);
return;
}
// @ts-ignore – we are hiding some symbols from public API autocompletion.
sub._handleJoin(join);
}
_handleLeave(channel, leave, id) {
const sub = this._getSubForPush(channel, id);
if (!sub) {
// See _handlePublication: a compacted push with an unknown id has an empty
// channel and no matching subscription — drop instead of crashing.
if (channel && this._isServerSub(channel)) {
const ctx = { channel: channel, info: this._getJoinLeaveContext(leave.info) };
this.emit('leave', ctx);
}
return;
}
// @ts-ignore – we are hiding some symbols from public API autocompletion.
if (!sub._isSubscribed()) {
this._debug('leave for a subscription that is not subscribed', channel);
return;
}
// @ts-ignore – we are hiding some symbols from public API autocompletion.
sub._handleLeave(leave);
}
_handleUnsubscribe(channel, unsubscribe) {
const sub = this._getSubForPush(channel, 0);
if (!sub) {
if (channel && this._isServerSub(channel)) {
delete this._serverSubs[channel];
this.emit('unsubscribed', { channel: channel });
}
return;
}
// @ts-ignore – we are hiding some symbols from public API autocompletion.
if (!sub._isSubscribed()) {
// It ends a previous subscription: one the app unsubscribed, or one that raced
// unsubscribe() and subscribe() of the app. The server unsubscribes a
// subscription in progress only after replying to its subscribe, and it sends
// the push also when the subscription is already gone. A resubscribe code must
// not subscribe again, nor invalidate the state of a subscribe in progress.
this._debug('unsubscribe push for a previous subscription', channel);
return;
}
if (unsubscribe.code < 2500) {
// @ts-ignore – we are hiding some symbols from public API autocompletion.
sub._setUnsubscribed(unsubscribe.code, unsubscribe.reason, false);
}
else {
if (unsubscribe.code === unsubscribedCodes.stateInvalidated) {
// State invalidated: clear subscription token and cached state so the
// resubscribe gets a fresh token and re-syncs.
// @ts-ignore – _invalidateState is internal.
sub._invalidateState();
}
// @ts-ignore – we are hiding some symbols from public API autocompletion.
sub._setSubscribing(unsubscribe.code, unsubscribe.reason);
}
}
_handleSubscribe(channel, sub) {
this._serverSubs[channel] = {
'offset': toOffset(sub.offset),
'epoch': sub.epoch,
'recoverable': sub.recoverable || false,
'subscribed': true
};
this.emit('subscribed', this._getSubscribeContext(channel, sub));
}
_handleDisconnect(disconnect) {
// The server pushed it over the transport, so the transport works: reconnect
// after the reconnect delay, as after a close code from the server, not at once
// with the next transport as for one that failed to open. An emulation transport
// is otherwise marked open only by a connect reply.
this._transportWasOpen = true;
const code = disconnect.code;
let reconnect = true;
if ((code >= 3500 && code < 4000) || (code >= 4500 && code < 5000)) {
reconnect = false;
}
// State invalidation (code 3014) is handled centrally in _disconnect so it
// covers both delivery paths: a Disconnect push (this method) and a raw
// WebSocket close code (transport onClose → _disconnect directly).
this._disconnect(code, disconnect.reason, reconnect);
}
_getPublicationContext(channel, pub) {
const ctx = {
channel: channel,
data: pub.data
};
if (hasOffset(pub.offset)) {
ctx.offset = toOffset(pub.offset);
}
if (pub.info) {
ctx.info = this._getJoinLeaveContext(pub.info);
}
if (pub.tags) {
ctx.tags = pub.tags;
}
return ctx;
}
_getJoinLeaveContext(clientInfo) {
const info = {
client: clientInfo.client,
user: clientInfo.user
};
const connInfo = clientInfo['conn_info'];
if (connInfo) {
info.connInfo = connInfo;
}
const chanInfo = clientInfo['chan_info'];
if (chanInfo) {
info.chanInfo = chanInfo;
}
return info;
}
_handlePublication(channel, pub, id) {
const sub = this._getSubForPush(channel, id);
if (!sub) {
// No client-side subscription. With channel compaction the push carries a
// numeric id and no channel, so an unknown id (e.g. a publication for a
// subscription already unsubscribed) has an empty channel here — it must
// be dropped, not fall through to sub._handlePublication on null.
if (channel && this._isServerSub(channel)) {
const ctx = this._getPublicationContext(channel, pub);
// The position moves after the app has the publication, so the position it can
// observe never runs ahead of what it received (see
// BaseSubscription._handlePublication). A connect command built while a handler
// runs takes the offset of the publication being dispatched (see the subs of
// _constructConnectCommand), so a connect() from that handler still recovers
// after it instead of receiving it again.
this._pendingServerSubOffsets[channel] = hasOffset(pub.offset) ? toOffset(pub.offset) : null;
const failures = this._handlerFailures;
try {
this.emit('publication', ctx);
}
finally {
delete this._pendingServerSubOffsets[channel];
}
// A publication whose handler threw isn't delivered: the position stays before
// it, so the next recovery delivers it again.
if (this._handlerFailures !== failures) {
return;
}
if (hasOffset(pub.offset)) {
this._serverSubs[channel].offset = toOffset(pub.offset);
}
// The epoch of a channel that had no stream at subscribe time comes with
// its first publication (see BaseSubscription._setPublicationPosition).
if (pub.epoch) {
this._serverSubs[channel].epoch = pub.epoch;
}
}
return;
}
// @ts-ignore – we are hiding some symbols from public API autocompletion.
if (!sub._isSubscribed()) {
// E.g. a publication already on its way when the app called unsubscribe().
this._debug('publication for a subscription that is not subscribed', channel);
return;
}
// @ts-ignore – we are hiding some symbols from public API autocompletion.
sub._handlePublication(pub);
}
_handleMessage(message) {
this.emit('message', { data: message.data });
}
_handleServerPing(next) {
this._resetReconnectAttemptsIfPending();
if (this._sendPong) {
const cmd = {};
this._transportSendCommands([cmd]);
}
next();
}
_handlePush(data, next) {
const channel = data.channel;
const id = data.id;
if (data.pub) {
this._handlePublication(channel, data.pub, id);
}
else if (data.message) {
this._handleMessage(data.message);
}
else if (data.join) {
this._handleJoin(channel, data.join, id);
}
else if (data.leave) {
this._handleLeave(channel, data.leave, id);
}
else if (data.unsubscribe) {
this._handleUnsubscribe(channel, data.unsubscribe);
}
else if (data.subscribe) {
this._handleSubscribe(channel, data.subscribe);
}
else if (data.disconnect) {
this._handleDisconnect(data.disconnect);
}
next();
}
_flush() {
const commands = this._commands.slice(0);
this._commands = [];
this._transportSendCommands(commands);
}
_createErrorObject(code, message, temporary) {
const errObject = {
code: code,
message: message
};
if (temporary) {
errObject.temporary = true;
}
return errObject;
}
_registerCall(id, callback, errback) {
this._callbacks[id] = {
callback: callback,
errback: errback,
timeout: null
};
const due = Date.now() + this._config.timeout;
this._callbacks[id].timeout = setTimeout(() => {
// The reply may have been received already but not processed yet, e.g. when
// a suspended process resumes and this overdue timer runs before the data
// waiting in the socket. Let that data be processed first: one event loop
// turn is enough in Node. A timer running far too late means the process was
// suspended or blocked, and browsers don't promise to run the socket events
// before it: the reply gets a grace period then.
const late = Date.now() - due >= lateCallTimer;
this._callbacks[id].timeout = setTimeout(() => {
delete this._callbacks[id];
if (isFunction(errback)) {
errback({ error: this._createErrorObject(errorCodes.timeout, 'timeout') });
}
}, late ? lateCallGrace : 0);
}, this._config.timeout);
}
_addCommand(command) {
if (this._batching) {
this._commands.push(command);
}
else {
this._transportSendCommands([command]);
}
}
_nextPromiseId() {
return ++this._promiseId;
}
_nextTransportId() {
return ++this._transportId;
}
_resolvePromises() {
for (const id in this._promises) {
if (!this._promises.hasOwnProperty(id)) {
continue;
}
if (this._promises[id].timeout) {
clearTimeout(this._promises[id].timeout);
}
this._promises[id].resolve();
delete this._promises[id];
}
}
_rejectPromises(err) {
for (const id in this._promises) {
if (!this._promises.hasOwnProperty(id)) {
continue;
}
if (this._promises[id].timeout) {
clearTimeout(this._promises[id].timeout);
}
this._promises[id].reject(err);
delete this._promises[id];
}
}
}
Centrifuge.SubscriptionState = SubscriptionState;
Centrifuge.State = State;
Centrifuge.UnauthorizedError = UnauthorizedError;
var indexMinimal = {};
var minimal$1 = {};
var aspromise;
var hasRequiredAspromise;
function requireAspromise () {
if (hasRequiredAspromise) return aspromise;
hasRequiredAspromise = 1;
aspromise = asPromise;
/**
* Callback as used by {@link util.asPromise}.
* @typedef asPromiseCallback
* @type {function}
* @param {Error|null} error Error, if any
* @param {...*} params Additional arguments
* @returns {undefined}
*/
/**
* Returns a promise from a node-style callback function.
* @memberof util
* @param {asPromiseCallback} fn Function to call
* @param {*} ctx Function context
* @param {...*} params Function arguments
* @returns {Promise<*>} Promisified function
*/
function asPromise(fn, ctx/*, varargs */) {
var params = new Array(arguments.length - 1),
offset = 0,
index = 2,
pending = true;
while (index < arguments.length)
params[offset++] = arguments[index++];
return new Promise(function executor(resolve, reject) {
params[offset] = function callback(err/*, varargs */) {
if (pending) {
pending = false;
if (err)
reject(err);
else {
var params = new Array(arguments.length - 1),
offset = 0;
while (offset < params.length)
params[offset++] = arguments[offset];
resolve.apply(null, params);
}
}
};
try {
fn.apply(ctx || null, params);
} catch (err) {
if (pending) {
pending = false;
reject(err);
}
}
});
}
return aspromise;
}
var base64 = {};
var hasRequiredBase64;
function requireBase64 () {
if (hasRequiredBase64) return base64;
hasRequiredBase64 = 1;
(function (exports) {
/**
* A minimal base64 implementation for number arrays.
* @memberof util
* @namespace
*/
var base64 = exports;
/**
* Calculates the byte length of a base64 encoded string.
* @param {string} string Base64 encoded string
* @returns {number} Byte length
*/
base64.length = function length(string) {
var p = string.length;
if (!p)
return 0;
var n = 0;
while (--p % 4 > 1 && string.charAt(p) === "=")
++n;
return Math.ceil(string.length * 3) / 4 - n;
};
// Base64 encoding table
var b64 = new Array(64);
// Base64 decoding table
var s64 = new Array(123);
// 65..90, 97..122, 48..57, 43, 47
for (var i = 0; i < 64;)
s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
/**
* Encodes a buffer to a base64 encoded string.
* @param {Uint8Array} buffer Source buffer
* @param {number} start Source start
* @param {number} end Source end
* @returns {string} Base64 encoded string
*/
base64.encode = function encode(buffer, start, end) {
var parts = null,
chunk = [];
var i = 0, // output index
j = 0, // goto index
t; // temporary
while (start < end) {
var b = buffer[start++];
switch (j) {
case 0:
chunk[i++] = b64[b >> 2];
t = (b & 3) << 4;
j = 1;
break;
case 1:
chunk[i++] = b64[t | b >> 4];
t = (b & 15) << 2;
j = 2;
break;
case 2:
chunk[i++] = b64[t | b >> 6];
chunk[i++] = b64[b & 63];
j = 0;
break;
}
if (i > 8191) {
(parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
i = 0;
}
}
if (j) {
chunk[i++] = b64[t];
chunk[i++] = 61;
if (j === 1)
chunk[i++] = 61;
}
if (parts) {
if (i)
parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
return parts.join("");
}
return String.fromCharCode.apply(String, chunk.slice(0, i));
};
var invalidEncoding = "invalid encoding";
/**
* Decodes a base64 encoded string to a buffer.
* @param {string} string Source string
* @param {Uint8Array} buffer Destination buffer
* @param {number} offset Destination offset
* @returns {number} Number of bytes written
* @throws {Error} If encoding is invalid
*/
base64.decode = function decode(string, buffer, offset) {
var start = offset;
var j = 0, // goto index
t; // temporary
for (var i = 0; i < string.length;) {
var c = string.charCodeAt(i++);
if (c === 61 && j > 1)
break;
if ((c = s64[c]) === undefined)
throw Error(invalidEncoding);
switch (j) {
case 0:
t = c;
j = 1;
break;
case 1:
buffer[offset++] = t << 2 | (c & 48) >> 4;
t = c;
j = 2;
break;
case 2:
buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;
t = c;
j = 3;
break;
case 3:
buffer[offset++] = (t & 3) << 6 | c;
j = 0;
break;
}
}
if (j === 1)
throw Error(invalidEncoding);
return offset - start;
};
/**
* Tests if the specified string appears to be base64 encoded.
* @param {string} string String to test
* @returns {boolean} `true` if probably base64 encoded, otherwise false
*/
base64.test = function test(string) {
return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);
};
} (base64));
return base64;
}
var eventemitter;
var hasRequiredEventemitter;
function requireEventemitter () {
if (hasRequiredEventemitter) return eventemitter;
hasRequiredEventemitter = 1;
eventemitter = EventEmitter;
/**
* Constructs a new event emitter instance.
* @classdesc A minimal event emitter.
* @memberof util
* @constructor
*/
function EventEmitter() {
/**
* Registered listeners.
* @type {Object.<string,*>}
* @private
*/
this._listeners = Object.create(null);
}
/**
* Event listener as used by {@link util.EventEmitter}.
* @typedef EventEmitterListener
* @type {function}
* @param {...*} args Arguments
* @returns {undefined}
*/
/**
* Registers an event listener.
* @param {string} evt Event name
* @param {EventEmitterListener} fn Listener
* @param {*} [ctx] Listener context
* @returns {this} `this`
*/
EventEmitter.prototype.on = function on(evt, fn, ctx) {
(this._listeners[evt] || (this._listeners[evt] = [])).push({
fn : fn,
ctx : ctx || this
});
return this;
};
/**
* Removes an event listener or any matching listeners if arguments are omitted.
* @param {string} [evt] Event name. Removes all listeners if omitted.
* @param {EventEmitterListener} [fn] Listener to remove. Removes all listeners of `evt` if omitted.
* @returns {this} `this`
*/
EventEmitter.prototype.off = function off(evt, fn) {
if (evt === undefined)
this._listeners = Object.create(null);
else {
if (fn === undefined)
this._listeners[evt] = [];
else {
var listeners = this._listeners[evt];
if (!listeners)
return this;
for (var i = 0; i < listeners.length;)
if (listeners[i].fn === fn)
listeners.splice(i, 1);
else
++i;
}
}
return this;
};
/**
* Emits an event by calling its listeners with the specified arguments.
* @param {string} evt Event name
* @param {...*} args Arguments
* @returns {this} `this`
*/
EventEmitter.prototype.emit = function emit(evt) {
var listeners = this._listeners[evt];
if (listeners) {
var args = [],
i = 1;
for (; i < arguments.length;)
args.push(arguments[i++]);
for (i = 0; i < listeners.length;)
listeners[i].fn.apply(listeners[i++].ctx, args);
}
return this;
};
return eventemitter;
}
var float;
var hasRequiredFloat;
function requireFloat () {
if (hasRequiredFloat) return float;
hasRequiredFloat = 1;
float = factory(factory);
/**
* Reads / writes floats / doubles from / to buffers.
* @name util.float
* @namespace
*/
/**
* Writes a 32 bit float to a buffer using little endian byte order.
* @name util.float.writeFloatLE
* @function
* @param {number} val Value to write
* @param {Uint8Array} buf Target buffer
* @param {number} pos Target buffer offset
* @returns {undefined}
*/
/**
* Writes a 32 bit float to a buffer using big endian byte order.
* @name util.float.writeFloatBE
* @function
* @param {number} val Value to write
* @param {Uint8Array} buf Target buffer
* @param {number} pos Target buffer offset
* @returns {undefined}
*/
/**
* Reads a 32 bit float from a buffer using little endian byte order.
* @name util.float.readFloatLE
* @function
* @param {Uint8Array} buf Source buffer
* @param {number} pos Source buffer offset
* @returns {number} Value read
*/
/**
* Reads a 32 bit float from a buffer using big endian byte order.
* @name util.float.readFloatBE
* @function
* @param {Uint8Array} buf Source buffer
* @param {number} pos Source buffer offset
* @returns {number} Value read
*/
/**
* Writes a 64 bit double to a buffer using little endian byte order.
* @name util.float.writeDoubleLE
* @function
* @param {number} val Value to write
* @param {Uint8Array} buf Target buffer
* @param {number} pos Target buffer offset
* @returns {undefined}
*/
/**
* Writes a 64 bit double to a buffer using big endian byte order.
* @name util.float.writeDoubleBE
* @function
* @param {number} val Value to write
* @param {Uint8Array} buf Target buffer
* @param {number} pos Target buffer offset
* @returns {undefined}
*/
/**
* Reads a 64 bit double from a buffer using little endian byte order.
* @name util.float.readDoubleLE
* @function
* @param {Uint8Array} buf Source buffer
* @param {number} pos Source buffer offset
* @returns {number} Value read
*/
/**
* Reads a 64 bit double from a buffer using big endian byte order.
* @name util.float.readDoubleBE
* @function
* @param {Uint8Array} buf Source buffer
* @param {number} pos Source buffer offset
* @returns {number} Value read
*/
// Factory function for the purpose of node-based testing in modified global environments
function factory(exports) {
// float: typed array
if (typeof Float32Array !== "undefined") (function() {
var f32 = new Float32Array([ -0 ]),
f8b = new Uint8Array(f32.buffer),
le = f8b[3] === 128;
function writeFloat_f32_cpy(val, buf, pos) {
f32[0] = val;
buf[pos ] = f8b[0];
buf[pos + 1] = f8b[1];
buf[pos + 2] = f8b[2];
buf[pos + 3] = f8b[3];
}
function writeFloat_f32_rev(val, buf, pos) {
f32[0] = val;
buf[pos ] = f8b[3];
buf[pos + 1] = f8b[2];
buf[pos + 2] = f8b[1];
buf[pos + 3] = f8b[0];
}
/* istanbul ignore next */
exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;
/* istanbul ignore next */
exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;
function readFloat_f32_cpy(buf, pos) {
f8b[0] = buf[pos ];
f8b[1] = buf[pos + 1];
f8b[2] = buf[pos + 2];
f8b[3] = buf[pos + 3];
return f32[0];
}
function readFloat_f32_rev(buf, pos) {
f8b[3] = buf[pos ];
f8b[2] = buf[pos + 1];
f8b[1] = buf[pos + 2];
f8b[0] = buf[pos + 3];
return f32[0];
}
/* istanbul ignore next */
exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;
/* istanbul ignore next */
exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;
// float: ieee754
})(); else (function() {
function writeFloat_ieee754(writeUint, val, buf, pos) {
var sign = val < 0 ? 1 : 0;
if (sign)
val = -val;
if (val === 0)
writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);
else if (isNaN(val))
writeUint(2143289344, buf, pos);
else if (val > 3.4028234663852886e+38) // +-Infinity
writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);
else if (val < 1.1754943508222875e-38) // denormal
writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);
else {
var exponent = Math.floor(Math.log(val) / Math.LN2),
mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;
writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);
}
}
exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);
exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);
function readFloat_ieee754(readUint, buf, pos) {
var uint = readUint(buf, pos),
sign = (uint >> 31) * 2 + 1,
exponent = uint >>> 23 & 255,
mantissa = uint & 8388607;
return exponent === 255
? mantissa
? NaN
: sign * Infinity
: exponent === 0 // denormal
? sign * 1.401298464324817e-45 * mantissa
: sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);
}
exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);
exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);
})();
// double: typed array
if (typeof Float64Array !== "undefined") (function() {
var f64 = new Float64Array([-0]),
f8b = new Uint8Array(f64.buffer),
le = f8b[7] === 128;
function writeDouble_f64_cpy(val, buf, pos) {
f64[0] = val;
buf[pos ] = f8b[0];
buf[pos + 1] = f8b[1];
buf[pos + 2] = f8b[2];
buf[pos + 3] = f8b[3];
buf[pos + 4] = f8b[4];
buf[pos + 5] = f8b[5];
buf[pos + 6] = f8b[6];
buf[pos + 7] = f8b[7];
}
function writeDouble_f64_rev(val, buf, pos) {
f64[0] = val;
buf[pos ] = f8b[7];
buf[pos + 1] = f8b[6];
buf[pos + 2] = f8b[5];
buf[pos + 3] = f8b[4];
buf[pos + 4] = f8b[3];
buf[pos + 5] = f8b[2];
buf[pos + 6] = f8b[1];
buf[pos + 7] = f8b[0];
}
/* istanbul ignore next */
exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;
/* istanbul ignore next */
exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;
function readDouble_f64_cpy(buf, pos) {
f8b[0] = buf[pos ];
f8b[1] = buf[pos + 1];
f8b[2] = buf[pos + 2];
f8b[3] = buf[pos + 3];
f8b[4] = buf[pos + 4];
f8b[5] = buf[pos + 5];
f8b[6] = buf[pos + 6];
f8b[7] = buf[pos + 7];
return f64[0];
}
function readDouble_f64_rev(buf, pos) {
f8b[7] = buf[pos ];
f8b[6] = buf[pos + 1];
f8b[5] = buf[pos + 2];
f8b[4] = buf[pos + 3];
f8b[3] = buf[pos + 4];
f8b[2] = buf[pos + 5];
f8b[1] = buf[pos + 6];
f8b[0] = buf[pos + 7];
return f64[0];
}
/* istanbul ignore next */
exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;
/* istanbul ignore next */
exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;
// double: ieee754
})(); else (function() {
function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {
var sign = val < 0 ? 1 : 0;
if (sign)
val = -val;
if (val === 0) {
writeUint(0, buf, pos + off0);
writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);
} else if (isNaN(val)) {
writeUint(0, buf, pos + off0);
writeUint(2146959360, buf, pos + off1);
} else if (val > 1.7976931348623157e+308) { // +-Infinity
writeUint(0, buf, pos + off0);
writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);
} else {
var mantissa;
if (val < 2.2250738585072014e-308) { // denormal
mantissa = val / 5e-324;
writeUint(mantissa >>> 0, buf, pos + off0);
writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);
} else {
var exponent = Math.floor(Math.log(val) / Math.LN2);
if (exponent === 1024)
exponent = 1023;
mantissa = val * Math.pow(2, -exponent);
writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);
writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);
}
}
}
exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);
exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);
function readDouble_ieee754(readUint, off0, off1, buf, pos) {
var lo = readUint(buf, pos + off0),
hi = readUint(buf, pos + off1);
var sign = (hi >> 31) * 2 + 1,
exponent = hi >>> 20 & 2047,
mantissa = 4294967296 * (hi & 1048575) + lo;
return exponent === 2047
? mantissa
? NaN
: sign * Infinity
: exponent === 0 // denormal
? sign * 5e-324 * mantissa
: sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);
}
exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);
exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);
})();
return exports;
}
// uint helpers
function writeUintLE(val, buf, pos) {
buf[pos ] = val & 255;
buf[pos + 1] = val >>> 8 & 255;
buf[pos + 2] = val >>> 16 & 255;
buf[pos + 3] = val >>> 24;
}
function writeUintBE(val, buf, pos) {
buf[pos ] = val >>> 24;
buf[pos + 1] = val >>> 16 & 255;
buf[pos + 2] = val >>> 8 & 255;
buf[pos + 3] = val & 255;
}
function readUintLE(buf, pos) {
return (buf[pos ]
| buf[pos + 1] << 8
| buf[pos + 2] << 16
| buf[pos + 3] << 24) >>> 0;
}
function readUintBE(buf, pos) {
return (buf[pos ] << 24
| buf[pos + 1] << 16
| buf[pos + 2] << 8
| buf[pos + 3]) >>> 0;
}
return float;
}
var utf8 = {};
var hasRequiredUtf8;
function requireUtf8 () {
if (hasRequiredUtf8) return utf8;
hasRequiredUtf8 = 1;
(function (exports) {
/**
* A minimal UTF8 implementation for number arrays.
* @memberof util
* @namespace
*/
var utf8 = exports,
replacementCharCode = 0xFFFD; // U+FFFD REPLACEMENT CHARACTER
/**
* Calculates the UTF8 byte length of a string.
* @param {string} string String
* @returns {number} Byte length
*/
utf8.length = function utf8_length(string) {
var len = 0,
c = 0;
for (var i = 0; i < string.length; ++i) {
c = string.charCodeAt(i);
if (c < 128)
len += 1;
else if (c < 2048)
len += 2;
else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {
++i;
len += 4;
} else
len += 3;
}
return len;
};
/**
* Reads UTF8 bytes as a string.
* @param {Uint8Array} buffer Source buffer
* @param {number} start Source start
* @param {number} end Source end
* @returns {string} String read
*/
utf8.read = function utf8_read(buffer, start, end) {
if (end - start < 1)
return "";
// Batch code units and flush via String.fromCharCode.apply in 8192-unit
// chunks to avoid the per-character ConsString buildup of `str += ...`.
var parts = null,
chunk = [],
i = 0, // chunk write index
t, t2, c2, c3;
while (start < end) {
t = buffer[start++];
if (t <= 0x7F) {
chunk[i++] = t;
} else if (t >= 0xC0 && t < 0xE0) {
c2 = (t & 0x1F) << 6 | buffer[start++] & 0x3F;
chunk[i++] = c2 >= 0x80 ? c2 : replacementCharCode;
} else if (t >= 0xE0 && t < 0xF0) {
c3 = (t & 0xF) << 12 | (buffer[start++] & 0x3F) << 6 | buffer[start++] & 0x3F;
chunk[i++] = c3 >= 0x800 ? c3 : replacementCharCode;
} else if (t >= 0xF0) {
t2 = (t & 7) << 18 | (buffer[start++] & 0x3F) << 12 | (buffer[start++] & 0x3F) << 6 | buffer[start++] & 0x3F;
if (t2 < 0x10000 || t2 > 0x10FFFF)
chunk[i++] = replacementCharCode;
else {
t2 -= 0x10000;
chunk[i++] = 0xD800 + (t2 >> 10);
chunk[i++] = 0xDC00 + (t2 & 0x3FF);
}
}
if (i > 8191) {
(parts || (parts = [])).push(String.fromCharCode.apply(String, chunk.slice(0, i)));
i = 0;
}
}
if (parts) {
if (i)
parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
return parts.join("");
}
return String.fromCharCode.apply(String, chunk.slice(0, i));
};
/**
* Writes a string as UTF8 bytes.
* @param {string} string Source string
* @param {Uint8Array} buffer Destination buffer
* @param {number} offset Destination offset
* @returns {number} Bytes written
*/
utf8.write = function utf8_write(string, buffer, offset) {
var start = offset,
c1, // character 1
c2; // character 2
for (var i = 0; i < string.length; ++i) {
c1 = string.charCodeAt(i);
if (c1 < 128) {
buffer[offset++] = c1;
} else if (c1 < 2048) {
buffer[offset++] = c1 >> 6 | 192;
buffer[offset++] = c1 & 63 | 128;
} else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {
c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);
++i;
buffer[offset++] = c1 >> 18 | 240;
buffer[offset++] = c1 >> 12 & 63 | 128;
buffer[offset++] = c1 >> 6 & 63 | 128;
buffer[offset++] = c1 & 63 | 128;
} else {
buffer[offset++] = c1 >> 12 | 224;
buffer[offset++] = c1 >> 6 & 63 | 128;
buffer[offset++] = c1 & 63 | 128;
}
}
return offset - start;
};
} (utf8));
return utf8;
}
var pool_1;
var hasRequiredPool;
function requirePool () {
if (hasRequiredPool) return pool_1;
hasRequiredPool = 1;
pool_1 = pool;
/**
* An allocator as used by {@link util.pool}.
* @typedef PoolAllocator
* @type {function}
* @param {number} size Buffer size
* @returns {Uint8Array} Buffer
*/
/**
* A slicer as used by {@link util.pool}.
* @typedef PoolSlicer
* @type {function}
* @param {number} start Start offset
* @param {number} end End offset
* @returns {Uint8Array} Buffer slice
* @this {Uint8Array}
*/
/**
* A general purpose buffer pool.
* @memberof util
* @function
* @param {PoolAllocator} alloc Allocator
* @param {PoolSlicer} slice Slicer
* @param {number} [size=8192] Slab size
* @returns {PoolAllocator} Pooled allocator
*/
function pool(alloc, slice, size) {
var SIZE = size || 8192;
var MAX = SIZE >>> 1;
var slab = null;
var offset = SIZE;
return function pool_alloc(size) {
if (size < 1 || size > MAX)
return alloc(size);
if (offset + size > SIZE) {
slab = alloc(SIZE);
offset = 0;
}
var buf = slice.call(slab, offset, offset += size);
if (offset & 7) // align to 32 bit
offset = (offset | 7) + 1;
return buf;
};
}
return pool_1;
}
var longbits;
var hasRequiredLongbits;
function requireLongbits () {
if (hasRequiredLongbits) return longbits;
hasRequiredLongbits = 1;
longbits = LongBits;
var util = requireMinimal$1();
/**
* Constructs new long bits.
* @classdesc Helper class for working with the low and high bits of a 64 bit value.
* @memberof util
* @constructor
* @param {number} lo Low 32 bits, unsigned
* @param {number} hi High 32 bits, unsigned
*/
function LongBits(lo, hi) {
// note that the casts below are theoretically unnecessary as of today, but older statically
// generated converter code might still call the ctor with signed 32bits. kept for compat.
/**
* Low bits.
* @type {number}
*/
this.lo = lo >>> 0;
/**
* High bits.
* @type {number}
*/
this.hi = hi >>> 0;
}
/**
* Zero bits.
* @memberof util.LongBits
* @type {util.LongBits}
*/
var zero = LongBits.zero = new LongBits(0, 0);
zero.toNumber = function() { return 0; };
zero.zzEncode = zero.zzDecode = function() { return this; };
zero.length = function() { return 1; };
/**
* Zero hash.
* @memberof util.LongBits
* @type {string}
*/
var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0";
/**
* Constructs new long bits from the specified number.
* @param {number} value Value
* @returns {util.LongBits} Instance
*/
LongBits.fromNumber = function fromNumber(value) {
if (value === 0)
return zero;
var sign = value < 0;
if (sign)
value = -value;
var lo = value >>> 0,
hi = (value - lo) / 4294967296 >>> 0;
if (sign) {
hi = ~hi >>> 0;
lo = ~lo >>> 0;
if (++lo > 4294967295) {
lo = 0;
if (++hi > 4294967295)
hi = 0;
}
}
return new LongBits(lo, hi);
};
/**
* Constructs new long bits from a number, long or string.
* @param {Long|number|string} value Value
* @returns {util.LongBits} Instance
*/
LongBits.from = function from(value) {
if (typeof value === "number")
return LongBits.fromNumber(value);
if (util.isString(value)) {
/* istanbul ignore else */
if (util.Long)
value = util.Long.fromString(value);
else
return LongBits.fromNumber(parseInt(value, 10));
}
return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;
};
/**
* Converts this long bits to a possibly unsafe JavaScript number.
* @param {boolean} [unsigned=false] Whether unsigned or not
* @returns {number} Possibly unsafe number
*/
LongBits.prototype.toNumber = function toNumber(unsigned) {
if (!unsigned && this.hi >>> 31) {
var lo = ~this.lo + 1 >>> 0,
hi = ~this.hi >>> 0;
if (!lo)
hi = hi + 1 >>> 0;
return -(lo + hi * 4294967296);
}
return this.lo + this.hi * 4294967296;
};
/**
* Converts this long bits to a long.
* @param {boolean} [unsigned=false] Whether unsigned or not
* @returns {Long} Long
*/
LongBits.prototype.toLong = function toLong(unsigned) {
return util.Long
? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))
/* istanbul ignore next */
: { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };
};
var charCodeAt = String.prototype.charCodeAt;
/**
* Constructs new long bits from the specified 8 characters long hash.
* @param {string} hash Hash
* @returns {util.LongBits} Bits
*/
LongBits.fromHash = function fromHash(hash) {
if (hash === zeroHash)
return zero;
return new LongBits(
( charCodeAt.call(hash, 0)
| charCodeAt.call(hash, 1) << 8
| charCodeAt.call(hash, 2) << 16
| charCodeAt.call(hash, 3) << 24) >>> 0
,
( charCodeAt.call(hash, 4)
| charCodeAt.call(hash, 5) << 8
| charCodeAt.call(hash, 6) << 16
| charCodeAt.call(hash, 7) << 24) >>> 0
);
};
/**
* Converts this long bits to a 8 characters long hash.
* @returns {string} Hash
*/
LongBits.prototype.toHash = function toHash() {
return String.fromCharCode(
this.lo & 255,
this.lo >>> 8 & 255,
this.lo >>> 16 & 255,
this.lo >>> 24 ,
this.hi & 255,
this.hi >>> 8 & 255,
this.hi >>> 16 & 255,
this.hi >>> 24
);
};
/**
* Zig-zag encodes this long bits.
* @returns {util.LongBits} `this`
*/
LongBits.prototype.zzEncode = function zzEncode() {
var mask = this.hi >> 31;
this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;
this.lo = ( this.lo << 1 ^ mask) >>> 0;
return this;
};
/**
* Zig-zag decodes this long bits.
* @returns {util.LongBits} `this`
*/
LongBits.prototype.zzDecode = function zzDecode() {
var mask = -(this.lo & 1);
this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;
this.hi = ( this.hi >>> 1 ^ mask) >>> 0;
return this;
};
/**
* Calculates the length of this longbits when encoded as a varint.
* @returns {number} Length
*/
LongBits.prototype.length = function length() {
var part0 = this.lo,
part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,
part2 = this.hi >>> 24;
return part2 === 0
? part1 === 0
? part0 < 16384
? part0 < 128 ? 1 : 2
: part0 < 2097152 ? 3 : 4
: part1 < 16384
? part1 < 128 ? 5 : 6
: part1 < 2097152 ? 7 : 8
: part2 < 128 ? 9 : 10;
};
return longbits;
}
var umd$1 = {exports: {}};
var umd = umd$1.exports;
var hasRequiredUmd;
function requireUmd () {
if (hasRequiredUmd) return umd$1.exports;
hasRequiredUmd = 1;
(function (module, exports) {
// GENERATED FILE. DO NOT EDIT.
(function (global, factory) {
function preferDefault(exports) {
return exports.default || exports;
}
{
factory(exports);
module.exports = preferDefault(exports);
}
})(
typeof globalThis !== "undefined"
? globalThis
: typeof self !== "undefined"
? self
: umd,
function (_exports) {
Object.defineProperty(_exports, "__esModule", {
value: true,
});
_exports.default = void 0;
/**
* @license
* Copyright 2009 The Closure Library Authors
* Copyright 2020 Daniel Wirtz / The long.js Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
// WebAssembly optimizations to do native i64 multiplication and divide
var wasm = null;
try {
wasm = new WebAssembly.Instance(
new WebAssembly.Module(
new Uint8Array([
// \0asm
0, 97, 115, 109,
// version 1
1, 0, 0, 0,
// section "type"
1, 13, 2,
// 0, () => i32
96, 0, 1, 127,
// 1, (i32, i32, i32, i32) => i32
96, 4, 127, 127, 127, 127, 1, 127,
// section "function"
3, 7, 6,
// 0, type 0
0,
// 1, type 1
1,
// 2, type 1
1,
// 3, type 1
1,
// 4, type 1
1,
// 5, type 1
1,
// section "global"
6, 6, 1,
// 0, "high", mutable i32
127, 1, 65, 0, 11,
// section "export"
7, 50, 6,
// 0, "mul"
3, 109, 117, 108, 0, 1,
// 1, "div_s"
5, 100, 105, 118, 95, 115, 0, 2,
// 2, "div_u"
5, 100, 105, 118, 95, 117, 0, 3,
// 3, "rem_s"
5, 114, 101, 109, 95, 115, 0, 4,
// 4, "rem_u"
5, 114, 101, 109, 95, 117, 0, 5,
// 5, "get_high"
8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0,
// section "code"
10, 191, 1, 6,
// 0, "get_high"
4, 0, 35, 0, 11,
// 1, "mul"
36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173,
32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0,
32, 4, 167, 11,
// 2, "div_s"
36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173,
32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0,
32, 4, 167, 11,
// 3, "div_u"
36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173,
32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0,
32, 4, 167, 11,
// 4, "rem_s"
36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173,
32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0,
32, 4, 167, 11,
// 5, "rem_u"
36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173,
32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0,
32, 4, 167, 11,
]),
),
{},
).exports;
} catch {
// no wasm support :(
}
/**
* Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
* See the from* functions below for more convenient ways of constructing Longs.
* @exports Long
* @class A Long class for representing a 64 bit two's-complement integer value.
* @param {number} low The low (signed) 32 bits of the long
* @param {number} high The high (signed) 32 bits of the long
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @constructor
*/
function Long(low, high, unsigned) {
/**
* The low 32 bits as a signed value.
* @type {number}
*/
this.low = low | 0;
/**
* The high 32 bits as a signed value.
* @type {number}
*/
this.high = high | 0;
/**
* Whether unsigned or not.
* @type {boolean}
*/
this.unsigned = !!unsigned;
}
// The internal representation of a long is the two given signed, 32-bit values.
// We use 32-bit pieces because these are the size of integers on which
// Javascript performs bit-operations. For operations like addition and
// multiplication, we split each number into 16 bit pieces, which can easily be
// multiplied within Javascript's floating-point representation without overflow
// or change in sign.
//
// In the algorithms below, we frequently reduce the negative case to the
// positive case by negating the input(s) and then post-processing the result.
// Note that we must ALWAYS check specially whether those values are MIN_VALUE
// (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
// a positive number, it overflows back into a negative). Not handling this
// case would often result in infinite recursion.
//
// Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
// methods on which they depend.
/**
* An indicator used to reliably determine if an object is a Long or not.
* @type {boolean}
* @const
* @private
*/
Long.prototype.__isLong__;
Object.defineProperty(Long.prototype, "__isLong__", {
value: true,
});
/**
* @function
* @param {*} obj Object
* @returns {boolean}
* @inner
*/
function isLong(obj) {
return (obj && obj["__isLong__"]) === true;
}
/**
* @function
* @param {*} value number
* @returns {number}
* @inner
*/
function ctz32(value) {
var c = Math.clz32(value & -value);
return value ? 31 - c : c;
}
/**
* Tests if the specified object is a Long.
* @function
* @param {*} obj Object
* @returns {boolean}
*/
Long.isLong = isLong;
/**
* A cache of the Long representations of small integer values.
* @type {!Object}
* @inner
*/
var INT_CACHE = {};
/**
* A cache of the Long representations of small unsigned integer values.
* @type {!Object}
* @inner
*/
var UINT_CACHE = {};
/**
* @param {number} value
* @param {boolean=} unsigned
* @returns {!Long}
* @inner
*/
function fromInt(value, unsigned) {
var obj, cachedObj, cache;
if (unsigned) {
value >>>= 0;
if ((cache = 0 <= value && value < 256)) {
cachedObj = UINT_CACHE[value];
if (cachedObj) return cachedObj;
}
obj = fromBits(value, 0, true);
if (cache) UINT_CACHE[value] = obj;
return obj;
} else {
value |= 0;
if ((cache = -128 <= value && value < 128)) {
cachedObj = INT_CACHE[value];
if (cachedObj) return cachedObj;
}
obj = fromBits(value, value < 0 ? -1 : 0, false);
if (cache) INT_CACHE[value] = obj;
return obj;
}
}
/**
* Returns a Long representing the given 32 bit integer value.
* @function
* @param {number} value The 32 bit integer in question
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {!Long} The corresponding Long value
*/
Long.fromInt = fromInt;
/**
* @param {number} value
* @param {boolean=} unsigned
* @returns {!Long}
* @inner
*/
function fromNumber(value, unsigned) {
if (isNaN(value)) return unsigned ? UZERO : ZERO;
if (unsigned) {
if (value < 0) return UZERO;
if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE;
} else {
if (value <= -TWO_PWR_63_DBL) return MIN_VALUE;
if (value + 1 >= TWO_PWR_63_DBL) return MAX_VALUE;
}
if (value < 0) return fromNumber(-value, unsigned).neg();
return fromBits(
value % TWO_PWR_32_DBL | 0,
(value / TWO_PWR_32_DBL) | 0,
unsigned,
);
}
/**
* Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
* @function
* @param {number} value The number in question
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {!Long} The corresponding Long value
*/
Long.fromNumber = fromNumber;
/**
* @param {number} lowBits
* @param {number} highBits
* @param {boolean=} unsigned
* @returns {!Long}
* @inner
*/
function fromBits(lowBits, highBits, unsigned) {
return new Long(lowBits, highBits, unsigned);
}
/**
* Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
* assumed to use 32 bits.
* @function
* @param {number} lowBits The low 32 bits
* @param {number} highBits The high 32 bits
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {!Long} The corresponding Long value
*/
Long.fromBits = fromBits;
/**
* @function
* @param {number} base
* @param {number} exponent
* @returns {number}
* @inner
*/
var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
/**
* @param {string} str
* @param {(boolean|number)=} unsigned
* @param {number=} radix
* @returns {!Long}
* @inner
*/
function fromString(str, unsigned, radix) {
if (str.length === 0) throw Error("empty string");
if (typeof unsigned === "number") {
// For goog.math.long compatibility
radix = unsigned;
unsigned = false;
} else {
unsigned = !!unsigned;
}
if (
str === "NaN" ||
str === "Infinity" ||
str === "+Infinity" ||
str === "-Infinity"
)
return unsigned ? UZERO : ZERO;
radix = radix || 10;
if (radix < 2 || 36 < radix) throw RangeError("radix");
var p;
if ((p = str.indexOf("-")) > 0) throw Error("interior hyphen");
else if (p === 0) {
return fromString(str.substring(1), unsigned, radix).neg();
}
// Do several (8) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = fromNumber(pow_dbl(radix, 8));
var result = ZERO;
for (var i = 0; i < str.length; i += 8) {
var size = Math.min(8, str.length - i),
value = parseInt(str.substring(i, i + size), radix);
if (size < 8) {
var power = fromNumber(pow_dbl(radix, size));
result = result.mul(power).add(fromNumber(value));
} else {
result = result.mul(radixToPower);
result = result.add(fromNumber(value));
}
}
result.unsigned = unsigned;
return result;
}
/**
* Returns a Long representation of the given string, written using the specified radix.
* @function
* @param {string} str The textual representation of the Long
* @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed
* @param {number=} radix The radix in which the text is written (2-36), defaults to 10
* @returns {!Long} The corresponding Long value
*/
Long.fromString = fromString;
/**
* @function
* @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val
* @param {boolean=} unsigned
* @returns {!Long}
* @inner
*/
function fromValue(val, unsigned) {
if (typeof val === "number") return fromNumber(val, unsigned);
if (typeof val === "string") return fromString(val, unsigned);
// Throws for non-objects, converts non-instanceof Long:
return fromBits(
val.low,
val.high,
typeof unsigned === "boolean" ? unsigned : val.unsigned,
);
}
/**
* Converts the specified value to a Long using the appropriate from* function for its type.
* @function
* @param {!Long|number|bigint|string|!{low: number, high: number, unsigned: boolean}} val Value
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {!Long}
*/
Long.fromValue = fromValue;
// NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
// no runtime penalty for these.
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_16_DBL = 1 << 16;
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_24_DBL = 1 << 24;
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
/**
* @type {!Long}
* @const
* @inner
*/
var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
/**
* @type {!Long}
* @inner
*/
var ZERO = fromInt(0);
/**
* Signed zero.
* @type {!Long}
*/
Long.ZERO = ZERO;
/**
* @type {!Long}
* @inner
*/
var UZERO = fromInt(0, true);
/**
* Unsigned zero.
* @type {!Long}
*/
Long.UZERO = UZERO;
/**
* @type {!Long}
* @inner
*/
var ONE = fromInt(1);
/**
* Signed one.
* @type {!Long}
*/
Long.ONE = ONE;
/**
* @type {!Long}
* @inner
*/
var UONE = fromInt(1, true);
/**
* Unsigned one.
* @type {!Long}
*/
Long.UONE = UONE;
/**
* @type {!Long}
* @inner
*/
var NEG_ONE = fromInt(-1);
/**
* Signed negative one.
* @type {!Long}
*/
Long.NEG_ONE = NEG_ONE;
/**
* @type {!Long}
* @inner
*/
var MAX_VALUE = fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
/**
* Maximum signed value.
* @type {!Long}
*/
Long.MAX_VALUE = MAX_VALUE;
/**
* @type {!Long}
* @inner
*/
var MAX_UNSIGNED_VALUE = fromBits(0xffffffff | 0, 0xffffffff | 0, true);
/**
* Maximum unsigned value.
* @type {!Long}
*/
Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
/**
* @type {!Long}
* @inner
*/
var MIN_VALUE = fromBits(0, 0x80000000 | 0, false);
/**
* Minimum signed value.
* @type {!Long}
*/
Long.MIN_VALUE = MIN_VALUE;
/**
* @alias Long.prototype
* @inner
*/
var LongPrototype = Long.prototype;
/**
* Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
* @this {!Long}
* @returns {number}
*/
LongPrototype.toInt = function toInt() {
return this.unsigned ? this.low >>> 0 : this.low;
};
/**
* Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
* @this {!Long}
* @returns {number}
*/
LongPrototype.toNumber = function toNumber() {
if (this.unsigned)
return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
};
/**
* Converts the Long to a string written in the specified radix.
* @this {!Long}
* @param {number=} radix Radix (2-36), defaults to 10
* @returns {string}
* @override
* @throws {RangeError} If `radix` is out of range
*/
LongPrototype.toString = function toString(radix) {
radix = radix || 10;
if (radix < 2 || 36 < radix) throw RangeError("radix");
if (this.isZero()) return "0";
if (this.isNegative()) {
// Unsigned Longs are never negative
if (this.eq(MIN_VALUE)) {
// We need to change the Long value before it can be negated, so we remove
// the bottom-most digit in this base and then recurse to do the rest.
var radixLong = fromNumber(radix),
div = this.div(radixLong),
rem1 = div.mul(radixLong).sub(this);
return div.toString(radix) + rem1.toInt().toString(radix);
} else return "-" + this.neg().toString(radix);
}
// Do several (6) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
rem = this;
var result = "";
while (true) {
var remDiv = rem.div(radixToPower),
intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
digits = intval.toString(radix);
rem = remDiv;
if (rem.isZero()) return digits + result;
else {
while (digits.length < 6) digits = "0" + digits;
result = "" + digits + result;
}
}
};
/**
* Gets the high 32 bits as a signed integer.
* @this {!Long}
* @returns {number} Signed high bits
*/
LongPrototype.getHighBits = function getHighBits() {
return this.high;
};
/**
* Gets the high 32 bits as an unsigned integer.
* @this {!Long}
* @returns {number} Unsigned high bits
*/
LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
return this.high >>> 0;
};
/**
* Gets the low 32 bits as a signed integer.
* @this {!Long}
* @returns {number} Signed low bits
*/
LongPrototype.getLowBits = function getLowBits() {
return this.low;
};
/**
* Gets the low 32 bits as an unsigned integer.
* @this {!Long}
* @returns {number} Unsigned low bits
*/
LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
return this.low >>> 0;
};
/**
* Gets the number of bits needed to represent the absolute value of this Long.
* @this {!Long}
* @returns {number}
*/
LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
if (this.isNegative())
// Unsigned Longs are never negative
return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
var val = this.high != 0 ? this.high : this.low;
for (var bit = 31; bit > 0; bit--) if ((val & (1 << bit)) != 0) break;
return this.high != 0 ? bit + 33 : bit + 1;
};
/**
* Tests if this Long can be safely represented as a JavaScript number.
* @this {!Long}
* @returns {boolean}
*/
LongPrototype.isSafeInteger = function isSafeInteger() {
// 2^53-1 is the maximum safe value
var top11Bits = this.high >> 21;
// [0, 2^53-1]
if (!top11Bits) return true;
// > 2^53-1
if (this.unsigned) return false;
// [-2^53, -1] except -2^53
return top11Bits === -1 && !(this.low === 0 && this.high === -2097152);
};
/**
* Tests if this Long's value equals zero.
* @this {!Long}
* @returns {boolean}
*/
LongPrototype.isZero = function isZero() {
return this.high === 0 && this.low === 0;
};
/**
* Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}.
* @returns {boolean}
*/
LongPrototype.eqz = LongPrototype.isZero;
/**
* Tests if this Long's value is negative.
* @this {!Long}
* @returns {boolean}
*/
LongPrototype.isNegative = function isNegative() {
return !this.unsigned && this.high < 0;
};
/**
* Tests if this Long's value is positive or zero.
* @this {!Long}
* @returns {boolean}
*/
LongPrototype.isPositive = function isPositive() {
return this.unsigned || this.high >= 0;
};
/**
* Tests if this Long's value is odd.
* @this {!Long}
* @returns {boolean}
*/
LongPrototype.isOdd = function isOdd() {
return (this.low & 1) === 1;
};
/**
* Tests if this Long's value is even.
* @this {!Long}
* @returns {boolean}
*/
LongPrototype.isEven = function isEven() {
return (this.low & 1) === 0;
};
/**
* Tests if this Long's value equals the specified's.
* @this {!Long}
* @param {!Long|number|bigint|string} other Other value
* @returns {boolean}
*/
LongPrototype.equals = function equals(other) {
if (!isLong(other)) other = fromValue(other);
if (
this.unsigned !== other.unsigned &&
this.high >>> 31 === 1 &&
other.high >>> 31 === 1
)
return false;
return this.high === other.high && this.low === other.low;
};
/**
* Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
* @function
* @param {!Long|number|bigint|string} other Other value
* @returns {boolean}
*/
LongPrototype.eq = LongPrototype.equals;
/**
* Tests if this Long's value differs from the specified's.
* @this {!Long}
* @param {!Long|number|bigint|string} other Other value
* @returns {boolean}
*/
LongPrototype.notEquals = function notEquals(other) {
return !this.eq(/* validates */ other);
};
/**
* Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
* @function
* @param {!Long|number|bigint|string} other Other value
* @returns {boolean}
*/
LongPrototype.neq = LongPrototype.notEquals;
/**
* Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
* @function
* @param {!Long|number|bigint|string} other Other value
* @returns {boolean}
*/
LongPrototype.ne = LongPrototype.notEquals;
/**
* Tests if this Long's value is less than the specified's.
* @this {!Long}
* @param {!Long|number|bigint|string} other Other value
* @returns {boolean}
*/
LongPrototype.lessThan = function lessThan(other) {
return this.comp(/* validates */ other) < 0;
};
/**
* Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
* @function
* @param {!Long|number|bigint|string} other Other value
* @returns {boolean}
*/
LongPrototype.lt = LongPrototype.lessThan;
/**
* Tests if this Long's value is less than or equal the specified's.
* @this {!Long}
* @param {!Long|number|bigint|string} other Other value
* @returns {boolean}
*/
LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
return this.comp(/* validates */ other) <= 0;
};
/**
* Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
* @function
* @param {!Long|number|bigint|string} other Other value
* @returns {boolean}
*/
LongPrototype.lte = LongPrototype.lessThanOrEqual;
/**
* Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
* @function
* @param {!Long|number|bigint|string} other Other value
* @returns {boolean}
*/
LongPrototype.le = LongPrototype.lessThanOrEqual;
/**
* Tests if this Long's value is greater than the specified's.
* @this {!Long}
* @param {!Long|number|bigint|string} other Other value
* @returns {boolean}
*/
LongPrototype.greaterThan = function greaterThan(other) {
return this.comp(/* validates */ other) > 0;
};
/**
* Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
* @function
* @param {!Long|number|bigint|string} other Other value
* @returns {boolean}
*/
LongPrototype.gt = LongPrototype.greaterThan;
/**
* Tests if this Long's value is greater than or equal the specified's.
* @this {!Long}
* @param {!Long|number|bigint|string} other Other value
* @returns {boolean}
*/
LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
return this.comp(/* validates */ other) >= 0;
};
/**
* Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
* @function
* @param {!Long|number|bigint|string} other Other value
* @returns {boolean}
*/
LongPrototype.gte = LongPrototype.greaterThanOrEqual;
/**
* Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
* @function
* @param {!Long|number|bigint|string} other Other value
* @returns {boolean}
*/
LongPrototype.ge = LongPrototype.greaterThanOrEqual;
/**
* Compares this Long's value with the specified's.
* @this {!Long}
* @param {!Long|number|bigint|string} other Other value
* @returns {number} 0 if they are the same, 1 if the this is greater and -1
* if the given one is greater
*/
LongPrototype.compare = function compare(other) {
if (!isLong(other)) other = fromValue(other);
if (this.eq(other)) return 0;
var thisNeg = this.isNegative(),
otherNeg = other.isNegative();
if (thisNeg && !otherNeg) return -1;
if (!thisNeg && otherNeg) return 1;
// At this point the sign bits are the same
if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1;
// Both are positive if at least one is unsigned
return other.high >>> 0 > this.high >>> 0 ||
(other.high === this.high && other.low >>> 0 > this.low >>> 0)
? -1
: 1;
};
/**
* Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
* @function
* @param {!Long|number|bigint|string} other Other value
* @returns {number} 0 if they are the same, 1 if the this is greater and -1
* if the given one is greater
*/
LongPrototype.comp = LongPrototype.compare;
/**
* Negates this Long's value.
* @this {!Long}
* @returns {!Long} Negated Long
*/
LongPrototype.negate = function negate() {
if (!this.unsigned && this.eq(MIN_VALUE)) return MIN_VALUE;
return this.not().add(ONE);
};
/**
* Negates this Long's value. This is an alias of {@link Long#negate}.
* @function
* @returns {!Long} Negated Long
*/
LongPrototype.neg = LongPrototype.negate;
/**
* Returns the sum of this and the specified Long.
* @this {!Long}
* @param {!Long|number|bigint|string} addend Addend
* @returns {!Long} Sum
*/
LongPrototype.add = function add(addend) {
if (!isLong(addend)) addend = fromValue(addend);
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
var a48 = this.high >>> 16;
var a32 = this.high & 0xffff;
var a16 = this.low >>> 16;
var a00 = this.low & 0xffff;
var b48 = addend.high >>> 16;
var b32 = addend.high & 0xffff;
var b16 = addend.low >>> 16;
var b00 = addend.low & 0xffff;
var c48 = 0,
c32 = 0,
c16 = 0,
c00 = 0;
c00 += a00 + b00;
c16 += c00 >>> 16;
c00 &= 0xffff;
c16 += a16 + b16;
c32 += c16 >>> 16;
c16 &= 0xffff;
c32 += a32 + b32;
c48 += c32 >>> 16;
c32 &= 0xffff;
c48 += a48 + b48;
c48 &= 0xffff;
return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
};
/**
* Returns the difference of this and the specified Long.
* @this {!Long}
* @param {!Long|number|bigint|string} subtrahend Subtrahend
* @returns {!Long} Difference
*/
LongPrototype.subtract = function subtract(subtrahend) {
if (!isLong(subtrahend)) subtrahend = fromValue(subtrahend);
return this.add(subtrahend.neg());
};
/**
* Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
* @function
* @param {!Long|number|bigint|string} subtrahend Subtrahend
* @returns {!Long} Difference
*/
LongPrototype.sub = LongPrototype.subtract;
/**
* Returns the product of this and the specified Long.
* @this {!Long}
* @param {!Long|number|bigint|string} multiplier Multiplier
* @returns {!Long} Product
*/
LongPrototype.multiply = function multiply(multiplier) {
if (this.isZero()) return this;
if (!isLong(multiplier)) multiplier = fromValue(multiplier);
// use wasm support if present
if (wasm) {
var low = wasm["mul"](
this.low,
this.high,
multiplier.low,
multiplier.high,
);
return fromBits(low, wasm["get_high"](), this.unsigned);
}
if (multiplier.isZero()) return this.unsigned ? UZERO : ZERO;
if (this.eq(MIN_VALUE)) return multiplier.isOdd() ? MIN_VALUE : ZERO;
if (multiplier.eq(MIN_VALUE)) return this.isOdd() ? MIN_VALUE : ZERO;
if (this.isNegative()) {
if (multiplier.isNegative()) return this.neg().mul(multiplier.neg());
else return this.neg().mul(multiplier).neg();
} else if (multiplier.isNegative())
return this.mul(multiplier.neg()).neg();
// If both longs are small, use float multiplication
if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
return fromNumber(
this.toNumber() * multiplier.toNumber(),
this.unsigned,
);
// Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
// We can skip products that would overflow.
var a48 = this.high >>> 16;
var a32 = this.high & 0xffff;
var a16 = this.low >>> 16;
var a00 = this.low & 0xffff;
var b48 = multiplier.high >>> 16;
var b32 = multiplier.high & 0xffff;
var b16 = multiplier.low >>> 16;
var b00 = multiplier.low & 0xffff;
var c48 = 0,
c32 = 0,
c16 = 0,
c00 = 0;
c00 += a00 * b00;
c16 += c00 >>> 16;
c00 &= 0xffff;
c16 += a16 * b00;
c32 += c16 >>> 16;
c16 &= 0xffff;
c16 += a00 * b16;
c32 += c16 >>> 16;
c16 &= 0xffff;
c32 += a32 * b00;
c48 += c32 >>> 16;
c32 &= 0xffff;
c32 += a16 * b16;
c48 += c32 >>> 16;
c32 &= 0xffff;
c32 += a00 * b32;
c48 += c32 >>> 16;
c32 &= 0xffff;
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
c48 &= 0xffff;
return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
};
/**
* Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
* @function
* @param {!Long|number|bigint|string} multiplier Multiplier
* @returns {!Long} Product
*/
LongPrototype.mul = LongPrototype.multiply;
/**
* Returns this Long divided by the specified. The result is signed if this Long is signed or
* unsigned if this Long is unsigned.
* @this {!Long}
* @param {!Long|number|bigint|string} divisor Divisor
* @returns {!Long} Quotient
*/
LongPrototype.divide = function divide(divisor) {
if (!isLong(divisor)) divisor = fromValue(divisor);
if (divisor.isZero()) throw Error("division by zero");
// use wasm support if present
if (wasm) {
// guard against signed division overflow: the largest
// negative number / -1 would be 1 larger than the largest
// positive number, due to two's complement.
if (
!this.unsigned &&
this.high === -2147483648 &&
divisor.low === -1 &&
divisor.high === -1
) {
// be consistent with non-wasm code path
return this;
}
var low = (this.unsigned ? wasm["div_u"] : wasm["div_s"])(
this.low,
this.high,
divisor.low,
divisor.high,
);
return fromBits(low, wasm["get_high"](), this.unsigned);
}
if (this.isZero()) return this.unsigned ? UZERO : ZERO;
var approx, rem, res;
if (!this.unsigned) {
// This section is only relevant for signed longs and is derived from the
// closure library as a whole.
if (this.eq(MIN_VALUE)) {
if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
else if (divisor.eq(MIN_VALUE)) return ONE;
else {
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
var halfThis = this.shr(1);
approx = halfThis.div(divisor).shl(1);
if (approx.eq(ZERO)) {
return divisor.isNegative() ? ONE : NEG_ONE;
} else {
rem = this.sub(divisor.mul(approx));
res = approx.add(rem.div(divisor));
return res;
}
}
} else if (divisor.eq(MIN_VALUE)) return this.unsigned ? UZERO : ZERO;
if (this.isNegative()) {
if (divisor.isNegative()) return this.neg().div(divisor.neg());
return this.neg().div(divisor).neg();
} else if (divisor.isNegative()) return this.div(divisor.neg()).neg();
res = ZERO;
} else {
// The algorithm below has not been made for unsigned longs. It's therefore
// required to take special care of the MSB prior to running it.
if (!divisor.unsigned) divisor = divisor.toUnsigned();
if (divisor.gt(this)) return UZERO;
if (divisor.gt(this.shru(1)))
// 15 >>> 1 = 7 ; with divisor = 8 ; true
return UONE;
res = UZERO;
}
// Repeat the following until the remainder is less than other: find a
// floating-point that approximates remainder / other *from below*, add this
// into the result, and subtract it from the remainder. It is critical that
// the approximate value is less than or equal to the real value so that the
// remainder never becomes negative.
rem = this;
while (rem.gte(divisor)) {
// Approximate the result of division. This may be a little greater or
// smaller than the actual value.
approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
// We will tweak the approximate result by changing it in the 48-th digit or
// the smallest non-fractional digit, whichever is larger.
var log2 = Math.ceil(Math.log(approx) / Math.LN2),
delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48),
// Decrease the approximation until it is smaller than the remainder. Note
// that if it is too large, the product overflows and is negative.
approxRes = fromNumber(approx),
approxRem = approxRes.mul(divisor);
while (approxRem.isNegative() || approxRem.gt(rem)) {
approx -= delta;
approxRes = fromNumber(approx, this.unsigned);
approxRem = approxRes.mul(divisor);
}
// We know the answer can't be zero... and actually, zero would cause
// infinite recursion since we would make no progress.
if (approxRes.isZero()) approxRes = ONE;
res = res.add(approxRes);
rem = rem.sub(approxRem);
}
return res;
};
/**
* Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
* @function
* @param {!Long|number|bigint|string} divisor Divisor
* @returns {!Long} Quotient
*/
LongPrototype.div = LongPrototype.divide;
/**
* Returns this Long modulo the specified.
* @this {!Long}
* @param {!Long|number|bigint|string} divisor Divisor
* @returns {!Long} Remainder
*/
LongPrototype.modulo = function modulo(divisor) {
if (!isLong(divisor)) divisor = fromValue(divisor);
// use wasm support if present
if (wasm) {
var low = (this.unsigned ? wasm["rem_u"] : wasm["rem_s"])(
this.low,
this.high,
divisor.low,
divisor.high,
);
return fromBits(low, wasm["get_high"](), this.unsigned);
}
return this.sub(this.div(divisor).mul(divisor));
};
/**
* Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
* @function
* @param {!Long|number|bigint|string} divisor Divisor
* @returns {!Long} Remainder
*/
LongPrototype.mod = LongPrototype.modulo;
/**
* Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
* @function
* @param {!Long|number|bigint|string} divisor Divisor
* @returns {!Long} Remainder
*/
LongPrototype.rem = LongPrototype.modulo;
/**
* Returns the bitwise NOT of this Long.
* @this {!Long}
* @returns {!Long}
*/
LongPrototype.not = function not() {
return fromBits(~this.low, ~this.high, this.unsigned);
};
/**
* Returns count leading zeros of this Long.
* @this {!Long}
* @returns {!number}
*/
LongPrototype.countLeadingZeros = function countLeadingZeros() {
return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32;
};
/**
* Returns count leading zeros. This is an alias of {@link Long#countLeadingZeros}.
* @function
* @param {!Long}
* @returns {!number}
*/
LongPrototype.clz = LongPrototype.countLeadingZeros;
/**
* Returns count trailing zeros of this Long.
* @this {!Long}
* @returns {!number}
*/
LongPrototype.countTrailingZeros = function countTrailingZeros() {
return this.low ? ctz32(this.low) : ctz32(this.high) + 32;
};
/**
* Returns count trailing zeros. This is an alias of {@link Long#countTrailingZeros}.
* @function
* @param {!Long}
* @returns {!number}
*/
LongPrototype.ctz = LongPrototype.countTrailingZeros;
/**
* Returns the bitwise AND of this Long and the specified.
* @this {!Long}
* @param {!Long|number|bigint|string} other Other Long
* @returns {!Long}
*/
LongPrototype.and = function and(other) {
if (!isLong(other)) other = fromValue(other);
return fromBits(
this.low & other.low,
this.high & other.high,
this.unsigned,
);
};
/**
* Returns the bitwise OR of this Long and the specified.
* @this {!Long}
* @param {!Long|number|bigint|string} other Other Long
* @returns {!Long}
*/
LongPrototype.or = function or(other) {
if (!isLong(other)) other = fromValue(other);
return fromBits(
this.low | other.low,
this.high | other.high,
this.unsigned,
);
};
/**
* Returns the bitwise XOR of this Long and the given one.
* @this {!Long}
* @param {!Long|number|bigint|string} other Other Long
* @returns {!Long}
*/
LongPrototype.xor = function xor(other) {
if (!isLong(other)) other = fromValue(other);
return fromBits(
this.low ^ other.low,
this.high ^ other.high,
this.unsigned,
);
};
/**
* Returns this Long with bits shifted to the left by the given amount.
* @this {!Long}
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
*/
LongPrototype.shiftLeft = function shiftLeft(numBits) {
if (isLong(numBits)) numBits = numBits.toInt();
if ((numBits &= 63) === 0) return this;
else if (numBits < 32)
return fromBits(
this.low << numBits,
(this.high << numBits) | (this.low >>> (32 - numBits)),
this.unsigned,
);
else return fromBits(0, this.low << (numBits - 32), this.unsigned);
};
/**
* Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
* @function
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
*/
LongPrototype.shl = LongPrototype.shiftLeft;
/**
* Returns this Long with bits arithmetically shifted to the right by the given amount.
* @this {!Long}
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
*/
LongPrototype.shiftRight = function shiftRight(numBits) {
if (isLong(numBits)) numBits = numBits.toInt();
if ((numBits &= 63) === 0) return this;
else if (numBits < 32)
return fromBits(
(this.low >>> numBits) | (this.high << (32 - numBits)),
this.high >> numBits,
this.unsigned,
);
else
return fromBits(
this.high >> (numBits - 32),
this.high >= 0 ? 0 : -1,
this.unsigned,
);
};
/**
* Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
* @function
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
*/
LongPrototype.shr = LongPrototype.shiftRight;
/**
* Returns this Long with bits logically shifted to the right by the given amount.
* @this {!Long}
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
*/
LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
if (isLong(numBits)) numBits = numBits.toInt();
if ((numBits &= 63) === 0) return this;
if (numBits < 32)
return fromBits(
(this.low >>> numBits) | (this.high << (32 - numBits)),
this.high >>> numBits,
this.unsigned,
);
if (numBits === 32) return fromBits(this.high, 0, this.unsigned);
return fromBits(this.high >>> (numBits - 32), 0, this.unsigned);
};
/**
* Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
* @function
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
*/
LongPrototype.shru = LongPrototype.shiftRightUnsigned;
/**
* Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
* @function
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
*/
LongPrototype.shr_u = LongPrototype.shiftRightUnsigned;
/**
* Returns this Long with bits rotated to the left by the given amount.
* @this {!Long}
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Rotated Long
*/
LongPrototype.rotateLeft = function rotateLeft(numBits) {
var b;
if (isLong(numBits)) numBits = numBits.toInt();
if ((numBits &= 63) === 0) return this;
if (numBits === 32) return fromBits(this.high, this.low, this.unsigned);
if (numBits < 32) {
b = 32 - numBits;
return fromBits(
(this.low << numBits) | (this.high >>> b),
(this.high << numBits) | (this.low >>> b),
this.unsigned,
);
}
numBits -= 32;
b = 32 - numBits;
return fromBits(
(this.high << numBits) | (this.low >>> b),
(this.low << numBits) | (this.high >>> b),
this.unsigned,
);
};
/**
* Returns this Long with bits rotated to the left by the given amount. This is an alias of {@link Long#rotateLeft}.
* @function
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Rotated Long
*/
LongPrototype.rotl = LongPrototype.rotateLeft;
/**
* Returns this Long with bits rotated to the right by the given amount.
* @this {!Long}
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Rotated Long
*/
LongPrototype.rotateRight = function rotateRight(numBits) {
var b;
if (isLong(numBits)) numBits = numBits.toInt();
if ((numBits &= 63) === 0) return this;
if (numBits === 32) return fromBits(this.high, this.low, this.unsigned);
if (numBits < 32) {
b = 32 - numBits;
return fromBits(
(this.high << b) | (this.low >>> numBits),
(this.low << b) | (this.high >>> numBits),
this.unsigned,
);
}
numBits -= 32;
b = 32 - numBits;
return fromBits(
(this.low << b) | (this.high >>> numBits),
(this.high << b) | (this.low >>> numBits),
this.unsigned,
);
};
/**
* Returns this Long with bits rotated to the right by the given amount. This is an alias of {@link Long#rotateRight}.
* @function
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Rotated Long
*/
LongPrototype.rotr = LongPrototype.rotateRight;
/**
* Converts this Long to signed.
* @this {!Long}
* @returns {!Long} Signed long
*/
LongPrototype.toSigned = function toSigned() {
if (!this.unsigned) return this;
return fromBits(this.low, this.high, false);
};
/**
* Converts this Long to unsigned.
* @this {!Long}
* @returns {!Long} Unsigned long
*/
LongPrototype.toUnsigned = function toUnsigned() {
if (this.unsigned) return this;
return fromBits(this.low, this.high, true);
};
/**
* Converts this Long to its byte representation.
* @param {boolean=} le Whether little or big endian, defaults to big endian
* @this {!Long}
* @returns {!Array.<number>} Byte representation
*/
LongPrototype.toBytes = function toBytes(le) {
return le ? this.toBytesLE() : this.toBytesBE();
};
/**
* Converts this Long to its little endian byte representation.
* @this {!Long}
* @returns {!Array.<number>} Little endian byte representation
*/
LongPrototype.toBytesLE = function toBytesLE() {
var hi = this.high,
lo = this.low;
return [
lo & 0xff,
(lo >>> 8) & 0xff,
(lo >>> 16) & 0xff,
lo >>> 24,
hi & 0xff,
(hi >>> 8) & 0xff,
(hi >>> 16) & 0xff,
hi >>> 24,
];
};
/**
* Converts this Long to its big endian byte representation.
* @this {!Long}
* @returns {!Array.<number>} Big endian byte representation
*/
LongPrototype.toBytesBE = function toBytesBE() {
var hi = this.high,
lo = this.low;
return [
hi >>> 24,
(hi >>> 16) & 0xff,
(hi >>> 8) & 0xff,
hi & 0xff,
lo >>> 24,
(lo >>> 16) & 0xff,
(lo >>> 8) & 0xff,
lo & 0xff,
];
};
/**
* Creates a Long from its byte representation.
* @param {!Array.<number>} bytes Byte representation
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @param {boolean=} le Whether little or big endian, defaults to big endian
* @returns {Long} The corresponding Long value
*/
Long.fromBytes = function fromBytes(bytes, unsigned, le) {
return le
? Long.fromBytesLE(bytes, unsigned)
: Long.fromBytesBE(bytes, unsigned);
};
/**
* Creates a Long from its little endian byte representation.
* @param {!Array.<number>} bytes Little endian byte representation
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {Long} The corresponding Long value
*/
Long.fromBytesLE = function fromBytesLE(bytes, unsigned) {
return new Long(
bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24),
bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24),
unsigned,
);
};
/**
* Creates a Long from its big endian byte representation.
* @param {!Array.<number>} bytes Big endian byte representation
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {Long} The corresponding Long value
*/
Long.fromBytesBE = function fromBytesBE(bytes, unsigned) {
return new Long(
(bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7],
(bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3],
unsigned,
);
};
// Support conversion to/from BigInt where available
if (typeof BigInt === "function") {
/**
* Returns a Long representing the given big integer.
* @function
* @param {number} value The big integer value
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {!Long} The corresponding Long value
*/
Long.fromBigInt = function fromBigInt(value, unsigned) {
var lowBits = Number(BigInt.asIntN(32, value));
var highBits = Number(BigInt.asIntN(32, value >> BigInt(32)));
return fromBits(lowBits, highBits, unsigned);
};
// Override
Long.fromValue = function fromValueWithBigInt(value, unsigned) {
if (typeof value === "bigint") return Long.fromBigInt(value, unsigned);
return fromValue(value, unsigned);
};
/**
* Converts the Long to its big integer representation.
* @this {!Long}
* @returns {bigint}
*/
LongPrototype.toBigInt = function toBigInt() {
var lowBigInt = BigInt(this.low >>> 0);
var highBigInt = BigInt(this.unsigned ? this.high >>> 0 : this.high);
return (highBigInt << BigInt(32)) | lowBigInt;
};
}
(_exports.default = Long);
},
);
} (umd$1, umd$1.exports));
return umd$1.exports;
}
var hasRequiredMinimal$1;
function requireMinimal$1 () {
if (hasRequiredMinimal$1) return minimal$1;
hasRequiredMinimal$1 = 1;
(function (exports) {
var util = exports;
// used to return a Promise where callback is omitted
util.asPromise = requireAspromise();
// converts to / from base64 encoded strings
util.base64 = requireBase64();
// base class of rpc.Service
util.EventEmitter = requireEventemitter();
// float handling accross browsers
util.float = requireFloat();
// converts to / from utf8 encoded strings
util.utf8 = requireUtf8();
// provides a node-like buffer pool in the browser
util.pool = requirePool();
// utility to work with the low and high bits of a 64 bit value
util.LongBits = requireLongbits();
/**
* Tests if the specified key can affect object prototypes.
* @memberof util
* @param {string} key Key to test
* @returns {boolean} `true` if the key is unsafe
*/
function isUnsafeProperty(key) {
return key === "__proto__" || key === "prototype" || key === "constructor";
}
util.isUnsafeProperty = isUnsafeProperty;
/**
* Whether running within node or not.
* @memberof util
* @type {boolean}
*/
util.isNode = Boolean(typeof commonjsGlobal !== "undefined"
&& commonjsGlobal
&& commonjsGlobal.process
&& commonjsGlobal.process.versions
&& commonjsGlobal.process.versions.node);
/**
* Global object reference.
* @memberof util
* @type {Object}
*/
util.global = util.isNode && commonjsGlobal
|| typeof window !== "undefined" && window
|| typeof self !== "undefined" && self
|| minimal$1; // eslint-disable-line no-invalid-this
/**
* An immuable empty array.
* @memberof util
* @type {Array.<*>}
* @const
*/
util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes
/**
* An immutable empty object.
* @type {Object}
* @const
*/
util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes
/**
* Tests if the specified value is an integer.
* @function
* @param {*} value Value to test
* @returns {boolean} `true` if the value is an integer
*/
util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {
return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
};
/**
* Tests if the specified value is a string.
* @param {*} value Value to test
* @returns {boolean} `true` if the value is a string
*/
util.isString = function isString(value) {
return typeof value === "string" || value instanceof String;
};
/**
* Tests if the specified value is a non-null object.
* @param {*} value Value to test
* @returns {boolean} `true` if the value is a non-null object
*/
util.isObject = function isObject(value) {
return value && typeof value === "object";
};
/**
* Checks if a property on a message is considered to be present.
* This is an alias of {@link util.isSet}.
* @function
* @param {Object} obj Plain object or message instance
* @param {string} prop Property name
* @returns {boolean} `true` if considered to be present, otherwise `false`
*/
util.isset =
/**
* Checks if a property on a message is considered to be present.
* @param {Object} obj Plain object or message instance
* @param {string} prop Property name
* @returns {boolean} `true` if considered to be present, otherwise `false`
*/
util.isSet = function isSet(obj, prop) {
var value = obj[prop];
if (value != null && Object.hasOwnProperty.call(obj, prop)) // eslint-disable-line eqeqeq
return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;
return false;
};
/**
* Any compatible Buffer instance.
* This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.
* @interface Buffer
* @extends Uint8Array
*/
/**
* Node's Buffer class if available.
* @type {Constructor<Buffer>}
*/
util.Buffer = (function() {
try {
var Buffer = util.global.Buffer;
// refuse to use non-node buffers if not explicitly assigned (perf reasons):
return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;
} catch (e) {
/* istanbul ignore next */
return null;
}
})();
// Internal alias of or polyfull for Buffer.from.
util._Buffer_from = null;
// Internal alias of or polyfill for Buffer.allocUnsafe.
util._Buffer_allocUnsafe = null;
/**
* Creates a new buffer of whatever type supported by the environment.
* @param {number|number[]} [sizeOrArray=0] Buffer size or number array
* @returns {Uint8Array|Buffer} Buffer
*/
util.newBuffer = function newBuffer(sizeOrArray) {
/* istanbul ignore next */
return typeof sizeOrArray === "number"
? util.Buffer
? util._Buffer_allocUnsafe(sizeOrArray)
: new util.Array(sizeOrArray)
: util.Buffer
? util._Buffer_from(sizeOrArray)
: typeof Uint8Array === "undefined"
? sizeOrArray
: new Uint8Array(sizeOrArray);
};
/**
* Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.
* @type {Constructor<Uint8Array>}
*/
util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array;
/**
* Any compatible Long instance.
* This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.
* @interface Long
* @property {number} low Low bits
* @property {number} high High bits
* @property {boolean} unsigned Whether unsigned or not
*/
/**
* Long.js's Long class if available.
* @type {Constructor<Long>}
*/
util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long
|| /* istanbul ignore next */ util.global.Long
|| (function() {
try {
var Long = requireUmd();
return Long && Long.isLong ? Long : null;
} catch (e) {
/* istanbul ignore next */
return null;
}
})();
/**
* Regular expression used to verify 2 bit (`bool`) map keys.
* @type {RegExp}
* @const
*/
util.key2Re = /^true|false|0|1$/;
/**
* Regular expression used to verify 32 bit (`int32` etc.) map keys.
* @type {RegExp}
* @const
*/
util.key32Re = /^-?(?:0|[1-9][0-9]*)$/;
/**
* Regular expression used to verify 64 bit (`int64` etc.) map keys.
* @type {RegExp}
* @const
*/
util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;
/**
* Converts a number or long to an 8 characters long hash string.
* @param {Long|number} value Value to convert
* @returns {string} Hash
*/
util.longToHash = function longToHash(value) {
return value
? util.LongBits.from(value).toHash()
: util.LongBits.zeroHash;
};
/**
* Converts an 8 characters long hash string to a long or number.
* @param {string} hash Hash
* @param {boolean} [unsigned=false] Whether unsigned or not
* @returns {Long|number} Original value
*/
util.longFromHash = function longFromHash(hash, unsigned) {
var bits = util.LongBits.fromHash(hash);
if (util.Long)
return util.Long.fromBits(bits.lo, bits.hi, unsigned);
return bits.toNumber(Boolean(unsigned));
};
/**
* Merges the properties of the source object into the destination object.
* @memberof util
* @param {Object.<string,*>} dst Destination object
* @param {...(Object.<string,*>|boolean)} src Source objects, optionally followed by an `ifNotSet` flag
* @returns {Object.<string,*>} Destination object
*/
function merge(dst) { // used by converters
var ifNotSet = typeof arguments[arguments.length - 1] === "boolean",
limit = ifNotSet ? arguments.length - 1 : arguments.length;
ifNotSet = ifNotSet && arguments[arguments.length - 1];
for (var a = 1; a < limit; ++a) {
var src = arguments[a];
if (!src)
continue;
for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)
if (!isUnsafeProperty(keys[i]) && (dst[keys[i]] === undefined || !ifNotSet))
dst[keys[i]] = src[keys[i]];
}
return dst;
}
util.merge = merge;
/**
* Schema declaration nesting limit.
* @memberof util
* @type {number}
*/
util.nestingLimit = 32; // protoc: MaxMessageDeclarationNestingDepth
/**
* Recursion limit.
* @memberof util
* @type {number}
*/
util.recursionLimit = 100; // protoc: CodedInputStream::default_recursion_limit_
/**
* Makes a property safe for assignment as an own property.
* @memberof util
* @param {Object.<string,*>} obj Object
* @param {string} key Property key
* @returns {undefined}
*/
util.makeProp = function makeProp(obj, key) {
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
writable: true
});
};
/**
* Converts the first character of a string to lower case.
* @param {string} str String to convert
* @returns {string} Converted string
*/
util.lcFirst = function lcFirst(str) {
return str.charAt(0).toLowerCase() + str.substring(1);
};
/**
* Creates a custom error constructor.
* @memberof util
* @param {string} name Error name
* @returns {Constructor<Error>} Custom error constructor
*/
function newError(name) {
function CustomError(message, properties) {
if (!(this instanceof CustomError))
return new CustomError(message, properties);
// Error.call(this, message);
// ^ just returns a new error instance because the ctor can be called as a function
Object.defineProperty(this, "message", { get: function() { return message; } });
/* istanbul ignore next */
if (Error.captureStackTrace) // node
Error.captureStackTrace(this, CustomError);
else
Object.defineProperty(this, "stack", { value: new Error().stack || "" });
if (properties)
merge(this, properties);
}
CustomError.prototype = Object.create(Error.prototype, {
constructor: {
value: CustomError,
writable: true,
enumerable: false,
configurable: true,
},
name: {
get: function get() { return name; },
set: undefined,
enumerable: false,
// configurable: false would accurately preserve the behavior of
// the original, but I'm guessing that was not intentional.
// For an actual error subclass, this property would
// be configurable.
configurable: true,
},
toString: {
value: function value() { return this.name + ": " + this.message; },
writable: true,
enumerable: false,
configurable: true,
},
});
return CustomError;
}
util.newError = newError;
/**
* Constructs a new protocol error.
* @classdesc Error subclass indicating a protocol specifc error.
* @memberof util
* @extends Error
* @template T extends Message<T>
* @constructor
* @param {string} message Error message
* @param {Object.<string,*>} [properties] Additional properties
* @example
* try {
* MyMessage.decode(someBuffer); // throws if required fields are missing
* } catch (e) {
* if (e instanceof ProtocolError && e.instance)
* console.log("decoded so far: " + JSON.stringify(e.instance));
* }
*/
util.ProtocolError = newError("ProtocolError");
/**
* So far decoded message instance.
* @name util.ProtocolError#instance
* @type {Message<T>}
*/
/**
* A OneOf getter as returned by {@link util.oneOfGetter}.
* @typedef OneOfGetter
* @type {function}
* @returns {string|undefined} Set field name, if any
*/
/**
* Builds a getter for a oneof's present field name.
* @param {string[]} fieldNames Field names
* @returns {OneOfGetter} Unbound getter
*/
util.oneOfGetter = function getOneOf(fieldNames) {
var fieldMap = {};
for (var i = 0; i < fieldNames.length; ++i)
fieldMap[fieldNames[i]] = 1;
/**
* @returns {string|undefined} Set field name, if any
* @this Object
* @ignore
*/
return function() { // eslint-disable-line consistent-return
for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)
if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)
return keys[i];
};
};
/**
* A OneOf setter as returned by {@link util.oneOfSetter}.
* @typedef OneOfSetter
* @type {function}
* @param {string|undefined} value Field name
* @returns {undefined}
*/
/**
* Builds a setter for a oneof's present field name.
* @param {string[]} fieldNames Field names
* @returns {OneOfSetter} Unbound setter
*/
util.oneOfSetter = function setOneOf(fieldNames) {
/**
* @param {string} name Field name
* @returns {undefined}
* @this Object
* @ignore
*/
return function(name) {
for (var i = 0; i < fieldNames.length; ++i)
if (fieldNames[i] !== name)
delete this[fieldNames[i]];
};
};
/**
* Default conversion options used for {@link Message#toJSON} implementations.
*
* These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:
*
* - Longs become strings
* - Enums become string keys
* - Bytes become base64 encoded strings
* - (Sub-)Messages become plain objects
* - Maps become plain objects with all string keys
* - Repeated fields become arrays
* - NaN and Infinity for float and double fields become strings
*
* @type {IConversionOptions}
* @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json
*/
util.toJSONOptions = {
longs: String,
enums: String,
bytes: String,
json: true
};
// Sets up buffer utility according to the environment (called in index-minimal)
util._configure = function() {
var Buffer = util.Buffer;
/* istanbul ignore if */
if (!Buffer) {
util._Buffer_from = util._Buffer_allocUnsafe = null;
return;
}
// because node 4.x buffers are incompatible & immutable
// see: https://github.com/dcodeIO/protobuf.js/pull/665
util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||
/* istanbul ignore next */
function Buffer_from(value, encoding) {
return new Buffer(value, encoding);
};
util._Buffer_allocUnsafe = Buffer.allocUnsafe ||
/* istanbul ignore next */
function Buffer_allocUnsafe(size) {
return new Buffer(size);
};
};
} (minimal$1));
return minimal$1;
}
var writer;
var hasRequiredWriter;
function requireWriter () {
if (hasRequiredWriter) return writer;
hasRequiredWriter = 1;
writer = Writer;
var util = requireMinimal$1();
var BufferWriter; // cyclic
var LongBits = util.LongBits,
base64 = util.base64,
utf8 = util.utf8;
/**
* Constructs a new writer operation instance.
* @classdesc Scheduled writer operation.
* @constructor
* @param {function(*, Uint8Array, number)} fn Function to call
* @param {number} len Value byte length
* @param {*} val Value to write
* @ignore
*/
function Op(fn, len, val) {
/**
* Function to call.
* @type {function(Uint8Array, number, *)}
*/
this.fn = fn;
/**
* Value byte length.
* @type {number}
*/
this.len = len;
/**
* Next operation.
* @type {Writer.Op|undefined}
*/
this.next = undefined;
/**
* Value to write.
* @type {*}
*/
this.val = val; // type varies
}
/* istanbul ignore next */
function noop() {} // eslint-disable-line no-empty-function
/**
* Constructs a new writer state instance.
* @classdesc Copied writer state.
* @memberof Writer
* @constructor
* @param {Writer} writer Writer to copy state from
* @ignore
*/
function State(writer) {
/**
* Current head.
* @type {Writer.Op}
*/
this.head = writer.head;
/**
* Current tail.
* @type {Writer.Op}
*/
this.tail = writer.tail;
/**
* Current buffer length.
* @type {number}
*/
this.len = writer.len;
/**
* Next state.
* @type {State|null}
*/
this.next = writer.states;
}
/**
* Constructs a new writer instance.
* @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.
* @constructor
*/
function Writer() {
/**
* Current length.
* @type {number}
*/
this.len = 0;
/**
* Operations head.
* @type {Object}
*/
this.head = new Op(noop, 0, 0);
/**
* Operations tail
* @type {Object}
*/
this.tail = this.head;
/**
* Linked forked states.
* @type {Object|null}
*/
this.states = null;
// When a value is written, the writer calculates its byte length and puts it into a linked
// list of operations to perform when finish() is called. This both allows us to allocate
// buffers of the exact required size and reduces the amount of work we have to do compared
// to first calculating over objects and then encoding over objects. In our case, the encoding
// part is just a linked list walk calling operations with already prepared values.
}
var create = function create() {
return util.Buffer
? function create_buffer_setup() {
return (Writer.create = function create_buffer() {
return new BufferWriter();
})();
}
/* istanbul ignore next */
: function create_array() {
return new Writer();
};
};
/**
* Creates a new writer.
* @function
* @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}
*/
Writer.create = create();
/**
* Allocates a buffer of the specified size.
* @param {number} size Buffer size
* @returns {Uint8Array} Buffer
*/
Writer.alloc = function alloc(size) {
return new util.Array(size);
};
// Use Uint8Array buffer pool in the browser, just like node does with buffers
/* istanbul ignore else */
if (util.Array !== Array)
Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);
/**
* Pushes a new operation to the queue.
* @param {function(Uint8Array, number, *)} fn Function to call
* @param {number} len Value byte length
* @param {number} val Value to write
* @returns {Writer} `this`
* @private
*/
Writer.prototype._push = function push(fn, len, val) {
this.tail = this.tail.next = new Op(fn, len, val);
this.len += len;
return this;
};
function writeByte(val, buf, pos) {
buf[pos] = val & 255;
}
function writeVarint32(val, buf, pos) {
while (val > 127) {
buf[pos++] = val & 127 | 128;
val >>>= 7;
}
buf[pos] = val;
}
/**
* Constructs a new varint writer operation instance.
* @classdesc Scheduled varint writer operation.
* @extends Op
* @constructor
* @param {number} len Value byte length
* @param {number} val Value to write
* @ignore
*/
function VarintOp(len, val) {
this.len = len;
this.next = undefined;
this.val = val;
}
VarintOp.prototype = Object.create(Op.prototype);
VarintOp.prototype.fn = writeVarint32;
/**
* Writes an unsigned 32 bit value as a varint.
* @param {number} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.uint32 = function write_uint32(value) {
// here, the call to this.push has been inlined and a varint specific Op subclass is used.
// uint32 is by far the most frequently used operation and benefits significantly from this.
this.len += (this.tail = this.tail.next = new VarintOp(
(value = value >>> 0)
< 128 ? 1
: value < 16384 ? 2
: value < 2097152 ? 3
: value < 268435456 ? 4
: 5,
value)).len;
return this;
};
/**
* Writes a signed 32 bit value as a varint.
* @function
* @param {number} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.int32 = function write_int32(value) {
return (value |= 0) < 0
? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec
: this.uint32(value);
};
/**
* Writes a 32 bit value as a varint, zig-zag encoded.
* @param {number} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.sint32 = function write_sint32(value) {
return this.uint32((value << 1 ^ value >> 31) >>> 0);
};
function writeVarint64(val, buf, pos) {
var lo = val.lo,
hi = val.hi;
while (hi) {
buf[pos++] = lo & 127 | 128;
lo = (lo >>> 7 | hi << 25) >>> 0;
hi >>>= 7;
}
while (lo > 127) {
buf[pos++] = lo & 127 | 128;
lo = lo >>> 7;
}
buf[pos++] = lo;
}
/**
* Writes an unsigned 64 bit value as a varint.
* @param {Long|number|string} value Value to write
* @returns {Writer} `this`
* @throws {TypeError} If `value` is a string and no long library is present.
*/
Writer.prototype.uint64 = function write_uint64(value) {
var bits = LongBits.from(value);
return this._push(writeVarint64, bits.length(), bits);
};
/**
* Writes a signed 64 bit value as a varint.
* @function
* @param {Long|number|string} value Value to write
* @returns {Writer} `this`
* @throws {TypeError} If `value` is a string and no long library is present.
*/
Writer.prototype.int64 = Writer.prototype.uint64;
/**
* Writes a signed 64 bit value as a varint, zig-zag encoded.
* @param {Long|number|string} value Value to write
* @returns {Writer} `this`
* @throws {TypeError} If `value` is a string and no long library is present.
*/
Writer.prototype.sint64 = function write_sint64(value) {
var bits = LongBits.from(value).zzEncode();
return this._push(writeVarint64, bits.length(), bits);
};
/**
* Writes a boolish value as a varint.
* @param {boolean} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.bool = function write_bool(value) {
return this._push(writeByte, 1, value ? 1 : 0);
};
function writeFixed32(val, buf, pos) {
buf[pos ] = val & 255;
buf[pos + 1] = val >>> 8 & 255;
buf[pos + 2] = val >>> 16 & 255;
buf[pos + 3] = val >>> 24;
}
/**
* Writes an unsigned 32 bit value as fixed 32 bits.
* @param {number} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.fixed32 = function write_fixed32(value) {
return this._push(writeFixed32, 4, value >>> 0);
};
/**
* Writes a signed 32 bit value as fixed 32 bits.
* @function
* @param {number} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.sfixed32 = Writer.prototype.fixed32;
/**
* Writes an unsigned 64 bit value as fixed 64 bits.
* @param {Long|number|string} value Value to write
* @returns {Writer} `this`
* @throws {TypeError} If `value` is a string and no long library is present.
*/
Writer.prototype.fixed64 = function write_fixed64(value) {
var bits = LongBits.from(value);
return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);
};
/**
* Writes a signed 64 bit value as fixed 64 bits.
* @function
* @param {Long|number|string} value Value to write
* @returns {Writer} `this`
* @throws {TypeError} If `value` is a string and no long library is present.
*/
Writer.prototype.sfixed64 = Writer.prototype.fixed64;
/**
* Writes a float (32 bit).
* @function
* @param {number} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.float = function write_float(value) {
return this._push(util.float.writeFloatLE, 4, value);
};
/**
* Writes a double (64 bit float).
* @function
* @param {number} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.double = function write_double(value) {
return this._push(util.float.writeDoubleLE, 8, value);
};
var writeBytes = util.Array.prototype.set
? function writeBytes_set(val, buf, pos) {
buf.set(val, pos); // also works for plain array values
}
/* istanbul ignore next */
: function writeBytes_for(val, buf, pos) {
for (var i = 0; i < val.length; ++i)
buf[pos + i] = val[i];
};
/**
* Writes a sequence of bytes.
* @param {Uint8Array|string} value Buffer or base64 encoded string to write
* @returns {Writer} `this`
*/
Writer.prototype.bytes = function write_bytes(value) {
var len = value.length >>> 0;
if (!len)
return this._push(writeByte, 1, 0);
if (util.isString(value)) {
var buf = Writer.alloc(len = base64.length(value));
base64.decode(value, buf, 0);
value = buf;
}
return this.uint32(len)._push(writeBytes, len, value);
};
/**
* Writes a string.
* @param {string} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.string = function write_string(value) {
var len = utf8.length(value);
return len
? this.uint32(len)._push(utf8.write, len, value)
: this._push(writeByte, 1, 0);
};
/**
* Forks this writer's state by pushing it to a stack.
* Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.
* @returns {Writer} `this`
*/
Writer.prototype.fork = function fork() {
this.states = new State(this);
this.head = this.tail = new Op(noop, 0, 0);
this.len = 0;
return this;
};
/**
* Resets this instance to the last state.
* @returns {Writer} `this`
*/
Writer.prototype.reset = function reset() {
if (this.states) {
this.head = this.states.head;
this.tail = this.states.tail;
this.len = this.states.len;
this.states = this.states.next;
} else {
this.head = this.tail = new Op(noop, 0, 0);
this.len = 0;
}
return this;
};
/**
* Resets to the last state and appends the fork state's current write length as a varint followed by its operations.
* @returns {Writer} `this`
*/
Writer.prototype.ldelim = function ldelim() {
var head = this.head,
tail = this.tail,
len = this.len;
this.reset().uint32(len);
if (len) {
this.tail.next = head.next; // skip noop
this.tail = tail;
this.len += len;
}
return this;
};
/**
* Finishes the write operation.
* @returns {Uint8Array} Finished buffer
*/
Writer.prototype.finish = function finish() {
var head = this.head.next, // skip noop
buf = this.constructor.alloc(this.len),
pos = 0;
while (head) {
head.fn(head.val, buf, pos);
pos += head.len;
head = head.next;
}
// this.head = this.tail = null;
return buf;
};
Writer._configure = function(BufferWriter_) {
BufferWriter = BufferWriter_;
Writer.create = create();
BufferWriter._configure();
};
return writer;
}
var writer_buffer;
var hasRequiredWriter_buffer;
function requireWriter_buffer () {
if (hasRequiredWriter_buffer) return writer_buffer;
hasRequiredWriter_buffer = 1;
writer_buffer = BufferWriter;
// extends Writer
var Writer = requireWriter();
(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;
var util = requireMinimal$1();
/**
* Constructs a new buffer writer instance.
* @classdesc Wire format writer using node buffers.
* @extends Writer
* @constructor
*/
function BufferWriter() {
Writer.call(this);
}
BufferWriter._configure = function () {
/**
* Allocates a buffer of the specified size.
* @function
* @param {number} size Buffer size
* @returns {Buffer} Buffer
*/
BufferWriter.alloc = util._Buffer_allocUnsafe;
BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set"
? function writeBytesBuffer_set(val, buf, pos) {
buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)
// also works for plain array values
}
/* istanbul ignore next */
: function writeBytesBuffer_copy(val, buf, pos) {
if (val.copy) // Buffer values
val.copy(buf, pos, 0, val.length);
else for (var i = 0; i < val.length;) // plain array values
buf[pos++] = val[i++];
};
};
/**
* @override
*/
BufferWriter.prototype.bytes = function write_bytes_buffer(value) {
if (util.isString(value))
value = util._Buffer_from(value, "base64");
var len = value.length >>> 0;
this.uint32(len);
if (len)
this._push(BufferWriter.writeBytesBuffer, len, value);
return this;
};
function writeStringBuffer(val, buf, pos) {
if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)
util.utf8.write(val, buf, pos);
else if (buf.utf8Write)
buf.utf8Write(val, pos);
else
buf.write(val, pos);
}
/**
* @override
*/
BufferWriter.prototype.string = function write_string_buffer(value) {
var len = util.Buffer.byteLength(value);
this.uint32(len);
if (len)
this._push(writeStringBuffer, len, value);
return this;
};
/**
* Finishes the write operation.
* @name BufferWriter#finish
* @function
* @returns {Buffer} Finished buffer
*/
BufferWriter._configure();
return writer_buffer;
}
var reader;
var hasRequiredReader;
function requireReader () {
if (hasRequiredReader) return reader;
hasRequiredReader = 1;
reader = Reader;
var util = requireMinimal$1();
var BufferReader; // cyclic
var LongBits = util.LongBits,
utf8 = util.utf8;
/* istanbul ignore next */
function indexOutOfRange(reader, writeLength) {
return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len);
}
/**
* Constructs a new reader instance using the specified buffer.
* @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.
* @constructor
* @param {Uint8Array} buffer Buffer to read from
*/
function Reader(buffer) {
/**
* Read buffer.
* @type {Uint8Array}
*/
this.buf = buffer;
/**
* Read buffer position.
* @type {number}
*/
this.pos = 0;
/**
* Read buffer length.
* @type {number}
*/
this.len = buffer.length;
}
var create_array = typeof Uint8Array !== "undefined"
? function create_typed_array(buffer) {
if (buffer instanceof Uint8Array || Array.isArray(buffer))
return new Reader(buffer);
throw Error("illegal buffer");
}
/* istanbul ignore next */
: function create_array(buffer) {
if (Array.isArray(buffer))
return new Reader(buffer);
throw Error("illegal buffer");
};
var create = function create() {
return util.Buffer
? function create_buffer_setup(buffer) {
return (Reader.create = function create_buffer(buffer) {
return util.Buffer.isBuffer(buffer)
? new BufferReader(buffer)
/* istanbul ignore next */
: create_array(buffer);
})(buffer);
}
/* istanbul ignore next */
: create_array;
};
/**
* Creates a new reader using the specified buffer.
* @function
* @param {Uint8Array|Buffer} buffer Buffer to read from
* @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}
* @throws {Error} If `buffer` is not a valid buffer
*/
Reader.create = create();
Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;
function readVarint32NearEnd(reader) {
// Safely read up to four bytes of a varint32 near the reader limit
var value = 0;
for (var i = 0; i < 4; ++i) {
if (reader.pos >= reader.len)
throw indexOutOfRange(reader);
var b = reader.buf[reader.pos++];
value = (value | (b & 127) << i * 7) >>> 0;
if (b < 128)
return value;
}
throw indexOutOfRange(reader);
}
/**
* Reads a varint as an unsigned 32 bit value.
* @function
* @returns {number} Value read
*/
Reader.prototype.uint32 = (function read_uint32_setup() {
var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)
return function read_uint32() {
if (this.len - this.pos < 5) {
if (this.pos >= this.len)
throw indexOutOfRange(this);
if (this.buf[this.pos] >= 128)
return readVarint32NearEnd(this);
}
value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;
value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;
value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;
value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;
value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;
/* istanbul ignore if */
if ((this.pos += 5) > this.len) {
this.pos = this.len;
throw indexOutOfRange(this, 10);
}
return value;
};
})();
/**
* Reads a varint as a signed 32 bit value.
* @returns {number} Value read
*/
Reader.prototype.int32 = function read_int32() {
return this.uint32() | 0;
};
/**
* Reads a zig-zag encoded varint as a signed 32 bit value.
* @returns {number} Value read
*/
Reader.prototype.sint32 = function read_sint32() {
var value = this.uint32();
return value >>> 1 ^ -(value & 1) | 0;
};
/* eslint-disable no-invalid-this */
function readLongVarint() {
// tends to deopt with local vars for octet etc.
var bits = new LongBits(0, 0);
var i = 0;
if (this.len - this.pos > 4) { // fast route (lo)
for (; i < 4; ++i) {
// 1st..4th
bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
if (this.buf[this.pos++] < 128)
return bits;
}
// 5th
bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;
bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;
if (this.buf[this.pos++] < 128)
return bits;
i = 0;
} else {
for (; i < 3; ++i) {
/* istanbul ignore if */
if (this.pos >= this.len)
throw indexOutOfRange(this);
// 1st..3th
bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
if (this.buf[this.pos++] < 128)
return bits;
}
// 4th
bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;
return bits;
}
if (this.len - this.pos > 4) { // fast route (hi)
for (; i < 5; ++i) {
// 6th..10th
bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
if (this.buf[this.pos++] < 128)
return bits;
}
} else {
for (; i < 5; ++i) {
/* istanbul ignore if */
if (this.pos >= this.len)
throw indexOutOfRange(this);
// 6th..10th
bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
if (this.buf[this.pos++] < 128)
return bits;
}
}
/* istanbul ignore next */
throw Error("invalid varint encoding");
}
/* eslint-enable no-invalid-this */
/**
* Reads a varint as a signed 64 bit value.
* @name Reader#int64
* @function
* @returns {Long} Value read
*/
/**
* Reads a varint as an unsigned 64 bit value.
* @name Reader#uint64
* @function
* @returns {Long} Value read
*/
/**
* Reads a zig-zag encoded varint as a signed 64 bit value.
* @name Reader#sint64
* @function
* @returns {Long} Value read
*/
/**
* Reads a varint as a boolean.
* @returns {boolean} Value read
*/
Reader.prototype.bool = function read_bool() {
return this.uint32() !== 0;
};
function readFixed32_end(buf, end) { // note that this uses `end`, not `pos`
return (buf[end - 4]
| buf[end - 3] << 8
| buf[end - 2] << 16
| buf[end - 1] << 24) >>> 0;
}
/**
* Reads fixed 32 bits as an unsigned 32 bit integer.
* @returns {number} Value read
*/
Reader.prototype.fixed32 = function read_fixed32() {
/* istanbul ignore if */
if (this.pos + 4 > this.len)
throw indexOutOfRange(this, 4);
return readFixed32_end(this.buf, this.pos += 4);
};
/**
* Reads fixed 32 bits as a signed 32 bit integer.
* @returns {number} Value read
*/
Reader.prototype.sfixed32 = function read_sfixed32() {
/* istanbul ignore if */
if (this.pos + 4 > this.len)
throw indexOutOfRange(this, 4);
return readFixed32_end(this.buf, this.pos += 4) | 0;
};
/* eslint-disable no-invalid-this */
function readFixed64(/* this: Reader */) {
/* istanbul ignore if */
if (this.pos + 8 > this.len)
throw indexOutOfRange(this, 8);
return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));
}
/* eslint-enable no-invalid-this */
/**
* Reads fixed 64 bits.
* @name Reader#fixed64
* @function
* @returns {Long} Value read
*/
/**
* Reads zig-zag encoded fixed 64 bits.
* @name Reader#sfixed64
* @function
* @returns {Long} Value read
*/
/**
* Reads a float (32 bit) as a number.
* @function
* @returns {number} Value read
*/
Reader.prototype.float = function read_float() {
/* istanbul ignore if */
if (this.pos + 4 > this.len)
throw indexOutOfRange(this, 4);
var value = util.float.readFloatLE(this.buf, this.pos);
this.pos += 4;
return value;
};
/**
* Reads a double (64 bit float) as a number.
* @function
* @returns {number} Value read
*/
Reader.prototype.double = function read_double() {
/* istanbul ignore if */
if (this.pos + 8 > this.len)
throw indexOutOfRange(this, 4);
var value = util.float.readDoubleLE(this.buf, this.pos);
this.pos += 8;
return value;
};
/**
* Reads a sequence of bytes preceeded by its length as a varint.
* @returns {Uint8Array} Value read
*/
Reader.prototype.bytes = function read_bytes() {
var length = this.uint32(),
start = this.pos,
end = this.pos + length;
/* istanbul ignore if */
if (end > this.len)
throw indexOutOfRange(this, length);
this.pos += length;
if (Array.isArray(this.buf)) // plain array
return this.buf.slice(start, end);
if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1
var nativeBuffer = util.Buffer;
return nativeBuffer
? nativeBuffer.alloc(0)
: new this.buf.constructor(0);
}
return this._slice.call(this.buf, start, end);
};
/**
* Reads a string preceeded by its byte length as a varint.
* @returns {string} Value read
*/
Reader.prototype.string = function read_string() {
var bytes = this.bytes();
return utf8.read(bytes, 0, bytes.length);
};
/**
* Skips the specified number of bytes if specified, otherwise skips a varint.
* @param {number} [length] Length if known, otherwise a varint is assumed
* @returns {Reader} `this`
*/
Reader.prototype.skip = function skip(length) {
if (typeof length === "number") {
/* istanbul ignore if */
if (this.pos + length > this.len)
throw indexOutOfRange(this, length);
this.pos += length;
} else {
do {
/* istanbul ignore if */
if (this.pos >= this.len)
throw indexOutOfRange(this);
} while (this.buf[this.pos++] & 128);
}
return this;
};
/**
* Recursion limit.
* @type {number}
*/
Reader.recursionLimit = util.recursionLimit;
/**
* Skips the next element of the specified wire type.
* @param {number} wireType Wire type received
* @param {number} [depth] Depth of recursion to control nested calls; 0 if omitted
* @returns {Reader} `this`
*/
Reader.prototype.skipType = function(wireType, depth) {
if (depth === undefined) depth = 0;
if (depth > Reader.recursionLimit)
throw Error("maximum nesting depth exceeded");
switch (wireType) {
case 0:
this.skip();
break;
case 1:
this.skip(8);
break;
case 2:
this.skip(this.uint32());
break;
case 3:
while ((wireType = this.uint32() & 7) !== 4) {
this.skipType(wireType, depth + 1);
}
break;
case 5:
this.skip(4);
break;
/* istanbul ignore next */
default:
throw Error("invalid wire type " + wireType + " at offset " + this.pos);
}
return this;
};
Reader._configure = function(BufferReader_) {
BufferReader = BufferReader_;
Reader.create = create();
BufferReader._configure();
var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber";
util.merge(Reader.prototype, {
int64: function read_int64() {
return readLongVarint.call(this)[fn](false);
},
uint64: function read_uint64() {
return readLongVarint.call(this)[fn](true);
},
sint64: function read_sint64() {
return readLongVarint.call(this).zzDecode()[fn](false);
},
fixed64: function read_fixed64() {
return readFixed64.call(this)[fn](true);
},
sfixed64: function read_sfixed64() {
return readFixed64.call(this)[fn](false);
}
});
};
return reader;
}
var reader_buffer;
var hasRequiredReader_buffer;
function requireReader_buffer () {
if (hasRequiredReader_buffer) return reader_buffer;
hasRequiredReader_buffer = 1;
reader_buffer = BufferReader;
// extends Reader
var Reader = requireReader();
(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;
var util = requireMinimal$1();
/**
* Constructs a new buffer reader instance.
* @classdesc Wire format reader using node buffers.
* @extends Reader
* @constructor
* @param {Buffer} buffer Buffer to read from
*/
function BufferReader(buffer) {
Reader.call(this, buffer);
/**
* Read buffer.
* @name BufferReader#buf
* @type {Buffer}
*/
}
BufferReader._configure = function () {
/* istanbul ignore else */
if (util.Buffer)
BufferReader.prototype._slice = util.Buffer.prototype.slice;
};
/**
* @override
*/
BufferReader.prototype.string = function read_string_buffer() {
var len = this.uint32(); // modifies pos
return this.buf.utf8Slice
? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))
: this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len));
};
/**
* Reads a sequence of bytes preceeded by its length as a varint.
* @name BufferReader#bytes
* @function
* @returns {Buffer} Value read
*/
BufferReader._configure();
return reader_buffer;
}
var rpc = {};
var service;
var hasRequiredService;
function requireService () {
if (hasRequiredService) return service;
hasRequiredService = 1;
service = Service;
var util = requireMinimal$1();
// Extends EventEmitter
(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;
/**
* A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.
*
* Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.
* @typedef rpc.ServiceMethodCallback
* @template TRes extends Message<TRes>
* @type {function}
* @param {Error|null} error Error, if any
* @param {TRes} [response] Response message
* @returns {undefined}
*/
/**
* A service method part of a {@link rpc.Service} as created by {@link Service.create}.
* @typedef rpc.ServiceMethod
* @template TReq extends Message<TReq>
* @template TRes extends Message<TRes>
* @type {function}
* @param {TReq|Properties<TReq>} request Request message or plain object
* @param {rpc.ServiceMethodCallback<TRes>} [callback] Node-style callback called with the error, if any, and the response message
* @returns {Promise<Message<TRes>>} Promise if `callback` has been omitted, otherwise `undefined`
*/
/**
* Constructs a new RPC service instance.
* @classdesc An RPC service as returned by {@link Service#create}.
* @exports rpc.Service
* @extends util.EventEmitter
* @constructor
* @param {RPCImpl} rpcImpl RPC implementation
* @param {boolean} [requestDelimited=false] Whether requests are length-delimited
* @param {boolean} [responseDelimited=false] Whether responses are length-delimited
*/
function Service(rpcImpl, requestDelimited, responseDelimited) {
if (typeof rpcImpl !== "function")
throw TypeError("rpcImpl must be a function");
util.EventEmitter.call(this);
/**
* RPC implementation. Becomes `null` once the service is ended.
* @type {RPCImpl|null}
*/
this.rpcImpl = rpcImpl;
/**
* Whether requests are length-delimited.
* @type {boolean}
*/
this.requestDelimited = Boolean(requestDelimited);
/**
* Whether responses are length-delimited.
* @type {boolean}
*/
this.responseDelimited = Boolean(responseDelimited);
}
/**
* Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.
* @param {Method|rpc.ServiceMethod<TReq,TRes>} method Reflected or static method
* @param {Constructor<TReq>} requestCtor Request constructor
* @param {Constructor<TRes>} responseCtor Response constructor
* @param {TReq|Properties<TReq>} request Request message or plain object
* @param {rpc.ServiceMethodCallback<TRes>} callback Service callback
* @returns {undefined}
* @template TReq extends Message<TReq>
* @template TRes extends Message<TRes>
*/
Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {
if (!request)
throw TypeError("request must be specified");
var self = this;
if (!callback)
return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);
if (!self.rpcImpl) {
setTimeout(function() { callback(Error("already ended")); }, 0);
return undefined;
}
try {
return self.rpcImpl(
method,
requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(),
function rpcCallback(err, response) {
if (err) {
self.emit("error", err, method);
return callback(err);
}
if (response === null) {
self.end(/* endedByRPC */ true);
return undefined;
}
if (!(response instanceof responseCtor)) {
try {
response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response);
} catch (err) {
self.emit("error", err, method);
return callback(err);
}
}
self.emit("data", response, method);
return callback(null, response);
}
);
} catch (err) {
self.emit("error", err, method);
setTimeout(function() { callback(err); }, 0);
return undefined;
}
};
/**
* Ends this service and emits the `end` event.
* @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.
* @returns {rpc.Service} `this`
*/
Service.prototype.end = function end(endedByRPC) {
if (this.rpcImpl) {
if (!endedByRPC) // signal end to rpcImpl
this.rpcImpl(null, null, null);
this.rpcImpl = null;
this.emit("end").off();
}
return this;
};
return service;
}
var hasRequiredRpc;
function requireRpc () {
if (hasRequiredRpc) return rpc;
hasRequiredRpc = 1;
(function (exports) {
/**
* Streaming RPC helpers.
* @namespace
*/
var rpc = exports;
/**
* RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.
* @typedef RPCImpl
* @type {function}
* @param {Method|rpc.ServiceMethod<Message<{}>,Message<{}>>} method Reflected or static method being called
* @param {Uint8Array} requestData Request data
* @param {RPCImplCallback} callback Callback function
* @returns {undefined}
* @example
* function rpcImpl(method, requestData, callback) {
* if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code
* throw Error("no such method");
* asynchronouslyObtainAResponse(requestData, function(err, responseData) {
* callback(err, responseData);
* });
* }
*/
/**
* Node-style callback as used by {@link RPCImpl}.
* @typedef RPCImplCallback
* @type {function}
* @param {Error|null} error Error, if any, otherwise `null`
* @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error
* @returns {undefined}
*/
rpc.Service = requireService();
} (rpc));
return rpc;
}
var roots;
var hasRequiredRoots;
function requireRoots () {
if (hasRequiredRoots) return roots;
hasRequiredRoots = 1;
roots = Object.create(null);
/**
* Named roots.
* This is where pbjs stores generated structures (the option `-r, --root` specifies a name).
* Can also be used manually to make roots available across modules.
* @name roots
* @type {Object.<string,Root>}
* @example
* // pbjs -r myroot -o compiled.js ...
*
* // in another module:
* require("./compiled.js");
*
* // in any subsequent module:
* var root = protobuf.roots["myroot"];
*/
return roots;
}
var hasRequiredIndexMinimal;
function requireIndexMinimal () {
if (hasRequiredIndexMinimal) return indexMinimal;
hasRequiredIndexMinimal = 1;
(function (exports) {
var protobuf = exports;
/**
* Build type, one of `"full"`, `"light"` or `"minimal"`.
* @name build
* @type {string}
* @const
*/
protobuf.build = "minimal";
// Serialization
protobuf.Writer = requireWriter();
protobuf.BufferWriter = requireWriter_buffer();
protobuf.Reader = requireReader();
protobuf.BufferReader = requireReader_buffer();
// Utility
protobuf.util = requireMinimal$1();
protobuf.rpc = requireRpc();
protobuf.roots = requireRoots();
protobuf.configure = configure;
/* istanbul ignore next */
/**
* Reconfigures the library according to the environment.
* @returns {undefined}
*/
function configure() {
protobuf.util._configure();
protobuf.Writer._configure(protobuf.BufferWriter);
protobuf.Reader._configure(protobuf.BufferReader);
}
// Set up buffer utility according to the environment
configure();
} (indexMinimal));
return indexMinimal;
}
var minimal;
var hasRequiredMinimal;
function requireMinimal () {
if (hasRequiredMinimal) return minimal;
hasRequiredMinimal = 1;
minimal = requireIndexMinimal();
return minimal;
}
var minimalExports = requireMinimal();
/*eslint-disable*/
// Common aliases
const $Reader = minimalExports.Reader, $Writer = minimalExports.Writer, $util = minimalExports.util;
// Exported root namespace
const $root = minimalExports.roots["default"] || (minimalExports.roots["default"] = {});
const centrifugal = $root.centrifugal = (() => {
/**
* Namespace centrifugal.
* @exports centrifugal
* @namespace
*/
const centrifugal = {};
centrifugal.centrifuge = (function () {
/**
* Namespace centrifuge.
* @memberof centrifugal
* @namespace
*/
const centrifuge = {};
centrifuge.protocol = (function () {
/**
* Namespace protocol.
* @memberof centrifugal.centrifuge
* @namespace
*/
const protocol = {};
protocol.Error = (function () {
/**
* Properties of an Error.
* @memberof centrifugal.centrifuge.protocol
* @interface IError
* @property {number|null} [code] Error code
* @property {string|null} [message] Error message
* @property {boolean|null} [temporary] Error temporary
*/
/**
* Constructs a new Error.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents an Error.
* @implements IError
* @constructor
* @param {centrifugal.centrifuge.protocol.IError=} [properties] Properties to set
*/
function Error(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Error code.
* @member {number} code
* @memberof centrifugal.centrifuge.protocol.Error
* @instance
*/
Error.prototype.code = 0;
/**
* Error message.
* @member {string} message
* @memberof centrifugal.centrifuge.protocol.Error
* @instance
*/
Error.prototype.message = "";
/**
* Error temporary.
* @member {boolean} temporary
* @memberof centrifugal.centrifuge.protocol.Error
* @instance
*/
Error.prototype.temporary = false;
/**
* Encodes the specified Error message. Does not implicitly {@link centrifugal.centrifuge.protocol.Error.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.Error
* @static
* @param {centrifugal.centrifuge.protocol.IError} message Error message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Error.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.code != null && Object.hasOwnProperty.call(message, "code"))
writer.uint32(/* id 1, wireType 0 =*/ 8).uint32(message.code);
if (message.message != null && Object.hasOwnProperty.call(message, "message"))
writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.message);
if (message.temporary != null && Object.hasOwnProperty.call(message, "temporary"))
writer.uint32(/* id 3, wireType 0 =*/ 24).bool(message.temporary);
return writer;
};
/**
* Encodes the specified Error message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.Error.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.Error
* @static
* @param {centrifugal.centrifuge.protocol.IError} message Error message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Error.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes an Error message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.Error
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.Error} Error
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Error.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.Error();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.code = reader.uint32();
break;
}
case 2: {
message.message = reader.string();
break;
}
case 3: {
message.temporary = reader.bool();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes an Error message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.Error
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.Error} Error
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Error.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies an Error message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.Error
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
Error.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.code != null && message.hasOwnProperty("code"))
if (!$util.isInteger(message.code))
return "code: integer expected";
if (message.message != null && message.hasOwnProperty("message"))
if (!$util.isString(message.message))
return "message: string expected";
if (message.temporary != null && message.hasOwnProperty("temporary"))
if (typeof message.temporary !== "boolean")
return "temporary: boolean expected";
return null;
};
/**
* Gets the default type url for Error
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.Error
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
Error.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.Error";
};
return Error;
})();
protocol.EmulationRequest = (function () {
/**
* Properties of an EmulationRequest.
* @memberof centrifugal.centrifuge.protocol
* @interface IEmulationRequest
* @property {string|null} [node] EmulationRequest node
* @property {string|null} [session] EmulationRequest session
* @property {Uint8Array|null} [data] EmulationRequest data
*/
/**
* Constructs a new EmulationRequest.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents an EmulationRequest.
* @implements IEmulationRequest
* @constructor
* @param {centrifugal.centrifuge.protocol.IEmulationRequest=} [properties] Properties to set
*/
function EmulationRequest(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* EmulationRequest node.
* @member {string} node
* @memberof centrifugal.centrifuge.protocol.EmulationRequest
* @instance
*/
EmulationRequest.prototype.node = "";
/**
* EmulationRequest session.
* @member {string} session
* @memberof centrifugal.centrifuge.protocol.EmulationRequest
* @instance
*/
EmulationRequest.prototype.session = "";
/**
* EmulationRequest data.
* @member {Uint8Array} data
* @memberof centrifugal.centrifuge.protocol.EmulationRequest
* @instance
*/
EmulationRequest.prototype.data = $util.newBuffer([]);
/**
* Encodes the specified EmulationRequest message. Does not implicitly {@link centrifugal.centrifuge.protocol.EmulationRequest.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.EmulationRequest
* @static
* @param {centrifugal.centrifuge.protocol.IEmulationRequest} message EmulationRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
EmulationRequest.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.node != null && Object.hasOwnProperty.call(message, "node"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.node);
if (message.session != null && Object.hasOwnProperty.call(message, "session"))
writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.session);
if (message.data != null && Object.hasOwnProperty.call(message, "data"))
writer.uint32(/* id 3, wireType 2 =*/ 26).bytes(message.data);
return writer;
};
/**
* Encodes the specified EmulationRequest message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.EmulationRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.EmulationRequest
* @static
* @param {centrifugal.centrifuge.protocol.IEmulationRequest} message EmulationRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
EmulationRequest.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes an EmulationRequest message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.EmulationRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.EmulationRequest} EmulationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
EmulationRequest.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.EmulationRequest();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.node = reader.string();
break;
}
case 2: {
message.session = reader.string();
break;
}
case 3: {
message.data = reader.bytes();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes an EmulationRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.EmulationRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.EmulationRequest} EmulationRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
EmulationRequest.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies an EmulationRequest message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.EmulationRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
EmulationRequest.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.node != null && message.hasOwnProperty("node"))
if (!$util.isString(message.node))
return "node: string expected";
if (message.session != null && message.hasOwnProperty("session"))
if (!$util.isString(message.session))
return "session: string expected";
if (message.data != null && message.hasOwnProperty("data"))
if (!(message.data && typeof message.data.length === "number" || $util.isString(message.data)))
return "data: buffer expected";
return null;
};
/**
* Gets the default type url for EmulationRequest
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.EmulationRequest
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
EmulationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.EmulationRequest";
};
return EmulationRequest;
})();
protocol.Command = (function () {
/**
* Properties of a Command.
* @memberof centrifugal.centrifuge.protocol
* @interface ICommand
* @property {number|null} [id] Command id
* @property {centrifugal.centrifuge.protocol.IConnectRequest|null} [connect] Command connect
* @property {centrifugal.centrifuge.protocol.ISubscribeRequest|null} [subscribe] Command subscribe
* @property {centrifugal.centrifuge.protocol.IUnsubscribeRequest|null} [unsubscribe] Command unsubscribe
* @property {centrifugal.centrifuge.protocol.IPublishRequest|null} [publish] Command publish
* @property {centrifugal.centrifuge.protocol.IPresenceRequest|null} [presence] Command presence
* @property {centrifugal.centrifuge.protocol.IPresenceStatsRequest|null} [presence_stats] Command presence_stats
* @property {centrifugal.centrifuge.protocol.IHistoryRequest|null} [history] Command history
* @property {centrifugal.centrifuge.protocol.IPingRequest|null} [ping] Command ping
* @property {centrifugal.centrifuge.protocol.ISendRequest|null} [send] Command send
* @property {centrifugal.centrifuge.protocol.IRPCRequest|null} [rpc] Command rpc
* @property {centrifugal.centrifuge.protocol.IRefreshRequest|null} [refresh] Command refresh
* @property {centrifugal.centrifuge.protocol.ISubRefreshRequest|null} [sub_refresh] Command sub_refresh
*/
/**
* Constructs a new Command.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a Command.
* @implements ICommand
* @constructor
* @param {centrifugal.centrifuge.protocol.ICommand=} [properties] Properties to set
*/
function Command(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Command id.
* @member {number} id
* @memberof centrifugal.centrifuge.protocol.Command
* @instance
*/
Command.prototype.id = 0;
/**
* Command connect.
* @member {centrifugal.centrifuge.protocol.IConnectRequest|null|undefined} connect
* @memberof centrifugal.centrifuge.protocol.Command
* @instance
*/
Command.prototype.connect = null;
/**
* Command subscribe.
* @member {centrifugal.centrifuge.protocol.ISubscribeRequest|null|undefined} subscribe
* @memberof centrifugal.centrifuge.protocol.Command
* @instance
*/
Command.prototype.subscribe = null;
/**
* Command unsubscribe.
* @member {centrifugal.centrifuge.protocol.IUnsubscribeRequest|null|undefined} unsubscribe
* @memberof centrifugal.centrifuge.protocol.Command
* @instance
*/
Command.prototype.unsubscribe = null;
/**
* Command publish.
* @member {centrifugal.centrifuge.protocol.IPublishRequest|null|undefined} publish
* @memberof centrifugal.centrifuge.protocol.Command
* @instance
*/
Command.prototype.publish = null;
/**
* Command presence.
* @member {centrifugal.centrifuge.protocol.IPresenceRequest|null|undefined} presence
* @memberof centrifugal.centrifuge.protocol.Command
* @instance
*/
Command.prototype.presence = null;
/**
* Command presence_stats.
* @member {centrifugal.centrifuge.protocol.IPresenceStatsRequest|null|undefined} presence_stats
* @memberof centrifugal.centrifuge.protocol.Command
* @instance
*/
Command.prototype.presence_stats = null;
/**
* Command history.
* @member {centrifugal.centrifuge.protocol.IHistoryRequest|null|undefined} history
* @memberof centrifugal.centrifuge.protocol.Command
* @instance
*/
Command.prototype.history = null;
/**
* Command ping.
* @member {centrifugal.centrifuge.protocol.IPingRequest|null|undefined} ping
* @memberof centrifugal.centrifuge.protocol.Command
* @instance
*/
Command.prototype.ping = null;
/**
* Command send.
* @member {centrifugal.centrifuge.protocol.ISendRequest|null|undefined} send
* @memberof centrifugal.centrifuge.protocol.Command
* @instance
*/
Command.prototype.send = null;
/**
* Command rpc.
* @member {centrifugal.centrifuge.protocol.IRPCRequest|null|undefined} rpc
* @memberof centrifugal.centrifuge.protocol.Command
* @instance
*/
Command.prototype.rpc = null;
/**
* Command refresh.
* @member {centrifugal.centrifuge.protocol.IRefreshRequest|null|undefined} refresh
* @memberof centrifugal.centrifuge.protocol.Command
* @instance
*/
Command.prototype.refresh = null;
/**
* Command sub_refresh.
* @member {centrifugal.centrifuge.protocol.ISubRefreshRequest|null|undefined} sub_refresh
* @memberof centrifugal.centrifuge.protocol.Command
* @instance
*/
Command.prototype.sub_refresh = null;
/**
* Encodes the specified Command message. Does not implicitly {@link centrifugal.centrifuge.protocol.Command.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.Command
* @static
* @param {centrifugal.centrifuge.protocol.ICommand} message Command message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Command.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.id != null && Object.hasOwnProperty.call(message, "id"))
writer.uint32(/* id 1, wireType 0 =*/ 8).uint32(message.id);
if (message.connect != null && Object.hasOwnProperty.call(message, "connect"))
$root.centrifugal.centrifuge.protocol.ConnectRequest.encode(message.connect, writer.uint32(/* id 4, wireType 2 =*/ 34).fork()).ldelim();
if (message.subscribe != null && Object.hasOwnProperty.call(message, "subscribe"))
$root.centrifugal.centrifuge.protocol.SubscribeRequest.encode(message.subscribe, writer.uint32(/* id 5, wireType 2 =*/ 42).fork()).ldelim();
if (message.unsubscribe != null && Object.hasOwnProperty.call(message, "unsubscribe"))
$root.centrifugal.centrifuge.protocol.UnsubscribeRequest.encode(message.unsubscribe, writer.uint32(/* id 6, wireType 2 =*/ 50).fork()).ldelim();
if (message.publish != null && Object.hasOwnProperty.call(message, "publish"))
$root.centrifugal.centrifuge.protocol.PublishRequest.encode(message.publish, writer.uint32(/* id 7, wireType 2 =*/ 58).fork()).ldelim();
if (message.presence != null && Object.hasOwnProperty.call(message, "presence"))
$root.centrifugal.centrifuge.protocol.PresenceRequest.encode(message.presence, writer.uint32(/* id 8, wireType 2 =*/ 66).fork()).ldelim();
if (message.presence_stats != null && Object.hasOwnProperty.call(message, "presence_stats"))
$root.centrifugal.centrifuge.protocol.PresenceStatsRequest.encode(message.presence_stats, writer.uint32(/* id 9, wireType 2 =*/ 74).fork()).ldelim();
if (message.history != null && Object.hasOwnProperty.call(message, "history"))
$root.centrifugal.centrifuge.protocol.HistoryRequest.encode(message.history, writer.uint32(/* id 10, wireType 2 =*/ 82).fork()).ldelim();
if (message.ping != null && Object.hasOwnProperty.call(message, "ping"))
$root.centrifugal.centrifuge.protocol.PingRequest.encode(message.ping, writer.uint32(/* id 11, wireType 2 =*/ 90).fork()).ldelim();
if (message.send != null && Object.hasOwnProperty.call(message, "send"))
$root.centrifugal.centrifuge.protocol.SendRequest.encode(message.send, writer.uint32(/* id 12, wireType 2 =*/ 98).fork()).ldelim();
if (message.rpc != null && Object.hasOwnProperty.call(message, "rpc"))
$root.centrifugal.centrifuge.protocol.RPCRequest.encode(message.rpc, writer.uint32(/* id 13, wireType 2 =*/ 106).fork()).ldelim();
if (message.refresh != null && Object.hasOwnProperty.call(message, "refresh"))
$root.centrifugal.centrifuge.protocol.RefreshRequest.encode(message.refresh, writer.uint32(/* id 14, wireType 2 =*/ 114).fork()).ldelim();
if (message.sub_refresh != null && Object.hasOwnProperty.call(message, "sub_refresh"))
$root.centrifugal.centrifuge.protocol.SubRefreshRequest.encode(message.sub_refresh, writer.uint32(/* id 15, wireType 2 =*/ 122).fork()).ldelim();
return writer;
};
/**
* Encodes the specified Command message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.Command.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.Command
* @static
* @param {centrifugal.centrifuge.protocol.ICommand} message Command message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Command.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a Command message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.Command
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.Command} Command
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Command.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.Command();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.id = reader.uint32();
break;
}
case 4: {
message.connect = $root.centrifugal.centrifuge.protocol.ConnectRequest.decode(reader, reader.uint32());
break;
}
case 5: {
message.subscribe = $root.centrifugal.centrifuge.protocol.SubscribeRequest.decode(reader, reader.uint32());
break;
}
case 6: {
message.unsubscribe = $root.centrifugal.centrifuge.protocol.UnsubscribeRequest.decode(reader, reader.uint32());
break;
}
case 7: {
message.publish = $root.centrifugal.centrifuge.protocol.PublishRequest.decode(reader, reader.uint32());
break;
}
case 8: {
message.presence = $root.centrifugal.centrifuge.protocol.PresenceRequest.decode(reader, reader.uint32());
break;
}
case 9: {
message.presence_stats = $root.centrifugal.centrifuge.protocol.PresenceStatsRequest.decode(reader, reader.uint32());
break;
}
case 10: {
message.history = $root.centrifugal.centrifuge.protocol.HistoryRequest.decode(reader, reader.uint32());
break;
}
case 11: {
message.ping = $root.centrifugal.centrifuge.protocol.PingRequest.decode(reader, reader.uint32());
break;
}
case 12: {
message.send = $root.centrifugal.centrifuge.protocol.SendRequest.decode(reader, reader.uint32());
break;
}
case 13: {
message.rpc = $root.centrifugal.centrifuge.protocol.RPCRequest.decode(reader, reader.uint32());
break;
}
case 14: {
message.refresh = $root.centrifugal.centrifuge.protocol.RefreshRequest.decode(reader, reader.uint32());
break;
}
case 15: {
message.sub_refresh = $root.centrifugal.centrifuge.protocol.SubRefreshRequest.decode(reader, reader.uint32());
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a Command message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.Command
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.Command} Command
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Command.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a Command message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.Command
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
Command.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.id != null && message.hasOwnProperty("id"))
if (!$util.isInteger(message.id))
return "id: integer expected";
if (message.connect != null && message.hasOwnProperty("connect")) {
let error = $root.centrifugal.centrifuge.protocol.ConnectRequest.verify(message.connect);
if (error)
return "connect." + error;
}
if (message.subscribe != null && message.hasOwnProperty("subscribe")) {
let error = $root.centrifugal.centrifuge.protocol.SubscribeRequest.verify(message.subscribe);
if (error)
return "subscribe." + error;
}
if (message.unsubscribe != null && message.hasOwnProperty("unsubscribe")) {
let error = $root.centrifugal.centrifuge.protocol.UnsubscribeRequest.verify(message.unsubscribe);
if (error)
return "unsubscribe." + error;
}
if (message.publish != null && message.hasOwnProperty("publish")) {
let error = $root.centrifugal.centrifuge.protocol.PublishRequest.verify(message.publish);
if (error)
return "publish." + error;
}
if (message.presence != null && message.hasOwnProperty("presence")) {
let error = $root.centrifugal.centrifuge.protocol.PresenceRequest.verify(message.presence);
if (error)
return "presence." + error;
}
if (message.presence_stats != null && message.hasOwnProperty("presence_stats")) {
let error = $root.centrifugal.centrifuge.protocol.PresenceStatsRequest.verify(message.presence_stats);
if (error)
return "presence_stats." + error;
}
if (message.history != null && message.hasOwnProperty("history")) {
let error = $root.centrifugal.centrifuge.protocol.HistoryRequest.verify(message.history);
if (error)
return "history." + error;
}
if (message.ping != null && message.hasOwnProperty("ping")) {
let error = $root.centrifugal.centrifuge.protocol.PingRequest.verify(message.ping);
if (error)
return "ping." + error;
}
if (message.send != null && message.hasOwnProperty("send")) {
let error = $root.centrifugal.centrifuge.protocol.SendRequest.verify(message.send);
if (error)
return "send." + error;
}
if (message.rpc != null && message.hasOwnProperty("rpc")) {
let error = $root.centrifugal.centrifuge.protocol.RPCRequest.verify(message.rpc);
if (error)
return "rpc." + error;
}
if (message.refresh != null && message.hasOwnProperty("refresh")) {
let error = $root.centrifugal.centrifuge.protocol.RefreshRequest.verify(message.refresh);
if (error)
return "refresh." + error;
}
if (message.sub_refresh != null && message.hasOwnProperty("sub_refresh")) {
let error = $root.centrifugal.centrifuge.protocol.SubRefreshRequest.verify(message.sub_refresh);
if (error)
return "sub_refresh." + error;
}
return null;
};
/**
* Gets the default type url for Command
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.Command
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
Command.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.Command";
};
return Command;
})();
protocol.Reply = (function () {
/**
* Properties of a Reply.
* @memberof centrifugal.centrifuge.protocol
* @interface IReply
* @property {number|null} [id] Reply id
* @property {centrifugal.centrifuge.protocol.IError|null} [error] Reply error
* @property {centrifugal.centrifuge.protocol.IPush|null} [push] Reply push
* @property {centrifugal.centrifuge.protocol.IConnectResult|null} [connect] Reply connect
* @property {centrifugal.centrifuge.protocol.ISubscribeResult|null} [subscribe] Reply subscribe
* @property {centrifugal.centrifuge.protocol.IUnsubscribeResult|null} [unsubscribe] Reply unsubscribe
* @property {centrifugal.centrifuge.protocol.IPublishResult|null} [publish] Reply publish
* @property {centrifugal.centrifuge.protocol.IPresenceResult|null} [presence] Reply presence
* @property {centrifugal.centrifuge.protocol.IPresenceStatsResult|null} [presence_stats] Reply presence_stats
* @property {centrifugal.centrifuge.protocol.IHistoryResult|null} [history] Reply history
* @property {centrifugal.centrifuge.protocol.IPingResult|null} [ping] Reply ping
* @property {centrifugal.centrifuge.protocol.IRPCResult|null} [rpc] Reply rpc
* @property {centrifugal.centrifuge.protocol.IRefreshResult|null} [refresh] Reply refresh
* @property {centrifugal.centrifuge.protocol.ISubRefreshResult|null} [sub_refresh] Reply sub_refresh
*/
/**
* Constructs a new Reply.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a Reply.
* @implements IReply
* @constructor
* @param {centrifugal.centrifuge.protocol.IReply=} [properties] Properties to set
*/
function Reply(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Reply id.
* @member {number} id
* @memberof centrifugal.centrifuge.protocol.Reply
* @instance
*/
Reply.prototype.id = 0;
/**
* Reply error.
* @member {centrifugal.centrifuge.protocol.IError|null|undefined} error
* @memberof centrifugal.centrifuge.protocol.Reply
* @instance
*/
Reply.prototype.error = null;
/**
* Reply push.
* @member {centrifugal.centrifuge.protocol.IPush|null|undefined} push
* @memberof centrifugal.centrifuge.protocol.Reply
* @instance
*/
Reply.prototype.push = null;
/**
* Reply connect.
* @member {centrifugal.centrifuge.protocol.IConnectResult|null|undefined} connect
* @memberof centrifugal.centrifuge.protocol.Reply
* @instance
*/
Reply.prototype.connect = null;
/**
* Reply subscribe.
* @member {centrifugal.centrifuge.protocol.ISubscribeResult|null|undefined} subscribe
* @memberof centrifugal.centrifuge.protocol.Reply
* @instance
*/
Reply.prototype.subscribe = null;
/**
* Reply unsubscribe.
* @member {centrifugal.centrifuge.protocol.IUnsubscribeResult|null|undefined} unsubscribe
* @memberof centrifugal.centrifuge.protocol.Reply
* @instance
*/
Reply.prototype.unsubscribe = null;
/**
* Reply publish.
* @member {centrifugal.centrifuge.protocol.IPublishResult|null|undefined} publish
* @memberof centrifugal.centrifuge.protocol.Reply
* @instance
*/
Reply.prototype.publish = null;
/**
* Reply presence.
* @member {centrifugal.centrifuge.protocol.IPresenceResult|null|undefined} presence
* @memberof centrifugal.centrifuge.protocol.Reply
* @instance
*/
Reply.prototype.presence = null;
/**
* Reply presence_stats.
* @member {centrifugal.centrifuge.protocol.IPresenceStatsResult|null|undefined} presence_stats
* @memberof centrifugal.centrifuge.protocol.Reply
* @instance
*/
Reply.prototype.presence_stats = null;
/**
* Reply history.
* @member {centrifugal.centrifuge.protocol.IHistoryResult|null|undefined} history
* @memberof centrifugal.centrifuge.protocol.Reply
* @instance
*/
Reply.prototype.history = null;
/**
* Reply ping.
* @member {centrifugal.centrifuge.protocol.IPingResult|null|undefined} ping
* @memberof centrifugal.centrifuge.protocol.Reply
* @instance
*/
Reply.prototype.ping = null;
/**
* Reply rpc.
* @member {centrifugal.centrifuge.protocol.IRPCResult|null|undefined} rpc
* @memberof centrifugal.centrifuge.protocol.Reply
* @instance
*/
Reply.prototype.rpc = null;
/**
* Reply refresh.
* @member {centrifugal.centrifuge.protocol.IRefreshResult|null|undefined} refresh
* @memberof centrifugal.centrifuge.protocol.Reply
* @instance
*/
Reply.prototype.refresh = null;
/**
* Reply sub_refresh.
* @member {centrifugal.centrifuge.protocol.ISubRefreshResult|null|undefined} sub_refresh
* @memberof centrifugal.centrifuge.protocol.Reply
* @instance
*/
Reply.prototype.sub_refresh = null;
/**
* Encodes the specified Reply message. Does not implicitly {@link centrifugal.centrifuge.protocol.Reply.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.Reply
* @static
* @param {centrifugal.centrifuge.protocol.IReply} message Reply message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Reply.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.id != null && Object.hasOwnProperty.call(message, "id"))
writer.uint32(/* id 1, wireType 0 =*/ 8).uint32(message.id);
if (message.error != null && Object.hasOwnProperty.call(message, "error"))
$root.centrifugal.centrifuge.protocol.Error.encode(message.error, writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim();
if (message.push != null && Object.hasOwnProperty.call(message, "push"))
$root.centrifugal.centrifuge.protocol.Push.encode(message.push, writer.uint32(/* id 4, wireType 2 =*/ 34).fork()).ldelim();
if (message.connect != null && Object.hasOwnProperty.call(message, "connect"))
$root.centrifugal.centrifuge.protocol.ConnectResult.encode(message.connect, writer.uint32(/* id 5, wireType 2 =*/ 42).fork()).ldelim();
if (message.subscribe != null && Object.hasOwnProperty.call(message, "subscribe"))
$root.centrifugal.centrifuge.protocol.SubscribeResult.encode(message.subscribe, writer.uint32(/* id 6, wireType 2 =*/ 50).fork()).ldelim();
if (message.unsubscribe != null && Object.hasOwnProperty.call(message, "unsubscribe"))
$root.centrifugal.centrifuge.protocol.UnsubscribeResult.encode(message.unsubscribe, writer.uint32(/* id 7, wireType 2 =*/ 58).fork()).ldelim();
if (message.publish != null && Object.hasOwnProperty.call(message, "publish"))
$root.centrifugal.centrifuge.protocol.PublishResult.encode(message.publish, writer.uint32(/* id 8, wireType 2 =*/ 66).fork()).ldelim();
if (message.presence != null && Object.hasOwnProperty.call(message, "presence"))
$root.centrifugal.centrifuge.protocol.PresenceResult.encode(message.presence, writer.uint32(/* id 9, wireType 2 =*/ 74).fork()).ldelim();
if (message.presence_stats != null && Object.hasOwnProperty.call(message, "presence_stats"))
$root.centrifugal.centrifuge.protocol.PresenceStatsResult.encode(message.presence_stats, writer.uint32(/* id 10, wireType 2 =*/ 82).fork()).ldelim();
if (message.history != null && Object.hasOwnProperty.call(message, "history"))
$root.centrifugal.centrifuge.protocol.HistoryResult.encode(message.history, writer.uint32(/* id 11, wireType 2 =*/ 90).fork()).ldelim();
if (message.ping != null && Object.hasOwnProperty.call(message, "ping"))
$root.centrifugal.centrifuge.protocol.PingResult.encode(message.ping, writer.uint32(/* id 12, wireType 2 =*/ 98).fork()).ldelim();
if (message.rpc != null && Object.hasOwnProperty.call(message, "rpc"))
$root.centrifugal.centrifuge.protocol.RPCResult.encode(message.rpc, writer.uint32(/* id 13, wireType 2 =*/ 106).fork()).ldelim();
if (message.refresh != null && Object.hasOwnProperty.call(message, "refresh"))
$root.centrifugal.centrifuge.protocol.RefreshResult.encode(message.refresh, writer.uint32(/* id 14, wireType 2 =*/ 114).fork()).ldelim();
if (message.sub_refresh != null && Object.hasOwnProperty.call(message, "sub_refresh"))
$root.centrifugal.centrifuge.protocol.SubRefreshResult.encode(message.sub_refresh, writer.uint32(/* id 15, wireType 2 =*/ 122).fork()).ldelim();
return writer;
};
/**
* Encodes the specified Reply message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.Reply.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.Reply
* @static
* @param {centrifugal.centrifuge.protocol.IReply} message Reply message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Reply.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a Reply message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.Reply
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.Reply} Reply
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Reply.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.Reply();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.id = reader.uint32();
break;
}
case 2: {
message.error = $root.centrifugal.centrifuge.protocol.Error.decode(reader, reader.uint32());
break;
}
case 4: {
message.push = $root.centrifugal.centrifuge.protocol.Push.decode(reader, reader.uint32());
break;
}
case 5: {
message.connect = $root.centrifugal.centrifuge.protocol.ConnectResult.decode(reader, reader.uint32());
break;
}
case 6: {
message.subscribe = $root.centrifugal.centrifuge.protocol.SubscribeResult.decode(reader, reader.uint32());
break;
}
case 7: {
message.unsubscribe = $root.centrifugal.centrifuge.protocol.UnsubscribeResult.decode(reader, reader.uint32());
break;
}
case 8: {
message.publish = $root.centrifugal.centrifuge.protocol.PublishResult.decode(reader, reader.uint32());
break;
}
case 9: {
message.presence = $root.centrifugal.centrifuge.protocol.PresenceResult.decode(reader, reader.uint32());
break;
}
case 10: {
message.presence_stats = $root.centrifugal.centrifuge.protocol.PresenceStatsResult.decode(reader, reader.uint32());
break;
}
case 11: {
message.history = $root.centrifugal.centrifuge.protocol.HistoryResult.decode(reader, reader.uint32());
break;
}
case 12: {
message.ping = $root.centrifugal.centrifuge.protocol.PingResult.decode(reader, reader.uint32());
break;
}
case 13: {
message.rpc = $root.centrifugal.centrifuge.protocol.RPCResult.decode(reader, reader.uint32());
break;
}
case 14: {
message.refresh = $root.centrifugal.centrifuge.protocol.RefreshResult.decode(reader, reader.uint32());
break;
}
case 15: {
message.sub_refresh = $root.centrifugal.centrifuge.protocol.SubRefreshResult.decode(reader, reader.uint32());
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a Reply message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.Reply
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.Reply} Reply
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Reply.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a Reply message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.Reply
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
Reply.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.id != null && message.hasOwnProperty("id"))
if (!$util.isInteger(message.id))
return "id: integer expected";
if (message.error != null && message.hasOwnProperty("error")) {
let error = $root.centrifugal.centrifuge.protocol.Error.verify(message.error);
if (error)
return "error." + error;
}
if (message.push != null && message.hasOwnProperty("push")) {
let error = $root.centrifugal.centrifuge.protocol.Push.verify(message.push);
if (error)
return "push." + error;
}
if (message.connect != null && message.hasOwnProperty("connect")) {
let error = $root.centrifugal.centrifuge.protocol.ConnectResult.verify(message.connect);
if (error)
return "connect." + error;
}
if (message.subscribe != null && message.hasOwnProperty("subscribe")) {
let error = $root.centrifugal.centrifuge.protocol.SubscribeResult.verify(message.subscribe);
if (error)
return "subscribe." + error;
}
if (message.unsubscribe != null && message.hasOwnProperty("unsubscribe")) {
let error = $root.centrifugal.centrifuge.protocol.UnsubscribeResult.verify(message.unsubscribe);
if (error)
return "unsubscribe." + error;
}
if (message.publish != null && message.hasOwnProperty("publish")) {
let error = $root.centrifugal.centrifuge.protocol.PublishResult.verify(message.publish);
if (error)
return "publish." + error;
}
if (message.presence != null && message.hasOwnProperty("presence")) {
let error = $root.centrifugal.centrifuge.protocol.PresenceResult.verify(message.presence);
if (error)
return "presence." + error;
}
if (message.presence_stats != null && message.hasOwnProperty("presence_stats")) {
let error = $root.centrifugal.centrifuge.protocol.PresenceStatsResult.verify(message.presence_stats);
if (error)
return "presence_stats." + error;
}
if (message.history != null && message.hasOwnProperty("history")) {
let error = $root.centrifugal.centrifuge.protocol.HistoryResult.verify(message.history);
if (error)
return "history." + error;
}
if (message.ping != null && message.hasOwnProperty("ping")) {
let error = $root.centrifugal.centrifuge.protocol.PingResult.verify(message.ping);
if (error)
return "ping." + error;
}
if (message.rpc != null && message.hasOwnProperty("rpc")) {
let error = $root.centrifugal.centrifuge.protocol.RPCResult.verify(message.rpc);
if (error)
return "rpc." + error;
}
if (message.refresh != null && message.hasOwnProperty("refresh")) {
let error = $root.centrifugal.centrifuge.protocol.RefreshResult.verify(message.refresh);
if (error)
return "refresh." + error;
}
if (message.sub_refresh != null && message.hasOwnProperty("sub_refresh")) {
let error = $root.centrifugal.centrifuge.protocol.SubRefreshResult.verify(message.sub_refresh);
if (error)
return "sub_refresh." + error;
}
return null;
};
/**
* Gets the default type url for Reply
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.Reply
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
Reply.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.Reply";
};
return Reply;
})();
protocol.Push = (function () {
/**
* Properties of a Push.
* @memberof centrifugal.centrifuge.protocol
* @interface IPush
* @property {number|Long|null} [id] Push id
* @property {string|null} [channel] Push channel
* @property {centrifugal.centrifuge.protocol.IPublication|null} [pub] Push pub
* @property {centrifugal.centrifuge.protocol.IJoin|null} [join] Push join
* @property {centrifugal.centrifuge.protocol.ILeave|null} [leave] Push leave
* @property {centrifugal.centrifuge.protocol.IUnsubscribe|null} [unsubscribe] Push unsubscribe
* @property {centrifugal.centrifuge.protocol.IMessage|null} [message] Push message
* @property {centrifugal.centrifuge.protocol.ISubscribe|null} [subscribe] Push subscribe
* @property {centrifugal.centrifuge.protocol.IConnect|null} [connect] Push connect
* @property {centrifugal.centrifuge.protocol.IDisconnect|null} [disconnect] Push disconnect
* @property {centrifugal.centrifuge.protocol.IRefresh|null} [refresh] Push refresh
*/
/**
* Constructs a new Push.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a Push.
* @implements IPush
* @constructor
* @param {centrifugal.centrifuge.protocol.IPush=} [properties] Properties to set
*/
function Push(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Push id.
* @member {number|Long} id
* @memberof centrifugal.centrifuge.protocol.Push
* @instance
*/
Push.prototype.id = $util.Long ? $util.Long.fromBits(0, 0, false) : 0;
/**
* Push channel.
* @member {string} channel
* @memberof centrifugal.centrifuge.protocol.Push
* @instance
*/
Push.prototype.channel = "";
/**
* Push pub.
* @member {centrifugal.centrifuge.protocol.IPublication|null|undefined} pub
* @memberof centrifugal.centrifuge.protocol.Push
* @instance
*/
Push.prototype.pub = null;
/**
* Push join.
* @member {centrifugal.centrifuge.protocol.IJoin|null|undefined} join
* @memberof centrifugal.centrifuge.protocol.Push
* @instance
*/
Push.prototype.join = null;
/**
* Push leave.
* @member {centrifugal.centrifuge.protocol.ILeave|null|undefined} leave
* @memberof centrifugal.centrifuge.protocol.Push
* @instance
*/
Push.prototype.leave = null;
/**
* Push unsubscribe.
* @member {centrifugal.centrifuge.protocol.IUnsubscribe|null|undefined} unsubscribe
* @memberof centrifugal.centrifuge.protocol.Push
* @instance
*/
Push.prototype.unsubscribe = null;
/**
* Push message.
* @member {centrifugal.centrifuge.protocol.IMessage|null|undefined} message
* @memberof centrifugal.centrifuge.protocol.Push
* @instance
*/
Push.prototype.message = null;
/**
* Push subscribe.
* @member {centrifugal.centrifuge.protocol.ISubscribe|null|undefined} subscribe
* @memberof centrifugal.centrifuge.protocol.Push
* @instance
*/
Push.prototype.subscribe = null;
/**
* Push connect.
* @member {centrifugal.centrifuge.protocol.IConnect|null|undefined} connect
* @memberof centrifugal.centrifuge.protocol.Push
* @instance
*/
Push.prototype.connect = null;
/**
* Push disconnect.
* @member {centrifugal.centrifuge.protocol.IDisconnect|null|undefined} disconnect
* @memberof centrifugal.centrifuge.protocol.Push
* @instance
*/
Push.prototype.disconnect = null;
/**
* Push refresh.
* @member {centrifugal.centrifuge.protocol.IRefresh|null|undefined} refresh
* @memberof centrifugal.centrifuge.protocol.Push
* @instance
*/
Push.prototype.refresh = null;
/**
* Encodes the specified Push message. Does not implicitly {@link centrifugal.centrifuge.protocol.Push.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.Push
* @static
* @param {centrifugal.centrifuge.protocol.IPush} message Push message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Push.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.id != null && Object.hasOwnProperty.call(message, "id"))
writer.uint32(/* id 1, wireType 0 =*/ 8).int64(message.id);
if (message.channel != null && Object.hasOwnProperty.call(message, "channel"))
writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.channel);
if (message.pub != null && Object.hasOwnProperty.call(message, "pub"))
$root.centrifugal.centrifuge.protocol.Publication.encode(message.pub, writer.uint32(/* id 4, wireType 2 =*/ 34).fork()).ldelim();
if (message.join != null && Object.hasOwnProperty.call(message, "join"))
$root.centrifugal.centrifuge.protocol.Join.encode(message.join, writer.uint32(/* id 5, wireType 2 =*/ 42).fork()).ldelim();
if (message.leave != null && Object.hasOwnProperty.call(message, "leave"))
$root.centrifugal.centrifuge.protocol.Leave.encode(message.leave, writer.uint32(/* id 6, wireType 2 =*/ 50).fork()).ldelim();
if (message.unsubscribe != null && Object.hasOwnProperty.call(message, "unsubscribe"))
$root.centrifugal.centrifuge.protocol.Unsubscribe.encode(message.unsubscribe, writer.uint32(/* id 7, wireType 2 =*/ 58).fork()).ldelim();
if (message.message != null && Object.hasOwnProperty.call(message, "message"))
$root.centrifugal.centrifuge.protocol.Message.encode(message.message, writer.uint32(/* id 8, wireType 2 =*/ 66).fork()).ldelim();
if (message.subscribe != null && Object.hasOwnProperty.call(message, "subscribe"))
$root.centrifugal.centrifuge.protocol.Subscribe.encode(message.subscribe, writer.uint32(/* id 9, wireType 2 =*/ 74).fork()).ldelim();
if (message.connect != null && Object.hasOwnProperty.call(message, "connect"))
$root.centrifugal.centrifuge.protocol.Connect.encode(message.connect, writer.uint32(/* id 10, wireType 2 =*/ 82).fork()).ldelim();
if (message.disconnect != null && Object.hasOwnProperty.call(message, "disconnect"))
$root.centrifugal.centrifuge.protocol.Disconnect.encode(message.disconnect, writer.uint32(/* id 11, wireType 2 =*/ 90).fork()).ldelim();
if (message.refresh != null && Object.hasOwnProperty.call(message, "refresh"))
$root.centrifugal.centrifuge.protocol.Refresh.encode(message.refresh, writer.uint32(/* id 12, wireType 2 =*/ 98).fork()).ldelim();
return writer;
};
/**
* Encodes the specified Push message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.Push.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.Push
* @static
* @param {centrifugal.centrifuge.protocol.IPush} message Push message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Push.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a Push message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.Push
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.Push} Push
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Push.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.Push();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.id = reader.int64();
break;
}
case 2: {
message.channel = reader.string();
break;
}
case 4: {
message.pub = $root.centrifugal.centrifuge.protocol.Publication.decode(reader, reader.uint32());
break;
}
case 5: {
message.join = $root.centrifugal.centrifuge.protocol.Join.decode(reader, reader.uint32());
break;
}
case 6: {
message.leave = $root.centrifugal.centrifuge.protocol.Leave.decode(reader, reader.uint32());
break;
}
case 7: {
message.unsubscribe = $root.centrifugal.centrifuge.protocol.Unsubscribe.decode(reader, reader.uint32());
break;
}
case 8: {
message.message = $root.centrifugal.centrifuge.protocol.Message.decode(reader, reader.uint32());
break;
}
case 9: {
message.subscribe = $root.centrifugal.centrifuge.protocol.Subscribe.decode(reader, reader.uint32());
break;
}
case 10: {
message.connect = $root.centrifugal.centrifuge.protocol.Connect.decode(reader, reader.uint32());
break;
}
case 11: {
message.disconnect = $root.centrifugal.centrifuge.protocol.Disconnect.decode(reader, reader.uint32());
break;
}
case 12: {
message.refresh = $root.centrifugal.centrifuge.protocol.Refresh.decode(reader, reader.uint32());
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a Push message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.Push
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.Push} Push
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Push.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a Push message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.Push
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
Push.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.id != null && message.hasOwnProperty("id"))
if (!$util.isInteger(message.id) && !(message.id && $util.isInteger(message.id.low) && $util.isInteger(message.id.high)))
return "id: integer|Long expected";
if (message.channel != null && message.hasOwnProperty("channel"))
if (!$util.isString(message.channel))
return "channel: string expected";
if (message.pub != null && message.hasOwnProperty("pub")) {
let error = $root.centrifugal.centrifuge.protocol.Publication.verify(message.pub);
if (error)
return "pub." + error;
}
if (message.join != null && message.hasOwnProperty("join")) {
let error = $root.centrifugal.centrifuge.protocol.Join.verify(message.join);
if (error)
return "join." + error;
}
if (message.leave != null && message.hasOwnProperty("leave")) {
let error = $root.centrifugal.centrifuge.protocol.Leave.verify(message.leave);
if (error)
return "leave." + error;
}
if (message.unsubscribe != null && message.hasOwnProperty("unsubscribe")) {
let error = $root.centrifugal.centrifuge.protocol.Unsubscribe.verify(message.unsubscribe);
if (error)
return "unsubscribe." + error;
}
if (message.message != null && message.hasOwnProperty("message")) {
let error = $root.centrifugal.centrifuge.protocol.Message.verify(message.message);
if (error)
return "message." + error;
}
if (message.subscribe != null && message.hasOwnProperty("subscribe")) {
let error = $root.centrifugal.centrifuge.protocol.Subscribe.verify(message.subscribe);
if (error)
return "subscribe." + error;
}
if (message.connect != null && message.hasOwnProperty("connect")) {
let error = $root.centrifugal.centrifuge.protocol.Connect.verify(message.connect);
if (error)
return "connect." + error;
}
if (message.disconnect != null && message.hasOwnProperty("disconnect")) {
let error = $root.centrifugal.centrifuge.protocol.Disconnect.verify(message.disconnect);
if (error)
return "disconnect." + error;
}
if (message.refresh != null && message.hasOwnProperty("refresh")) {
let error = $root.centrifugal.centrifuge.protocol.Refresh.verify(message.refresh);
if (error)
return "refresh." + error;
}
return null;
};
/**
* Gets the default type url for Push
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.Push
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
Push.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.Push";
};
return Push;
})();
protocol.ClientInfo = (function () {
/**
* Properties of a ClientInfo.
* @memberof centrifugal.centrifuge.protocol
* @interface IClientInfo
* @property {string|null} [user] ClientInfo user
* @property {string|null} [client] ClientInfo client
* @property {Uint8Array|null} [conn_info] ClientInfo conn_info
* @property {Uint8Array|null} [chan_info] ClientInfo chan_info
*/
/**
* Constructs a new ClientInfo.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a ClientInfo.
* @implements IClientInfo
* @constructor
* @param {centrifugal.centrifuge.protocol.IClientInfo=} [properties] Properties to set
*/
function ClientInfo(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* ClientInfo user.
* @member {string} user
* @memberof centrifugal.centrifuge.protocol.ClientInfo
* @instance
*/
ClientInfo.prototype.user = "";
/**
* ClientInfo client.
* @member {string} client
* @memberof centrifugal.centrifuge.protocol.ClientInfo
* @instance
*/
ClientInfo.prototype.client = "";
/**
* ClientInfo conn_info.
* @member {Uint8Array} conn_info
* @memberof centrifugal.centrifuge.protocol.ClientInfo
* @instance
*/
ClientInfo.prototype.conn_info = $util.newBuffer([]);
/**
* ClientInfo chan_info.
* @member {Uint8Array} chan_info
* @memberof centrifugal.centrifuge.protocol.ClientInfo
* @instance
*/
ClientInfo.prototype.chan_info = $util.newBuffer([]);
/**
* Encodes the specified ClientInfo message. Does not implicitly {@link centrifugal.centrifuge.protocol.ClientInfo.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.ClientInfo
* @static
* @param {centrifugal.centrifuge.protocol.IClientInfo} message ClientInfo message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
ClientInfo.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.user != null && Object.hasOwnProperty.call(message, "user"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.user);
if (message.client != null && Object.hasOwnProperty.call(message, "client"))
writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.client);
if (message.conn_info != null && Object.hasOwnProperty.call(message, "conn_info"))
writer.uint32(/* id 3, wireType 2 =*/ 26).bytes(message.conn_info);
if (message.chan_info != null && Object.hasOwnProperty.call(message, "chan_info"))
writer.uint32(/* id 4, wireType 2 =*/ 34).bytes(message.chan_info);
return writer;
};
/**
* Encodes the specified ClientInfo message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.ClientInfo.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.ClientInfo
* @static
* @param {centrifugal.centrifuge.protocol.IClientInfo} message ClientInfo message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
ClientInfo.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a ClientInfo message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.ClientInfo
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.ClientInfo} ClientInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
ClientInfo.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.ClientInfo();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.user = reader.string();
break;
}
case 2: {
message.client = reader.string();
break;
}
case 3: {
message.conn_info = reader.bytes();
break;
}
case 4: {
message.chan_info = reader.bytes();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a ClientInfo message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.ClientInfo
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.ClientInfo} ClientInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
ClientInfo.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a ClientInfo message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.ClientInfo
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
ClientInfo.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.user != null && message.hasOwnProperty("user"))
if (!$util.isString(message.user))
return "user: string expected";
if (message.client != null && message.hasOwnProperty("client"))
if (!$util.isString(message.client))
return "client: string expected";
if (message.conn_info != null && message.hasOwnProperty("conn_info"))
if (!(message.conn_info && typeof message.conn_info.length === "number" || $util.isString(message.conn_info)))
return "conn_info: buffer expected";
if (message.chan_info != null && message.hasOwnProperty("chan_info"))
if (!(message.chan_info && typeof message.chan_info.length === "number" || $util.isString(message.chan_info)))
return "chan_info: buffer expected";
return null;
};
/**
* Gets the default type url for ClientInfo
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.ClientInfo
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
ClientInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.ClientInfo";
};
return ClientInfo;
})();
protocol.Publication = (function () {
/**
* Properties of a Publication.
* @memberof centrifugal.centrifuge.protocol
* @interface IPublication
* @property {Uint8Array|null} [data] Publication data
* @property {centrifugal.centrifuge.protocol.IClientInfo|null} [info] Publication info
* @property {number|Long|null} [offset] Publication offset
* @property {Object.<string,string>|null} [tags] Publication tags
* @property {boolean|null} [delta] Publication delta
* @property {number|Long|null} [time] Publication time
* @property {string|null} [channel] Publication channel
* @property {string|null} [key] Publication key
* @property {boolean|null} [removed] Publication removed
* @property {number|Long|null} [score] Publication score
* @property {string|null} [epoch] Publication epoch
* @property {Uint8Array|null} [prev_data] Publication prev_data
* @property {number|Long|null} [version] Publication version
*/
/**
* Constructs a new Publication.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a Publication.
* @implements IPublication
* @constructor
* @param {centrifugal.centrifuge.protocol.IPublication=} [properties] Properties to set
*/
function Publication(properties) {
this.tags = {};
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Publication data.
* @member {Uint8Array} data
* @memberof centrifugal.centrifuge.protocol.Publication
* @instance
*/
Publication.prototype.data = $util.newBuffer([]);
/**
* Publication info.
* @member {centrifugal.centrifuge.protocol.IClientInfo|null|undefined} info
* @memberof centrifugal.centrifuge.protocol.Publication
* @instance
*/
Publication.prototype.info = null;
/**
* Publication offset.
* @member {number|Long} offset
* @memberof centrifugal.centrifuge.protocol.Publication
* @instance
*/
Publication.prototype.offset = $util.Long ? $util.Long.fromBits(0, 0, true) : 0;
/**
* Publication tags.
* @member {Object.<string,string>} tags
* @memberof centrifugal.centrifuge.protocol.Publication
* @instance
*/
Publication.prototype.tags = $util.emptyObject;
/**
* Publication delta.
* @member {boolean} delta
* @memberof centrifugal.centrifuge.protocol.Publication
* @instance
*/
Publication.prototype.delta = false;
/**
* Publication time.
* @member {number|Long} time
* @memberof centrifugal.centrifuge.protocol.Publication
* @instance
*/
Publication.prototype.time = $util.Long ? $util.Long.fromBits(0, 0, false) : 0;
/**
* Publication channel.
* @member {string} channel
* @memberof centrifugal.centrifuge.protocol.Publication
* @instance
*/
Publication.prototype.channel = "";
/**
* Publication key.
* @member {string} key
* @memberof centrifugal.centrifuge.protocol.Publication
* @instance
*/
Publication.prototype.key = "";
/**
* Publication removed.
* @member {boolean} removed
* @memberof centrifugal.centrifuge.protocol.Publication
* @instance
*/
Publication.prototype.removed = false;
/**
* Publication score.
* @member {number|Long} score
* @memberof centrifugal.centrifuge.protocol.Publication
* @instance
*/
Publication.prototype.score = $util.Long ? $util.Long.fromBits(0, 0, false) : 0;
/**
* Publication epoch.
* @member {string} epoch
* @memberof centrifugal.centrifuge.protocol.Publication
* @instance
*/
Publication.prototype.epoch = "";
/**
* Publication prev_data.
* @member {Uint8Array} prev_data
* @memberof centrifugal.centrifuge.protocol.Publication
* @instance
*/
Publication.prototype.prev_data = $util.newBuffer([]);
/**
* Publication version.
* @member {number|Long} version
* @memberof centrifugal.centrifuge.protocol.Publication
* @instance
*/
Publication.prototype.version = $util.Long ? $util.Long.fromBits(0, 0, true) : 0;
/**
* Encodes the specified Publication message. Does not implicitly {@link centrifugal.centrifuge.protocol.Publication.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.Publication
* @static
* @param {centrifugal.centrifuge.protocol.IPublication} message Publication message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Publication.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.data != null && Object.hasOwnProperty.call(message, "data"))
writer.uint32(/* id 4, wireType 2 =*/ 34).bytes(message.data);
if (message.info != null && Object.hasOwnProperty.call(message, "info"))
$root.centrifugal.centrifuge.protocol.ClientInfo.encode(message.info, writer.uint32(/* id 5, wireType 2 =*/ 42).fork()).ldelim();
if (message.offset != null && Object.hasOwnProperty.call(message, "offset"))
writer.uint32(/* id 6, wireType 0 =*/ 48).uint64(message.offset);
if (message.tags != null && Object.hasOwnProperty.call(message, "tags"))
for (let keys = Object.keys(message.tags), i = 0; i < keys.length; ++i)
writer.uint32(/* id 7, wireType 2 =*/ 58).fork().uint32(/* id 1, wireType 2 =*/ 10).string(keys[i]).uint32(/* id 2, wireType 2 =*/ 18).string(message.tags[keys[i]]).ldelim();
if (message.delta != null && Object.hasOwnProperty.call(message, "delta"))
writer.uint32(/* id 8, wireType 0 =*/ 64).bool(message.delta);
if (message.time != null && Object.hasOwnProperty.call(message, "time"))
writer.uint32(/* id 9, wireType 0 =*/ 72).int64(message.time);
if (message.channel != null && Object.hasOwnProperty.call(message, "channel"))
writer.uint32(/* id 10, wireType 2 =*/ 82).string(message.channel);
if (message.key != null && Object.hasOwnProperty.call(message, "key"))
writer.uint32(/* id 11, wireType 2 =*/ 90).string(message.key);
if (message.removed != null && Object.hasOwnProperty.call(message, "removed"))
writer.uint32(/* id 12, wireType 0 =*/ 96).bool(message.removed);
if (message.score != null && Object.hasOwnProperty.call(message, "score"))
writer.uint32(/* id 13, wireType 0 =*/ 104).sint64(message.score);
if (message.epoch != null && Object.hasOwnProperty.call(message, "epoch"))
writer.uint32(/* id 14, wireType 2 =*/ 114).string(message.epoch);
if (message.prev_data != null && Object.hasOwnProperty.call(message, "prev_data"))
writer.uint32(/* id 15, wireType 2 =*/ 122).bytes(message.prev_data);
if (message.version != null && Object.hasOwnProperty.call(message, "version"))
writer.uint32(/* id 16, wireType 0 =*/ 128).uint64(message.version);
return writer;
};
/**
* Encodes the specified Publication message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.Publication.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.Publication
* @static
* @param {centrifugal.centrifuge.protocol.IPublication} message Publication message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Publication.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a Publication message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.Publication
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.Publication} Publication
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Publication.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.Publication(), key, value;
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 4: {
message.data = reader.bytes();
break;
}
case 5: {
message.info = $root.centrifugal.centrifuge.protocol.ClientInfo.decode(reader, reader.uint32());
break;
}
case 6: {
message.offset = reader.uint64();
break;
}
case 7: {
if (message.tags === $util.emptyObject)
message.tags = {};
let end2 = reader.uint32() + reader.pos;
key = "";
value = "";
while (reader.pos < end2) {
let tag2 = reader.uint32();
switch (tag2 >>> 3) {
case 1:
key = reader.string();
break;
case 2:
value = reader.string();
break;
default:
reader.skipType(tag2 & 7);
break;
}
}
message.tags[key] = value;
break;
}
case 8: {
message.delta = reader.bool();
break;
}
case 9: {
message.time = reader.int64();
break;
}
case 10: {
message.channel = reader.string();
break;
}
case 11: {
message.key = reader.string();
break;
}
case 12: {
message.removed = reader.bool();
break;
}
case 13: {
message.score = reader.sint64();
break;
}
case 14: {
message.epoch = reader.string();
break;
}
case 15: {
message.prev_data = reader.bytes();
break;
}
case 16: {
message.version = reader.uint64();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a Publication message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.Publication
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.Publication} Publication
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Publication.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a Publication message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.Publication
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
Publication.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.data != null && message.hasOwnProperty("data"))
if (!(message.data && typeof message.data.length === "number" || $util.isString(message.data)))
return "data: buffer expected";
if (message.info != null && message.hasOwnProperty("info")) {
let error = $root.centrifugal.centrifuge.protocol.ClientInfo.verify(message.info);
if (error)
return "info." + error;
}
if (message.offset != null && message.hasOwnProperty("offset"))
if (!$util.isInteger(message.offset) && !(message.offset && $util.isInteger(message.offset.low) && $util.isInteger(message.offset.high)))
return "offset: integer|Long expected";
if (message.tags != null && message.hasOwnProperty("tags")) {
if (!$util.isObject(message.tags))
return "tags: object expected";
let key = Object.keys(message.tags);
for (let i = 0; i < key.length; ++i)
if (!$util.isString(message.tags[key[i]]))
return "tags: string{k:string} expected";
}
if (message.delta != null && message.hasOwnProperty("delta"))
if (typeof message.delta !== "boolean")
return "delta: boolean expected";
if (message.time != null && message.hasOwnProperty("time"))
if (!$util.isInteger(message.time) && !(message.time && $util.isInteger(message.time.low) && $util.isInteger(message.time.high)))
return "time: integer|Long expected";
if (message.channel != null && message.hasOwnProperty("channel"))
if (!$util.isString(message.channel))
return "channel: string expected";
if (message.key != null && message.hasOwnProperty("key"))
if (!$util.isString(message.key))
return "key: string expected";
if (message.removed != null && message.hasOwnProperty("removed"))
if (typeof message.removed !== "boolean")
return "removed: boolean expected";
if (message.score != null && message.hasOwnProperty("score"))
if (!$util.isInteger(message.score) && !(message.score && $util.isInteger(message.score.low) && $util.isInteger(message.score.high)))
return "score: integer|Long expected";
if (message.epoch != null && message.hasOwnProperty("epoch"))
if (!$util.isString(message.epoch))
return "epoch: string expected";
if (message.prev_data != null && message.hasOwnProperty("prev_data"))
if (!(message.prev_data && typeof message.prev_data.length === "number" || $util.isString(message.prev_data)))
return "prev_data: buffer expected";
if (message.version != null && message.hasOwnProperty("version"))
if (!$util.isInteger(message.version) && !(message.version && $util.isInteger(message.version.low) && $util.isInteger(message.version.high)))
return "version: integer|Long expected";
return null;
};
/**
* Gets the default type url for Publication
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.Publication
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
Publication.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.Publication";
};
return Publication;
})();
protocol.Join = (function () {
/**
* Properties of a Join.
* @memberof centrifugal.centrifuge.protocol
* @interface IJoin
* @property {centrifugal.centrifuge.protocol.IClientInfo|null} [info] Join info
*/
/**
* Constructs a new Join.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a Join.
* @implements IJoin
* @constructor
* @param {centrifugal.centrifuge.protocol.IJoin=} [properties] Properties to set
*/
function Join(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Join info.
* @member {centrifugal.centrifuge.protocol.IClientInfo|null|undefined} info
* @memberof centrifugal.centrifuge.protocol.Join
* @instance
*/
Join.prototype.info = null;
/**
* Encodes the specified Join message. Does not implicitly {@link centrifugal.centrifuge.protocol.Join.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.Join
* @static
* @param {centrifugal.centrifuge.protocol.IJoin} message Join message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Join.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.info != null && Object.hasOwnProperty.call(message, "info"))
$root.centrifugal.centrifuge.protocol.ClientInfo.encode(message.info, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim();
return writer;
};
/**
* Encodes the specified Join message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.Join.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.Join
* @static
* @param {centrifugal.centrifuge.protocol.IJoin} message Join message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Join.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a Join message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.Join
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.Join} Join
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Join.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.Join();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.info = $root.centrifugal.centrifuge.protocol.ClientInfo.decode(reader, reader.uint32());
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a Join message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.Join
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.Join} Join
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Join.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a Join message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.Join
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
Join.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.info != null && message.hasOwnProperty("info")) {
let error = $root.centrifugal.centrifuge.protocol.ClientInfo.verify(message.info);
if (error)
return "info." + error;
}
return null;
};
/**
* Gets the default type url for Join
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.Join
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
Join.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.Join";
};
return Join;
})();
protocol.Leave = (function () {
/**
* Properties of a Leave.
* @memberof centrifugal.centrifuge.protocol
* @interface ILeave
* @property {centrifugal.centrifuge.protocol.IClientInfo|null} [info] Leave info
*/
/**
* Constructs a new Leave.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a Leave.
* @implements ILeave
* @constructor
* @param {centrifugal.centrifuge.protocol.ILeave=} [properties] Properties to set
*/
function Leave(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Leave info.
* @member {centrifugal.centrifuge.protocol.IClientInfo|null|undefined} info
* @memberof centrifugal.centrifuge.protocol.Leave
* @instance
*/
Leave.prototype.info = null;
/**
* Encodes the specified Leave message. Does not implicitly {@link centrifugal.centrifuge.protocol.Leave.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.Leave
* @static
* @param {centrifugal.centrifuge.protocol.ILeave} message Leave message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Leave.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.info != null && Object.hasOwnProperty.call(message, "info"))
$root.centrifugal.centrifuge.protocol.ClientInfo.encode(message.info, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim();
return writer;
};
/**
* Encodes the specified Leave message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.Leave.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.Leave
* @static
* @param {centrifugal.centrifuge.protocol.ILeave} message Leave message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Leave.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a Leave message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.Leave
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.Leave} Leave
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Leave.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.Leave();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.info = $root.centrifugal.centrifuge.protocol.ClientInfo.decode(reader, reader.uint32());
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a Leave message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.Leave
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.Leave} Leave
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Leave.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a Leave message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.Leave
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
Leave.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.info != null && message.hasOwnProperty("info")) {
let error = $root.centrifugal.centrifuge.protocol.ClientInfo.verify(message.info);
if (error)
return "info." + error;
}
return null;
};
/**
* Gets the default type url for Leave
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.Leave
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
Leave.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.Leave";
};
return Leave;
})();
protocol.Unsubscribe = (function () {
/**
* Properties of an Unsubscribe.
* @memberof centrifugal.centrifuge.protocol
* @interface IUnsubscribe
* @property {number|null} [code] Unsubscribe code
* @property {string|null} [reason] Unsubscribe reason
*/
/**
* Constructs a new Unsubscribe.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents an Unsubscribe.
* @implements IUnsubscribe
* @constructor
* @param {centrifugal.centrifuge.protocol.IUnsubscribe=} [properties] Properties to set
*/
function Unsubscribe(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Unsubscribe code.
* @member {number} code
* @memberof centrifugal.centrifuge.protocol.Unsubscribe
* @instance
*/
Unsubscribe.prototype.code = 0;
/**
* Unsubscribe reason.
* @member {string} reason
* @memberof centrifugal.centrifuge.protocol.Unsubscribe
* @instance
*/
Unsubscribe.prototype.reason = "";
/**
* Encodes the specified Unsubscribe message. Does not implicitly {@link centrifugal.centrifuge.protocol.Unsubscribe.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.Unsubscribe
* @static
* @param {centrifugal.centrifuge.protocol.IUnsubscribe} message Unsubscribe message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Unsubscribe.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.code != null && Object.hasOwnProperty.call(message, "code"))
writer.uint32(/* id 2, wireType 0 =*/ 16).uint32(message.code);
if (message.reason != null && Object.hasOwnProperty.call(message, "reason"))
writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.reason);
return writer;
};
/**
* Encodes the specified Unsubscribe message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.Unsubscribe.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.Unsubscribe
* @static
* @param {centrifugal.centrifuge.protocol.IUnsubscribe} message Unsubscribe message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Unsubscribe.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes an Unsubscribe message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.Unsubscribe
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.Unsubscribe} Unsubscribe
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Unsubscribe.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.Unsubscribe();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 2: {
message.code = reader.uint32();
break;
}
case 3: {
message.reason = reader.string();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes an Unsubscribe message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.Unsubscribe
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.Unsubscribe} Unsubscribe
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Unsubscribe.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies an Unsubscribe message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.Unsubscribe
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
Unsubscribe.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.code != null && message.hasOwnProperty("code"))
if (!$util.isInteger(message.code))
return "code: integer expected";
if (message.reason != null && message.hasOwnProperty("reason"))
if (!$util.isString(message.reason))
return "reason: string expected";
return null;
};
/**
* Gets the default type url for Unsubscribe
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.Unsubscribe
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
Unsubscribe.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.Unsubscribe";
};
return Unsubscribe;
})();
protocol.Subscribe = (function () {
/**
* Properties of a Subscribe.
* @memberof centrifugal.centrifuge.protocol
* @interface ISubscribe
* @property {boolean|null} [recoverable] Subscribe recoverable
* @property {string|null} [epoch] Subscribe epoch
* @property {number|Long|null} [offset] Subscribe offset
* @property {boolean|null} [positioned] Subscribe positioned
* @property {Uint8Array|null} [data] Subscribe data
*/
/**
* Constructs a new Subscribe.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a Subscribe.
* @implements ISubscribe
* @constructor
* @param {centrifugal.centrifuge.protocol.ISubscribe=} [properties] Properties to set
*/
function Subscribe(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Subscribe recoverable.
* @member {boolean} recoverable
* @memberof centrifugal.centrifuge.protocol.Subscribe
* @instance
*/
Subscribe.prototype.recoverable = false;
/**
* Subscribe epoch.
* @member {string} epoch
* @memberof centrifugal.centrifuge.protocol.Subscribe
* @instance
*/
Subscribe.prototype.epoch = "";
/**
* Subscribe offset.
* @member {number|Long} offset
* @memberof centrifugal.centrifuge.protocol.Subscribe
* @instance
*/
Subscribe.prototype.offset = $util.Long ? $util.Long.fromBits(0, 0, true) : 0;
/**
* Subscribe positioned.
* @member {boolean} positioned
* @memberof centrifugal.centrifuge.protocol.Subscribe
* @instance
*/
Subscribe.prototype.positioned = false;
/**
* Subscribe data.
* @member {Uint8Array} data
* @memberof centrifugal.centrifuge.protocol.Subscribe
* @instance
*/
Subscribe.prototype.data = $util.newBuffer([]);
/**
* Encodes the specified Subscribe message. Does not implicitly {@link centrifugal.centrifuge.protocol.Subscribe.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.Subscribe
* @static
* @param {centrifugal.centrifuge.protocol.ISubscribe} message Subscribe message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Subscribe.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.recoverable != null && Object.hasOwnProperty.call(message, "recoverable"))
writer.uint32(/* id 1, wireType 0 =*/ 8).bool(message.recoverable);
if (message.epoch != null && Object.hasOwnProperty.call(message, "epoch"))
writer.uint32(/* id 4, wireType 2 =*/ 34).string(message.epoch);
if (message.offset != null && Object.hasOwnProperty.call(message, "offset"))
writer.uint32(/* id 5, wireType 0 =*/ 40).uint64(message.offset);
if (message.positioned != null && Object.hasOwnProperty.call(message, "positioned"))
writer.uint32(/* id 6, wireType 0 =*/ 48).bool(message.positioned);
if (message.data != null && Object.hasOwnProperty.call(message, "data"))
writer.uint32(/* id 7, wireType 2 =*/ 58).bytes(message.data);
return writer;
};
/**
* Encodes the specified Subscribe message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.Subscribe.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.Subscribe
* @static
* @param {centrifugal.centrifuge.protocol.ISubscribe} message Subscribe message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Subscribe.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a Subscribe message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.Subscribe
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.Subscribe} Subscribe
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Subscribe.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.Subscribe();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.recoverable = reader.bool();
break;
}
case 4: {
message.epoch = reader.string();
break;
}
case 5: {
message.offset = reader.uint64();
break;
}
case 6: {
message.positioned = reader.bool();
break;
}
case 7: {
message.data = reader.bytes();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a Subscribe message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.Subscribe
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.Subscribe} Subscribe
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Subscribe.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a Subscribe message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.Subscribe
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
Subscribe.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.recoverable != null && message.hasOwnProperty("recoverable"))
if (typeof message.recoverable !== "boolean")
return "recoverable: boolean expected";
if (message.epoch != null && message.hasOwnProperty("epoch"))
if (!$util.isString(message.epoch))
return "epoch: string expected";
if (message.offset != null && message.hasOwnProperty("offset"))
if (!$util.isInteger(message.offset) && !(message.offset && $util.isInteger(message.offset.low) && $util.isInteger(message.offset.high)))
return "offset: integer|Long expected";
if (message.positioned != null && message.hasOwnProperty("positioned"))
if (typeof message.positioned !== "boolean")
return "positioned: boolean expected";
if (message.data != null && message.hasOwnProperty("data"))
if (!(message.data && typeof message.data.length === "number" || $util.isString(message.data)))
return "data: buffer expected";
return null;
};
/**
* Gets the default type url for Subscribe
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.Subscribe
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
Subscribe.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.Subscribe";
};
return Subscribe;
})();
protocol.Message = (function () {
/**
* Properties of a Message.
* @memberof centrifugal.centrifuge.protocol
* @interface IMessage
* @property {Uint8Array|null} [data] Message data
*/
/**
* Constructs a new Message.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a Message.
* @implements IMessage
* @constructor
* @param {centrifugal.centrifuge.protocol.IMessage=} [properties] Properties to set
*/
function Message(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Message data.
* @member {Uint8Array} data
* @memberof centrifugal.centrifuge.protocol.Message
* @instance
*/
Message.prototype.data = $util.newBuffer([]);
/**
* Encodes the specified Message message. Does not implicitly {@link centrifugal.centrifuge.protocol.Message.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.Message
* @static
* @param {centrifugal.centrifuge.protocol.IMessage} message Message message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Message.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.data != null && Object.hasOwnProperty.call(message, "data"))
writer.uint32(/* id 1, wireType 2 =*/ 10).bytes(message.data);
return writer;
};
/**
* Encodes the specified Message message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.Message.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.Message
* @static
* @param {centrifugal.centrifuge.protocol.IMessage} message Message message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Message.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a Message message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.Message
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.Message} Message
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Message.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.Message();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.data = reader.bytes();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a Message message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.Message
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.Message} Message
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Message.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a Message message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.Message
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
Message.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.data != null && message.hasOwnProperty("data"))
if (!(message.data && typeof message.data.length === "number" || $util.isString(message.data)))
return "data: buffer expected";
return null;
};
/**
* Gets the default type url for Message
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.Message
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
Message.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.Message";
};
return Message;
})();
protocol.Connect = (function () {
/**
* Properties of a Connect.
* @memberof centrifugal.centrifuge.protocol
* @interface IConnect
* @property {string|null} [client] Connect client
* @property {string|null} [version] Connect version
* @property {Uint8Array|null} [data] Connect data
* @property {Object.<string,centrifugal.centrifuge.protocol.ISubscribeResult>|null} [subs] Connect subs
* @property {boolean|null} [expires] Connect expires
* @property {number|null} [ttl] Connect ttl
* @property {number|null} [ping] Connect ping
* @property {boolean|null} [pong] Connect pong
* @property {string|null} [session] Connect session
* @property {string|null} [node] Connect node
* @property {number|Long|null} [time] Connect time
*/
/**
* Constructs a new Connect.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a Connect.
* @implements IConnect
* @constructor
* @param {centrifugal.centrifuge.protocol.IConnect=} [properties] Properties to set
*/
function Connect(properties) {
this.subs = {};
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Connect client.
* @member {string} client
* @memberof centrifugal.centrifuge.protocol.Connect
* @instance
*/
Connect.prototype.client = "";
/**
* Connect version.
* @member {string} version
* @memberof centrifugal.centrifuge.protocol.Connect
* @instance
*/
Connect.prototype.version = "";
/**
* Connect data.
* @member {Uint8Array} data
* @memberof centrifugal.centrifuge.protocol.Connect
* @instance
*/
Connect.prototype.data = $util.newBuffer([]);
/**
* Connect subs.
* @member {Object.<string,centrifugal.centrifuge.protocol.ISubscribeResult>} subs
* @memberof centrifugal.centrifuge.protocol.Connect
* @instance
*/
Connect.prototype.subs = $util.emptyObject;
/**
* Connect expires.
* @member {boolean} expires
* @memberof centrifugal.centrifuge.protocol.Connect
* @instance
*/
Connect.prototype.expires = false;
/**
* Connect ttl.
* @member {number} ttl
* @memberof centrifugal.centrifuge.protocol.Connect
* @instance
*/
Connect.prototype.ttl = 0;
/**
* Connect ping.
* @member {number} ping
* @memberof centrifugal.centrifuge.protocol.Connect
* @instance
*/
Connect.prototype.ping = 0;
/**
* Connect pong.
* @member {boolean} pong
* @memberof centrifugal.centrifuge.protocol.Connect
* @instance
*/
Connect.prototype.pong = false;
/**
* Connect session.
* @member {string} session
* @memberof centrifugal.centrifuge.protocol.Connect
* @instance
*/
Connect.prototype.session = "";
/**
* Connect node.
* @member {string} node
* @memberof centrifugal.centrifuge.protocol.Connect
* @instance
*/
Connect.prototype.node = "";
/**
* Connect time.
* @member {number|Long} time
* @memberof centrifugal.centrifuge.protocol.Connect
* @instance
*/
Connect.prototype.time = $util.Long ? $util.Long.fromBits(0, 0, false) : 0;
/**
* Encodes the specified Connect message. Does not implicitly {@link centrifugal.centrifuge.protocol.Connect.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.Connect
* @static
* @param {centrifugal.centrifuge.protocol.IConnect} message Connect message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Connect.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.client != null && Object.hasOwnProperty.call(message, "client"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.client);
if (message.version != null && Object.hasOwnProperty.call(message, "version"))
writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.version);
if (message.data != null && Object.hasOwnProperty.call(message, "data"))
writer.uint32(/* id 3, wireType 2 =*/ 26).bytes(message.data);
if (message.subs != null && Object.hasOwnProperty.call(message, "subs"))
for (let keys = Object.keys(message.subs), i = 0; i < keys.length; ++i) {
writer.uint32(/* id 4, wireType 2 =*/ 34).fork().uint32(/* id 1, wireType 2 =*/ 10).string(keys[i]);
$root.centrifugal.centrifuge.protocol.SubscribeResult.encode(message.subs[keys[i]], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim().ldelim();
}
if (message.expires != null && Object.hasOwnProperty.call(message, "expires"))
writer.uint32(/* id 5, wireType 0 =*/ 40).bool(message.expires);
if (message.ttl != null && Object.hasOwnProperty.call(message, "ttl"))
writer.uint32(/* id 6, wireType 0 =*/ 48).uint32(message.ttl);
if (message.ping != null && Object.hasOwnProperty.call(message, "ping"))
writer.uint32(/* id 7, wireType 0 =*/ 56).uint32(message.ping);
if (message.pong != null && Object.hasOwnProperty.call(message, "pong"))
writer.uint32(/* id 8, wireType 0 =*/ 64).bool(message.pong);
if (message.session != null && Object.hasOwnProperty.call(message, "session"))
writer.uint32(/* id 9, wireType 2 =*/ 74).string(message.session);
if (message.node != null && Object.hasOwnProperty.call(message, "node"))
writer.uint32(/* id 10, wireType 2 =*/ 82).string(message.node);
if (message.time != null && Object.hasOwnProperty.call(message, "time"))
writer.uint32(/* id 11, wireType 0 =*/ 88).int64(message.time);
return writer;
};
/**
* Encodes the specified Connect message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.Connect.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.Connect
* @static
* @param {centrifugal.centrifuge.protocol.IConnect} message Connect message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Connect.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a Connect message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.Connect
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.Connect} Connect
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Connect.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.Connect(), key, value;
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.client = reader.string();
break;
}
case 2: {
message.version = reader.string();
break;
}
case 3: {
message.data = reader.bytes();
break;
}
case 4: {
if (message.subs === $util.emptyObject)
message.subs = {};
let end2 = reader.uint32() + reader.pos;
key = "";
value = null;
while (reader.pos < end2) {
let tag2 = reader.uint32();
switch (tag2 >>> 3) {
case 1:
key = reader.string();
break;
case 2:
value = $root.centrifugal.centrifuge.protocol.SubscribeResult.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag2 & 7);
break;
}
}
message.subs[key] = value;
break;
}
case 5: {
message.expires = reader.bool();
break;
}
case 6: {
message.ttl = reader.uint32();
break;
}
case 7: {
message.ping = reader.uint32();
break;
}
case 8: {
message.pong = reader.bool();
break;
}
case 9: {
message.session = reader.string();
break;
}
case 10: {
message.node = reader.string();
break;
}
case 11: {
message.time = reader.int64();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a Connect message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.Connect
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.Connect} Connect
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Connect.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a Connect message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.Connect
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
Connect.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.client != null && message.hasOwnProperty("client"))
if (!$util.isString(message.client))
return "client: string expected";
if (message.version != null && message.hasOwnProperty("version"))
if (!$util.isString(message.version))
return "version: string expected";
if (message.data != null && message.hasOwnProperty("data"))
if (!(message.data && typeof message.data.length === "number" || $util.isString(message.data)))
return "data: buffer expected";
if (message.subs != null && message.hasOwnProperty("subs")) {
if (!$util.isObject(message.subs))
return "subs: object expected";
let key = Object.keys(message.subs);
for (let i = 0; i < key.length; ++i) {
let error = $root.centrifugal.centrifuge.protocol.SubscribeResult.verify(message.subs[key[i]]);
if (error)
return "subs." + error;
}
}
if (message.expires != null && message.hasOwnProperty("expires"))
if (typeof message.expires !== "boolean")
return "expires: boolean expected";
if (message.ttl != null && message.hasOwnProperty("ttl"))
if (!$util.isInteger(message.ttl))
return "ttl: integer expected";
if (message.ping != null && message.hasOwnProperty("ping"))
if (!$util.isInteger(message.ping))
return "ping: integer expected";
if (message.pong != null && message.hasOwnProperty("pong"))
if (typeof message.pong !== "boolean")
return "pong: boolean expected";
if (message.session != null && message.hasOwnProperty("session"))
if (!$util.isString(message.session))
return "session: string expected";
if (message.node != null && message.hasOwnProperty("node"))
if (!$util.isString(message.node))
return "node: string expected";
if (message.time != null && message.hasOwnProperty("time"))
if (!$util.isInteger(message.time) && !(message.time && $util.isInteger(message.time.low) && $util.isInteger(message.time.high)))
return "time: integer|Long expected";
return null;
};
/**
* Gets the default type url for Connect
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.Connect
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
Connect.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.Connect";
};
return Connect;
})();
protocol.Disconnect = (function () {
/**
* Properties of a Disconnect.
* @memberof centrifugal.centrifuge.protocol
* @interface IDisconnect
* @property {number|null} [code] Disconnect code
* @property {string|null} [reason] Disconnect reason
* @property {boolean|null} [reconnect] Disconnect reconnect
*/
/**
* Constructs a new Disconnect.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a Disconnect.
* @implements IDisconnect
* @constructor
* @param {centrifugal.centrifuge.protocol.IDisconnect=} [properties] Properties to set
*/
function Disconnect(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Disconnect code.
* @member {number} code
* @memberof centrifugal.centrifuge.protocol.Disconnect
* @instance
*/
Disconnect.prototype.code = 0;
/**
* Disconnect reason.
* @member {string} reason
* @memberof centrifugal.centrifuge.protocol.Disconnect
* @instance
*/
Disconnect.prototype.reason = "";
/**
* Disconnect reconnect.
* @member {boolean} reconnect
* @memberof centrifugal.centrifuge.protocol.Disconnect
* @instance
*/
Disconnect.prototype.reconnect = false;
/**
* Encodes the specified Disconnect message. Does not implicitly {@link centrifugal.centrifuge.protocol.Disconnect.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.Disconnect
* @static
* @param {centrifugal.centrifuge.protocol.IDisconnect} message Disconnect message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Disconnect.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.code != null && Object.hasOwnProperty.call(message, "code"))
writer.uint32(/* id 1, wireType 0 =*/ 8).uint32(message.code);
if (message.reason != null && Object.hasOwnProperty.call(message, "reason"))
writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.reason);
if (message.reconnect != null && Object.hasOwnProperty.call(message, "reconnect"))
writer.uint32(/* id 3, wireType 0 =*/ 24).bool(message.reconnect);
return writer;
};
/**
* Encodes the specified Disconnect message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.Disconnect.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.Disconnect
* @static
* @param {centrifugal.centrifuge.protocol.IDisconnect} message Disconnect message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Disconnect.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a Disconnect message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.Disconnect
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.Disconnect} Disconnect
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Disconnect.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.Disconnect();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.code = reader.uint32();
break;
}
case 2: {
message.reason = reader.string();
break;
}
case 3: {
message.reconnect = reader.bool();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a Disconnect message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.Disconnect
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.Disconnect} Disconnect
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Disconnect.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a Disconnect message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.Disconnect
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
Disconnect.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.code != null && message.hasOwnProperty("code"))
if (!$util.isInteger(message.code))
return "code: integer expected";
if (message.reason != null && message.hasOwnProperty("reason"))
if (!$util.isString(message.reason))
return "reason: string expected";
if (message.reconnect != null && message.hasOwnProperty("reconnect"))
if (typeof message.reconnect !== "boolean")
return "reconnect: boolean expected";
return null;
};
/**
* Gets the default type url for Disconnect
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.Disconnect
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
Disconnect.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.Disconnect";
};
return Disconnect;
})();
protocol.Refresh = (function () {
/**
* Properties of a Refresh.
* @memberof centrifugal.centrifuge.protocol
* @interface IRefresh
* @property {boolean|null} [expires] Refresh expires
* @property {number|null} [ttl] Refresh ttl
*/
/**
* Constructs a new Refresh.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a Refresh.
* @implements IRefresh
* @constructor
* @param {centrifugal.centrifuge.protocol.IRefresh=} [properties] Properties to set
*/
function Refresh(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Refresh expires.
* @member {boolean} expires
* @memberof centrifugal.centrifuge.protocol.Refresh
* @instance
*/
Refresh.prototype.expires = false;
/**
* Refresh ttl.
* @member {number} ttl
* @memberof centrifugal.centrifuge.protocol.Refresh
* @instance
*/
Refresh.prototype.ttl = 0;
/**
* Encodes the specified Refresh message. Does not implicitly {@link centrifugal.centrifuge.protocol.Refresh.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.Refresh
* @static
* @param {centrifugal.centrifuge.protocol.IRefresh} message Refresh message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Refresh.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.expires != null && Object.hasOwnProperty.call(message, "expires"))
writer.uint32(/* id 1, wireType 0 =*/ 8).bool(message.expires);
if (message.ttl != null && Object.hasOwnProperty.call(message, "ttl"))
writer.uint32(/* id 2, wireType 0 =*/ 16).uint32(message.ttl);
return writer;
};
/**
* Encodes the specified Refresh message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.Refresh.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.Refresh
* @static
* @param {centrifugal.centrifuge.protocol.IRefresh} message Refresh message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
Refresh.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a Refresh message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.Refresh
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.Refresh} Refresh
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Refresh.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.Refresh();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.expires = reader.bool();
break;
}
case 2: {
message.ttl = reader.uint32();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a Refresh message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.Refresh
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.Refresh} Refresh
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
Refresh.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a Refresh message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.Refresh
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
Refresh.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.expires != null && message.hasOwnProperty("expires"))
if (typeof message.expires !== "boolean")
return "expires: boolean expected";
if (message.ttl != null && message.hasOwnProperty("ttl"))
if (!$util.isInteger(message.ttl))
return "ttl: integer expected";
return null;
};
/**
* Gets the default type url for Refresh
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.Refresh
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
Refresh.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.Refresh";
};
return Refresh;
})();
protocol.ConnectRequest = (function () {
/**
* Properties of a ConnectRequest.
* @memberof centrifugal.centrifuge.protocol
* @interface IConnectRequest
* @property {string|null} [token] ConnectRequest token
* @property {Uint8Array|null} [data] ConnectRequest data
* @property {Object.<string,centrifugal.centrifuge.protocol.ISubscribeRequest>|null} [subs] ConnectRequest subs
* @property {string|null} [name] ConnectRequest name
* @property {string|null} [version] ConnectRequest version
* @property {Object.<string,string>|null} [headers] ConnectRequest headers
* @property {number|Long|null} [flag] ConnectRequest flag
*/
/**
* Constructs a new ConnectRequest.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a ConnectRequest.
* @implements IConnectRequest
* @constructor
* @param {centrifugal.centrifuge.protocol.IConnectRequest=} [properties] Properties to set
*/
function ConnectRequest(properties) {
this.subs = {};
this.headers = {};
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* ConnectRequest token.
* @member {string} token
* @memberof centrifugal.centrifuge.protocol.ConnectRequest
* @instance
*/
ConnectRequest.prototype.token = "";
/**
* ConnectRequest data.
* @member {Uint8Array} data
* @memberof centrifugal.centrifuge.protocol.ConnectRequest
* @instance
*/
ConnectRequest.prototype.data = $util.newBuffer([]);
/**
* ConnectRequest subs.
* @member {Object.<string,centrifugal.centrifuge.protocol.ISubscribeRequest>} subs
* @memberof centrifugal.centrifuge.protocol.ConnectRequest
* @instance
*/
ConnectRequest.prototype.subs = $util.emptyObject;
/**
* ConnectRequest name.
* @member {string} name
* @memberof centrifugal.centrifuge.protocol.ConnectRequest
* @instance
*/
ConnectRequest.prototype.name = "";
/**
* ConnectRequest version.
* @member {string} version
* @memberof centrifugal.centrifuge.protocol.ConnectRequest
* @instance
*/
ConnectRequest.prototype.version = "";
/**
* ConnectRequest headers.
* @member {Object.<string,string>} headers
* @memberof centrifugal.centrifuge.protocol.ConnectRequest
* @instance
*/
ConnectRequest.prototype.headers = $util.emptyObject;
/**
* ConnectRequest flag.
* @member {number|Long} flag
* @memberof centrifugal.centrifuge.protocol.ConnectRequest
* @instance
*/
ConnectRequest.prototype.flag = $util.Long ? $util.Long.fromBits(0, 0, false) : 0;
/**
* Encodes the specified ConnectRequest message. Does not implicitly {@link centrifugal.centrifuge.protocol.ConnectRequest.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.ConnectRequest
* @static
* @param {centrifugal.centrifuge.protocol.IConnectRequest} message ConnectRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
ConnectRequest.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.token != null && Object.hasOwnProperty.call(message, "token"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.token);
if (message.data != null && Object.hasOwnProperty.call(message, "data"))
writer.uint32(/* id 2, wireType 2 =*/ 18).bytes(message.data);
if (message.subs != null && Object.hasOwnProperty.call(message, "subs"))
for (let keys = Object.keys(message.subs), i = 0; i < keys.length; ++i) {
writer.uint32(/* id 3, wireType 2 =*/ 26).fork().uint32(/* id 1, wireType 2 =*/ 10).string(keys[i]);
$root.centrifugal.centrifuge.protocol.SubscribeRequest.encode(message.subs[keys[i]], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim().ldelim();
}
if (message.name != null && Object.hasOwnProperty.call(message, "name"))
writer.uint32(/* id 4, wireType 2 =*/ 34).string(message.name);
if (message.version != null && Object.hasOwnProperty.call(message, "version"))
writer.uint32(/* id 5, wireType 2 =*/ 42).string(message.version);
if (message.headers != null && Object.hasOwnProperty.call(message, "headers"))
for (let keys = Object.keys(message.headers), i = 0; i < keys.length; ++i)
writer.uint32(/* id 6, wireType 2 =*/ 50).fork().uint32(/* id 1, wireType 2 =*/ 10).string(keys[i]).uint32(/* id 2, wireType 2 =*/ 18).string(message.headers[keys[i]]).ldelim();
if (message.flag != null && Object.hasOwnProperty.call(message, "flag"))
writer.uint32(/* id 7, wireType 0 =*/ 56).int64(message.flag);
return writer;
};
/**
* Encodes the specified ConnectRequest message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.ConnectRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.ConnectRequest
* @static
* @param {centrifugal.centrifuge.protocol.IConnectRequest} message ConnectRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
ConnectRequest.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a ConnectRequest message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.ConnectRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.ConnectRequest} ConnectRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
ConnectRequest.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.ConnectRequest(), key, value;
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.token = reader.string();
break;
}
case 2: {
message.data = reader.bytes();
break;
}
case 3: {
if (message.subs === $util.emptyObject)
message.subs = {};
let end2 = reader.uint32() + reader.pos;
key = "";
value = null;
while (reader.pos < end2) {
let tag2 = reader.uint32();
switch (tag2 >>> 3) {
case 1:
key = reader.string();
break;
case 2:
value = $root.centrifugal.centrifuge.protocol.SubscribeRequest.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag2 & 7);
break;
}
}
message.subs[key] = value;
break;
}
case 4: {
message.name = reader.string();
break;
}
case 5: {
message.version = reader.string();
break;
}
case 6: {
if (message.headers === $util.emptyObject)
message.headers = {};
let end2 = reader.uint32() + reader.pos;
key = "";
value = "";
while (reader.pos < end2) {
let tag2 = reader.uint32();
switch (tag2 >>> 3) {
case 1:
key = reader.string();
break;
case 2:
value = reader.string();
break;
default:
reader.skipType(tag2 & 7);
break;
}
}
message.headers[key] = value;
break;
}
case 7: {
message.flag = reader.int64();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a ConnectRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.ConnectRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.ConnectRequest} ConnectRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
ConnectRequest.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a ConnectRequest message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.ConnectRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
ConnectRequest.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.token != null && message.hasOwnProperty("token"))
if (!$util.isString(message.token))
return "token: string expected";
if (message.data != null && message.hasOwnProperty("data"))
if (!(message.data && typeof message.data.length === "number" || $util.isString(message.data)))
return "data: buffer expected";
if (message.subs != null && message.hasOwnProperty("subs")) {
if (!$util.isObject(message.subs))
return "subs: object expected";
let key = Object.keys(message.subs);
for (let i = 0; i < key.length; ++i) {
let error = $root.centrifugal.centrifuge.protocol.SubscribeRequest.verify(message.subs[key[i]]);
if (error)
return "subs." + error;
}
}
if (message.name != null && message.hasOwnProperty("name"))
if (!$util.isString(message.name))
return "name: string expected";
if (message.version != null && message.hasOwnProperty("version"))
if (!$util.isString(message.version))
return "version: string expected";
if (message.headers != null && message.hasOwnProperty("headers")) {
if (!$util.isObject(message.headers))
return "headers: object expected";
let key = Object.keys(message.headers);
for (let i = 0; i < key.length; ++i)
if (!$util.isString(message.headers[key[i]]))
return "headers: string{k:string} expected";
}
if (message.flag != null && message.hasOwnProperty("flag"))
if (!$util.isInteger(message.flag) && !(message.flag && $util.isInteger(message.flag.low) && $util.isInteger(message.flag.high)))
return "flag: integer|Long expected";
return null;
};
/**
* Gets the default type url for ConnectRequest
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.ConnectRequest
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
ConnectRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.ConnectRequest";
};
return ConnectRequest;
})();
protocol.ConnectResult = (function () {
/**
* Properties of a ConnectResult.
* @memberof centrifugal.centrifuge.protocol
* @interface IConnectResult
* @property {string|null} [client] ConnectResult client
* @property {string|null} [version] ConnectResult version
* @property {boolean|null} [expires] ConnectResult expires
* @property {number|null} [ttl] ConnectResult ttl
* @property {Uint8Array|null} [data] ConnectResult data
* @property {Object.<string,centrifugal.centrifuge.protocol.ISubscribeResult>|null} [subs] ConnectResult subs
* @property {number|null} [ping] ConnectResult ping
* @property {boolean|null} [pong] ConnectResult pong
* @property {string|null} [session] ConnectResult session
* @property {string|null} [node] ConnectResult node
* @property {number|Long|null} [time] ConnectResult time
*/
/**
* Constructs a new ConnectResult.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a ConnectResult.
* @implements IConnectResult
* @constructor
* @param {centrifugal.centrifuge.protocol.IConnectResult=} [properties] Properties to set
*/
function ConnectResult(properties) {
this.subs = {};
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* ConnectResult client.
* @member {string} client
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @instance
*/
ConnectResult.prototype.client = "";
/**
* ConnectResult version.
* @member {string} version
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @instance
*/
ConnectResult.prototype.version = "";
/**
* ConnectResult expires.
* @member {boolean} expires
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @instance
*/
ConnectResult.prototype.expires = false;
/**
* ConnectResult ttl.
* @member {number} ttl
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @instance
*/
ConnectResult.prototype.ttl = 0;
/**
* ConnectResult data.
* @member {Uint8Array} data
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @instance
*/
ConnectResult.prototype.data = $util.newBuffer([]);
/**
* ConnectResult subs.
* @member {Object.<string,centrifugal.centrifuge.protocol.ISubscribeResult>} subs
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @instance
*/
ConnectResult.prototype.subs = $util.emptyObject;
/**
* ConnectResult ping.
* @member {number} ping
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @instance
*/
ConnectResult.prototype.ping = 0;
/**
* ConnectResult pong.
* @member {boolean} pong
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @instance
*/
ConnectResult.prototype.pong = false;
/**
* ConnectResult session.
* @member {string} session
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @instance
*/
ConnectResult.prototype.session = "";
/**
* ConnectResult node.
* @member {string} node
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @instance
*/
ConnectResult.prototype.node = "";
/**
* ConnectResult time.
* @member {number|Long} time
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @instance
*/
ConnectResult.prototype.time = $util.Long ? $util.Long.fromBits(0, 0, false) : 0;
/**
* Encodes the specified ConnectResult message. Does not implicitly {@link centrifugal.centrifuge.protocol.ConnectResult.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @static
* @param {centrifugal.centrifuge.protocol.IConnectResult} message ConnectResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
ConnectResult.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.client != null && Object.hasOwnProperty.call(message, "client"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.client);
if (message.version != null && Object.hasOwnProperty.call(message, "version"))
writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.version);
if (message.expires != null && Object.hasOwnProperty.call(message, "expires"))
writer.uint32(/* id 3, wireType 0 =*/ 24).bool(message.expires);
if (message.ttl != null && Object.hasOwnProperty.call(message, "ttl"))
writer.uint32(/* id 4, wireType 0 =*/ 32).uint32(message.ttl);
if (message.data != null && Object.hasOwnProperty.call(message, "data"))
writer.uint32(/* id 5, wireType 2 =*/ 42).bytes(message.data);
if (message.subs != null && Object.hasOwnProperty.call(message, "subs"))
for (let keys = Object.keys(message.subs), i = 0; i < keys.length; ++i) {
writer.uint32(/* id 6, wireType 2 =*/ 50).fork().uint32(/* id 1, wireType 2 =*/ 10).string(keys[i]);
$root.centrifugal.centrifuge.protocol.SubscribeResult.encode(message.subs[keys[i]], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim().ldelim();
}
if (message.ping != null && Object.hasOwnProperty.call(message, "ping"))
writer.uint32(/* id 7, wireType 0 =*/ 56).uint32(message.ping);
if (message.pong != null && Object.hasOwnProperty.call(message, "pong"))
writer.uint32(/* id 8, wireType 0 =*/ 64).bool(message.pong);
if (message.session != null && Object.hasOwnProperty.call(message, "session"))
writer.uint32(/* id 9, wireType 2 =*/ 74).string(message.session);
if (message.node != null && Object.hasOwnProperty.call(message, "node"))
writer.uint32(/* id 10, wireType 2 =*/ 82).string(message.node);
if (message.time != null && Object.hasOwnProperty.call(message, "time"))
writer.uint32(/* id 11, wireType 0 =*/ 88).int64(message.time);
return writer;
};
/**
* Encodes the specified ConnectResult message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.ConnectResult.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @static
* @param {centrifugal.centrifuge.protocol.IConnectResult} message ConnectResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
ConnectResult.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a ConnectResult message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.ConnectResult} ConnectResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
ConnectResult.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.ConnectResult(), key, value;
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.client = reader.string();
break;
}
case 2: {
message.version = reader.string();
break;
}
case 3: {
message.expires = reader.bool();
break;
}
case 4: {
message.ttl = reader.uint32();
break;
}
case 5: {
message.data = reader.bytes();
break;
}
case 6: {
if (message.subs === $util.emptyObject)
message.subs = {};
let end2 = reader.uint32() + reader.pos;
key = "";
value = null;
while (reader.pos < end2) {
let tag2 = reader.uint32();
switch (tag2 >>> 3) {
case 1:
key = reader.string();
break;
case 2:
value = $root.centrifugal.centrifuge.protocol.SubscribeResult.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag2 & 7);
break;
}
}
message.subs[key] = value;
break;
}
case 7: {
message.ping = reader.uint32();
break;
}
case 8: {
message.pong = reader.bool();
break;
}
case 9: {
message.session = reader.string();
break;
}
case 10: {
message.node = reader.string();
break;
}
case 11: {
message.time = reader.int64();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a ConnectResult message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.ConnectResult} ConnectResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
ConnectResult.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a ConnectResult message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
ConnectResult.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.client != null && message.hasOwnProperty("client"))
if (!$util.isString(message.client))
return "client: string expected";
if (message.version != null && message.hasOwnProperty("version"))
if (!$util.isString(message.version))
return "version: string expected";
if (message.expires != null && message.hasOwnProperty("expires"))
if (typeof message.expires !== "boolean")
return "expires: boolean expected";
if (message.ttl != null && message.hasOwnProperty("ttl"))
if (!$util.isInteger(message.ttl))
return "ttl: integer expected";
if (message.data != null && message.hasOwnProperty("data"))
if (!(message.data && typeof message.data.length === "number" || $util.isString(message.data)))
return "data: buffer expected";
if (message.subs != null && message.hasOwnProperty("subs")) {
if (!$util.isObject(message.subs))
return "subs: object expected";
let key = Object.keys(message.subs);
for (let i = 0; i < key.length; ++i) {
let error = $root.centrifugal.centrifuge.protocol.SubscribeResult.verify(message.subs[key[i]]);
if (error)
return "subs." + error;
}
}
if (message.ping != null && message.hasOwnProperty("ping"))
if (!$util.isInteger(message.ping))
return "ping: integer expected";
if (message.pong != null && message.hasOwnProperty("pong"))
if (typeof message.pong !== "boolean")
return "pong: boolean expected";
if (message.session != null && message.hasOwnProperty("session"))
if (!$util.isString(message.session))
return "session: string expected";
if (message.node != null && message.hasOwnProperty("node"))
if (!$util.isString(message.node))
return "node: string expected";
if (message.time != null && message.hasOwnProperty("time"))
if (!$util.isInteger(message.time) && !(message.time && $util.isInteger(message.time.low) && $util.isInteger(message.time.high)))
return "time: integer|Long expected";
return null;
};
/**
* Gets the default type url for ConnectResult
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.ConnectResult
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
ConnectResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.ConnectResult";
};
return ConnectResult;
})();
protocol.RefreshRequest = (function () {
/**
* Properties of a RefreshRequest.
* @memberof centrifugal.centrifuge.protocol
* @interface IRefreshRequest
* @property {string|null} [token] RefreshRequest token
*/
/**
* Constructs a new RefreshRequest.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a RefreshRequest.
* @implements IRefreshRequest
* @constructor
* @param {centrifugal.centrifuge.protocol.IRefreshRequest=} [properties] Properties to set
*/
function RefreshRequest(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* RefreshRequest token.
* @member {string} token
* @memberof centrifugal.centrifuge.protocol.RefreshRequest
* @instance
*/
RefreshRequest.prototype.token = "";
/**
* Encodes the specified RefreshRequest message. Does not implicitly {@link centrifugal.centrifuge.protocol.RefreshRequest.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.RefreshRequest
* @static
* @param {centrifugal.centrifuge.protocol.IRefreshRequest} message RefreshRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
RefreshRequest.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.token != null && Object.hasOwnProperty.call(message, "token"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.token);
return writer;
};
/**
* Encodes the specified RefreshRequest message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.RefreshRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.RefreshRequest
* @static
* @param {centrifugal.centrifuge.protocol.IRefreshRequest} message RefreshRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
RefreshRequest.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a RefreshRequest message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.RefreshRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.RefreshRequest} RefreshRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
RefreshRequest.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.RefreshRequest();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.token = reader.string();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a RefreshRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.RefreshRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.RefreshRequest} RefreshRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
RefreshRequest.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a RefreshRequest message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.RefreshRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
RefreshRequest.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.token != null && message.hasOwnProperty("token"))
if (!$util.isString(message.token))
return "token: string expected";
return null;
};
/**
* Gets the default type url for RefreshRequest
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.RefreshRequest
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
RefreshRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.RefreshRequest";
};
return RefreshRequest;
})();
protocol.RefreshResult = (function () {
/**
* Properties of a RefreshResult.
* @memberof centrifugal.centrifuge.protocol
* @interface IRefreshResult
* @property {string|null} [client] RefreshResult client
* @property {string|null} [version] RefreshResult version
* @property {boolean|null} [expires] RefreshResult expires
* @property {number|null} [ttl] RefreshResult ttl
*/
/**
* Constructs a new RefreshResult.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a RefreshResult.
* @implements IRefreshResult
* @constructor
* @param {centrifugal.centrifuge.protocol.IRefreshResult=} [properties] Properties to set
*/
function RefreshResult(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* RefreshResult client.
* @member {string} client
* @memberof centrifugal.centrifuge.protocol.RefreshResult
* @instance
*/
RefreshResult.prototype.client = "";
/**
* RefreshResult version.
* @member {string} version
* @memberof centrifugal.centrifuge.protocol.RefreshResult
* @instance
*/
RefreshResult.prototype.version = "";
/**
* RefreshResult expires.
* @member {boolean} expires
* @memberof centrifugal.centrifuge.protocol.RefreshResult
* @instance
*/
RefreshResult.prototype.expires = false;
/**
* RefreshResult ttl.
* @member {number} ttl
* @memberof centrifugal.centrifuge.protocol.RefreshResult
* @instance
*/
RefreshResult.prototype.ttl = 0;
/**
* Encodes the specified RefreshResult message. Does not implicitly {@link centrifugal.centrifuge.protocol.RefreshResult.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.RefreshResult
* @static
* @param {centrifugal.centrifuge.protocol.IRefreshResult} message RefreshResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
RefreshResult.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.client != null && Object.hasOwnProperty.call(message, "client"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.client);
if (message.version != null && Object.hasOwnProperty.call(message, "version"))
writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.version);
if (message.expires != null && Object.hasOwnProperty.call(message, "expires"))
writer.uint32(/* id 3, wireType 0 =*/ 24).bool(message.expires);
if (message.ttl != null && Object.hasOwnProperty.call(message, "ttl"))
writer.uint32(/* id 4, wireType 0 =*/ 32).uint32(message.ttl);
return writer;
};
/**
* Encodes the specified RefreshResult message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.RefreshResult.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.RefreshResult
* @static
* @param {centrifugal.centrifuge.protocol.IRefreshResult} message RefreshResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
RefreshResult.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a RefreshResult message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.RefreshResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.RefreshResult} RefreshResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
RefreshResult.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.RefreshResult();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.client = reader.string();
break;
}
case 2: {
message.version = reader.string();
break;
}
case 3: {
message.expires = reader.bool();
break;
}
case 4: {
message.ttl = reader.uint32();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a RefreshResult message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.RefreshResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.RefreshResult} RefreshResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
RefreshResult.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a RefreshResult message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.RefreshResult
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
RefreshResult.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.client != null && message.hasOwnProperty("client"))
if (!$util.isString(message.client))
return "client: string expected";
if (message.version != null && message.hasOwnProperty("version"))
if (!$util.isString(message.version))
return "version: string expected";
if (message.expires != null && message.hasOwnProperty("expires"))
if (typeof message.expires !== "boolean")
return "expires: boolean expected";
if (message.ttl != null && message.hasOwnProperty("ttl"))
if (!$util.isInteger(message.ttl))
return "ttl: integer expected";
return null;
};
/**
* Gets the default type url for RefreshResult
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.RefreshResult
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
RefreshResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.RefreshResult";
};
return RefreshResult;
})();
protocol.SubscribeRequest = (function () {
/**
* Properties of a SubscribeRequest.
* @memberof centrifugal.centrifuge.protocol
* @interface ISubscribeRequest
* @property {string|null} [channel] SubscribeRequest channel
* @property {string|null} [token] SubscribeRequest token
* @property {boolean|null} [recover] SubscribeRequest recover
* @property {string|null} [epoch] SubscribeRequest epoch
* @property {number|Long|null} [offset] SubscribeRequest offset
* @property {Uint8Array|null} [data] SubscribeRequest data
* @property {boolean|null} [positioned] SubscribeRequest positioned
* @property {boolean|null} [recoverable] SubscribeRequest recoverable
* @property {boolean|null} [join_leave] SubscribeRequest join_leave
* @property {string|null} [delta] SubscribeRequest delta
* @property {centrifugal.centrifuge.protocol.IFilterNode|null} [tf] SubscribeRequest tf
* @property {number|Long|null} [flag] SubscribeRequest flag
* @property {number|null} [type] SubscribeRequest type
* @property {number|null} [phase] SubscribeRequest phase
* @property {string|null} [cursor] SubscribeRequest cursor
* @property {number|null} [limit] SubscribeRequest limit
* @property {boolean|null} [asc] SubscribeRequest asc
*/
/**
* Constructs a new SubscribeRequest.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a SubscribeRequest.
* @implements ISubscribeRequest
* @constructor
* @param {centrifugal.centrifuge.protocol.ISubscribeRequest=} [properties] Properties to set
*/
function SubscribeRequest(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* SubscribeRequest channel.
* @member {string} channel
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.channel = "";
/**
* SubscribeRequest token.
* @member {string} token
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.token = "";
/**
* SubscribeRequest recover.
* @member {boolean} recover
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.recover = false;
/**
* SubscribeRequest epoch.
* @member {string} epoch
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.epoch = "";
/**
* SubscribeRequest offset.
* @member {number|Long} offset
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.offset = $util.Long ? $util.Long.fromBits(0, 0, true) : 0;
/**
* SubscribeRequest data.
* @member {Uint8Array} data
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.data = $util.newBuffer([]);
/**
* SubscribeRequest positioned.
* @member {boolean} positioned
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.positioned = false;
/**
* SubscribeRequest recoverable.
* @member {boolean} recoverable
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.recoverable = false;
/**
* SubscribeRequest join_leave.
* @member {boolean} join_leave
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.join_leave = false;
/**
* SubscribeRequest delta.
* @member {string} delta
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.delta = "";
/**
* SubscribeRequest tf.
* @member {centrifugal.centrifuge.protocol.IFilterNode|null|undefined} tf
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.tf = null;
/**
* SubscribeRequest flag.
* @member {number|Long} flag
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.flag = $util.Long ? $util.Long.fromBits(0, 0, false) : 0;
/**
* SubscribeRequest type.
* @member {number} type
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.type = 0;
/**
* SubscribeRequest phase.
* @member {number} phase
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.phase = 0;
/**
* SubscribeRequest cursor.
* @member {string} cursor
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.cursor = "";
/**
* SubscribeRequest limit.
* @member {number} limit
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.limit = 0;
/**
* SubscribeRequest asc.
* @member {boolean} asc
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @instance
*/
SubscribeRequest.prototype.asc = false;
/**
* Encodes the specified SubscribeRequest message. Does not implicitly {@link centrifugal.centrifuge.protocol.SubscribeRequest.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @static
* @param {centrifugal.centrifuge.protocol.ISubscribeRequest} message SubscribeRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
SubscribeRequest.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.channel != null && Object.hasOwnProperty.call(message, "channel"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.channel);
if (message.token != null && Object.hasOwnProperty.call(message, "token"))
writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.token);
if (message.recover != null && Object.hasOwnProperty.call(message, "recover"))
writer.uint32(/* id 3, wireType 0 =*/ 24).bool(message.recover);
if (message.epoch != null && Object.hasOwnProperty.call(message, "epoch"))
writer.uint32(/* id 6, wireType 2 =*/ 50).string(message.epoch);
if (message.offset != null && Object.hasOwnProperty.call(message, "offset"))
writer.uint32(/* id 7, wireType 0 =*/ 56).uint64(message.offset);
if (message.data != null && Object.hasOwnProperty.call(message, "data"))
writer.uint32(/* id 8, wireType 2 =*/ 66).bytes(message.data);
if (message.positioned != null && Object.hasOwnProperty.call(message, "positioned"))
writer.uint32(/* id 9, wireType 0 =*/ 72).bool(message.positioned);
if (message.recoverable != null && Object.hasOwnProperty.call(message, "recoverable"))
writer.uint32(/* id 10, wireType 0 =*/ 80).bool(message.recoverable);
if (message.join_leave != null && Object.hasOwnProperty.call(message, "join_leave"))
writer.uint32(/* id 11, wireType 0 =*/ 88).bool(message.join_leave);
if (message.delta != null && Object.hasOwnProperty.call(message, "delta"))
writer.uint32(/* id 12, wireType 2 =*/ 98).string(message.delta);
if (message.tf != null && Object.hasOwnProperty.call(message, "tf"))
$root.centrifugal.centrifuge.protocol.FilterNode.encode(message.tf, writer.uint32(/* id 13, wireType 2 =*/ 106).fork()).ldelim();
if (message.flag != null && Object.hasOwnProperty.call(message, "flag"))
writer.uint32(/* id 14, wireType 0 =*/ 112).int64(message.flag);
if (message.type != null && Object.hasOwnProperty.call(message, "type"))
writer.uint32(/* id 15, wireType 0 =*/ 120).int32(message.type);
if (message.phase != null && Object.hasOwnProperty.call(message, "phase"))
writer.uint32(/* id 16, wireType 0 =*/ 128).int32(message.phase);
if (message.cursor != null && Object.hasOwnProperty.call(message, "cursor"))
writer.uint32(/* id 17, wireType 2 =*/ 138).string(message.cursor);
if (message.limit != null && Object.hasOwnProperty.call(message, "limit"))
writer.uint32(/* id 18, wireType 0 =*/ 144).int32(message.limit);
if (message.asc != null && Object.hasOwnProperty.call(message, "asc"))
writer.uint32(/* id 19, wireType 0 =*/ 152).bool(message.asc);
return writer;
};
/**
* Encodes the specified SubscribeRequest message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.SubscribeRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @static
* @param {centrifugal.centrifuge.protocol.ISubscribeRequest} message SubscribeRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
SubscribeRequest.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a SubscribeRequest message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.SubscribeRequest} SubscribeRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
SubscribeRequest.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.SubscribeRequest();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.channel = reader.string();
break;
}
case 2: {
message.token = reader.string();
break;
}
case 3: {
message.recover = reader.bool();
break;
}
case 6: {
message.epoch = reader.string();
break;
}
case 7: {
message.offset = reader.uint64();
break;
}
case 8: {
message.data = reader.bytes();
break;
}
case 9: {
message.positioned = reader.bool();
break;
}
case 10: {
message.recoverable = reader.bool();
break;
}
case 11: {
message.join_leave = reader.bool();
break;
}
case 12: {
message.delta = reader.string();
break;
}
case 13: {
message.tf = $root.centrifugal.centrifuge.protocol.FilterNode.decode(reader, reader.uint32());
break;
}
case 14: {
message.flag = reader.int64();
break;
}
case 15: {
message.type = reader.int32();
break;
}
case 16: {
message.phase = reader.int32();
break;
}
case 17: {
message.cursor = reader.string();
break;
}
case 18: {
message.limit = reader.int32();
break;
}
case 19: {
message.asc = reader.bool();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a SubscribeRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.SubscribeRequest} SubscribeRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
SubscribeRequest.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a SubscribeRequest message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
SubscribeRequest.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.channel != null && message.hasOwnProperty("channel"))
if (!$util.isString(message.channel))
return "channel: string expected";
if (message.token != null && message.hasOwnProperty("token"))
if (!$util.isString(message.token))
return "token: string expected";
if (message.recover != null && message.hasOwnProperty("recover"))
if (typeof message.recover !== "boolean")
return "recover: boolean expected";
if (message.epoch != null && message.hasOwnProperty("epoch"))
if (!$util.isString(message.epoch))
return "epoch: string expected";
if (message.offset != null && message.hasOwnProperty("offset"))
if (!$util.isInteger(message.offset) && !(message.offset && $util.isInteger(message.offset.low) && $util.isInteger(message.offset.high)))
return "offset: integer|Long expected";
if (message.data != null && message.hasOwnProperty("data"))
if (!(message.data && typeof message.data.length === "number" || $util.isString(message.data)))
return "data: buffer expected";
if (message.positioned != null && message.hasOwnProperty("positioned"))
if (typeof message.positioned !== "boolean")
return "positioned: boolean expected";
if (message.recoverable != null && message.hasOwnProperty("recoverable"))
if (typeof message.recoverable !== "boolean")
return "recoverable: boolean expected";
if (message.join_leave != null && message.hasOwnProperty("join_leave"))
if (typeof message.join_leave !== "boolean")
return "join_leave: boolean expected";
if (message.delta != null && message.hasOwnProperty("delta"))
if (!$util.isString(message.delta))
return "delta: string expected";
if (message.tf != null && message.hasOwnProperty("tf")) {
let error = $root.centrifugal.centrifuge.protocol.FilterNode.verify(message.tf);
if (error)
return "tf." + error;
}
if (message.flag != null && message.hasOwnProperty("flag"))
if (!$util.isInteger(message.flag) && !(message.flag && $util.isInteger(message.flag.low) && $util.isInteger(message.flag.high)))
return "flag: integer|Long expected";
if (message.type != null && message.hasOwnProperty("type"))
if (!$util.isInteger(message.type))
return "type: integer expected";
if (message.phase != null && message.hasOwnProperty("phase"))
if (!$util.isInteger(message.phase))
return "phase: integer expected";
if (message.cursor != null && message.hasOwnProperty("cursor"))
if (!$util.isString(message.cursor))
return "cursor: string expected";
if (message.limit != null && message.hasOwnProperty("limit"))
if (!$util.isInteger(message.limit))
return "limit: integer expected";
if (message.asc != null && message.hasOwnProperty("asc"))
if (typeof message.asc !== "boolean")
return "asc: boolean expected";
return null;
};
/**
* Gets the default type url for SubscribeRequest
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.SubscribeRequest
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
SubscribeRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.SubscribeRequest";
};
return SubscribeRequest;
})();
protocol.SubscribeResult = (function () {
/**
* Properties of a SubscribeResult.
* @memberof centrifugal.centrifuge.protocol
* @interface ISubscribeResult
* @property {boolean|null} [expires] SubscribeResult expires
* @property {number|null} [ttl] SubscribeResult ttl
* @property {boolean|null} [recoverable] SubscribeResult recoverable
* @property {string|null} [epoch] SubscribeResult epoch
* @property {Array.<centrifugal.centrifuge.protocol.IPublication>|null} [publications] SubscribeResult publications
* @property {boolean|null} [recovered] SubscribeResult recovered
* @property {number|Long|null} [offset] SubscribeResult offset
* @property {boolean|null} [positioned] SubscribeResult positioned
* @property {Uint8Array|null} [data] SubscribeResult data
* @property {boolean|null} [was_recovering] SubscribeResult was_recovering
* @property {boolean|null} [delta] SubscribeResult delta
* @property {number|Long|null} [id] SubscribeResult id
* @property {number|null} [type] SubscribeResult type
* @property {number|null} [phase] SubscribeResult phase
* @property {string|null} [cursor] SubscribeResult cursor
* @property {Array.<centrifugal.centrifuge.protocol.IPublication>|null} [state] SubscribeResult state
* @property {number|null} [publish_debounce] SubscribeResult publish_debounce
*/
/**
* Constructs a new SubscribeResult.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a SubscribeResult.
* @implements ISubscribeResult
* @constructor
* @param {centrifugal.centrifuge.protocol.ISubscribeResult=} [properties] Properties to set
*/
function SubscribeResult(properties) {
this.publications = [];
this.state = [];
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* SubscribeResult expires.
* @member {boolean} expires
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.expires = false;
/**
* SubscribeResult ttl.
* @member {number} ttl
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.ttl = 0;
/**
* SubscribeResult recoverable.
* @member {boolean} recoverable
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.recoverable = false;
/**
* SubscribeResult epoch.
* @member {string} epoch
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.epoch = "";
/**
* SubscribeResult publications.
* @member {Array.<centrifugal.centrifuge.protocol.IPublication>} publications
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.publications = $util.emptyArray;
/**
* SubscribeResult recovered.
* @member {boolean} recovered
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.recovered = false;
/**
* SubscribeResult offset.
* @member {number|Long} offset
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.offset = $util.Long ? $util.Long.fromBits(0, 0, true) : 0;
/**
* SubscribeResult positioned.
* @member {boolean} positioned
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.positioned = false;
/**
* SubscribeResult data.
* @member {Uint8Array} data
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.data = $util.newBuffer([]);
/**
* SubscribeResult was_recovering.
* @member {boolean} was_recovering
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.was_recovering = false;
/**
* SubscribeResult delta.
* @member {boolean} delta
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.delta = false;
/**
* SubscribeResult id.
* @member {number|Long} id
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.id = $util.Long ? $util.Long.fromBits(0, 0, false) : 0;
/**
* SubscribeResult type.
* @member {number} type
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.type = 0;
/**
* SubscribeResult phase.
* @member {number} phase
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.phase = 0;
/**
* SubscribeResult cursor.
* @member {string} cursor
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.cursor = "";
/**
* SubscribeResult state.
* @member {Array.<centrifugal.centrifuge.protocol.IPublication>} state
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.state = $util.emptyArray;
/**
* SubscribeResult publish_debounce.
* @member {number} publish_debounce
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @instance
*/
SubscribeResult.prototype.publish_debounce = 0;
/**
* Encodes the specified SubscribeResult message. Does not implicitly {@link centrifugal.centrifuge.protocol.SubscribeResult.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @static
* @param {centrifugal.centrifuge.protocol.ISubscribeResult} message SubscribeResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
SubscribeResult.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.expires != null && Object.hasOwnProperty.call(message, "expires"))
writer.uint32(/* id 1, wireType 0 =*/ 8).bool(message.expires);
if (message.ttl != null && Object.hasOwnProperty.call(message, "ttl"))
writer.uint32(/* id 2, wireType 0 =*/ 16).uint32(message.ttl);
if (message.recoverable != null && Object.hasOwnProperty.call(message, "recoverable"))
writer.uint32(/* id 3, wireType 0 =*/ 24).bool(message.recoverable);
if (message.epoch != null && Object.hasOwnProperty.call(message, "epoch"))
writer.uint32(/* id 6, wireType 2 =*/ 50).string(message.epoch);
if (message.publications != null && message.publications.length)
for (let i = 0; i < message.publications.length; ++i)
$root.centrifugal.centrifuge.protocol.Publication.encode(message.publications[i], writer.uint32(/* id 7, wireType 2 =*/ 58).fork()).ldelim();
if (message.recovered != null && Object.hasOwnProperty.call(message, "recovered"))
writer.uint32(/* id 8, wireType 0 =*/ 64).bool(message.recovered);
if (message.offset != null && Object.hasOwnProperty.call(message, "offset"))
writer.uint32(/* id 9, wireType 0 =*/ 72).uint64(message.offset);
if (message.positioned != null && Object.hasOwnProperty.call(message, "positioned"))
writer.uint32(/* id 10, wireType 0 =*/ 80).bool(message.positioned);
if (message.data != null && Object.hasOwnProperty.call(message, "data"))
writer.uint32(/* id 11, wireType 2 =*/ 90).bytes(message.data);
if (message.was_recovering != null && Object.hasOwnProperty.call(message, "was_recovering"))
writer.uint32(/* id 12, wireType 0 =*/ 96).bool(message.was_recovering);
if (message.delta != null && Object.hasOwnProperty.call(message, "delta"))
writer.uint32(/* id 13, wireType 0 =*/ 104).bool(message.delta);
if (message.id != null && Object.hasOwnProperty.call(message, "id"))
writer.uint32(/* id 14, wireType 0 =*/ 112).int64(message.id);
if (message.type != null && Object.hasOwnProperty.call(message, "type"))
writer.uint32(/* id 15, wireType 0 =*/ 120).int32(message.type);
if (message.phase != null && Object.hasOwnProperty.call(message, "phase"))
writer.uint32(/* id 16, wireType 0 =*/ 128).int32(message.phase);
if (message.cursor != null && Object.hasOwnProperty.call(message, "cursor"))
writer.uint32(/* id 17, wireType 2 =*/ 138).string(message.cursor);
if (message.state != null && message.state.length)
for (let i = 0; i < message.state.length; ++i)
$root.centrifugal.centrifuge.protocol.Publication.encode(message.state[i], writer.uint32(/* id 18, wireType 2 =*/ 146).fork()).ldelim();
if (message.publish_debounce != null && Object.hasOwnProperty.call(message, "publish_debounce"))
writer.uint32(/* id 19, wireType 0 =*/ 152).uint32(message.publish_debounce);
return writer;
};
/**
* Encodes the specified SubscribeResult message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.SubscribeResult.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @static
* @param {centrifugal.centrifuge.protocol.ISubscribeResult} message SubscribeResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
SubscribeResult.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a SubscribeResult message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.SubscribeResult} SubscribeResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
SubscribeResult.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.SubscribeResult();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.expires = reader.bool();
break;
}
case 2: {
message.ttl = reader.uint32();
break;
}
case 3: {
message.recoverable = reader.bool();
break;
}
case 6: {
message.epoch = reader.string();
break;
}
case 7: {
if (!(message.publications && message.publications.length))
message.publications = [];
message.publications.push($root.centrifugal.centrifuge.protocol.Publication.decode(reader, reader.uint32()));
break;
}
case 8: {
message.recovered = reader.bool();
break;
}
case 9: {
message.offset = reader.uint64();
break;
}
case 10: {
message.positioned = reader.bool();
break;
}
case 11: {
message.data = reader.bytes();
break;
}
case 12: {
message.was_recovering = reader.bool();
break;
}
case 13: {
message.delta = reader.bool();
break;
}
case 14: {
message.id = reader.int64();
break;
}
case 15: {
message.type = reader.int32();
break;
}
case 16: {
message.phase = reader.int32();
break;
}
case 17: {
message.cursor = reader.string();
break;
}
case 18: {
if (!(message.state && message.state.length))
message.state = [];
message.state.push($root.centrifugal.centrifuge.protocol.Publication.decode(reader, reader.uint32()));
break;
}
case 19: {
message.publish_debounce = reader.uint32();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a SubscribeResult message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.SubscribeResult} SubscribeResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
SubscribeResult.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a SubscribeResult message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
SubscribeResult.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.expires != null && message.hasOwnProperty("expires"))
if (typeof message.expires !== "boolean")
return "expires: boolean expected";
if (message.ttl != null && message.hasOwnProperty("ttl"))
if (!$util.isInteger(message.ttl))
return "ttl: integer expected";
if (message.recoverable != null && message.hasOwnProperty("recoverable"))
if (typeof message.recoverable !== "boolean")
return "recoverable: boolean expected";
if (message.epoch != null && message.hasOwnProperty("epoch"))
if (!$util.isString(message.epoch))
return "epoch: string expected";
if (message.publications != null && message.hasOwnProperty("publications")) {
if (!Array.isArray(message.publications))
return "publications: array expected";
for (let i = 0; i < message.publications.length; ++i) {
let error = $root.centrifugal.centrifuge.protocol.Publication.verify(message.publications[i]);
if (error)
return "publications." + error;
}
}
if (message.recovered != null && message.hasOwnProperty("recovered"))
if (typeof message.recovered !== "boolean")
return "recovered: boolean expected";
if (message.offset != null && message.hasOwnProperty("offset"))
if (!$util.isInteger(message.offset) && !(message.offset && $util.isInteger(message.offset.low) && $util.isInteger(message.offset.high)))
return "offset: integer|Long expected";
if (message.positioned != null && message.hasOwnProperty("positioned"))
if (typeof message.positioned !== "boolean")
return "positioned: boolean expected";
if (message.data != null && message.hasOwnProperty("data"))
if (!(message.data && typeof message.data.length === "number" || $util.isString(message.data)))
return "data: buffer expected";
if (message.was_recovering != null && message.hasOwnProperty("was_recovering"))
if (typeof message.was_recovering !== "boolean")
return "was_recovering: boolean expected";
if (message.delta != null && message.hasOwnProperty("delta"))
if (typeof message.delta !== "boolean")
return "delta: boolean expected";
if (message.id != null && message.hasOwnProperty("id"))
if (!$util.isInteger(message.id) && !(message.id && $util.isInteger(message.id.low) && $util.isInteger(message.id.high)))
return "id: integer|Long expected";
if (message.type != null && message.hasOwnProperty("type"))
if (!$util.isInteger(message.type))
return "type: integer expected";
if (message.phase != null && message.hasOwnProperty("phase"))
if (!$util.isInteger(message.phase))
return "phase: integer expected";
if (message.cursor != null && message.hasOwnProperty("cursor"))
if (!$util.isString(message.cursor))
return "cursor: string expected";
if (message.state != null && message.hasOwnProperty("state")) {
if (!Array.isArray(message.state))
return "state: array expected";
for (let i = 0; i < message.state.length; ++i) {
let error = $root.centrifugal.centrifuge.protocol.Publication.verify(message.state[i]);
if (error)
return "state." + error;
}
}
if (message.publish_debounce != null && message.hasOwnProperty("publish_debounce"))
if (!$util.isInteger(message.publish_debounce))
return "publish_debounce: integer expected";
return null;
};
/**
* Gets the default type url for SubscribeResult
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.SubscribeResult
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
SubscribeResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.SubscribeResult";
};
return SubscribeResult;
})();
protocol.KeyedItem = (function () {
/**
* Properties of a KeyedItem.
* @memberof centrifugal.centrifuge.protocol
* @interface IKeyedItem
* @property {string|null} [key] KeyedItem key
* @property {number|Long|null} [version] KeyedItem version
*/
/**
* Constructs a new KeyedItem.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a KeyedItem.
* @implements IKeyedItem
* @constructor
* @param {centrifugal.centrifuge.protocol.IKeyedItem=} [properties] Properties to set
*/
function KeyedItem(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* KeyedItem key.
* @member {string} key
* @memberof centrifugal.centrifuge.protocol.KeyedItem
* @instance
*/
KeyedItem.prototype.key = "";
/**
* KeyedItem version.
* @member {number|Long} version
* @memberof centrifugal.centrifuge.protocol.KeyedItem
* @instance
*/
KeyedItem.prototype.version = $util.Long ? $util.Long.fromBits(0, 0, true) : 0;
/**
* Encodes the specified KeyedItem message. Does not implicitly {@link centrifugal.centrifuge.protocol.KeyedItem.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.KeyedItem
* @static
* @param {centrifugal.centrifuge.protocol.IKeyedItem} message KeyedItem message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
KeyedItem.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.key != null && Object.hasOwnProperty.call(message, "key"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.key);
if (message.version != null && Object.hasOwnProperty.call(message, "version"))
writer.uint32(/* id 2, wireType 0 =*/ 16).uint64(message.version);
return writer;
};
/**
* Encodes the specified KeyedItem message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.KeyedItem.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.KeyedItem
* @static
* @param {centrifugal.centrifuge.protocol.IKeyedItem} message KeyedItem message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
KeyedItem.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a KeyedItem message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.KeyedItem
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.KeyedItem} KeyedItem
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
KeyedItem.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.KeyedItem();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.key = reader.string();
break;
}
case 2: {
message.version = reader.uint64();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a KeyedItem message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.KeyedItem
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.KeyedItem} KeyedItem
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
KeyedItem.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a KeyedItem message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.KeyedItem
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
KeyedItem.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.key != null && message.hasOwnProperty("key"))
if (!$util.isString(message.key))
return "key: string expected";
if (message.version != null && message.hasOwnProperty("version"))
if (!$util.isInteger(message.version) && !(message.version && $util.isInteger(message.version.low) && $util.isInteger(message.version.high)))
return "version: integer|Long expected";
return null;
};
/**
* Gets the default type url for KeyedItem
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.KeyedItem
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
KeyedItem.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.KeyedItem";
};
return KeyedItem;
})();
protocol.TrackBatch = (function () {
/**
* Properties of a TrackBatch.
* @memberof centrifugal.centrifuge.protocol
* @interface ITrackBatch
* @property {string|null} [signature] TrackBatch signature
* @property {Array.<centrifugal.centrifuge.protocol.IKeyedItem>|null} [items] TrackBatch items
*/
/**
* Constructs a new TrackBatch.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a TrackBatch.
* @implements ITrackBatch
* @constructor
* @param {centrifugal.centrifuge.protocol.ITrackBatch=} [properties] Properties to set
*/
function TrackBatch(properties) {
this.items = [];
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* TrackBatch signature.
* @member {string} signature
* @memberof centrifugal.centrifuge.protocol.TrackBatch
* @instance
*/
TrackBatch.prototype.signature = "";
/**
* TrackBatch items.
* @member {Array.<centrifugal.centrifuge.protocol.IKeyedItem>} items
* @memberof centrifugal.centrifuge.protocol.TrackBatch
* @instance
*/
TrackBatch.prototype.items = $util.emptyArray;
/**
* Encodes the specified TrackBatch message. Does not implicitly {@link centrifugal.centrifuge.protocol.TrackBatch.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.TrackBatch
* @static
* @param {centrifugal.centrifuge.protocol.ITrackBatch} message TrackBatch message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
TrackBatch.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.signature != null && Object.hasOwnProperty.call(message, "signature"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.signature);
if (message.items != null && message.items.length)
for (let i = 0; i < message.items.length; ++i)
$root.centrifugal.centrifuge.protocol.KeyedItem.encode(message.items[i], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim();
return writer;
};
/**
* Encodes the specified TrackBatch message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.TrackBatch.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.TrackBatch
* @static
* @param {centrifugal.centrifuge.protocol.ITrackBatch} message TrackBatch message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
TrackBatch.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a TrackBatch message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.TrackBatch
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.TrackBatch} TrackBatch
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
TrackBatch.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.TrackBatch();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.signature = reader.string();
break;
}
case 2: {
if (!(message.items && message.items.length))
message.items = [];
message.items.push($root.centrifugal.centrifuge.protocol.KeyedItem.decode(reader, reader.uint32()));
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a TrackBatch message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.TrackBatch
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.TrackBatch} TrackBatch
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
TrackBatch.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a TrackBatch message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.TrackBatch
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
TrackBatch.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.signature != null && message.hasOwnProperty("signature"))
if (!$util.isString(message.signature))
return "signature: string expected";
if (message.items != null && message.hasOwnProperty("items")) {
if (!Array.isArray(message.items))
return "items: array expected";
for (let i = 0; i < message.items.length; ++i) {
let error = $root.centrifugal.centrifuge.protocol.KeyedItem.verify(message.items[i]);
if (error)
return "items." + error;
}
}
return null;
};
/**
* Gets the default type url for TrackBatch
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.TrackBatch
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
TrackBatch.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.TrackBatch";
};
return TrackBatch;
})();
protocol.SubRefreshRequest = (function () {
/**
* Properties of a SubRefreshRequest.
* @memberof centrifugal.centrifuge.protocol
* @interface ISubRefreshRequest
* @property {string|null} [channel] SubRefreshRequest channel
* @property {string|null} [token] SubRefreshRequest token
* @property {number|null} [type] SubRefreshRequest type
* @property {Array.<centrifugal.centrifuge.protocol.ITrackBatch>|null} [track] SubRefreshRequest track
* @property {Array.<string>|null} [untrack] SubRefreshRequest untrack
*/
/**
* Constructs a new SubRefreshRequest.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a SubRefreshRequest.
* @implements ISubRefreshRequest
* @constructor
* @param {centrifugal.centrifuge.protocol.ISubRefreshRequest=} [properties] Properties to set
*/
function SubRefreshRequest(properties) {
this.track = [];
this.untrack = [];
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* SubRefreshRequest channel.
* @member {string} channel
* @memberof centrifugal.centrifuge.protocol.SubRefreshRequest
* @instance
*/
SubRefreshRequest.prototype.channel = "";
/**
* SubRefreshRequest token.
* @member {string} token
* @memberof centrifugal.centrifuge.protocol.SubRefreshRequest
* @instance
*/
SubRefreshRequest.prototype.token = "";
/**
* SubRefreshRequest type.
* @member {number} type
* @memberof centrifugal.centrifuge.protocol.SubRefreshRequest
* @instance
*/
SubRefreshRequest.prototype.type = 0;
/**
* SubRefreshRequest track.
* @member {Array.<centrifugal.centrifuge.protocol.ITrackBatch>} track
* @memberof centrifugal.centrifuge.protocol.SubRefreshRequest
* @instance
*/
SubRefreshRequest.prototype.track = $util.emptyArray;
/**
* SubRefreshRequest untrack.
* @member {Array.<string>} untrack
* @memberof centrifugal.centrifuge.protocol.SubRefreshRequest
* @instance
*/
SubRefreshRequest.prototype.untrack = $util.emptyArray;
/**
* Encodes the specified SubRefreshRequest message. Does not implicitly {@link centrifugal.centrifuge.protocol.SubRefreshRequest.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.SubRefreshRequest
* @static
* @param {centrifugal.centrifuge.protocol.ISubRefreshRequest} message SubRefreshRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
SubRefreshRequest.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.channel != null && Object.hasOwnProperty.call(message, "channel"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.channel);
if (message.token != null && Object.hasOwnProperty.call(message, "token"))
writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.token);
if (message.type != null && Object.hasOwnProperty.call(message, "type"))
writer.uint32(/* id 3, wireType 0 =*/ 24).int32(message.type);
if (message.track != null && message.track.length)
for (let i = 0; i < message.track.length; ++i)
$root.centrifugal.centrifuge.protocol.TrackBatch.encode(message.track[i], writer.uint32(/* id 4, wireType 2 =*/ 34).fork()).ldelim();
if (message.untrack != null && message.untrack.length)
for (let i = 0; i < message.untrack.length; ++i)
writer.uint32(/* id 5, wireType 2 =*/ 42).string(message.untrack[i]);
return writer;
};
/**
* Encodes the specified SubRefreshRequest message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.SubRefreshRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.SubRefreshRequest
* @static
* @param {centrifugal.centrifuge.protocol.ISubRefreshRequest} message SubRefreshRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
SubRefreshRequest.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a SubRefreshRequest message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.SubRefreshRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.SubRefreshRequest} SubRefreshRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
SubRefreshRequest.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.SubRefreshRequest();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.channel = reader.string();
break;
}
case 2: {
message.token = reader.string();
break;
}
case 3: {
message.type = reader.int32();
break;
}
case 4: {
if (!(message.track && message.track.length))
message.track = [];
message.track.push($root.centrifugal.centrifuge.protocol.TrackBatch.decode(reader, reader.uint32()));
break;
}
case 5: {
if (!(message.untrack && message.untrack.length))
message.untrack = [];
message.untrack.push(reader.string());
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a SubRefreshRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.SubRefreshRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.SubRefreshRequest} SubRefreshRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
SubRefreshRequest.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a SubRefreshRequest message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.SubRefreshRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
SubRefreshRequest.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.channel != null && message.hasOwnProperty("channel"))
if (!$util.isString(message.channel))
return "channel: string expected";
if (message.token != null && message.hasOwnProperty("token"))
if (!$util.isString(message.token))
return "token: string expected";
if (message.type != null && message.hasOwnProperty("type"))
if (!$util.isInteger(message.type))
return "type: integer expected";
if (message.track != null && message.hasOwnProperty("track")) {
if (!Array.isArray(message.track))
return "track: array expected";
for (let i = 0; i < message.track.length; ++i) {
let error = $root.centrifugal.centrifuge.protocol.TrackBatch.verify(message.track[i]);
if (error)
return "track." + error;
}
}
if (message.untrack != null && message.hasOwnProperty("untrack")) {
if (!Array.isArray(message.untrack))
return "untrack: array expected";
for (let i = 0; i < message.untrack.length; ++i)
if (!$util.isString(message.untrack[i]))
return "untrack: string[] expected";
}
return null;
};
/**
* Gets the default type url for SubRefreshRequest
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.SubRefreshRequest
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
SubRefreshRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.SubRefreshRequest";
};
return SubRefreshRequest;
})();
protocol.SubRefreshResult = (function () {
/**
* Properties of a SubRefreshResult.
* @memberof centrifugal.centrifuge.protocol
* @interface ISubRefreshResult
* @property {boolean|null} [expires] SubRefreshResult expires
* @property {number|null} [ttl] SubRefreshResult ttl
* @property {Array.<centrifugal.centrifuge.protocol.IPublication>|null} [items] SubRefreshResult items
*/
/**
* Constructs a new SubRefreshResult.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a SubRefreshResult.
* @implements ISubRefreshResult
* @constructor
* @param {centrifugal.centrifuge.protocol.ISubRefreshResult=} [properties] Properties to set
*/
function SubRefreshResult(properties) {
this.items = [];
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* SubRefreshResult expires.
* @member {boolean} expires
* @memberof centrifugal.centrifuge.protocol.SubRefreshResult
* @instance
*/
SubRefreshResult.prototype.expires = false;
/**
* SubRefreshResult ttl.
* @member {number} ttl
* @memberof centrifugal.centrifuge.protocol.SubRefreshResult
* @instance
*/
SubRefreshResult.prototype.ttl = 0;
/**
* SubRefreshResult items.
* @member {Array.<centrifugal.centrifuge.protocol.IPublication>} items
* @memberof centrifugal.centrifuge.protocol.SubRefreshResult
* @instance
*/
SubRefreshResult.prototype.items = $util.emptyArray;
/**
* Encodes the specified SubRefreshResult message. Does not implicitly {@link centrifugal.centrifuge.protocol.SubRefreshResult.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.SubRefreshResult
* @static
* @param {centrifugal.centrifuge.protocol.ISubRefreshResult} message SubRefreshResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
SubRefreshResult.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.expires != null && Object.hasOwnProperty.call(message, "expires"))
writer.uint32(/* id 1, wireType 0 =*/ 8).bool(message.expires);
if (message.ttl != null && Object.hasOwnProperty.call(message, "ttl"))
writer.uint32(/* id 2, wireType 0 =*/ 16).uint32(message.ttl);
if (message.items != null && message.items.length)
for (let i = 0; i < message.items.length; ++i)
$root.centrifugal.centrifuge.protocol.Publication.encode(message.items[i], writer.uint32(/* id 3, wireType 2 =*/ 26).fork()).ldelim();
return writer;
};
/**
* Encodes the specified SubRefreshResult message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.SubRefreshResult.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.SubRefreshResult
* @static
* @param {centrifugal.centrifuge.protocol.ISubRefreshResult} message SubRefreshResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
SubRefreshResult.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a SubRefreshResult message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.SubRefreshResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.SubRefreshResult} SubRefreshResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
SubRefreshResult.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.SubRefreshResult();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.expires = reader.bool();
break;
}
case 2: {
message.ttl = reader.uint32();
break;
}
case 3: {
if (!(message.items && message.items.length))
message.items = [];
message.items.push($root.centrifugal.centrifuge.protocol.Publication.decode(reader, reader.uint32()));
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a SubRefreshResult message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.SubRefreshResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.SubRefreshResult} SubRefreshResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
SubRefreshResult.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a SubRefreshResult message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.SubRefreshResult
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
SubRefreshResult.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.expires != null && message.hasOwnProperty("expires"))
if (typeof message.expires !== "boolean")
return "expires: boolean expected";
if (message.ttl != null && message.hasOwnProperty("ttl"))
if (!$util.isInteger(message.ttl))
return "ttl: integer expected";
if (message.items != null && message.hasOwnProperty("items")) {
if (!Array.isArray(message.items))
return "items: array expected";
for (let i = 0; i < message.items.length; ++i) {
let error = $root.centrifugal.centrifuge.protocol.Publication.verify(message.items[i]);
if (error)
return "items." + error;
}
}
return null;
};
/**
* Gets the default type url for SubRefreshResult
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.SubRefreshResult
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
SubRefreshResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.SubRefreshResult";
};
return SubRefreshResult;
})();
protocol.UnsubscribeRequest = (function () {
/**
* Properties of an UnsubscribeRequest.
* @memberof centrifugal.centrifuge.protocol
* @interface IUnsubscribeRequest
* @property {string|null} [channel] UnsubscribeRequest channel
*/
/**
* Constructs a new UnsubscribeRequest.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents an UnsubscribeRequest.
* @implements IUnsubscribeRequest
* @constructor
* @param {centrifugal.centrifuge.protocol.IUnsubscribeRequest=} [properties] Properties to set
*/
function UnsubscribeRequest(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* UnsubscribeRequest channel.
* @member {string} channel
* @memberof centrifugal.centrifuge.protocol.UnsubscribeRequest
* @instance
*/
UnsubscribeRequest.prototype.channel = "";
/**
* Encodes the specified UnsubscribeRequest message. Does not implicitly {@link centrifugal.centrifuge.protocol.UnsubscribeRequest.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.UnsubscribeRequest
* @static
* @param {centrifugal.centrifuge.protocol.IUnsubscribeRequest} message UnsubscribeRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
UnsubscribeRequest.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.channel != null && Object.hasOwnProperty.call(message, "channel"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.channel);
return writer;
};
/**
* Encodes the specified UnsubscribeRequest message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.UnsubscribeRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.UnsubscribeRequest
* @static
* @param {centrifugal.centrifuge.protocol.IUnsubscribeRequest} message UnsubscribeRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
UnsubscribeRequest.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes an UnsubscribeRequest message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.UnsubscribeRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.UnsubscribeRequest} UnsubscribeRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
UnsubscribeRequest.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.UnsubscribeRequest();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.channel = reader.string();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes an UnsubscribeRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.UnsubscribeRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.UnsubscribeRequest} UnsubscribeRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
UnsubscribeRequest.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies an UnsubscribeRequest message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.UnsubscribeRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
UnsubscribeRequest.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.channel != null && message.hasOwnProperty("channel"))
if (!$util.isString(message.channel))
return "channel: string expected";
return null;
};
/**
* Gets the default type url for UnsubscribeRequest
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.UnsubscribeRequest
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
UnsubscribeRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.UnsubscribeRequest";
};
return UnsubscribeRequest;
})();
protocol.UnsubscribeResult = (function () {
/**
* Properties of an UnsubscribeResult.
* @memberof centrifugal.centrifuge.protocol
* @interface IUnsubscribeResult
*/
/**
* Constructs a new UnsubscribeResult.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents an UnsubscribeResult.
* @implements IUnsubscribeResult
* @constructor
* @param {centrifugal.centrifuge.protocol.IUnsubscribeResult=} [properties] Properties to set
*/
function UnsubscribeResult(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Encodes the specified UnsubscribeResult message. Does not implicitly {@link centrifugal.centrifuge.protocol.UnsubscribeResult.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.UnsubscribeResult
* @static
* @param {centrifugal.centrifuge.protocol.IUnsubscribeResult} message UnsubscribeResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
UnsubscribeResult.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
return writer;
};
/**
* Encodes the specified UnsubscribeResult message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.UnsubscribeResult.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.UnsubscribeResult
* @static
* @param {centrifugal.centrifuge.protocol.IUnsubscribeResult} message UnsubscribeResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
UnsubscribeResult.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes an UnsubscribeResult message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.UnsubscribeResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.UnsubscribeResult} UnsubscribeResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
UnsubscribeResult.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.UnsubscribeResult();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes an UnsubscribeResult message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.UnsubscribeResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.UnsubscribeResult} UnsubscribeResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
UnsubscribeResult.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies an UnsubscribeResult message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.UnsubscribeResult
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
UnsubscribeResult.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
return null;
};
/**
* Gets the default type url for UnsubscribeResult
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.UnsubscribeResult
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
UnsubscribeResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.UnsubscribeResult";
};
return UnsubscribeResult;
})();
protocol.PublishRequest = (function () {
/**
* Properties of a PublishRequest.
* @memberof centrifugal.centrifuge.protocol
* @interface IPublishRequest
* @property {string|null} [channel] PublishRequest channel
* @property {Uint8Array|null} [data] PublishRequest data
* @property {number|null} [type] PublishRequest type
* @property {string|null} [key] PublishRequest key
* @property {boolean|null} [removed] PublishRequest removed
*/
/**
* Constructs a new PublishRequest.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a PublishRequest.
* @implements IPublishRequest
* @constructor
* @param {centrifugal.centrifuge.protocol.IPublishRequest=} [properties] Properties to set
*/
function PublishRequest(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* PublishRequest channel.
* @member {string} channel
* @memberof centrifugal.centrifuge.protocol.PublishRequest
* @instance
*/
PublishRequest.prototype.channel = "";
/**
* PublishRequest data.
* @member {Uint8Array} data
* @memberof centrifugal.centrifuge.protocol.PublishRequest
* @instance
*/
PublishRequest.prototype.data = $util.newBuffer([]);
/**
* PublishRequest type.
* @member {number} type
* @memberof centrifugal.centrifuge.protocol.PublishRequest
* @instance
*/
PublishRequest.prototype.type = 0;
/**
* PublishRequest key.
* @member {string} key
* @memberof centrifugal.centrifuge.protocol.PublishRequest
* @instance
*/
PublishRequest.prototype.key = "";
/**
* PublishRequest removed.
* @member {boolean} removed
* @memberof centrifugal.centrifuge.protocol.PublishRequest
* @instance
*/
PublishRequest.prototype.removed = false;
/**
* Encodes the specified PublishRequest message. Does not implicitly {@link centrifugal.centrifuge.protocol.PublishRequest.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.PublishRequest
* @static
* @param {centrifugal.centrifuge.protocol.IPublishRequest} message PublishRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PublishRequest.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.channel != null && Object.hasOwnProperty.call(message, "channel"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.channel);
if (message.data != null && Object.hasOwnProperty.call(message, "data"))
writer.uint32(/* id 2, wireType 2 =*/ 18).bytes(message.data);
if (message.type != null && Object.hasOwnProperty.call(message, "type"))
writer.uint32(/* id 3, wireType 0 =*/ 24).int32(message.type);
if (message.key != null && Object.hasOwnProperty.call(message, "key"))
writer.uint32(/* id 4, wireType 2 =*/ 34).string(message.key);
if (message.removed != null && Object.hasOwnProperty.call(message, "removed"))
writer.uint32(/* id 5, wireType 0 =*/ 40).bool(message.removed);
return writer;
};
/**
* Encodes the specified PublishRequest message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.PublishRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.PublishRequest
* @static
* @param {centrifugal.centrifuge.protocol.IPublishRequest} message PublishRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PublishRequest.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a PublishRequest message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.PublishRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.PublishRequest} PublishRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PublishRequest.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.PublishRequest();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.channel = reader.string();
break;
}
case 2: {
message.data = reader.bytes();
break;
}
case 3: {
message.type = reader.int32();
break;
}
case 4: {
message.key = reader.string();
break;
}
case 5: {
message.removed = reader.bool();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a PublishRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.PublishRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.PublishRequest} PublishRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PublishRequest.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a PublishRequest message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.PublishRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
PublishRequest.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.channel != null && message.hasOwnProperty("channel"))
if (!$util.isString(message.channel))
return "channel: string expected";
if (message.data != null && message.hasOwnProperty("data"))
if (!(message.data && typeof message.data.length === "number" || $util.isString(message.data)))
return "data: buffer expected";
if (message.type != null && message.hasOwnProperty("type"))
if (!$util.isInteger(message.type))
return "type: integer expected";
if (message.key != null && message.hasOwnProperty("key"))
if (!$util.isString(message.key))
return "key: string expected";
if (message.removed != null && message.hasOwnProperty("removed"))
if (typeof message.removed !== "boolean")
return "removed: boolean expected";
return null;
};
/**
* Gets the default type url for PublishRequest
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.PublishRequest
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
PublishRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.PublishRequest";
};
return PublishRequest;
})();
protocol.PublishResult = (function () {
/**
* Properties of a PublishResult.
* @memberof centrifugal.centrifuge.protocol
* @interface IPublishResult
*/
/**
* Constructs a new PublishResult.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a PublishResult.
* @implements IPublishResult
* @constructor
* @param {centrifugal.centrifuge.protocol.IPublishResult=} [properties] Properties to set
*/
function PublishResult(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Encodes the specified PublishResult message. Does not implicitly {@link centrifugal.centrifuge.protocol.PublishResult.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.PublishResult
* @static
* @param {centrifugal.centrifuge.protocol.IPublishResult} message PublishResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PublishResult.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
return writer;
};
/**
* Encodes the specified PublishResult message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.PublishResult.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.PublishResult
* @static
* @param {centrifugal.centrifuge.protocol.IPublishResult} message PublishResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PublishResult.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a PublishResult message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.PublishResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.PublishResult} PublishResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PublishResult.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.PublishResult();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a PublishResult message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.PublishResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.PublishResult} PublishResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PublishResult.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a PublishResult message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.PublishResult
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
PublishResult.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
return null;
};
/**
* Gets the default type url for PublishResult
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.PublishResult
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
PublishResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.PublishResult";
};
return PublishResult;
})();
protocol.PresenceRequest = (function () {
/**
* Properties of a PresenceRequest.
* @memberof centrifugal.centrifuge.protocol
* @interface IPresenceRequest
* @property {string|null} [channel] PresenceRequest channel
*/
/**
* Constructs a new PresenceRequest.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a PresenceRequest.
* @implements IPresenceRequest
* @constructor
* @param {centrifugal.centrifuge.protocol.IPresenceRequest=} [properties] Properties to set
*/
function PresenceRequest(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* PresenceRequest channel.
* @member {string} channel
* @memberof centrifugal.centrifuge.protocol.PresenceRequest
* @instance
*/
PresenceRequest.prototype.channel = "";
/**
* Encodes the specified PresenceRequest message. Does not implicitly {@link centrifugal.centrifuge.protocol.PresenceRequest.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.PresenceRequest
* @static
* @param {centrifugal.centrifuge.protocol.IPresenceRequest} message PresenceRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PresenceRequest.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.channel != null && Object.hasOwnProperty.call(message, "channel"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.channel);
return writer;
};
/**
* Encodes the specified PresenceRequest message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.PresenceRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.PresenceRequest
* @static
* @param {centrifugal.centrifuge.protocol.IPresenceRequest} message PresenceRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PresenceRequest.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a PresenceRequest message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.PresenceRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.PresenceRequest} PresenceRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PresenceRequest.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.PresenceRequest();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.channel = reader.string();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a PresenceRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.PresenceRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.PresenceRequest} PresenceRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PresenceRequest.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a PresenceRequest message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.PresenceRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
PresenceRequest.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.channel != null && message.hasOwnProperty("channel"))
if (!$util.isString(message.channel))
return "channel: string expected";
return null;
};
/**
* Gets the default type url for PresenceRequest
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.PresenceRequest
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
PresenceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.PresenceRequest";
};
return PresenceRequest;
})();
protocol.PresenceResult = (function () {
/**
* Properties of a PresenceResult.
* @memberof centrifugal.centrifuge.protocol
* @interface IPresenceResult
* @property {Object.<string,centrifugal.centrifuge.protocol.IClientInfo>|null} [presence] PresenceResult presence
*/
/**
* Constructs a new PresenceResult.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a PresenceResult.
* @implements IPresenceResult
* @constructor
* @param {centrifugal.centrifuge.protocol.IPresenceResult=} [properties] Properties to set
*/
function PresenceResult(properties) {
this.presence = {};
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* PresenceResult presence.
* @member {Object.<string,centrifugal.centrifuge.protocol.IClientInfo>} presence
* @memberof centrifugal.centrifuge.protocol.PresenceResult
* @instance
*/
PresenceResult.prototype.presence = $util.emptyObject;
/**
* Encodes the specified PresenceResult message. Does not implicitly {@link centrifugal.centrifuge.protocol.PresenceResult.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.PresenceResult
* @static
* @param {centrifugal.centrifuge.protocol.IPresenceResult} message PresenceResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PresenceResult.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.presence != null && Object.hasOwnProperty.call(message, "presence"))
for (let keys = Object.keys(message.presence), i = 0; i < keys.length; ++i) {
writer.uint32(/* id 1, wireType 2 =*/ 10).fork().uint32(/* id 1, wireType 2 =*/ 10).string(keys[i]);
$root.centrifugal.centrifuge.protocol.ClientInfo.encode(message.presence[keys[i]], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim().ldelim();
}
return writer;
};
/**
* Encodes the specified PresenceResult message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.PresenceResult.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.PresenceResult
* @static
* @param {centrifugal.centrifuge.protocol.IPresenceResult} message PresenceResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PresenceResult.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a PresenceResult message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.PresenceResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.PresenceResult} PresenceResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PresenceResult.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.PresenceResult(), key, value;
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
if (message.presence === $util.emptyObject)
message.presence = {};
let end2 = reader.uint32() + reader.pos;
key = "";
value = null;
while (reader.pos < end2) {
let tag2 = reader.uint32();
switch (tag2 >>> 3) {
case 1:
key = reader.string();
break;
case 2:
value = $root.centrifugal.centrifuge.protocol.ClientInfo.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag2 & 7);
break;
}
}
message.presence[key] = value;
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a PresenceResult message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.PresenceResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.PresenceResult} PresenceResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PresenceResult.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a PresenceResult message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.PresenceResult
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
PresenceResult.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.presence != null && message.hasOwnProperty("presence")) {
if (!$util.isObject(message.presence))
return "presence: object expected";
let key = Object.keys(message.presence);
for (let i = 0; i < key.length; ++i) {
let error = $root.centrifugal.centrifuge.protocol.ClientInfo.verify(message.presence[key[i]]);
if (error)
return "presence." + error;
}
}
return null;
};
/**
* Gets the default type url for PresenceResult
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.PresenceResult
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
PresenceResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.PresenceResult";
};
return PresenceResult;
})();
protocol.PresenceStatsRequest = (function () {
/**
* Properties of a PresenceStatsRequest.
* @memberof centrifugal.centrifuge.protocol
* @interface IPresenceStatsRequest
* @property {string|null} [channel] PresenceStatsRequest channel
*/
/**
* Constructs a new PresenceStatsRequest.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a PresenceStatsRequest.
* @implements IPresenceStatsRequest
* @constructor
* @param {centrifugal.centrifuge.protocol.IPresenceStatsRequest=} [properties] Properties to set
*/
function PresenceStatsRequest(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* PresenceStatsRequest channel.
* @member {string} channel
* @memberof centrifugal.centrifuge.protocol.PresenceStatsRequest
* @instance
*/
PresenceStatsRequest.prototype.channel = "";
/**
* Encodes the specified PresenceStatsRequest message. Does not implicitly {@link centrifugal.centrifuge.protocol.PresenceStatsRequest.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.PresenceStatsRequest
* @static
* @param {centrifugal.centrifuge.protocol.IPresenceStatsRequest} message PresenceStatsRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PresenceStatsRequest.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.channel != null && Object.hasOwnProperty.call(message, "channel"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.channel);
return writer;
};
/**
* Encodes the specified PresenceStatsRequest message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.PresenceStatsRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.PresenceStatsRequest
* @static
* @param {centrifugal.centrifuge.protocol.IPresenceStatsRequest} message PresenceStatsRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PresenceStatsRequest.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a PresenceStatsRequest message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.PresenceStatsRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.PresenceStatsRequest} PresenceStatsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PresenceStatsRequest.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.PresenceStatsRequest();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.channel = reader.string();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a PresenceStatsRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.PresenceStatsRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.PresenceStatsRequest} PresenceStatsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PresenceStatsRequest.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a PresenceStatsRequest message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.PresenceStatsRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
PresenceStatsRequest.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.channel != null && message.hasOwnProperty("channel"))
if (!$util.isString(message.channel))
return "channel: string expected";
return null;
};
/**
* Gets the default type url for PresenceStatsRequest
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.PresenceStatsRequest
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
PresenceStatsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.PresenceStatsRequest";
};
return PresenceStatsRequest;
})();
protocol.PresenceStatsResult = (function () {
/**
* Properties of a PresenceStatsResult.
* @memberof centrifugal.centrifuge.protocol
* @interface IPresenceStatsResult
* @property {number|null} [num_clients] PresenceStatsResult num_clients
* @property {number|null} [num_users] PresenceStatsResult num_users
*/
/**
* Constructs a new PresenceStatsResult.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a PresenceStatsResult.
* @implements IPresenceStatsResult
* @constructor
* @param {centrifugal.centrifuge.protocol.IPresenceStatsResult=} [properties] Properties to set
*/
function PresenceStatsResult(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* PresenceStatsResult num_clients.
* @member {number} num_clients
* @memberof centrifugal.centrifuge.protocol.PresenceStatsResult
* @instance
*/
PresenceStatsResult.prototype.num_clients = 0;
/**
* PresenceStatsResult num_users.
* @member {number} num_users
* @memberof centrifugal.centrifuge.protocol.PresenceStatsResult
* @instance
*/
PresenceStatsResult.prototype.num_users = 0;
/**
* Encodes the specified PresenceStatsResult message. Does not implicitly {@link centrifugal.centrifuge.protocol.PresenceStatsResult.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.PresenceStatsResult
* @static
* @param {centrifugal.centrifuge.protocol.IPresenceStatsResult} message PresenceStatsResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PresenceStatsResult.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.num_clients != null && Object.hasOwnProperty.call(message, "num_clients"))
writer.uint32(/* id 1, wireType 0 =*/ 8).uint32(message.num_clients);
if (message.num_users != null && Object.hasOwnProperty.call(message, "num_users"))
writer.uint32(/* id 2, wireType 0 =*/ 16).uint32(message.num_users);
return writer;
};
/**
* Encodes the specified PresenceStatsResult message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.PresenceStatsResult.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.PresenceStatsResult
* @static
* @param {centrifugal.centrifuge.protocol.IPresenceStatsResult} message PresenceStatsResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PresenceStatsResult.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a PresenceStatsResult message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.PresenceStatsResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.PresenceStatsResult} PresenceStatsResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PresenceStatsResult.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.PresenceStatsResult();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.num_clients = reader.uint32();
break;
}
case 2: {
message.num_users = reader.uint32();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a PresenceStatsResult message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.PresenceStatsResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.PresenceStatsResult} PresenceStatsResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PresenceStatsResult.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a PresenceStatsResult message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.PresenceStatsResult
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
PresenceStatsResult.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.num_clients != null && message.hasOwnProperty("num_clients"))
if (!$util.isInteger(message.num_clients))
return "num_clients: integer expected";
if (message.num_users != null && message.hasOwnProperty("num_users"))
if (!$util.isInteger(message.num_users))
return "num_users: integer expected";
return null;
};
/**
* Gets the default type url for PresenceStatsResult
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.PresenceStatsResult
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
PresenceStatsResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.PresenceStatsResult";
};
return PresenceStatsResult;
})();
protocol.StreamPosition = (function () {
/**
* Properties of a StreamPosition.
* @memberof centrifugal.centrifuge.protocol
* @interface IStreamPosition
* @property {number|Long|null} [offset] StreamPosition offset
* @property {string|null} [epoch] StreamPosition epoch
*/
/**
* Constructs a new StreamPosition.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a StreamPosition.
* @implements IStreamPosition
* @constructor
* @param {centrifugal.centrifuge.protocol.IStreamPosition=} [properties] Properties to set
*/
function StreamPosition(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* StreamPosition offset.
* @member {number|Long} offset
* @memberof centrifugal.centrifuge.protocol.StreamPosition
* @instance
*/
StreamPosition.prototype.offset = $util.Long ? $util.Long.fromBits(0, 0, true) : 0;
/**
* StreamPosition epoch.
* @member {string} epoch
* @memberof centrifugal.centrifuge.protocol.StreamPosition
* @instance
*/
StreamPosition.prototype.epoch = "";
/**
* Encodes the specified StreamPosition message. Does not implicitly {@link centrifugal.centrifuge.protocol.StreamPosition.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.StreamPosition
* @static
* @param {centrifugal.centrifuge.protocol.IStreamPosition} message StreamPosition message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
StreamPosition.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.offset != null && Object.hasOwnProperty.call(message, "offset"))
writer.uint32(/* id 1, wireType 0 =*/ 8).uint64(message.offset);
if (message.epoch != null && Object.hasOwnProperty.call(message, "epoch"))
writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.epoch);
return writer;
};
/**
* Encodes the specified StreamPosition message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.StreamPosition.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.StreamPosition
* @static
* @param {centrifugal.centrifuge.protocol.IStreamPosition} message StreamPosition message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
StreamPosition.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a StreamPosition message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.StreamPosition
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.StreamPosition} StreamPosition
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
StreamPosition.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.StreamPosition();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.offset = reader.uint64();
break;
}
case 2: {
message.epoch = reader.string();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a StreamPosition message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.StreamPosition
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.StreamPosition} StreamPosition
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
StreamPosition.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a StreamPosition message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.StreamPosition
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
StreamPosition.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.offset != null && message.hasOwnProperty("offset"))
if (!$util.isInteger(message.offset) && !(message.offset && $util.isInteger(message.offset.low) && $util.isInteger(message.offset.high)))
return "offset: integer|Long expected";
if (message.epoch != null && message.hasOwnProperty("epoch"))
if (!$util.isString(message.epoch))
return "epoch: string expected";
return null;
};
/**
* Gets the default type url for StreamPosition
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.StreamPosition
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
StreamPosition.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.StreamPosition";
};
return StreamPosition;
})();
protocol.HistoryRequest = (function () {
/**
* Properties of a HistoryRequest.
* @memberof centrifugal.centrifuge.protocol
* @interface IHistoryRequest
* @property {string|null} [channel] HistoryRequest channel
* @property {number|null} [limit] HistoryRequest limit
* @property {centrifugal.centrifuge.protocol.IStreamPosition|null} [since] HistoryRequest since
* @property {boolean|null} [reverse] HistoryRequest reverse
*/
/**
* Constructs a new HistoryRequest.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a HistoryRequest.
* @implements IHistoryRequest
* @constructor
* @param {centrifugal.centrifuge.protocol.IHistoryRequest=} [properties] Properties to set
*/
function HistoryRequest(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* HistoryRequest channel.
* @member {string} channel
* @memberof centrifugal.centrifuge.protocol.HistoryRequest
* @instance
*/
HistoryRequest.prototype.channel = "";
/**
* HistoryRequest limit.
* @member {number} limit
* @memberof centrifugal.centrifuge.protocol.HistoryRequest
* @instance
*/
HistoryRequest.prototype.limit = 0;
/**
* HistoryRequest since.
* @member {centrifugal.centrifuge.protocol.IStreamPosition|null|undefined} since
* @memberof centrifugal.centrifuge.protocol.HistoryRequest
* @instance
*/
HistoryRequest.prototype.since = null;
/**
* HistoryRequest reverse.
* @member {boolean} reverse
* @memberof centrifugal.centrifuge.protocol.HistoryRequest
* @instance
*/
HistoryRequest.prototype.reverse = false;
/**
* Encodes the specified HistoryRequest message. Does not implicitly {@link centrifugal.centrifuge.protocol.HistoryRequest.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.HistoryRequest
* @static
* @param {centrifugal.centrifuge.protocol.IHistoryRequest} message HistoryRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
HistoryRequest.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.channel != null && Object.hasOwnProperty.call(message, "channel"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.channel);
if (message.limit != null && Object.hasOwnProperty.call(message, "limit"))
writer.uint32(/* id 7, wireType 0 =*/ 56).int32(message.limit);
if (message.since != null && Object.hasOwnProperty.call(message, "since"))
$root.centrifugal.centrifuge.protocol.StreamPosition.encode(message.since, writer.uint32(/* id 8, wireType 2 =*/ 66).fork()).ldelim();
if (message.reverse != null && Object.hasOwnProperty.call(message, "reverse"))
writer.uint32(/* id 9, wireType 0 =*/ 72).bool(message.reverse);
return writer;
};
/**
* Encodes the specified HistoryRequest message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.HistoryRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.HistoryRequest
* @static
* @param {centrifugal.centrifuge.protocol.IHistoryRequest} message HistoryRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
HistoryRequest.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a HistoryRequest message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.HistoryRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.HistoryRequest} HistoryRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
HistoryRequest.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.HistoryRequest();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.channel = reader.string();
break;
}
case 7: {
message.limit = reader.int32();
break;
}
case 8: {
message.since = $root.centrifugal.centrifuge.protocol.StreamPosition.decode(reader, reader.uint32());
break;
}
case 9: {
message.reverse = reader.bool();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a HistoryRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.HistoryRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.HistoryRequest} HistoryRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
HistoryRequest.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a HistoryRequest message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.HistoryRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
HistoryRequest.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.channel != null && message.hasOwnProperty("channel"))
if (!$util.isString(message.channel))
return "channel: string expected";
if (message.limit != null && message.hasOwnProperty("limit"))
if (!$util.isInteger(message.limit))
return "limit: integer expected";
if (message.since != null && message.hasOwnProperty("since")) {
let error = $root.centrifugal.centrifuge.protocol.StreamPosition.verify(message.since);
if (error)
return "since." + error;
}
if (message.reverse != null && message.hasOwnProperty("reverse"))
if (typeof message.reverse !== "boolean")
return "reverse: boolean expected";
return null;
};
/**
* Gets the default type url for HistoryRequest
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.HistoryRequest
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
HistoryRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.HistoryRequest";
};
return HistoryRequest;
})();
protocol.HistoryResult = (function () {
/**
* Properties of a HistoryResult.
* @memberof centrifugal.centrifuge.protocol
* @interface IHistoryResult
* @property {Array.<centrifugal.centrifuge.protocol.IPublication>|null} [publications] HistoryResult publications
* @property {string|null} [epoch] HistoryResult epoch
* @property {number|Long|null} [offset] HistoryResult offset
*/
/**
* Constructs a new HistoryResult.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a HistoryResult.
* @implements IHistoryResult
* @constructor
* @param {centrifugal.centrifuge.protocol.IHistoryResult=} [properties] Properties to set
*/
function HistoryResult(properties) {
this.publications = [];
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* HistoryResult publications.
* @member {Array.<centrifugal.centrifuge.protocol.IPublication>} publications
* @memberof centrifugal.centrifuge.protocol.HistoryResult
* @instance
*/
HistoryResult.prototype.publications = $util.emptyArray;
/**
* HistoryResult epoch.
* @member {string} epoch
* @memberof centrifugal.centrifuge.protocol.HistoryResult
* @instance
*/
HistoryResult.prototype.epoch = "";
/**
* HistoryResult offset.
* @member {number|Long} offset
* @memberof centrifugal.centrifuge.protocol.HistoryResult
* @instance
*/
HistoryResult.prototype.offset = $util.Long ? $util.Long.fromBits(0, 0, true) : 0;
/**
* Encodes the specified HistoryResult message. Does not implicitly {@link centrifugal.centrifuge.protocol.HistoryResult.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.HistoryResult
* @static
* @param {centrifugal.centrifuge.protocol.IHistoryResult} message HistoryResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
HistoryResult.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.publications != null && message.publications.length)
for (let i = 0; i < message.publications.length; ++i)
$root.centrifugal.centrifuge.protocol.Publication.encode(message.publications[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim();
if (message.epoch != null && Object.hasOwnProperty.call(message, "epoch"))
writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.epoch);
if (message.offset != null && Object.hasOwnProperty.call(message, "offset"))
writer.uint32(/* id 3, wireType 0 =*/ 24).uint64(message.offset);
return writer;
};
/**
* Encodes the specified HistoryResult message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.HistoryResult.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.HistoryResult
* @static
* @param {centrifugal.centrifuge.protocol.IHistoryResult} message HistoryResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
HistoryResult.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a HistoryResult message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.HistoryResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.HistoryResult} HistoryResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
HistoryResult.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.HistoryResult();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
if (!(message.publications && message.publications.length))
message.publications = [];
message.publications.push($root.centrifugal.centrifuge.protocol.Publication.decode(reader, reader.uint32()));
break;
}
case 2: {
message.epoch = reader.string();
break;
}
case 3: {
message.offset = reader.uint64();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a HistoryResult message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.HistoryResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.HistoryResult} HistoryResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
HistoryResult.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a HistoryResult message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.HistoryResult
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
HistoryResult.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.publications != null && message.hasOwnProperty("publications")) {
if (!Array.isArray(message.publications))
return "publications: array expected";
for (let i = 0; i < message.publications.length; ++i) {
let error = $root.centrifugal.centrifuge.protocol.Publication.verify(message.publications[i]);
if (error)
return "publications." + error;
}
}
if (message.epoch != null && message.hasOwnProperty("epoch"))
if (!$util.isString(message.epoch))
return "epoch: string expected";
if (message.offset != null && message.hasOwnProperty("offset"))
if (!$util.isInteger(message.offset) && !(message.offset && $util.isInteger(message.offset.low) && $util.isInteger(message.offset.high)))
return "offset: integer|Long expected";
return null;
};
/**
* Gets the default type url for HistoryResult
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.HistoryResult
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
HistoryResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.HistoryResult";
};
return HistoryResult;
})();
protocol.PingRequest = (function () {
/**
* Properties of a PingRequest.
* @memberof centrifugal.centrifuge.protocol
* @interface IPingRequest
*/
/**
* Constructs a new PingRequest.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a PingRequest.
* @implements IPingRequest
* @constructor
* @param {centrifugal.centrifuge.protocol.IPingRequest=} [properties] Properties to set
*/
function PingRequest(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Encodes the specified PingRequest message. Does not implicitly {@link centrifugal.centrifuge.protocol.PingRequest.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.PingRequest
* @static
* @param {centrifugal.centrifuge.protocol.IPingRequest} message PingRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PingRequest.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
return writer;
};
/**
* Encodes the specified PingRequest message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.PingRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.PingRequest
* @static
* @param {centrifugal.centrifuge.protocol.IPingRequest} message PingRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PingRequest.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a PingRequest message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.PingRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.PingRequest} PingRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PingRequest.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.PingRequest();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a PingRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.PingRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.PingRequest} PingRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PingRequest.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a PingRequest message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.PingRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
PingRequest.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
return null;
};
/**
* Gets the default type url for PingRequest
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.PingRequest
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
PingRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.PingRequest";
};
return PingRequest;
})();
protocol.PingResult = (function () {
/**
* Properties of a PingResult.
* @memberof centrifugal.centrifuge.protocol
* @interface IPingResult
*/
/**
* Constructs a new PingResult.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a PingResult.
* @implements IPingResult
* @constructor
* @param {centrifugal.centrifuge.protocol.IPingResult=} [properties] Properties to set
*/
function PingResult(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* Encodes the specified PingResult message. Does not implicitly {@link centrifugal.centrifuge.protocol.PingResult.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.PingResult
* @static
* @param {centrifugal.centrifuge.protocol.IPingResult} message PingResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PingResult.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
return writer;
};
/**
* Encodes the specified PingResult message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.PingResult.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.PingResult
* @static
* @param {centrifugal.centrifuge.protocol.IPingResult} message PingResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PingResult.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a PingResult message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.PingResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.PingResult} PingResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PingResult.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.PingResult();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a PingResult message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.PingResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.PingResult} PingResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PingResult.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a PingResult message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.PingResult
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
PingResult.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
return null;
};
/**
* Gets the default type url for PingResult
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.PingResult
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
PingResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.PingResult";
};
return PingResult;
})();
protocol.RPCRequest = (function () {
/**
* Properties of a RPCRequest.
* @memberof centrifugal.centrifuge.protocol
* @interface IRPCRequest
* @property {Uint8Array|null} [data] RPCRequest data
* @property {string|null} [method] RPCRequest method
*/
/**
* Constructs a new RPCRequest.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a RPCRequest.
* @implements IRPCRequest
* @constructor
* @param {centrifugal.centrifuge.protocol.IRPCRequest=} [properties] Properties to set
*/
function RPCRequest(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* RPCRequest data.
* @member {Uint8Array} data
* @memberof centrifugal.centrifuge.protocol.RPCRequest
* @instance
*/
RPCRequest.prototype.data = $util.newBuffer([]);
/**
* RPCRequest method.
* @member {string} method
* @memberof centrifugal.centrifuge.protocol.RPCRequest
* @instance
*/
RPCRequest.prototype.method = "";
/**
* Encodes the specified RPCRequest message. Does not implicitly {@link centrifugal.centrifuge.protocol.RPCRequest.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.RPCRequest
* @static
* @param {centrifugal.centrifuge.protocol.IRPCRequest} message RPCRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
RPCRequest.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.data != null && Object.hasOwnProperty.call(message, "data"))
writer.uint32(/* id 1, wireType 2 =*/ 10).bytes(message.data);
if (message.method != null && Object.hasOwnProperty.call(message, "method"))
writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.method);
return writer;
};
/**
* Encodes the specified RPCRequest message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.RPCRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.RPCRequest
* @static
* @param {centrifugal.centrifuge.protocol.IRPCRequest} message RPCRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
RPCRequest.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a RPCRequest message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.RPCRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.RPCRequest} RPCRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
RPCRequest.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.RPCRequest();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.data = reader.bytes();
break;
}
case 2: {
message.method = reader.string();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a RPCRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.RPCRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.RPCRequest} RPCRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
RPCRequest.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a RPCRequest message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.RPCRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
RPCRequest.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.data != null && message.hasOwnProperty("data"))
if (!(message.data && typeof message.data.length === "number" || $util.isString(message.data)))
return "data: buffer expected";
if (message.method != null && message.hasOwnProperty("method"))
if (!$util.isString(message.method))
return "method: string expected";
return null;
};
/**
* Gets the default type url for RPCRequest
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.RPCRequest
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
RPCRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.RPCRequest";
};
return RPCRequest;
})();
protocol.RPCResult = (function () {
/**
* Properties of a RPCResult.
* @memberof centrifugal.centrifuge.protocol
* @interface IRPCResult
* @property {Uint8Array|null} [data] RPCResult data
*/
/**
* Constructs a new RPCResult.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a RPCResult.
* @implements IRPCResult
* @constructor
* @param {centrifugal.centrifuge.protocol.IRPCResult=} [properties] Properties to set
*/
function RPCResult(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* RPCResult data.
* @member {Uint8Array} data
* @memberof centrifugal.centrifuge.protocol.RPCResult
* @instance
*/
RPCResult.prototype.data = $util.newBuffer([]);
/**
* Encodes the specified RPCResult message. Does not implicitly {@link centrifugal.centrifuge.protocol.RPCResult.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.RPCResult
* @static
* @param {centrifugal.centrifuge.protocol.IRPCResult} message RPCResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
RPCResult.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.data != null && Object.hasOwnProperty.call(message, "data"))
writer.uint32(/* id 1, wireType 2 =*/ 10).bytes(message.data);
return writer;
};
/**
* Encodes the specified RPCResult message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.RPCResult.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.RPCResult
* @static
* @param {centrifugal.centrifuge.protocol.IRPCResult} message RPCResult message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
RPCResult.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a RPCResult message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.RPCResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.RPCResult} RPCResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
RPCResult.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.RPCResult();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.data = reader.bytes();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a RPCResult message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.RPCResult
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.RPCResult} RPCResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
RPCResult.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a RPCResult message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.RPCResult
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
RPCResult.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.data != null && message.hasOwnProperty("data"))
if (!(message.data && typeof message.data.length === "number" || $util.isString(message.data)))
return "data: buffer expected";
return null;
};
/**
* Gets the default type url for RPCResult
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.RPCResult
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
RPCResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.RPCResult";
};
return RPCResult;
})();
protocol.SendRequest = (function () {
/**
* Properties of a SendRequest.
* @memberof centrifugal.centrifuge.protocol
* @interface ISendRequest
* @property {Uint8Array|null} [data] SendRequest data
*/
/**
* Constructs a new SendRequest.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a SendRequest.
* @implements ISendRequest
* @constructor
* @param {centrifugal.centrifuge.protocol.ISendRequest=} [properties] Properties to set
*/
function SendRequest(properties) {
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* SendRequest data.
* @member {Uint8Array} data
* @memberof centrifugal.centrifuge.protocol.SendRequest
* @instance
*/
SendRequest.prototype.data = $util.newBuffer([]);
/**
* Encodes the specified SendRequest message. Does not implicitly {@link centrifugal.centrifuge.protocol.SendRequest.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.SendRequest
* @static
* @param {centrifugal.centrifuge.protocol.ISendRequest} message SendRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
SendRequest.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.data != null && Object.hasOwnProperty.call(message, "data"))
writer.uint32(/* id 1, wireType 2 =*/ 10).bytes(message.data);
return writer;
};
/**
* Encodes the specified SendRequest message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.SendRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.SendRequest
* @static
* @param {centrifugal.centrifuge.protocol.ISendRequest} message SendRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
SendRequest.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a SendRequest message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.SendRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.SendRequest} SendRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
SendRequest.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.SendRequest();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.data = reader.bytes();
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a SendRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.SendRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.SendRequest} SendRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
SendRequest.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a SendRequest message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.SendRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
SendRequest.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.data != null && message.hasOwnProperty("data"))
if (!(message.data && typeof message.data.length === "number" || $util.isString(message.data)))
return "data: buffer expected";
return null;
};
/**
* Gets the default type url for SendRequest
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.SendRequest
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
SendRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.SendRequest";
};
return SendRequest;
})();
protocol.FilterNode = (function () {
/**
* Properties of a FilterNode.
* @memberof centrifugal.centrifuge.protocol
* @interface IFilterNode
* @property {string|null} [op] FilterNode op
* @property {string|null} [key] FilterNode key
* @property {string|null} [cmp] FilterNode cmp
* @property {string|null} [val] FilterNode val
* @property {Array.<string>|null} [vals] FilterNode vals
* @property {Array.<centrifugal.centrifuge.protocol.IFilterNode>|null} [nodes] FilterNode nodes
*/
/**
* Constructs a new FilterNode.
* @memberof centrifugal.centrifuge.protocol
* @classdesc Represents a FilterNode.
* @implements IFilterNode
* @constructor
* @param {centrifugal.centrifuge.protocol.IFilterNode=} [properties] Properties to set
*/
function FilterNode(properties) {
this.vals = [];
this.nodes = [];
if (properties)
for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
/**
* FilterNode op.
* @member {string} op
* @memberof centrifugal.centrifuge.protocol.FilterNode
* @instance
*/
FilterNode.prototype.op = "";
/**
* FilterNode key.
* @member {string} key
* @memberof centrifugal.centrifuge.protocol.FilterNode
* @instance
*/
FilterNode.prototype.key = "";
/**
* FilterNode cmp.
* @member {string} cmp
* @memberof centrifugal.centrifuge.protocol.FilterNode
* @instance
*/
FilterNode.prototype.cmp = "";
/**
* FilterNode val.
* @member {string} val
* @memberof centrifugal.centrifuge.protocol.FilterNode
* @instance
*/
FilterNode.prototype.val = "";
/**
* FilterNode vals.
* @member {Array.<string>} vals
* @memberof centrifugal.centrifuge.protocol.FilterNode
* @instance
*/
FilterNode.prototype.vals = $util.emptyArray;
/**
* FilterNode nodes.
* @member {Array.<centrifugal.centrifuge.protocol.IFilterNode>} nodes
* @memberof centrifugal.centrifuge.protocol.FilterNode
* @instance
*/
FilterNode.prototype.nodes = $util.emptyArray;
/**
* Encodes the specified FilterNode message. Does not implicitly {@link centrifugal.centrifuge.protocol.FilterNode.verify|verify} messages.
* @function encode
* @memberof centrifugal.centrifuge.protocol.FilterNode
* @static
* @param {centrifugal.centrifuge.protocol.IFilterNode} message FilterNode message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
FilterNode.encode = function encode(message, writer) {
if (!writer)
writer = $Writer.create();
if (message.op != null && Object.hasOwnProperty.call(message, "op"))
writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.op);
if (message.key != null && Object.hasOwnProperty.call(message, "key"))
writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.key);
if (message.cmp != null && Object.hasOwnProperty.call(message, "cmp"))
writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.cmp);
if (message.val != null && Object.hasOwnProperty.call(message, "val"))
writer.uint32(/* id 4, wireType 2 =*/ 34).string(message.val);
if (message.vals != null && message.vals.length)
for (let i = 0; i < message.vals.length; ++i)
writer.uint32(/* id 5, wireType 2 =*/ 42).string(message.vals[i]);
if (message.nodes != null && message.nodes.length)
for (let i = 0; i < message.nodes.length; ++i)
$root.centrifugal.centrifuge.protocol.FilterNode.encode(message.nodes[i], writer.uint32(/* id 6, wireType 2 =*/ 50).fork()).ldelim();
return writer;
};
/**
* Encodes the specified FilterNode message, length delimited. Does not implicitly {@link centrifugal.centrifuge.protocol.FilterNode.verify|verify} messages.
* @function encodeDelimited
* @memberof centrifugal.centrifuge.protocol.FilterNode
* @static
* @param {centrifugal.centrifuge.protocol.IFilterNode} message FilterNode message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
FilterNode.encodeDelimited = function encodeDelimited(message, writer) {
return this.encode(message, writer).ldelim();
};
/**
* Decodes a FilterNode message from the specified reader or buffer.
* @function decode
* @memberof centrifugal.centrifuge.protocol.FilterNode
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {centrifugal.centrifuge.protocol.FilterNode} FilterNode
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
FilterNode.decode = function decode(reader, length) {
if (!(reader instanceof $Reader))
reader = $Reader.create(reader);
let end = length === undefined ? reader.len : reader.pos + length, message = new $root.centrifugal.centrifuge.protocol.FilterNode();
while (reader.pos < end) {
let tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
message.op = reader.string();
break;
}
case 2: {
message.key = reader.string();
break;
}
case 3: {
message.cmp = reader.string();
break;
}
case 4: {
message.val = reader.string();
break;
}
case 5: {
if (!(message.vals && message.vals.length))
message.vals = [];
message.vals.push(reader.string());
break;
}
case 6: {
if (!(message.nodes && message.nodes.length))
message.nodes = [];
message.nodes.push($root.centrifugal.centrifuge.protocol.FilterNode.decode(reader, reader.uint32()));
break;
}
default:
reader.skipType(tag & 7);
break;
}
}
return message;
};
/**
* Decodes a FilterNode message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof centrifugal.centrifuge.protocol.FilterNode
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {centrifugal.centrifuge.protocol.FilterNode} FilterNode
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
FilterNode.decodeDelimited = function decodeDelimited(reader) {
if (!(reader instanceof $Reader))
reader = new $Reader(reader);
return this.decode(reader, reader.uint32());
};
/**
* Verifies a FilterNode message.
* @function verify
* @memberof centrifugal.centrifuge.protocol.FilterNode
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/
FilterNode.verify = function verify(message) {
if (typeof message !== "object" || message === null)
return "object expected";
if (message.op != null && message.hasOwnProperty("op"))
if (!$util.isString(message.op))
return "op: string expected";
if (message.key != null && message.hasOwnProperty("key"))
if (!$util.isString(message.key))
return "key: string expected";
if (message.cmp != null && message.hasOwnProperty("cmp"))
if (!$util.isString(message.cmp))
return "cmp: string expected";
if (message.val != null && message.hasOwnProperty("val"))
if (!$util.isString(message.val))
return "val: string expected";
if (message.vals != null && message.hasOwnProperty("vals")) {
if (!Array.isArray(message.vals))
return "vals: array expected";
for (let i = 0; i < message.vals.length; ++i)
if (!$util.isString(message.vals[i]))
return "vals: string[] expected";
}
if (message.nodes != null && message.hasOwnProperty("nodes")) {
if (!Array.isArray(message.nodes))
return "nodes: array expected";
for (let i = 0; i < message.nodes.length; ++i) {
let error = $root.centrifugal.centrifuge.protocol.FilterNode.verify(message.nodes[i]);
if (error)
return "nodes." + error;
}
}
return null;
};
/**
* Gets the default type url for FilterNode
* @function getTypeUrl
* @memberof centrifugal.centrifuge.protocol.FilterNode
* @static
* @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com")
* @returns {string} The default type url
*/
FilterNode.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
if (typeUrlPrefix === undefined) {
typeUrlPrefix = "type.googleapis.com";
}
return typeUrlPrefix + "/centrifugal.centrifuge.protocol.FilterNode";
};
return FilterNode;
})();
return protocol;
})();
return centrifuge;
})();
return centrifugal;
})();
const Command = centrifugal.centrifuge.protocol.Command;
const Reply = centrifugal.centrifuge.protocol.Reply;
const EmulationRequest = centrifugal.centrifuge.protocol.EmulationRequest;
// A reply length beyond this means the data isn't a stream of replies.
const maxReplyLength = 64 * 1024 * 1024;
/** @internal */
class ProtobufCodec {
name() {
return 'protobuf';
}
encodeEmulationRequest(req) {
const writer = minimalExports.Writer.create();
EmulationRequest.encode(req, writer);
return writer.finish();
}
encodeCommands(commands) {
const writer = minimalExports.Writer.create();
for (const command of commands) {
writer.fork();
Command.encodeDelimited(command, writer);
}
return writer.finish();
}
encodeReplies(replies) {
const writer = minimalExports.Writer.create();
for (const reply of replies) {
writer.fork();
Reply.encodeDelimited(reply, writer);
}
return writer.finish();
}
decodeReplies(data) {
const replies = [];
const reader = minimalExports.Reader.create(new Uint8Array(data));
while (reader.pos < reader.len) {
const reply = Reply.decodeDelimited(reader);
replies.push(reply);
}
return replies;
}
decodeCommands(data) {
const commands = [];
const reader = minimalExports.Reader.create(new Uint8Array(data));
while (reader.pos < reader.len) {
const reply = Command.decodeDelimited(reader);
commands.push(reply);
}
return commands;
}
decodeReply(data) {
// Without a copy: a stream buffer passes a view of the data it holds.
const reader = minimalExports.Reader.create(data instanceof Uint8Array ? data : new Uint8Array(data));
if (reader.pos >= reader.len) {
return { ok: false };
}
// A stream read may end in the middle of a reply, even inside its length
// prefix: more data is needed then, it is not a decoding error.
let length;
try {
length = reader.uint32();
}
catch (e) {
if (e instanceof RangeError) {
return { ok: false };
}
throw e;
}
if (length > maxReplyLength) {
// E.g. an HTML page from a captive portal: fail instead of waiting for that
// much data, so the transport is closed.
throw new Error(`reply length ${length} exceeds ${maxReplyLength}`);
}
if (reader.pos + length > reader.len) {
return { ok: false };
}
Reply.decode(reader, length);
return {
ok: true,
pos: reader.pos
};
}
applyDeltaIfNeeded(pub, prevValue) {
let newData, newPrevValue;
let isDelta;
if (pub.delta) {
isDelta = true;
// binary delta.
const valueArray = applyDelta(prevValue, pub.data);
newData = new Uint8Array(valueArray);
newPrevValue = valueArray;
}
else {
isDelta = false;
// full binary data.
newData = pub.data;
newPrevValue = pub.data;
}
return { newData, newPrevValue, isDelta, wireBytes: pub.data.length, fullBytes: newPrevValue.length };
}
}
class CentrifugeProtobuf extends Centrifuge {
_formatOverride() {
this._codec = new ProtobufCodec();
}
}
export { CentrifugeProtobuf as Centrifuge, State, Subscription, SubscriptionState, UnauthorizedError, connectingCodes, disconnectedCodes, errorCodes, subscribingCodes, subscriptionFlags, unsubscribedCodes };