@zaplier/sdk 1.2.1 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/sdk.js CHANGED
@@ -6328,100 +6328,6 @@
6328
6328
  }
6329
6329
  }
6330
6330
  }
6331
- /**
6332
- * Socket.io Transport (Real-time bidirectional communication for anti-adblock)
6333
- */
6334
- class SocketIOTransport {
6335
- constructor(baseUrl) {
6336
- this.name = 'socketio';
6337
- this.available = typeof WebSocket !== 'undefined';
6338
- this.connected = false;
6339
- this.baseUrl = baseUrl;
6340
- }
6341
- async send(data, _endpoint) {
6342
- const start = Date.now();
6343
- if (!this.available) {
6344
- return { success: false, method: this.name, error: 'WebRTC not available' };
6345
- }
6346
- try {
6347
- if (!this.connected) {
6348
- await this.connect();
6349
- }
6350
- return new Promise((resolve) => {
6351
- // Emit tracking data via enhanced WebSocket
6352
- this.socket.emit('track', data);
6353
- // Listen for success response
6354
- this.socket.once('track_success', () => {
6355
- resolve({
6356
- success: true,
6357
- method: this.name,
6358
- latency: Date.now() - start
6359
- });
6360
- });
6361
- // Listen for error response
6362
- this.socket.once('track_error', (error) => {
6363
- resolve({
6364
- success: false,
6365
- method: this.name,
6366
- error: error.error || 'WebSocket send failed'
6367
- });
6368
- });
6369
- // Timeout after 5 seconds
6370
- setTimeout(() => {
6371
- resolve({
6372
- success: false,
6373
- method: this.name,
6374
- error: 'WebSocket timeout'
6375
- });
6376
- }, 5000);
6377
- });
6378
- }
6379
- catch (error) {
6380
- return {
6381
- success: false,
6382
- method: this.name,
6383
- error: error instanceof Error ? error.message : String(error)
6384
- };
6385
- }
6386
- }
6387
- async connect() {
6388
- return new Promise((resolve, reject) => {
6389
- try {
6390
- // Use dynamic import to load socket.io-client only when needed
6391
- Promise.resolve().then(function () { return index; }).then(({ io }) => {
6392
- // Extract domain from baseUrl - preserve protocol (HTTP/HTTPS)
6393
- const url = new URL(this.baseUrl);
6394
- const socketUrl = `${url.protocol}//${url.host}`;
6395
- this.socket = io(socketUrl, {
6396
- transports: ['polling', 'websocket'], // Try polling first for better proxy compatibility
6397
- timeout: 5000,
6398
- upgrade: true,
6399
- rememberUpgrade: false
6400
- });
6401
- this.socket.on('connect', () => {
6402
- this.connected = true;
6403
- resolve();
6404
- });
6405
- this.socket.on('connect_error', (error) => {
6406
- reject(error);
6407
- });
6408
- this.socket.on('disconnect', () => {
6409
- this.connected = false;
6410
- });
6411
- }).catch(reject);
6412
- }
6413
- catch (error) {
6414
- reject(error);
6415
- }
6416
- });
6417
- }
6418
- destroy() {
6419
- if (this.socket) {
6420
- this.socket.disconnect();
6421
- this.connected = false;
6422
- }
6423
- }
6424
- }
6425
6331
  /**
6426
6332
  * WebRTC DataChannel Transport (experimental - legacy)
6427
6333
  */
@@ -6526,7 +6432,6 @@
6526
6432
  initializeTransports() {
6527
6433
  const transportMap = {
6528
6434
  'elysia-websocket': () => new ElysiaWebSocketTransport(this.baseUrl, this.token),
6529
- socketio: () => new SocketIOTransport(this.baseUrl),
6530
6435
  fetch: () => new FetchTransport(),
6531
6436
  resource: () => new ResourceSpoofTransport(this.baseUrl),
6532
6437
  webrtc: () => new WebRTCTransport()
@@ -12831,4045 +12736,6 @@
12831
12736
  collectDeviceSignals: collectDeviceSignals
12832
12737
  });
12833
12738
 
12834
- const PACKET_TYPES = Object.create(null); // no Map = no polyfill
12835
- PACKET_TYPES["open"] = "0";
12836
- PACKET_TYPES["close"] = "1";
12837
- PACKET_TYPES["ping"] = "2";
12838
- PACKET_TYPES["pong"] = "3";
12839
- PACKET_TYPES["message"] = "4";
12840
- PACKET_TYPES["upgrade"] = "5";
12841
- PACKET_TYPES["noop"] = "6";
12842
- const PACKET_TYPES_REVERSE = Object.create(null);
12843
- Object.keys(PACKET_TYPES).forEach((key) => {
12844
- PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
12845
- });
12846
- const ERROR_PACKET = { type: "error", data: "parser error" };
12847
-
12848
- const withNativeBlob$1 = typeof Blob === "function" ||
12849
- (typeof Blob !== "undefined" &&
12850
- Object.prototype.toString.call(Blob) === "[object BlobConstructor]");
12851
- const withNativeArrayBuffer$2 = typeof ArrayBuffer === "function";
12852
- // ArrayBuffer.isView method is not defined in IE10
12853
- const isView$1 = (obj) => {
12854
- return typeof ArrayBuffer.isView === "function"
12855
- ? ArrayBuffer.isView(obj)
12856
- : obj && obj.buffer instanceof ArrayBuffer;
12857
- };
12858
- const encodePacket = ({ type, data }, supportsBinary, callback) => {
12859
- if (withNativeBlob$1 && data instanceof Blob) {
12860
- if (supportsBinary) {
12861
- return callback(data);
12862
- }
12863
- else {
12864
- return encodeBlobAsBase64(data, callback);
12865
- }
12866
- }
12867
- else if (withNativeArrayBuffer$2 &&
12868
- (data instanceof ArrayBuffer || isView$1(data))) {
12869
- if (supportsBinary) {
12870
- return callback(data);
12871
- }
12872
- else {
12873
- return encodeBlobAsBase64(new Blob([data]), callback);
12874
- }
12875
- }
12876
- // plain string
12877
- return callback(PACKET_TYPES[type] + (data || ""));
12878
- };
12879
- const encodeBlobAsBase64 = (data, callback) => {
12880
- const fileReader = new FileReader();
12881
- fileReader.onload = function () {
12882
- const content = fileReader.result.split(",")[1];
12883
- callback("b" + (content || ""));
12884
- };
12885
- return fileReader.readAsDataURL(data);
12886
- };
12887
- function toArray(data) {
12888
- if (data instanceof Uint8Array) {
12889
- return data;
12890
- }
12891
- else if (data instanceof ArrayBuffer) {
12892
- return new Uint8Array(data);
12893
- }
12894
- else {
12895
- return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
12896
- }
12897
- }
12898
- let TEXT_ENCODER;
12899
- function encodePacketToBinary(packet, callback) {
12900
- if (withNativeBlob$1 && packet.data instanceof Blob) {
12901
- return packet.data.arrayBuffer().then(toArray).then(callback);
12902
- }
12903
- else if (withNativeArrayBuffer$2 &&
12904
- (packet.data instanceof ArrayBuffer || isView$1(packet.data))) {
12905
- return callback(toArray(packet.data));
12906
- }
12907
- encodePacket(packet, false, (encoded) => {
12908
- if (!TEXT_ENCODER) {
12909
- TEXT_ENCODER = new TextEncoder();
12910
- }
12911
- callback(TEXT_ENCODER.encode(encoded));
12912
- });
12913
- }
12914
-
12915
- // imported from https://github.com/socketio/base64-arraybuffer
12916
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
12917
- // Use a lookup table to find the index.
12918
- const lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
12919
- for (let i = 0; i < chars.length; i++) {
12920
- lookup$1[chars.charCodeAt(i)] = i;
12921
- }
12922
- const decode$1 = (base64) => {
12923
- let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
12924
- if (base64[base64.length - 1] === '=') {
12925
- bufferLength--;
12926
- if (base64[base64.length - 2] === '=') {
12927
- bufferLength--;
12928
- }
12929
- }
12930
- const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
12931
- for (i = 0; i < len; i += 4) {
12932
- encoded1 = lookup$1[base64.charCodeAt(i)];
12933
- encoded2 = lookup$1[base64.charCodeAt(i + 1)];
12934
- encoded3 = lookup$1[base64.charCodeAt(i + 2)];
12935
- encoded4 = lookup$1[base64.charCodeAt(i + 3)];
12936
- bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
12937
- bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
12938
- bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
12939
- }
12940
- return arraybuffer;
12941
- };
12942
-
12943
- const withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
12944
- const decodePacket = (encodedPacket, binaryType) => {
12945
- if (typeof encodedPacket !== "string") {
12946
- return {
12947
- type: "message",
12948
- data: mapBinary(encodedPacket, binaryType),
12949
- };
12950
- }
12951
- const type = encodedPacket.charAt(0);
12952
- if (type === "b") {
12953
- return {
12954
- type: "message",
12955
- data: decodeBase64Packet(encodedPacket.substring(1), binaryType),
12956
- };
12957
- }
12958
- const packetType = PACKET_TYPES_REVERSE[type];
12959
- if (!packetType) {
12960
- return ERROR_PACKET;
12961
- }
12962
- return encodedPacket.length > 1
12963
- ? {
12964
- type: PACKET_TYPES_REVERSE[type],
12965
- data: encodedPacket.substring(1),
12966
- }
12967
- : {
12968
- type: PACKET_TYPES_REVERSE[type],
12969
- };
12970
- };
12971
- const decodeBase64Packet = (data, binaryType) => {
12972
- if (withNativeArrayBuffer$1) {
12973
- const decoded = decode$1(data);
12974
- return mapBinary(decoded, binaryType);
12975
- }
12976
- else {
12977
- return { base64: true, data }; // fallback for old browsers
12978
- }
12979
- };
12980
- const mapBinary = (data, binaryType) => {
12981
- switch (binaryType) {
12982
- case "blob":
12983
- if (data instanceof Blob) {
12984
- // from WebSocket + binaryType "blob"
12985
- return data;
12986
- }
12987
- else {
12988
- // from HTTP long-polling or WebTransport
12989
- return new Blob([data]);
12990
- }
12991
- case "arraybuffer":
12992
- default:
12993
- if (data instanceof ArrayBuffer) {
12994
- // from HTTP long-polling (base64) or WebSocket + binaryType "arraybuffer"
12995
- return data;
12996
- }
12997
- else {
12998
- // from WebTransport (Uint8Array)
12999
- return data.buffer;
13000
- }
13001
- }
13002
- };
13003
-
13004
- const SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
13005
- const encodePayload = (packets, callback) => {
13006
- // some packets may be added to the array while encoding, so the initial length must be saved
13007
- const length = packets.length;
13008
- const encodedPackets = new Array(length);
13009
- let count = 0;
13010
- packets.forEach((packet, i) => {
13011
- // force base64 encoding for binary packets
13012
- encodePacket(packet, false, (encodedPacket) => {
13013
- encodedPackets[i] = encodedPacket;
13014
- if (++count === length) {
13015
- callback(encodedPackets.join(SEPARATOR));
13016
- }
13017
- });
13018
- });
13019
- };
13020
- const decodePayload = (encodedPayload, binaryType) => {
13021
- const encodedPackets = encodedPayload.split(SEPARATOR);
13022
- const packets = [];
13023
- for (let i = 0; i < encodedPackets.length; i++) {
13024
- const decodedPacket = decodePacket(encodedPackets[i], binaryType);
13025
- packets.push(decodedPacket);
13026
- if (decodedPacket.type === "error") {
13027
- break;
13028
- }
13029
- }
13030
- return packets;
13031
- };
13032
- function createPacketEncoderStream() {
13033
- return new TransformStream({
13034
- transform(packet, controller) {
13035
- encodePacketToBinary(packet, (encodedPacket) => {
13036
- const payloadLength = encodedPacket.length;
13037
- let header;
13038
- // inspired by the WebSocket format: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#decoding_payload_length
13039
- if (payloadLength < 126) {
13040
- header = new Uint8Array(1);
13041
- new DataView(header.buffer).setUint8(0, payloadLength);
13042
- }
13043
- else if (payloadLength < 65536) {
13044
- header = new Uint8Array(3);
13045
- const view = new DataView(header.buffer);
13046
- view.setUint8(0, 126);
13047
- view.setUint16(1, payloadLength);
13048
- }
13049
- else {
13050
- header = new Uint8Array(9);
13051
- const view = new DataView(header.buffer);
13052
- view.setUint8(0, 127);
13053
- view.setBigUint64(1, BigInt(payloadLength));
13054
- }
13055
- // first bit indicates whether the payload is plain text (0) or binary (1)
13056
- if (packet.data && typeof packet.data !== "string") {
13057
- header[0] |= 0x80;
13058
- }
13059
- controller.enqueue(header);
13060
- controller.enqueue(encodedPacket);
13061
- });
13062
- },
13063
- });
13064
- }
13065
- let TEXT_DECODER;
13066
- function totalLength(chunks) {
13067
- return chunks.reduce((acc, chunk) => acc + chunk.length, 0);
13068
- }
13069
- function concatChunks(chunks, size) {
13070
- if (chunks[0].length === size) {
13071
- return chunks.shift();
13072
- }
13073
- const buffer = new Uint8Array(size);
13074
- let j = 0;
13075
- for (let i = 0; i < size; i++) {
13076
- buffer[i] = chunks[0][j++];
13077
- if (j === chunks[0].length) {
13078
- chunks.shift();
13079
- j = 0;
13080
- }
13081
- }
13082
- if (chunks.length && j < chunks[0].length) {
13083
- chunks[0] = chunks[0].slice(j);
13084
- }
13085
- return buffer;
13086
- }
13087
- function createPacketDecoderStream(maxPayload, binaryType) {
13088
- if (!TEXT_DECODER) {
13089
- TEXT_DECODER = new TextDecoder();
13090
- }
13091
- const chunks = [];
13092
- let state = 0 /* State.READ_HEADER */;
13093
- let expectedLength = -1;
13094
- let isBinary = false;
13095
- return new TransformStream({
13096
- transform(chunk, controller) {
13097
- chunks.push(chunk);
13098
- while (true) {
13099
- if (state === 0 /* State.READ_HEADER */) {
13100
- if (totalLength(chunks) < 1) {
13101
- break;
13102
- }
13103
- const header = concatChunks(chunks, 1);
13104
- isBinary = (header[0] & 0x80) === 0x80;
13105
- expectedLength = header[0] & 0x7f;
13106
- if (expectedLength < 126) {
13107
- state = 3 /* State.READ_PAYLOAD */;
13108
- }
13109
- else if (expectedLength === 126) {
13110
- state = 1 /* State.READ_EXTENDED_LENGTH_16 */;
13111
- }
13112
- else {
13113
- state = 2 /* State.READ_EXTENDED_LENGTH_64 */;
13114
- }
13115
- }
13116
- else if (state === 1 /* State.READ_EXTENDED_LENGTH_16 */) {
13117
- if (totalLength(chunks) < 2) {
13118
- break;
13119
- }
13120
- const headerArray = concatChunks(chunks, 2);
13121
- expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
13122
- state = 3 /* State.READ_PAYLOAD */;
13123
- }
13124
- else if (state === 2 /* State.READ_EXTENDED_LENGTH_64 */) {
13125
- if (totalLength(chunks) < 8) {
13126
- break;
13127
- }
13128
- const headerArray = concatChunks(chunks, 8);
13129
- const view = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length);
13130
- const n = view.getUint32(0);
13131
- if (n > Math.pow(2, 53 - 32) - 1) {
13132
- // the maximum safe integer in JavaScript is 2^53 - 1
13133
- controller.enqueue(ERROR_PACKET);
13134
- break;
13135
- }
13136
- expectedLength = n * Math.pow(2, 32) + view.getUint32(4);
13137
- state = 3 /* State.READ_PAYLOAD */;
13138
- }
13139
- else {
13140
- if (totalLength(chunks) < expectedLength) {
13141
- break;
13142
- }
13143
- const data = concatChunks(chunks, expectedLength);
13144
- controller.enqueue(decodePacket(isBinary ? data : TEXT_DECODER.decode(data), binaryType));
13145
- state = 0 /* State.READ_HEADER */;
13146
- }
13147
- if (expectedLength === 0 || expectedLength > maxPayload) {
13148
- controller.enqueue(ERROR_PACKET);
13149
- break;
13150
- }
13151
- }
13152
- },
13153
- });
13154
- }
13155
- const protocol$1 = 4;
13156
-
13157
- /**
13158
- * Initialize a new `Emitter`.
13159
- *
13160
- * @api public
13161
- */
13162
-
13163
- function Emitter(obj) {
13164
- if (obj) return mixin(obj);
13165
- }
13166
-
13167
- /**
13168
- * Mixin the emitter properties.
13169
- *
13170
- * @param {Object} obj
13171
- * @return {Object}
13172
- * @api private
13173
- */
13174
-
13175
- function mixin(obj) {
13176
- for (var key in Emitter.prototype) {
13177
- obj[key] = Emitter.prototype[key];
13178
- }
13179
- return obj;
13180
- }
13181
-
13182
- /**
13183
- * Listen on the given `event` with `fn`.
13184
- *
13185
- * @param {String} event
13186
- * @param {Function} fn
13187
- * @return {Emitter}
13188
- * @api public
13189
- */
13190
-
13191
- Emitter.prototype.on =
13192
- Emitter.prototype.addEventListener = function(event, fn){
13193
- this._callbacks = this._callbacks || {};
13194
- (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
13195
- .push(fn);
13196
- return this;
13197
- };
13198
-
13199
- /**
13200
- * Adds an `event` listener that will be invoked a single
13201
- * time then automatically removed.
13202
- *
13203
- * @param {String} event
13204
- * @param {Function} fn
13205
- * @return {Emitter}
13206
- * @api public
13207
- */
13208
-
13209
- Emitter.prototype.once = function(event, fn){
13210
- function on() {
13211
- this.off(event, on);
13212
- fn.apply(this, arguments);
13213
- }
13214
-
13215
- on.fn = fn;
13216
- this.on(event, on);
13217
- return this;
13218
- };
13219
-
13220
- /**
13221
- * Remove the given callback for `event` or all
13222
- * registered callbacks.
13223
- *
13224
- * @param {String} event
13225
- * @param {Function} fn
13226
- * @return {Emitter}
13227
- * @api public
13228
- */
13229
-
13230
- Emitter.prototype.off =
13231
- Emitter.prototype.removeListener =
13232
- Emitter.prototype.removeAllListeners =
13233
- Emitter.prototype.removeEventListener = function(event, fn){
13234
- this._callbacks = this._callbacks || {};
13235
-
13236
- // all
13237
- if (0 == arguments.length) {
13238
- this._callbacks = {};
13239
- return this;
13240
- }
13241
-
13242
- // specific event
13243
- var callbacks = this._callbacks['$' + event];
13244
- if (!callbacks) return this;
13245
-
13246
- // remove all handlers
13247
- if (1 == arguments.length) {
13248
- delete this._callbacks['$' + event];
13249
- return this;
13250
- }
13251
-
13252
- // remove specific handler
13253
- var cb;
13254
- for (var i = 0; i < callbacks.length; i++) {
13255
- cb = callbacks[i];
13256
- if (cb === fn || cb.fn === fn) {
13257
- callbacks.splice(i, 1);
13258
- break;
13259
- }
13260
- }
13261
-
13262
- // Remove event specific arrays for event types that no
13263
- // one is subscribed for to avoid memory leak.
13264
- if (callbacks.length === 0) {
13265
- delete this._callbacks['$' + event];
13266
- }
13267
-
13268
- return this;
13269
- };
13270
-
13271
- /**
13272
- * Emit `event` with the given args.
13273
- *
13274
- * @param {String} event
13275
- * @param {Mixed} ...
13276
- * @return {Emitter}
13277
- */
13278
-
13279
- Emitter.prototype.emit = function(event){
13280
- this._callbacks = this._callbacks || {};
13281
-
13282
- var args = new Array(arguments.length - 1)
13283
- , callbacks = this._callbacks['$' + event];
13284
-
13285
- for (var i = 1; i < arguments.length; i++) {
13286
- args[i - 1] = arguments[i];
13287
- }
13288
-
13289
- if (callbacks) {
13290
- callbacks = callbacks.slice(0);
13291
- for (var i = 0, len = callbacks.length; i < len; ++i) {
13292
- callbacks[i].apply(this, args);
13293
- }
13294
- }
13295
-
13296
- return this;
13297
- };
13298
-
13299
- // alias used for reserved events (protected method)
13300
- Emitter.prototype.emitReserved = Emitter.prototype.emit;
13301
-
13302
- /**
13303
- * Return array of callbacks for `event`.
13304
- *
13305
- * @param {String} event
13306
- * @return {Array}
13307
- * @api public
13308
- */
13309
-
13310
- Emitter.prototype.listeners = function(event){
13311
- this._callbacks = this._callbacks || {};
13312
- return this._callbacks['$' + event] || [];
13313
- };
13314
-
13315
- /**
13316
- * Check if this emitter has `event` handlers.
13317
- *
13318
- * @param {String} event
13319
- * @return {Boolean}
13320
- * @api public
13321
- */
13322
-
13323
- Emitter.prototype.hasListeners = function(event){
13324
- return !! this.listeners(event).length;
13325
- };
13326
-
13327
- const nextTick = (() => {
13328
- const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
13329
- if (isPromiseAvailable) {
13330
- return (cb) => Promise.resolve().then(cb);
13331
- }
13332
- else {
13333
- return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);
13334
- }
13335
- })();
13336
- const globalThisShim = (() => {
13337
- if (typeof self !== "undefined") {
13338
- return self;
13339
- }
13340
- else if (typeof window !== "undefined") {
13341
- return window;
13342
- }
13343
- else {
13344
- return Function("return this")();
13345
- }
13346
- })();
13347
- const defaultBinaryType = "arraybuffer";
13348
- function createCookieJar() { }
13349
-
13350
- function pick(obj, ...attr) {
13351
- return attr.reduce((acc, k) => {
13352
- if (obj.hasOwnProperty(k)) {
13353
- acc[k] = obj[k];
13354
- }
13355
- return acc;
13356
- }, {});
13357
- }
13358
- // Keep a reference to the real timeout functions so they can be used when overridden
13359
- const NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
13360
- const NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
13361
- function installTimerFunctions(obj, opts) {
13362
- if (opts.useNativeTimers) {
13363
- obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
13364
- obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
13365
- }
13366
- else {
13367
- obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
13368
- obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
13369
- }
13370
- }
13371
- // base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)
13372
- const BASE64_OVERHEAD = 1.33;
13373
- // we could also have used `new Blob([obj]).size`, but it isn't supported in IE9
13374
- function byteLength(obj) {
13375
- if (typeof obj === "string") {
13376
- return utf8Length(obj);
13377
- }
13378
- // arraybuffer or blob
13379
- return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
13380
- }
13381
- function utf8Length(str) {
13382
- let c = 0, length = 0;
13383
- for (let i = 0, l = str.length; i < l; i++) {
13384
- c = str.charCodeAt(i);
13385
- if (c < 0x80) {
13386
- length += 1;
13387
- }
13388
- else if (c < 0x800) {
13389
- length += 2;
13390
- }
13391
- else if (c < 0xd800 || c >= 0xe000) {
13392
- length += 3;
13393
- }
13394
- else {
13395
- i++;
13396
- length += 4;
13397
- }
13398
- }
13399
- return length;
13400
- }
13401
- /**
13402
- * Generates a random 8-characters string.
13403
- */
13404
- function randomString() {
13405
- return (Date.now().toString(36).substring(3) +
13406
- Math.random().toString(36).substring(2, 5));
13407
- }
13408
-
13409
- // imported from https://github.com/galkn/querystring
13410
- /**
13411
- * Compiles a querystring
13412
- * Returns string representation of the object
13413
- *
13414
- * @param {Object}
13415
- * @api private
13416
- */
13417
- function encode(obj) {
13418
- let str = '';
13419
- for (let i in obj) {
13420
- if (obj.hasOwnProperty(i)) {
13421
- if (str.length)
13422
- str += '&';
13423
- str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
13424
- }
13425
- }
13426
- return str;
13427
- }
13428
- /**
13429
- * Parses a simple querystring into an object
13430
- *
13431
- * @param {String} qs
13432
- * @api private
13433
- */
13434
- function decode(qs) {
13435
- let qry = {};
13436
- let pairs = qs.split('&');
13437
- for (let i = 0, l = pairs.length; i < l; i++) {
13438
- let pair = pairs[i].split('=');
13439
- qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
13440
- }
13441
- return qry;
13442
- }
13443
-
13444
- class TransportError extends Error {
13445
- constructor(reason, description, context) {
13446
- super(reason);
13447
- this.description = description;
13448
- this.context = context;
13449
- this.type = "TransportError";
13450
- }
13451
- }
13452
- class Transport extends Emitter {
13453
- /**
13454
- * Transport abstract constructor.
13455
- *
13456
- * @param {Object} opts - options
13457
- * @protected
13458
- */
13459
- constructor(opts) {
13460
- super();
13461
- this.writable = false;
13462
- installTimerFunctions(this, opts);
13463
- this.opts = opts;
13464
- this.query = opts.query;
13465
- this.socket = opts.socket;
13466
- this.supportsBinary = !opts.forceBase64;
13467
- }
13468
- /**
13469
- * Emits an error.
13470
- *
13471
- * @param {String} reason
13472
- * @param description
13473
- * @param context - the error context
13474
- * @return {Transport} for chaining
13475
- * @protected
13476
- */
13477
- onError(reason, description, context) {
13478
- super.emitReserved("error", new TransportError(reason, description, context));
13479
- return this;
13480
- }
13481
- /**
13482
- * Opens the transport.
13483
- */
13484
- open() {
13485
- this.readyState = "opening";
13486
- this.doOpen();
13487
- return this;
13488
- }
13489
- /**
13490
- * Closes the transport.
13491
- */
13492
- close() {
13493
- if (this.readyState === "opening" || this.readyState === "open") {
13494
- this.doClose();
13495
- this.onClose();
13496
- }
13497
- return this;
13498
- }
13499
- /**
13500
- * Sends multiple packets.
13501
- *
13502
- * @param {Array} packets
13503
- */
13504
- send(packets) {
13505
- if (this.readyState === "open") {
13506
- this.write(packets);
13507
- }
13508
- }
13509
- /**
13510
- * Called upon open
13511
- *
13512
- * @protected
13513
- */
13514
- onOpen() {
13515
- this.readyState = "open";
13516
- this.writable = true;
13517
- super.emitReserved("open");
13518
- }
13519
- /**
13520
- * Called with data.
13521
- *
13522
- * @param {String} data
13523
- * @protected
13524
- */
13525
- onData(data) {
13526
- const packet = decodePacket(data, this.socket.binaryType);
13527
- this.onPacket(packet);
13528
- }
13529
- /**
13530
- * Called with a decoded packet.
13531
- *
13532
- * @protected
13533
- */
13534
- onPacket(packet) {
13535
- super.emitReserved("packet", packet);
13536
- }
13537
- /**
13538
- * Called upon close.
13539
- *
13540
- * @protected
13541
- */
13542
- onClose(details) {
13543
- this.readyState = "closed";
13544
- super.emitReserved("close", details);
13545
- }
13546
- /**
13547
- * Pauses the transport, in order not to lose packets during an upgrade.
13548
- *
13549
- * @param onPause
13550
- */
13551
- pause(onPause) { }
13552
- createUri(schema, query = {}) {
13553
- return (schema +
13554
- "://" +
13555
- this._hostname() +
13556
- this._port() +
13557
- this.opts.path +
13558
- this._query(query));
13559
- }
13560
- _hostname() {
13561
- const hostname = this.opts.hostname;
13562
- return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
13563
- }
13564
- _port() {
13565
- if (this.opts.port &&
13566
- ((this.opts.secure && Number(this.opts.port !== 443)) ||
13567
- (!this.opts.secure && Number(this.opts.port) !== 80))) {
13568
- return ":" + this.opts.port;
13569
- }
13570
- else {
13571
- return "";
13572
- }
13573
- }
13574
- _query(query) {
13575
- const encodedQuery = encode(query);
13576
- return encodedQuery.length ? "?" + encodedQuery : "";
13577
- }
13578
- }
13579
-
13580
- class Polling extends Transport {
13581
- constructor() {
13582
- super(...arguments);
13583
- this._polling = false;
13584
- }
13585
- get name() {
13586
- return "polling";
13587
- }
13588
- /**
13589
- * Opens the socket (triggers polling). We write a PING message to determine
13590
- * when the transport is open.
13591
- *
13592
- * @protected
13593
- */
13594
- doOpen() {
13595
- this._poll();
13596
- }
13597
- /**
13598
- * Pauses polling.
13599
- *
13600
- * @param {Function} onPause - callback upon buffers are flushed and transport is paused
13601
- * @package
13602
- */
13603
- pause(onPause) {
13604
- this.readyState = "pausing";
13605
- const pause = () => {
13606
- this.readyState = "paused";
13607
- onPause();
13608
- };
13609
- if (this._polling || !this.writable) {
13610
- let total = 0;
13611
- if (this._polling) {
13612
- total++;
13613
- this.once("pollComplete", function () {
13614
- --total || pause();
13615
- });
13616
- }
13617
- if (!this.writable) {
13618
- total++;
13619
- this.once("drain", function () {
13620
- --total || pause();
13621
- });
13622
- }
13623
- }
13624
- else {
13625
- pause();
13626
- }
13627
- }
13628
- /**
13629
- * Starts polling cycle.
13630
- *
13631
- * @private
13632
- */
13633
- _poll() {
13634
- this._polling = true;
13635
- this.doPoll();
13636
- this.emitReserved("poll");
13637
- }
13638
- /**
13639
- * Overloads onData to detect payloads.
13640
- *
13641
- * @protected
13642
- */
13643
- onData(data) {
13644
- const callback = (packet) => {
13645
- // if its the first message we consider the transport open
13646
- if ("opening" === this.readyState && packet.type === "open") {
13647
- this.onOpen();
13648
- }
13649
- // if its a close packet, we close the ongoing requests
13650
- if ("close" === packet.type) {
13651
- this.onClose({ description: "transport closed by the server" });
13652
- return false;
13653
- }
13654
- // otherwise bypass onData and handle the message
13655
- this.onPacket(packet);
13656
- };
13657
- // decode payload
13658
- decodePayload(data, this.socket.binaryType).forEach(callback);
13659
- // if an event did not trigger closing
13660
- if ("closed" !== this.readyState) {
13661
- // if we got data we're not polling
13662
- this._polling = false;
13663
- this.emitReserved("pollComplete");
13664
- if ("open" === this.readyState) {
13665
- this._poll();
13666
- }
13667
- }
13668
- }
13669
- /**
13670
- * For polling, send a close packet.
13671
- *
13672
- * @protected
13673
- */
13674
- doClose() {
13675
- const close = () => {
13676
- this.write([{ type: "close" }]);
13677
- };
13678
- if ("open" === this.readyState) {
13679
- close();
13680
- }
13681
- else {
13682
- // in case we're trying to close while
13683
- // handshaking is in progress (GH-164)
13684
- this.once("open", close);
13685
- }
13686
- }
13687
- /**
13688
- * Writes a packets payload.
13689
- *
13690
- * @param {Array} packets - data packets
13691
- * @protected
13692
- */
13693
- write(packets) {
13694
- this.writable = false;
13695
- encodePayload(packets, (data) => {
13696
- this.doWrite(data, () => {
13697
- this.writable = true;
13698
- this.emitReserved("drain");
13699
- });
13700
- });
13701
- }
13702
- /**
13703
- * Generates uri for connection.
13704
- *
13705
- * @private
13706
- */
13707
- uri() {
13708
- const schema = this.opts.secure ? "https" : "http";
13709
- const query = this.query || {};
13710
- // cache busting is forced
13711
- if (false !== this.opts.timestampRequests) {
13712
- query[this.opts.timestampParam] = randomString();
13713
- }
13714
- if (!this.supportsBinary && !query.sid) {
13715
- query.b64 = 1;
13716
- }
13717
- return this.createUri(schema, query);
13718
- }
13719
- }
13720
-
13721
- // imported from https://github.com/component/has-cors
13722
- let value = false;
13723
- try {
13724
- value = typeof XMLHttpRequest !== 'undefined' &&
13725
- 'withCredentials' in new XMLHttpRequest();
13726
- }
13727
- catch (err) {
13728
- // if XMLHttp support is disabled in IE then it will throw
13729
- // when trying to create
13730
- }
13731
- const hasCORS = value;
13732
-
13733
- function empty() { }
13734
- class BaseXHR extends Polling {
13735
- /**
13736
- * XHR Polling constructor.
13737
- *
13738
- * @param {Object} opts
13739
- * @package
13740
- */
13741
- constructor(opts) {
13742
- super(opts);
13743
- if (typeof location !== "undefined") {
13744
- const isSSL = "https:" === location.protocol;
13745
- let port = location.port;
13746
- // some user agents have empty `location.port`
13747
- if (!port) {
13748
- port = isSSL ? "443" : "80";
13749
- }
13750
- this.xd =
13751
- (typeof location !== "undefined" &&
13752
- opts.hostname !== location.hostname) ||
13753
- port !== opts.port;
13754
- }
13755
- }
13756
- /**
13757
- * Sends data.
13758
- *
13759
- * @param {String} data to send.
13760
- * @param {Function} called upon flush.
13761
- * @private
13762
- */
13763
- doWrite(data, fn) {
13764
- const req = this.request({
13765
- method: "POST",
13766
- data: data,
13767
- });
13768
- req.on("success", fn);
13769
- req.on("error", (xhrStatus, context) => {
13770
- this.onError("xhr post error", xhrStatus, context);
13771
- });
13772
- }
13773
- /**
13774
- * Starts a poll cycle.
13775
- *
13776
- * @private
13777
- */
13778
- doPoll() {
13779
- const req = this.request();
13780
- req.on("data", this.onData.bind(this));
13781
- req.on("error", (xhrStatus, context) => {
13782
- this.onError("xhr poll error", xhrStatus, context);
13783
- });
13784
- this.pollXhr = req;
13785
- }
13786
- }
13787
- class Request extends Emitter {
13788
- /**
13789
- * Request constructor
13790
- *
13791
- * @param {Object} options
13792
- * @package
13793
- */
13794
- constructor(createRequest, uri, opts) {
13795
- super();
13796
- this.createRequest = createRequest;
13797
- installTimerFunctions(this, opts);
13798
- this._opts = opts;
13799
- this._method = opts.method || "GET";
13800
- this._uri = uri;
13801
- this._data = undefined !== opts.data ? opts.data : null;
13802
- this._create();
13803
- }
13804
- /**
13805
- * Creates the XHR object and sends the request.
13806
- *
13807
- * @private
13808
- */
13809
- _create() {
13810
- var _a;
13811
- const opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
13812
- opts.xdomain = !!this._opts.xd;
13813
- const xhr = (this._xhr = this.createRequest(opts));
13814
- try {
13815
- xhr.open(this._method, this._uri, true);
13816
- try {
13817
- if (this._opts.extraHeaders) {
13818
- // @ts-ignore
13819
- xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
13820
- for (let i in this._opts.extraHeaders) {
13821
- if (this._opts.extraHeaders.hasOwnProperty(i)) {
13822
- xhr.setRequestHeader(i, this._opts.extraHeaders[i]);
13823
- }
13824
- }
13825
- }
13826
- }
13827
- catch (e) { }
13828
- if ("POST" === this._method) {
13829
- try {
13830
- xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
13831
- }
13832
- catch (e) { }
13833
- }
13834
- try {
13835
- xhr.setRequestHeader("Accept", "*/*");
13836
- }
13837
- catch (e) { }
13838
- (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
13839
- // ie6 check
13840
- if ("withCredentials" in xhr) {
13841
- xhr.withCredentials = this._opts.withCredentials;
13842
- }
13843
- if (this._opts.requestTimeout) {
13844
- xhr.timeout = this._opts.requestTimeout;
13845
- }
13846
- xhr.onreadystatechange = () => {
13847
- var _a;
13848
- if (xhr.readyState === 3) {
13849
- (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(
13850
- // @ts-ignore
13851
- xhr.getResponseHeader("set-cookie"));
13852
- }
13853
- if (4 !== xhr.readyState)
13854
- return;
13855
- if (200 === xhr.status || 1223 === xhr.status) {
13856
- this._onLoad();
13857
- }
13858
- else {
13859
- // make sure the `error` event handler that's user-set
13860
- // does not throw in the same tick and gets caught here
13861
- this.setTimeoutFn(() => {
13862
- this._onError(typeof xhr.status === "number" ? xhr.status : 0);
13863
- }, 0);
13864
- }
13865
- };
13866
- xhr.send(this._data);
13867
- }
13868
- catch (e) {
13869
- // Need to defer since .create() is called directly from the constructor
13870
- // and thus the 'error' event can only be only bound *after* this exception
13871
- // occurs. Therefore, also, we cannot throw here at all.
13872
- this.setTimeoutFn(() => {
13873
- this._onError(e);
13874
- }, 0);
13875
- return;
13876
- }
13877
- if (typeof document !== "undefined") {
13878
- this._index = Request.requestsCount++;
13879
- Request.requests[this._index] = this;
13880
- }
13881
- }
13882
- /**
13883
- * Called upon error.
13884
- *
13885
- * @private
13886
- */
13887
- _onError(err) {
13888
- this.emitReserved("error", err, this._xhr);
13889
- this._cleanup(true);
13890
- }
13891
- /**
13892
- * Cleans up house.
13893
- *
13894
- * @private
13895
- */
13896
- _cleanup(fromError) {
13897
- if ("undefined" === typeof this._xhr || null === this._xhr) {
13898
- return;
13899
- }
13900
- this._xhr.onreadystatechange = empty;
13901
- if (fromError) {
13902
- try {
13903
- this._xhr.abort();
13904
- }
13905
- catch (e) { }
13906
- }
13907
- if (typeof document !== "undefined") {
13908
- delete Request.requests[this._index];
13909
- }
13910
- this._xhr = null;
13911
- }
13912
- /**
13913
- * Called upon load.
13914
- *
13915
- * @private
13916
- */
13917
- _onLoad() {
13918
- const data = this._xhr.responseText;
13919
- if (data !== null) {
13920
- this.emitReserved("data", data);
13921
- this.emitReserved("success");
13922
- this._cleanup();
13923
- }
13924
- }
13925
- /**
13926
- * Aborts the request.
13927
- *
13928
- * @package
13929
- */
13930
- abort() {
13931
- this._cleanup();
13932
- }
13933
- }
13934
- Request.requestsCount = 0;
13935
- Request.requests = {};
13936
- /**
13937
- * Aborts pending requests when unloading the window. This is needed to prevent
13938
- * memory leaks (e.g. when using IE) and to ensure that no spurious error is
13939
- * emitted.
13940
- */
13941
- if (typeof document !== "undefined") {
13942
- // @ts-ignore
13943
- if (typeof attachEvent === "function") {
13944
- // @ts-ignore
13945
- attachEvent("onunload", unloadHandler);
13946
- }
13947
- else if (typeof addEventListener === "function") {
13948
- const terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
13949
- addEventListener(terminationEvent, unloadHandler, false);
13950
- }
13951
- }
13952
- function unloadHandler() {
13953
- for (let i in Request.requests) {
13954
- if (Request.requests.hasOwnProperty(i)) {
13955
- Request.requests[i].abort();
13956
- }
13957
- }
13958
- }
13959
- const hasXHR2 = (function () {
13960
- const xhr = newRequest({
13961
- xdomain: false,
13962
- });
13963
- return xhr && xhr.responseType !== null;
13964
- })();
13965
- /**
13966
- * HTTP long-polling based on the built-in `XMLHttpRequest` object.
13967
- *
13968
- * Usage: browser
13969
- *
13970
- * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
13971
- */
13972
- class XHR extends BaseXHR {
13973
- constructor(opts) {
13974
- super(opts);
13975
- const forceBase64 = opts && opts.forceBase64;
13976
- this.supportsBinary = hasXHR2 && !forceBase64;
13977
- }
13978
- request(opts = {}) {
13979
- Object.assign(opts, { xd: this.xd }, this.opts);
13980
- return new Request(newRequest, this.uri(), opts);
13981
- }
13982
- }
13983
- function newRequest(opts) {
13984
- const xdomain = opts.xdomain;
13985
- // XMLHttpRequest can be disabled on IE
13986
- try {
13987
- if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
13988
- return new XMLHttpRequest();
13989
- }
13990
- }
13991
- catch (e) { }
13992
- if (!xdomain) {
13993
- try {
13994
- return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
13995
- }
13996
- catch (e) { }
13997
- }
13998
- }
13999
-
14000
- // detect ReactNative environment
14001
- const isReactNative = typeof navigator !== "undefined" &&
14002
- typeof navigator.product === "string" &&
14003
- navigator.product.toLowerCase() === "reactnative";
14004
- class BaseWS extends Transport {
14005
- get name() {
14006
- return "websocket";
14007
- }
14008
- doOpen() {
14009
- const uri = this.uri();
14010
- const protocols = this.opts.protocols;
14011
- // React Native only supports the 'headers' option, and will print a warning if anything else is passed
14012
- const opts = isReactNative
14013
- ? {}
14014
- : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
14015
- if (this.opts.extraHeaders) {
14016
- opts.headers = this.opts.extraHeaders;
14017
- }
14018
- try {
14019
- this.ws = this.createSocket(uri, protocols, opts);
14020
- }
14021
- catch (err) {
14022
- return this.emitReserved("error", err);
14023
- }
14024
- this.ws.binaryType = this.socket.binaryType;
14025
- this.addEventListeners();
14026
- }
14027
- /**
14028
- * Adds event listeners to the socket
14029
- *
14030
- * @private
14031
- */
14032
- addEventListeners() {
14033
- this.ws.onopen = () => {
14034
- if (this.opts.autoUnref) {
14035
- this.ws._socket.unref();
14036
- }
14037
- this.onOpen();
14038
- };
14039
- this.ws.onclose = (closeEvent) => this.onClose({
14040
- description: "websocket connection closed",
14041
- context: closeEvent,
14042
- });
14043
- this.ws.onmessage = (ev) => this.onData(ev.data);
14044
- this.ws.onerror = (e) => this.onError("websocket error", e);
14045
- }
14046
- write(packets) {
14047
- this.writable = false;
14048
- // encodePacket efficient as it uses WS framing
14049
- // no need for encodePayload
14050
- for (let i = 0; i < packets.length; i++) {
14051
- const packet = packets[i];
14052
- const lastPacket = i === packets.length - 1;
14053
- encodePacket(packet, this.supportsBinary, (data) => {
14054
- // Sometimes the websocket has already been closed but the browser didn't
14055
- // have a chance of informing us about it yet, in that case send will
14056
- // throw an error
14057
- try {
14058
- this.doWrite(packet, data);
14059
- }
14060
- catch (e) {
14061
- }
14062
- if (lastPacket) {
14063
- // fake drain
14064
- // defer to next tick to allow Socket to clear writeBuffer
14065
- nextTick(() => {
14066
- this.writable = true;
14067
- this.emitReserved("drain");
14068
- }, this.setTimeoutFn);
14069
- }
14070
- });
14071
- }
14072
- }
14073
- doClose() {
14074
- if (typeof this.ws !== "undefined") {
14075
- this.ws.onerror = () => { };
14076
- this.ws.close();
14077
- this.ws = null;
14078
- }
14079
- }
14080
- /**
14081
- * Generates uri for connection.
14082
- *
14083
- * @private
14084
- */
14085
- uri() {
14086
- const schema = this.opts.secure ? "wss" : "ws";
14087
- const query = this.query || {};
14088
- // append timestamp to URI
14089
- if (this.opts.timestampRequests) {
14090
- query[this.opts.timestampParam] = randomString();
14091
- }
14092
- // communicate binary support capabilities
14093
- if (!this.supportsBinary) {
14094
- query.b64 = 1;
14095
- }
14096
- return this.createUri(schema, query);
14097
- }
14098
- }
14099
- const WebSocketCtor = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
14100
- /**
14101
- * WebSocket transport based on the built-in `WebSocket` object.
14102
- *
14103
- * Usage: browser, Node.js (since v21), Deno, Bun
14104
- *
14105
- * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
14106
- * @see https://caniuse.com/mdn-api_websocket
14107
- * @see https://nodejs.org/api/globals.html#websocket
14108
- */
14109
- class WS extends BaseWS {
14110
- createSocket(uri, protocols, opts) {
14111
- return !isReactNative
14112
- ? protocols
14113
- ? new WebSocketCtor(uri, protocols)
14114
- : new WebSocketCtor(uri)
14115
- : new WebSocketCtor(uri, protocols, opts);
14116
- }
14117
- doWrite(_packet, data) {
14118
- this.ws.send(data);
14119
- }
14120
- }
14121
-
14122
- /**
14123
- * WebTransport transport based on the built-in `WebTransport` object.
14124
- *
14125
- * Usage: browser, Node.js (with the `@fails-components/webtransport` package)
14126
- *
14127
- * @see https://developer.mozilla.org/en-US/docs/Web/API/WebTransport
14128
- * @see https://caniuse.com/webtransport
14129
- */
14130
- class WT extends Transport {
14131
- get name() {
14132
- return "webtransport";
14133
- }
14134
- doOpen() {
14135
- try {
14136
- // @ts-ignore
14137
- this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
14138
- }
14139
- catch (err) {
14140
- return this.emitReserved("error", err);
14141
- }
14142
- this._transport.closed
14143
- .then(() => {
14144
- this.onClose();
14145
- })
14146
- .catch((err) => {
14147
- this.onError("webtransport error", err);
14148
- });
14149
- // note: we could have used async/await, but that would require some additional polyfills
14150
- this._transport.ready.then(() => {
14151
- this._transport.createBidirectionalStream().then((stream) => {
14152
- const decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, this.socket.binaryType);
14153
- const reader = stream.readable.pipeThrough(decoderStream).getReader();
14154
- const encoderStream = createPacketEncoderStream();
14155
- encoderStream.readable.pipeTo(stream.writable);
14156
- this._writer = encoderStream.writable.getWriter();
14157
- const read = () => {
14158
- reader
14159
- .read()
14160
- .then(({ done, value }) => {
14161
- if (done) {
14162
- return;
14163
- }
14164
- this.onPacket(value);
14165
- read();
14166
- })
14167
- .catch((err) => {
14168
- });
14169
- };
14170
- read();
14171
- const packet = { type: "open" };
14172
- if (this.query.sid) {
14173
- packet.data = `{"sid":"${this.query.sid}"}`;
14174
- }
14175
- this._writer.write(packet).then(() => this.onOpen());
14176
- });
14177
- });
14178
- }
14179
- write(packets) {
14180
- this.writable = false;
14181
- for (let i = 0; i < packets.length; i++) {
14182
- const packet = packets[i];
14183
- const lastPacket = i === packets.length - 1;
14184
- this._writer.write(packet).then(() => {
14185
- if (lastPacket) {
14186
- nextTick(() => {
14187
- this.writable = true;
14188
- this.emitReserved("drain");
14189
- }, this.setTimeoutFn);
14190
- }
14191
- });
14192
- }
14193
- }
14194
- doClose() {
14195
- var _a;
14196
- (_a = this._transport) === null || _a === void 0 ? void 0 : _a.close();
14197
- }
14198
- }
14199
-
14200
- const transports = {
14201
- websocket: WS,
14202
- webtransport: WT,
14203
- polling: XHR,
14204
- };
14205
-
14206
- // imported from https://github.com/galkn/parseuri
14207
- /**
14208
- * Parses a URI
14209
- *
14210
- * Note: we could also have used the built-in URL object, but it isn't supported on all platforms.
14211
- *
14212
- * See:
14213
- * - https://developer.mozilla.org/en-US/docs/Web/API/URL
14214
- * - https://caniuse.com/url
14215
- * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B
14216
- *
14217
- * History of the parse() method:
14218
- * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c
14219
- * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3
14220
- * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242
14221
- *
14222
- * @author Steven Levithan <stevenlevithan.com> (MIT license)
14223
- * @api private
14224
- */
14225
- const re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
14226
- const parts = [
14227
- 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
14228
- ];
14229
- function parse(str) {
14230
- if (str.length > 8000) {
14231
- throw "URI too long";
14232
- }
14233
- const src = str, b = str.indexOf('['), e = str.indexOf(']');
14234
- if (b != -1 && e != -1) {
14235
- str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
14236
- }
14237
- let m = re.exec(str || ''), uri = {}, i = 14;
14238
- while (i--) {
14239
- uri[parts[i]] = m[i] || '';
14240
- }
14241
- if (b != -1 && e != -1) {
14242
- uri.source = src;
14243
- uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
14244
- uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
14245
- uri.ipv6uri = true;
14246
- }
14247
- uri.pathNames = pathNames(uri, uri['path']);
14248
- uri.queryKey = queryKey(uri, uri['query']);
14249
- return uri;
14250
- }
14251
- function pathNames(obj, path) {
14252
- const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/");
14253
- if (path.slice(0, 1) == '/' || path.length === 0) {
14254
- names.splice(0, 1);
14255
- }
14256
- if (path.slice(-1) == '/') {
14257
- names.splice(names.length - 1, 1);
14258
- }
14259
- return names;
14260
- }
14261
- function queryKey(uri, query) {
14262
- const data = {};
14263
- query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
14264
- if ($1) {
14265
- data[$1] = $2;
14266
- }
14267
- });
14268
- return data;
14269
- }
14270
-
14271
- const withEventListeners = typeof addEventListener === "function" &&
14272
- typeof removeEventListener === "function";
14273
- const OFFLINE_EVENT_LISTENERS = [];
14274
- if (withEventListeners) {
14275
- // within a ServiceWorker, any event handler for the 'offline' event must be added on the initial evaluation of the
14276
- // script, so we create one single event listener here which will forward the event to the socket instances
14277
- addEventListener("offline", () => {
14278
- OFFLINE_EVENT_LISTENERS.forEach((listener) => listener());
14279
- }, false);
14280
- }
14281
- /**
14282
- * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
14283
- * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
14284
- *
14285
- * This class comes without upgrade mechanism, which means that it will keep the first low-level transport that
14286
- * successfully establishes the connection.
14287
- *
14288
- * In order to allow tree-shaking, there are no transports included, that's why the `transports` option is mandatory.
14289
- *
14290
- * @example
14291
- * import { SocketWithoutUpgrade, WebSocket } from "engine.io-client";
14292
- *
14293
- * const socket = new SocketWithoutUpgrade({
14294
- * transports: [WebSocket]
14295
- * });
14296
- *
14297
- * socket.on("open", () => {
14298
- * socket.send("hello");
14299
- * });
14300
- *
14301
- * @see SocketWithUpgrade
14302
- * @see Socket
14303
- */
14304
- class SocketWithoutUpgrade extends Emitter {
14305
- /**
14306
- * Socket constructor.
14307
- *
14308
- * @param {String|Object} uri - uri or options
14309
- * @param {Object} opts - options
14310
- */
14311
- constructor(uri, opts) {
14312
- super();
14313
- this.binaryType = defaultBinaryType;
14314
- this.writeBuffer = [];
14315
- this._prevBufferLen = 0;
14316
- this._pingInterval = -1;
14317
- this._pingTimeout = -1;
14318
- this._maxPayload = -1;
14319
- /**
14320
- * The expiration timestamp of the {@link _pingTimeoutTimer} object is tracked, in case the timer is throttled and the
14321
- * callback is not fired on time. This can happen for example when a laptop is suspended or when a phone is locked.
14322
- */
14323
- this._pingTimeoutTime = Infinity;
14324
- if (uri && "object" === typeof uri) {
14325
- opts = uri;
14326
- uri = null;
14327
- }
14328
- if (uri) {
14329
- const parsedUri = parse(uri);
14330
- opts.hostname = parsedUri.host;
14331
- opts.secure =
14332
- parsedUri.protocol === "https" || parsedUri.protocol === "wss";
14333
- opts.port = parsedUri.port;
14334
- if (parsedUri.query)
14335
- opts.query = parsedUri.query;
14336
- }
14337
- else if (opts.host) {
14338
- opts.hostname = parse(opts.host).host;
14339
- }
14340
- installTimerFunctions(this, opts);
14341
- this.secure =
14342
- null != opts.secure
14343
- ? opts.secure
14344
- : typeof location !== "undefined" && "https:" === location.protocol;
14345
- if (opts.hostname && !opts.port) {
14346
- // if no port is specified manually, use the protocol default
14347
- opts.port = this.secure ? "443" : "80";
14348
- }
14349
- this.hostname =
14350
- opts.hostname ||
14351
- (typeof location !== "undefined" ? location.hostname : "localhost");
14352
- this.port =
14353
- opts.port ||
14354
- (typeof location !== "undefined" && location.port
14355
- ? location.port
14356
- : this.secure
14357
- ? "443"
14358
- : "80");
14359
- this.transports = [];
14360
- this._transportsByName = {};
14361
- opts.transports.forEach((t) => {
14362
- const transportName = t.prototype.name;
14363
- this.transports.push(transportName);
14364
- this._transportsByName[transportName] = t;
14365
- });
14366
- this.opts = Object.assign({
14367
- path: "/engine.io",
14368
- agent: false,
14369
- withCredentials: false,
14370
- upgrade: true,
14371
- timestampParam: "t",
14372
- rememberUpgrade: false,
14373
- addTrailingSlash: true,
14374
- rejectUnauthorized: true,
14375
- perMessageDeflate: {
14376
- threshold: 1024,
14377
- },
14378
- transportOptions: {},
14379
- closeOnBeforeunload: false,
14380
- }, opts);
14381
- this.opts.path =
14382
- this.opts.path.replace(/\/$/, "") +
14383
- (this.opts.addTrailingSlash ? "/" : "");
14384
- if (typeof this.opts.query === "string") {
14385
- this.opts.query = decode(this.opts.query);
14386
- }
14387
- if (withEventListeners) {
14388
- if (this.opts.closeOnBeforeunload) {
14389
- // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
14390
- // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
14391
- // closed/reloaded)
14392
- this._beforeunloadEventListener = () => {
14393
- if (this.transport) {
14394
- // silently close the transport
14395
- this.transport.removeAllListeners();
14396
- this.transport.close();
14397
- }
14398
- };
14399
- addEventListener("beforeunload", this._beforeunloadEventListener, false);
14400
- }
14401
- if (this.hostname !== "localhost") {
14402
- this._offlineEventListener = () => {
14403
- this._onClose("transport close", {
14404
- description: "network connection lost",
14405
- });
14406
- };
14407
- OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener);
14408
- }
14409
- }
14410
- if (this.opts.withCredentials) {
14411
- this._cookieJar = createCookieJar();
14412
- }
14413
- this._open();
14414
- }
14415
- /**
14416
- * Creates transport of the given type.
14417
- *
14418
- * @param {String} name - transport name
14419
- * @return {Transport}
14420
- * @private
14421
- */
14422
- createTransport(name) {
14423
- const query = Object.assign({}, this.opts.query);
14424
- // append engine.io protocol identifier
14425
- query.EIO = protocol$1;
14426
- // transport name
14427
- query.transport = name;
14428
- // session id if we already have one
14429
- if (this.id)
14430
- query.sid = this.id;
14431
- const opts = Object.assign({}, this.opts, {
14432
- query,
14433
- socket: this,
14434
- hostname: this.hostname,
14435
- secure: this.secure,
14436
- port: this.port,
14437
- }, this.opts.transportOptions[name]);
14438
- return new this._transportsByName[name](opts);
14439
- }
14440
- /**
14441
- * Initializes transport to use and starts probe.
14442
- *
14443
- * @private
14444
- */
14445
- _open() {
14446
- if (this.transports.length === 0) {
14447
- // Emit error on next tick so it can be listened to
14448
- this.setTimeoutFn(() => {
14449
- this.emitReserved("error", "No transports available");
14450
- }, 0);
14451
- return;
14452
- }
14453
- const transportName = this.opts.rememberUpgrade &&
14454
- SocketWithoutUpgrade.priorWebsocketSuccess &&
14455
- this.transports.indexOf("websocket") !== -1
14456
- ? "websocket"
14457
- : this.transports[0];
14458
- this.readyState = "opening";
14459
- const transport = this.createTransport(transportName);
14460
- transport.open();
14461
- this.setTransport(transport);
14462
- }
14463
- /**
14464
- * Sets the current transport. Disables the existing one (if any).
14465
- *
14466
- * @private
14467
- */
14468
- setTransport(transport) {
14469
- if (this.transport) {
14470
- this.transport.removeAllListeners();
14471
- }
14472
- // set up transport
14473
- this.transport = transport;
14474
- // set up transport listeners
14475
- transport
14476
- .on("drain", this._onDrain.bind(this))
14477
- .on("packet", this._onPacket.bind(this))
14478
- .on("error", this._onError.bind(this))
14479
- .on("close", (reason) => this._onClose("transport close", reason));
14480
- }
14481
- /**
14482
- * Called when connection is deemed open.
14483
- *
14484
- * @private
14485
- */
14486
- onOpen() {
14487
- this.readyState = "open";
14488
- SocketWithoutUpgrade.priorWebsocketSuccess =
14489
- "websocket" === this.transport.name;
14490
- this.emitReserved("open");
14491
- this.flush();
14492
- }
14493
- /**
14494
- * Handles a packet.
14495
- *
14496
- * @private
14497
- */
14498
- _onPacket(packet) {
14499
- if ("opening" === this.readyState ||
14500
- "open" === this.readyState ||
14501
- "closing" === this.readyState) {
14502
- this.emitReserved("packet", packet);
14503
- // Socket is live - any packet counts
14504
- this.emitReserved("heartbeat");
14505
- switch (packet.type) {
14506
- case "open":
14507
- this.onHandshake(JSON.parse(packet.data));
14508
- break;
14509
- case "ping":
14510
- this._sendPacket("pong");
14511
- this.emitReserved("ping");
14512
- this.emitReserved("pong");
14513
- this._resetPingTimeout();
14514
- break;
14515
- case "error":
14516
- const err = new Error("server error");
14517
- // @ts-ignore
14518
- err.code = packet.data;
14519
- this._onError(err);
14520
- break;
14521
- case "message":
14522
- this.emitReserved("data", packet.data);
14523
- this.emitReserved("message", packet.data);
14524
- break;
14525
- }
14526
- }
14527
- }
14528
- /**
14529
- * Called upon handshake completion.
14530
- *
14531
- * @param {Object} data - handshake obj
14532
- * @private
14533
- */
14534
- onHandshake(data) {
14535
- this.emitReserved("handshake", data);
14536
- this.id = data.sid;
14537
- this.transport.query.sid = data.sid;
14538
- this._pingInterval = data.pingInterval;
14539
- this._pingTimeout = data.pingTimeout;
14540
- this._maxPayload = data.maxPayload;
14541
- this.onOpen();
14542
- // In case open handler closes socket
14543
- if ("closed" === this.readyState)
14544
- return;
14545
- this._resetPingTimeout();
14546
- }
14547
- /**
14548
- * Sets and resets ping timeout timer based on server pings.
14549
- *
14550
- * @private
14551
- */
14552
- _resetPingTimeout() {
14553
- this.clearTimeoutFn(this._pingTimeoutTimer);
14554
- const delay = this._pingInterval + this._pingTimeout;
14555
- this._pingTimeoutTime = Date.now() + delay;
14556
- this._pingTimeoutTimer = this.setTimeoutFn(() => {
14557
- this._onClose("ping timeout");
14558
- }, delay);
14559
- if (this.opts.autoUnref) {
14560
- this._pingTimeoutTimer.unref();
14561
- }
14562
- }
14563
- /**
14564
- * Called on `drain` event
14565
- *
14566
- * @private
14567
- */
14568
- _onDrain() {
14569
- this.writeBuffer.splice(0, this._prevBufferLen);
14570
- // setting prevBufferLen = 0 is very important
14571
- // for example, when upgrading, upgrade packet is sent over,
14572
- // and a nonzero prevBufferLen could cause problems on `drain`
14573
- this._prevBufferLen = 0;
14574
- if (0 === this.writeBuffer.length) {
14575
- this.emitReserved("drain");
14576
- }
14577
- else {
14578
- this.flush();
14579
- }
14580
- }
14581
- /**
14582
- * Flush write buffers.
14583
- *
14584
- * @private
14585
- */
14586
- flush() {
14587
- if ("closed" !== this.readyState &&
14588
- this.transport.writable &&
14589
- !this.upgrading &&
14590
- this.writeBuffer.length) {
14591
- const packets = this._getWritablePackets();
14592
- this.transport.send(packets);
14593
- // keep track of current length of writeBuffer
14594
- // splice writeBuffer and callbackBuffer on `drain`
14595
- this._prevBufferLen = packets.length;
14596
- this.emitReserved("flush");
14597
- }
14598
- }
14599
- /**
14600
- * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
14601
- * long-polling)
14602
- *
14603
- * @private
14604
- */
14605
- _getWritablePackets() {
14606
- const shouldCheckPayloadSize = this._maxPayload &&
14607
- this.transport.name === "polling" &&
14608
- this.writeBuffer.length > 1;
14609
- if (!shouldCheckPayloadSize) {
14610
- return this.writeBuffer;
14611
- }
14612
- let payloadSize = 1; // first packet type
14613
- for (let i = 0; i < this.writeBuffer.length; i++) {
14614
- const data = this.writeBuffer[i].data;
14615
- if (data) {
14616
- payloadSize += byteLength(data);
14617
- }
14618
- if (i > 0 && payloadSize > this._maxPayload) {
14619
- return this.writeBuffer.slice(0, i);
14620
- }
14621
- payloadSize += 2; // separator + packet type
14622
- }
14623
- return this.writeBuffer;
14624
- }
14625
- /**
14626
- * Checks whether the heartbeat timer has expired but the socket has not yet been notified.
14627
- *
14628
- * Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
14629
- * `write()` method then the message would not be buffered by the Socket.IO client.
14630
- *
14631
- * @return {boolean}
14632
- * @private
14633
- */
14634
- /* private */ _hasPingExpired() {
14635
- if (!this._pingTimeoutTime)
14636
- return true;
14637
- const hasExpired = Date.now() > this._pingTimeoutTime;
14638
- if (hasExpired) {
14639
- this._pingTimeoutTime = 0;
14640
- nextTick(() => {
14641
- this._onClose("ping timeout");
14642
- }, this.setTimeoutFn);
14643
- }
14644
- return hasExpired;
14645
- }
14646
- /**
14647
- * Sends a message.
14648
- *
14649
- * @param {String} msg - message.
14650
- * @param {Object} options.
14651
- * @param {Function} fn - callback function.
14652
- * @return {Socket} for chaining.
14653
- */
14654
- write(msg, options, fn) {
14655
- this._sendPacket("message", msg, options, fn);
14656
- return this;
14657
- }
14658
- /**
14659
- * Sends a message. Alias of {@link Socket#write}.
14660
- *
14661
- * @param {String} msg - message.
14662
- * @param {Object} options.
14663
- * @param {Function} fn - callback function.
14664
- * @return {Socket} for chaining.
14665
- */
14666
- send(msg, options, fn) {
14667
- this._sendPacket("message", msg, options, fn);
14668
- return this;
14669
- }
14670
- /**
14671
- * Sends a packet.
14672
- *
14673
- * @param {String} type: packet type.
14674
- * @param {String} data.
14675
- * @param {Object} options.
14676
- * @param {Function} fn - callback function.
14677
- * @private
14678
- */
14679
- _sendPacket(type, data, options, fn) {
14680
- if ("function" === typeof data) {
14681
- fn = data;
14682
- data = undefined;
14683
- }
14684
- if ("function" === typeof options) {
14685
- fn = options;
14686
- options = null;
14687
- }
14688
- if ("closing" === this.readyState || "closed" === this.readyState) {
14689
- return;
14690
- }
14691
- options = options || {};
14692
- options.compress = false !== options.compress;
14693
- const packet = {
14694
- type: type,
14695
- data: data,
14696
- options: options,
14697
- };
14698
- this.emitReserved("packetCreate", packet);
14699
- this.writeBuffer.push(packet);
14700
- if (fn)
14701
- this.once("flush", fn);
14702
- this.flush();
14703
- }
14704
- /**
14705
- * Closes the connection.
14706
- */
14707
- close() {
14708
- const close = () => {
14709
- this._onClose("forced close");
14710
- this.transport.close();
14711
- };
14712
- const cleanupAndClose = () => {
14713
- this.off("upgrade", cleanupAndClose);
14714
- this.off("upgradeError", cleanupAndClose);
14715
- close();
14716
- };
14717
- const waitForUpgrade = () => {
14718
- // wait for upgrade to finish since we can't send packets while pausing a transport
14719
- this.once("upgrade", cleanupAndClose);
14720
- this.once("upgradeError", cleanupAndClose);
14721
- };
14722
- if ("opening" === this.readyState || "open" === this.readyState) {
14723
- this.readyState = "closing";
14724
- if (this.writeBuffer.length) {
14725
- this.once("drain", () => {
14726
- if (this.upgrading) {
14727
- waitForUpgrade();
14728
- }
14729
- else {
14730
- close();
14731
- }
14732
- });
14733
- }
14734
- else if (this.upgrading) {
14735
- waitForUpgrade();
14736
- }
14737
- else {
14738
- close();
14739
- }
14740
- }
14741
- return this;
14742
- }
14743
- /**
14744
- * Called upon transport error
14745
- *
14746
- * @private
14747
- */
14748
- _onError(err) {
14749
- SocketWithoutUpgrade.priorWebsocketSuccess = false;
14750
- if (this.opts.tryAllTransports &&
14751
- this.transports.length > 1 &&
14752
- this.readyState === "opening") {
14753
- this.transports.shift();
14754
- return this._open();
14755
- }
14756
- this.emitReserved("error", err);
14757
- this._onClose("transport error", err);
14758
- }
14759
- /**
14760
- * Called upon transport close.
14761
- *
14762
- * @private
14763
- */
14764
- _onClose(reason, description) {
14765
- if ("opening" === this.readyState ||
14766
- "open" === this.readyState ||
14767
- "closing" === this.readyState) {
14768
- // clear timers
14769
- this.clearTimeoutFn(this._pingTimeoutTimer);
14770
- // stop event from firing again for transport
14771
- this.transport.removeAllListeners("close");
14772
- // ensure transport won't stay open
14773
- this.transport.close();
14774
- // ignore further transport communication
14775
- this.transport.removeAllListeners();
14776
- if (withEventListeners) {
14777
- if (this._beforeunloadEventListener) {
14778
- removeEventListener("beforeunload", this._beforeunloadEventListener, false);
14779
- }
14780
- if (this._offlineEventListener) {
14781
- const i = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
14782
- if (i !== -1) {
14783
- OFFLINE_EVENT_LISTENERS.splice(i, 1);
14784
- }
14785
- }
14786
- }
14787
- // set ready state
14788
- this.readyState = "closed";
14789
- // clear session id
14790
- this.id = null;
14791
- // emit close event
14792
- this.emitReserved("close", reason, description);
14793
- // clean buffers after, so users can still
14794
- // grab the buffers on `close` event
14795
- this.writeBuffer = [];
14796
- this._prevBufferLen = 0;
14797
- }
14798
- }
14799
- }
14800
- SocketWithoutUpgrade.protocol = protocol$1;
14801
- /**
14802
- * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
14803
- * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
14804
- *
14805
- * This class comes with an upgrade mechanism, which means that once the connection is established with the first
14806
- * low-level transport, it will try to upgrade to a better transport.
14807
- *
14808
- * In order to allow tree-shaking, there are no transports included, that's why the `transports` option is mandatory.
14809
- *
14810
- * @example
14811
- * import { SocketWithUpgrade, WebSocket } from "engine.io-client";
14812
- *
14813
- * const socket = new SocketWithUpgrade({
14814
- * transports: [WebSocket]
14815
- * });
14816
- *
14817
- * socket.on("open", () => {
14818
- * socket.send("hello");
14819
- * });
14820
- *
14821
- * @see SocketWithoutUpgrade
14822
- * @see Socket
14823
- */
14824
- class SocketWithUpgrade extends SocketWithoutUpgrade {
14825
- constructor() {
14826
- super(...arguments);
14827
- this._upgrades = [];
14828
- }
14829
- onOpen() {
14830
- super.onOpen();
14831
- if ("open" === this.readyState && this.opts.upgrade) {
14832
- for (let i = 0; i < this._upgrades.length; i++) {
14833
- this._probe(this._upgrades[i]);
14834
- }
14835
- }
14836
- }
14837
- /**
14838
- * Probes a transport.
14839
- *
14840
- * @param {String} name - transport name
14841
- * @private
14842
- */
14843
- _probe(name) {
14844
- let transport = this.createTransport(name);
14845
- let failed = false;
14846
- SocketWithoutUpgrade.priorWebsocketSuccess = false;
14847
- const onTransportOpen = () => {
14848
- if (failed)
14849
- return;
14850
- transport.send([{ type: "ping", data: "probe" }]);
14851
- transport.once("packet", (msg) => {
14852
- if (failed)
14853
- return;
14854
- if ("pong" === msg.type && "probe" === msg.data) {
14855
- this.upgrading = true;
14856
- this.emitReserved("upgrading", transport);
14857
- if (!transport)
14858
- return;
14859
- SocketWithoutUpgrade.priorWebsocketSuccess =
14860
- "websocket" === transport.name;
14861
- this.transport.pause(() => {
14862
- if (failed)
14863
- return;
14864
- if ("closed" === this.readyState)
14865
- return;
14866
- cleanup();
14867
- this.setTransport(transport);
14868
- transport.send([{ type: "upgrade" }]);
14869
- this.emitReserved("upgrade", transport);
14870
- transport = null;
14871
- this.upgrading = false;
14872
- this.flush();
14873
- });
14874
- }
14875
- else {
14876
- const err = new Error("probe error");
14877
- // @ts-ignore
14878
- err.transport = transport.name;
14879
- this.emitReserved("upgradeError", err);
14880
- }
14881
- });
14882
- };
14883
- function freezeTransport() {
14884
- if (failed)
14885
- return;
14886
- // Any callback called by transport should be ignored since now
14887
- failed = true;
14888
- cleanup();
14889
- transport.close();
14890
- transport = null;
14891
- }
14892
- // Handle any error that happens while probing
14893
- const onerror = (err) => {
14894
- const error = new Error("probe error: " + err);
14895
- // @ts-ignore
14896
- error.transport = transport.name;
14897
- freezeTransport();
14898
- this.emitReserved("upgradeError", error);
14899
- };
14900
- function onTransportClose() {
14901
- onerror("transport closed");
14902
- }
14903
- // When the socket is closed while we're probing
14904
- function onclose() {
14905
- onerror("socket closed");
14906
- }
14907
- // When the socket is upgraded while we're probing
14908
- function onupgrade(to) {
14909
- if (transport && to.name !== transport.name) {
14910
- freezeTransport();
14911
- }
14912
- }
14913
- // Remove all listeners on the transport and on self
14914
- const cleanup = () => {
14915
- transport.removeListener("open", onTransportOpen);
14916
- transport.removeListener("error", onerror);
14917
- transport.removeListener("close", onTransportClose);
14918
- this.off("close", onclose);
14919
- this.off("upgrading", onupgrade);
14920
- };
14921
- transport.once("open", onTransportOpen);
14922
- transport.once("error", onerror);
14923
- transport.once("close", onTransportClose);
14924
- this.once("close", onclose);
14925
- this.once("upgrading", onupgrade);
14926
- if (this._upgrades.indexOf("webtransport") !== -1 &&
14927
- name !== "webtransport") {
14928
- // favor WebTransport
14929
- this.setTimeoutFn(() => {
14930
- if (!failed) {
14931
- transport.open();
14932
- }
14933
- }, 200);
14934
- }
14935
- else {
14936
- transport.open();
14937
- }
14938
- }
14939
- onHandshake(data) {
14940
- this._upgrades = this._filterUpgrades(data.upgrades);
14941
- super.onHandshake(data);
14942
- }
14943
- /**
14944
- * Filters upgrades, returning only those matching client transports.
14945
- *
14946
- * @param {Array} upgrades - server upgrades
14947
- * @private
14948
- */
14949
- _filterUpgrades(upgrades) {
14950
- const filteredUpgrades = [];
14951
- for (let i = 0; i < upgrades.length; i++) {
14952
- if (~this.transports.indexOf(upgrades[i]))
14953
- filteredUpgrades.push(upgrades[i]);
14954
- }
14955
- return filteredUpgrades;
14956
- }
14957
- }
14958
- /**
14959
- * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
14960
- * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
14961
- *
14962
- * This class comes with an upgrade mechanism, which means that once the connection is established with the first
14963
- * low-level transport, it will try to upgrade to a better transport.
14964
- *
14965
- * @example
14966
- * import { Socket } from "engine.io-client";
14967
- *
14968
- * const socket = new Socket();
14969
- *
14970
- * socket.on("open", () => {
14971
- * socket.send("hello");
14972
- * });
14973
- *
14974
- * @see SocketWithoutUpgrade
14975
- * @see SocketWithUpgrade
14976
- */
14977
- let Socket$1 = class Socket extends SocketWithUpgrade {
14978
- constructor(uri, opts = {}) {
14979
- const o = typeof uri === "object" ? uri : opts;
14980
- if (!o.transports ||
14981
- (o.transports && typeof o.transports[0] === "string")) {
14982
- o.transports = (o.transports || ["polling", "websocket", "webtransport"])
14983
- .map((transportName) => transports[transportName])
14984
- .filter((t) => !!t);
14985
- }
14986
- super(uri, o);
14987
- }
14988
- };
14989
-
14990
- /**
14991
- * URL parser.
14992
- *
14993
- * @param uri - url
14994
- * @param path - the request path of the connection
14995
- * @param loc - An object meant to mimic window.location.
14996
- * Defaults to window.location.
14997
- * @public
14998
- */
14999
- function url(uri, path = "", loc) {
15000
- let obj = uri;
15001
- // default to window.location
15002
- loc = loc || (typeof location !== "undefined" && location);
15003
- if (null == uri)
15004
- uri = loc.protocol + "//" + loc.host;
15005
- // relative path support
15006
- if (typeof uri === "string") {
15007
- if ("/" === uri.charAt(0)) {
15008
- if ("/" === uri.charAt(1)) {
15009
- uri = loc.protocol + uri;
15010
- }
15011
- else {
15012
- uri = loc.host + uri;
15013
- }
15014
- }
15015
- if (!/^(https?|wss?):\/\//.test(uri)) {
15016
- if ("undefined" !== typeof loc) {
15017
- uri = loc.protocol + "//" + uri;
15018
- }
15019
- else {
15020
- uri = "https://" + uri;
15021
- }
15022
- }
15023
- // parse
15024
- obj = parse(uri);
15025
- }
15026
- // make sure we treat `localhost:80` and `localhost` equally
15027
- if (!obj.port) {
15028
- if (/^(http|ws)$/.test(obj.protocol)) {
15029
- obj.port = "80";
15030
- }
15031
- else if (/^(http|ws)s$/.test(obj.protocol)) {
15032
- obj.port = "443";
15033
- }
15034
- }
15035
- obj.path = obj.path || "/";
15036
- const ipv6 = obj.host.indexOf(":") !== -1;
15037
- const host = ipv6 ? "[" + obj.host + "]" : obj.host;
15038
- // define unique id
15039
- obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
15040
- // define href
15041
- obj.href =
15042
- obj.protocol +
15043
- "://" +
15044
- host +
15045
- (loc && loc.port === obj.port ? "" : ":" + obj.port);
15046
- return obj;
15047
- }
15048
-
15049
- const withNativeArrayBuffer = typeof ArrayBuffer === "function";
15050
- const isView = (obj) => {
15051
- return typeof ArrayBuffer.isView === "function"
15052
- ? ArrayBuffer.isView(obj)
15053
- : obj.buffer instanceof ArrayBuffer;
15054
- };
15055
- const toString = Object.prototype.toString;
15056
- const withNativeBlob = typeof Blob === "function" ||
15057
- (typeof Blob !== "undefined" &&
15058
- toString.call(Blob) === "[object BlobConstructor]");
15059
- const withNativeFile = typeof File === "function" ||
15060
- (typeof File !== "undefined" &&
15061
- toString.call(File) === "[object FileConstructor]");
15062
- /**
15063
- * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.
15064
- *
15065
- * @private
15066
- */
15067
- function isBinary(obj) {
15068
- return ((withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))) ||
15069
- (withNativeBlob && obj instanceof Blob) ||
15070
- (withNativeFile && obj instanceof File));
15071
- }
15072
- function hasBinary(obj, toJSON) {
15073
- if (!obj || typeof obj !== "object") {
15074
- return false;
15075
- }
15076
- if (Array.isArray(obj)) {
15077
- for (let i = 0, l = obj.length; i < l; i++) {
15078
- if (hasBinary(obj[i])) {
15079
- return true;
15080
- }
15081
- }
15082
- return false;
15083
- }
15084
- if (isBinary(obj)) {
15085
- return true;
15086
- }
15087
- if (obj.toJSON &&
15088
- typeof obj.toJSON === "function" &&
15089
- arguments.length === 1) {
15090
- return hasBinary(obj.toJSON(), true);
15091
- }
15092
- for (const key in obj) {
15093
- if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
15094
- return true;
15095
- }
15096
- }
15097
- return false;
15098
- }
15099
-
15100
- /**
15101
- * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.
15102
- *
15103
- * @param {Object} packet - socket.io event packet
15104
- * @return {Object} with deconstructed packet and list of buffers
15105
- * @public
15106
- */
15107
- function deconstructPacket(packet) {
15108
- const buffers = [];
15109
- const packetData = packet.data;
15110
- const pack = packet;
15111
- pack.data = _deconstructPacket(packetData, buffers);
15112
- pack.attachments = buffers.length; // number of binary 'attachments'
15113
- return { packet: pack, buffers: buffers };
15114
- }
15115
- function _deconstructPacket(data, buffers) {
15116
- if (!data)
15117
- return data;
15118
- if (isBinary(data)) {
15119
- const placeholder = { _placeholder: true, num: buffers.length };
15120
- buffers.push(data);
15121
- return placeholder;
15122
- }
15123
- else if (Array.isArray(data)) {
15124
- const newData = new Array(data.length);
15125
- for (let i = 0; i < data.length; i++) {
15126
- newData[i] = _deconstructPacket(data[i], buffers);
15127
- }
15128
- return newData;
15129
- }
15130
- else if (typeof data === "object" && !(data instanceof Date)) {
15131
- const newData = {};
15132
- for (const key in data) {
15133
- if (Object.prototype.hasOwnProperty.call(data, key)) {
15134
- newData[key] = _deconstructPacket(data[key], buffers);
15135
- }
15136
- }
15137
- return newData;
15138
- }
15139
- return data;
15140
- }
15141
- /**
15142
- * Reconstructs a binary packet from its placeholder packet and buffers
15143
- *
15144
- * @param {Object} packet - event packet with placeholders
15145
- * @param {Array} buffers - binary buffers to put in placeholder positions
15146
- * @return {Object} reconstructed packet
15147
- * @public
15148
- */
15149
- function reconstructPacket(packet, buffers) {
15150
- packet.data = _reconstructPacket(packet.data, buffers);
15151
- delete packet.attachments; // no longer useful
15152
- return packet;
15153
- }
15154
- function _reconstructPacket(data, buffers) {
15155
- if (!data)
15156
- return data;
15157
- if (data && data._placeholder === true) {
15158
- const isIndexValid = typeof data.num === "number" &&
15159
- data.num >= 0 &&
15160
- data.num < buffers.length;
15161
- if (isIndexValid) {
15162
- return buffers[data.num]; // appropriate buffer (should be natural order anyway)
15163
- }
15164
- else {
15165
- throw new Error("illegal attachments");
15166
- }
15167
- }
15168
- else if (Array.isArray(data)) {
15169
- for (let i = 0; i < data.length; i++) {
15170
- data[i] = _reconstructPacket(data[i], buffers);
15171
- }
15172
- }
15173
- else if (typeof data === "object") {
15174
- for (const key in data) {
15175
- if (Object.prototype.hasOwnProperty.call(data, key)) {
15176
- data[key] = _reconstructPacket(data[key], buffers);
15177
- }
15178
- }
15179
- }
15180
- return data;
15181
- }
15182
-
15183
- /**
15184
- * These strings must not be used as event names, as they have a special meaning.
15185
- */
15186
- const RESERVED_EVENTS$1 = [
15187
- "connect",
15188
- "connect_error",
15189
- "disconnect",
15190
- "disconnecting",
15191
- "newListener",
15192
- "removeListener", // used by the Node.js EventEmitter
15193
- ];
15194
- /**
15195
- * Protocol version.
15196
- *
15197
- * @public
15198
- */
15199
- const protocol = 5;
15200
- var PacketType;
15201
- (function (PacketType) {
15202
- PacketType[PacketType["CONNECT"] = 0] = "CONNECT";
15203
- PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT";
15204
- PacketType[PacketType["EVENT"] = 2] = "EVENT";
15205
- PacketType[PacketType["ACK"] = 3] = "ACK";
15206
- PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
15207
- PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT";
15208
- PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK";
15209
- })(PacketType || (PacketType = {}));
15210
- /**
15211
- * A socket.io Encoder instance
15212
- */
15213
- class Encoder {
15214
- /**
15215
- * Encoder constructor
15216
- *
15217
- * @param {function} replacer - custom replacer to pass down to JSON.parse
15218
- */
15219
- constructor(replacer) {
15220
- this.replacer = replacer;
15221
- }
15222
- /**
15223
- * Encode a packet as a single string if non-binary, or as a
15224
- * buffer sequence, depending on packet type.
15225
- *
15226
- * @param {Object} obj - packet object
15227
- */
15228
- encode(obj) {
15229
- if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
15230
- if (hasBinary(obj)) {
15231
- return this.encodeAsBinary({
15232
- type: obj.type === PacketType.EVENT
15233
- ? PacketType.BINARY_EVENT
15234
- : PacketType.BINARY_ACK,
15235
- nsp: obj.nsp,
15236
- data: obj.data,
15237
- id: obj.id,
15238
- });
15239
- }
15240
- }
15241
- return [this.encodeAsString(obj)];
15242
- }
15243
- /**
15244
- * Encode packet as string.
15245
- */
15246
- encodeAsString(obj) {
15247
- // first is type
15248
- let str = "" + obj.type;
15249
- // attachments if we have them
15250
- if (obj.type === PacketType.BINARY_EVENT ||
15251
- obj.type === PacketType.BINARY_ACK) {
15252
- str += obj.attachments + "-";
15253
- }
15254
- // if we have a namespace other than `/`
15255
- // we append it followed by a comma `,`
15256
- if (obj.nsp && "/" !== obj.nsp) {
15257
- str += obj.nsp + ",";
15258
- }
15259
- // immediately followed by the id
15260
- if (null != obj.id) {
15261
- str += obj.id;
15262
- }
15263
- // json data
15264
- if (null != obj.data) {
15265
- str += JSON.stringify(obj.data, this.replacer);
15266
- }
15267
- return str;
15268
- }
15269
- /**
15270
- * Encode packet as 'buffer sequence' by removing blobs, and
15271
- * deconstructing packet into object with placeholders and
15272
- * a list of buffers.
15273
- */
15274
- encodeAsBinary(obj) {
15275
- const deconstruction = deconstructPacket(obj);
15276
- const pack = this.encodeAsString(deconstruction.packet);
15277
- const buffers = deconstruction.buffers;
15278
- buffers.unshift(pack); // add packet info to beginning of data list
15279
- return buffers; // write all the buffers
15280
- }
15281
- }
15282
- // see https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript
15283
- function isObject(value) {
15284
- return Object.prototype.toString.call(value) === "[object Object]";
15285
- }
15286
- /**
15287
- * A socket.io Decoder instance
15288
- *
15289
- * @return {Object} decoder
15290
- */
15291
- class Decoder extends Emitter {
15292
- /**
15293
- * Decoder constructor
15294
- *
15295
- * @param {function} reviver - custom reviver to pass down to JSON.stringify
15296
- */
15297
- constructor(reviver) {
15298
- super();
15299
- this.reviver = reviver;
15300
- }
15301
- /**
15302
- * Decodes an encoded packet string into packet JSON.
15303
- *
15304
- * @param {String} obj - encoded packet
15305
- */
15306
- add(obj) {
15307
- let packet;
15308
- if (typeof obj === "string") {
15309
- if (this.reconstructor) {
15310
- throw new Error("got plaintext data when reconstructing a packet");
15311
- }
15312
- packet = this.decodeString(obj);
15313
- const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
15314
- if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
15315
- packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
15316
- // binary packet's json
15317
- this.reconstructor = new BinaryReconstructor(packet);
15318
- // no attachments, labeled binary but no binary data to follow
15319
- if (packet.attachments === 0) {
15320
- super.emitReserved("decoded", packet);
15321
- }
15322
- }
15323
- else {
15324
- // non-binary full packet
15325
- super.emitReserved("decoded", packet);
15326
- }
15327
- }
15328
- else if (isBinary(obj) || obj.base64) {
15329
- // raw binary data
15330
- if (!this.reconstructor) {
15331
- throw new Error("got binary data when not reconstructing a packet");
15332
- }
15333
- else {
15334
- packet = this.reconstructor.takeBinaryData(obj);
15335
- if (packet) {
15336
- // received final buffer
15337
- this.reconstructor = null;
15338
- super.emitReserved("decoded", packet);
15339
- }
15340
- }
15341
- }
15342
- else {
15343
- throw new Error("Unknown type: " + obj);
15344
- }
15345
- }
15346
- /**
15347
- * Decode a packet String (JSON data)
15348
- *
15349
- * @param {String} str
15350
- * @return {Object} packet
15351
- */
15352
- decodeString(str) {
15353
- let i = 0;
15354
- // look up type
15355
- const p = {
15356
- type: Number(str.charAt(0)),
15357
- };
15358
- if (PacketType[p.type] === undefined) {
15359
- throw new Error("unknown packet type " + p.type);
15360
- }
15361
- // look up attachments if type binary
15362
- if (p.type === PacketType.BINARY_EVENT ||
15363
- p.type === PacketType.BINARY_ACK) {
15364
- const start = i + 1;
15365
- while (str.charAt(++i) !== "-" && i != str.length) { }
15366
- const buf = str.substring(start, i);
15367
- if (buf != Number(buf) || str.charAt(i) !== "-") {
15368
- throw new Error("Illegal attachments");
15369
- }
15370
- p.attachments = Number(buf);
15371
- }
15372
- // look up namespace (if any)
15373
- if ("/" === str.charAt(i + 1)) {
15374
- const start = i + 1;
15375
- while (++i) {
15376
- const c = str.charAt(i);
15377
- if ("," === c)
15378
- break;
15379
- if (i === str.length)
15380
- break;
15381
- }
15382
- p.nsp = str.substring(start, i);
15383
- }
15384
- else {
15385
- p.nsp = "/";
15386
- }
15387
- // look up id
15388
- const next = str.charAt(i + 1);
15389
- if ("" !== next && Number(next) == next) {
15390
- const start = i + 1;
15391
- while (++i) {
15392
- const c = str.charAt(i);
15393
- if (null == c || Number(c) != c) {
15394
- --i;
15395
- break;
15396
- }
15397
- if (i === str.length)
15398
- break;
15399
- }
15400
- p.id = Number(str.substring(start, i + 1));
15401
- }
15402
- // look up json data
15403
- if (str.charAt(++i)) {
15404
- const payload = this.tryParse(str.substr(i));
15405
- if (Decoder.isPayloadValid(p.type, payload)) {
15406
- p.data = payload;
15407
- }
15408
- else {
15409
- throw new Error("invalid payload");
15410
- }
15411
- }
15412
- return p;
15413
- }
15414
- tryParse(str) {
15415
- try {
15416
- return JSON.parse(str, this.reviver);
15417
- }
15418
- catch (e) {
15419
- return false;
15420
- }
15421
- }
15422
- static isPayloadValid(type, payload) {
15423
- switch (type) {
15424
- case PacketType.CONNECT:
15425
- return isObject(payload);
15426
- case PacketType.DISCONNECT:
15427
- return payload === undefined;
15428
- case PacketType.CONNECT_ERROR:
15429
- return typeof payload === "string" || isObject(payload);
15430
- case PacketType.EVENT:
15431
- case PacketType.BINARY_EVENT:
15432
- return (Array.isArray(payload) &&
15433
- (typeof payload[0] === "number" ||
15434
- (typeof payload[0] === "string" &&
15435
- RESERVED_EVENTS$1.indexOf(payload[0]) === -1)));
15436
- case PacketType.ACK:
15437
- case PacketType.BINARY_ACK:
15438
- return Array.isArray(payload);
15439
- }
15440
- }
15441
- /**
15442
- * Deallocates a parser's resources
15443
- */
15444
- destroy() {
15445
- if (this.reconstructor) {
15446
- this.reconstructor.finishedReconstruction();
15447
- this.reconstructor = null;
15448
- }
15449
- }
15450
- }
15451
- /**
15452
- * A manager of a binary event's 'buffer sequence'. Should
15453
- * be constructed whenever a packet of type BINARY_EVENT is
15454
- * decoded.
15455
- *
15456
- * @param {Object} packet
15457
- * @return {BinaryReconstructor} initialized reconstructor
15458
- */
15459
- class BinaryReconstructor {
15460
- constructor(packet) {
15461
- this.packet = packet;
15462
- this.buffers = [];
15463
- this.reconPack = packet;
15464
- }
15465
- /**
15466
- * Method to be called when binary data received from connection
15467
- * after a BINARY_EVENT packet.
15468
- *
15469
- * @param {Buffer | ArrayBuffer} binData - the raw binary data received
15470
- * @return {null | Object} returns null if more binary data is expected or
15471
- * a reconstructed packet object if all buffers have been received.
15472
- */
15473
- takeBinaryData(binData) {
15474
- this.buffers.push(binData);
15475
- if (this.buffers.length === this.reconPack.attachments) {
15476
- // done with buffer list
15477
- const packet = reconstructPacket(this.reconPack, this.buffers);
15478
- this.finishedReconstruction();
15479
- return packet;
15480
- }
15481
- return null;
15482
- }
15483
- /**
15484
- * Cleans up binary packet reconstruction variables.
15485
- */
15486
- finishedReconstruction() {
15487
- this.reconPack = null;
15488
- this.buffers = [];
15489
- }
15490
- }
15491
-
15492
- var parser = /*#__PURE__*/Object.freeze({
15493
- __proto__: null,
15494
- Decoder: Decoder,
15495
- Encoder: Encoder,
15496
- get PacketType () { return PacketType; },
15497
- protocol: protocol
15498
- });
15499
-
15500
- function on(obj, ev, fn) {
15501
- obj.on(ev, fn);
15502
- return function subDestroy() {
15503
- obj.off(ev, fn);
15504
- };
15505
- }
15506
-
15507
- /**
15508
- * Internal events.
15509
- * These events can't be emitted by the user.
15510
- */
15511
- const RESERVED_EVENTS = Object.freeze({
15512
- connect: 1,
15513
- connect_error: 1,
15514
- disconnect: 1,
15515
- disconnecting: 1,
15516
- // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
15517
- newListener: 1,
15518
- removeListener: 1,
15519
- });
15520
- /**
15521
- * A Socket is the fundamental class for interacting with the server.
15522
- *
15523
- * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
15524
- *
15525
- * @example
15526
- * const socket = io();
15527
- *
15528
- * socket.on("connect", () => {
15529
- * console.log("connected");
15530
- * });
15531
- *
15532
- * // send an event to the server
15533
- * socket.emit("foo", "bar");
15534
- *
15535
- * socket.on("foobar", () => {
15536
- * // an event was received from the server
15537
- * });
15538
- *
15539
- * // upon disconnection
15540
- * socket.on("disconnect", (reason) => {
15541
- * console.log(`disconnected due to ${reason}`);
15542
- * });
15543
- */
15544
- class Socket extends Emitter {
15545
- /**
15546
- * `Socket` constructor.
15547
- */
15548
- constructor(io, nsp, opts) {
15549
- super();
15550
- /**
15551
- * Whether the socket is currently connected to the server.
15552
- *
15553
- * @example
15554
- * const socket = io();
15555
- *
15556
- * socket.on("connect", () => {
15557
- * console.log(socket.connected); // true
15558
- * });
15559
- *
15560
- * socket.on("disconnect", () => {
15561
- * console.log(socket.connected); // false
15562
- * });
15563
- */
15564
- this.connected = false;
15565
- /**
15566
- * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
15567
- * be transmitted by the server.
15568
- */
15569
- this.recovered = false;
15570
- /**
15571
- * Buffer for packets received before the CONNECT packet
15572
- */
15573
- this.receiveBuffer = [];
15574
- /**
15575
- * Buffer for packets that will be sent once the socket is connected
15576
- */
15577
- this.sendBuffer = [];
15578
- /**
15579
- * The queue of packets to be sent with retry in case of failure.
15580
- *
15581
- * Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
15582
- * @private
15583
- */
15584
- this._queue = [];
15585
- /**
15586
- * A sequence to generate the ID of the {@link QueuedPacket}.
15587
- * @private
15588
- */
15589
- this._queueSeq = 0;
15590
- this.ids = 0;
15591
- /**
15592
- * A map containing acknowledgement handlers.
15593
- *
15594
- * The `withError` attribute is used to differentiate handlers that accept an error as first argument:
15595
- *
15596
- * - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
15597
- * - `socket.timeout(5000).emit("test", (err, value) => { ... })`
15598
- * - `const value = await socket.emitWithAck("test")`
15599
- *
15600
- * From those that don't:
15601
- *
15602
- * - `socket.emit("test", (value) => { ... });`
15603
- *
15604
- * In the first case, the handlers will be called with an error when:
15605
- *
15606
- * - the timeout is reached
15607
- * - the socket gets disconnected
15608
- *
15609
- * In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
15610
- * an acknowledgement from the server.
15611
- *
15612
- * @private
15613
- */
15614
- this.acks = {};
15615
- this.flags = {};
15616
- this.io = io;
15617
- this.nsp = nsp;
15618
- if (opts && opts.auth) {
15619
- this.auth = opts.auth;
15620
- }
15621
- this._opts = Object.assign({}, opts);
15622
- if (this.io._autoConnect)
15623
- this.open();
15624
- }
15625
- /**
15626
- * Whether the socket is currently disconnected
15627
- *
15628
- * @example
15629
- * const socket = io();
15630
- *
15631
- * socket.on("connect", () => {
15632
- * console.log(socket.disconnected); // false
15633
- * });
15634
- *
15635
- * socket.on("disconnect", () => {
15636
- * console.log(socket.disconnected); // true
15637
- * });
15638
- */
15639
- get disconnected() {
15640
- return !this.connected;
15641
- }
15642
- /**
15643
- * Subscribe to open, close and packet events
15644
- *
15645
- * @private
15646
- */
15647
- subEvents() {
15648
- if (this.subs)
15649
- return;
15650
- const io = this.io;
15651
- this.subs = [
15652
- on(io, "open", this.onopen.bind(this)),
15653
- on(io, "packet", this.onpacket.bind(this)),
15654
- on(io, "error", this.onerror.bind(this)),
15655
- on(io, "close", this.onclose.bind(this)),
15656
- ];
15657
- }
15658
- /**
15659
- * Whether the Socket will try to reconnect when its Manager connects or reconnects.
15660
- *
15661
- * @example
15662
- * const socket = io();
15663
- *
15664
- * console.log(socket.active); // true
15665
- *
15666
- * socket.on("disconnect", (reason) => {
15667
- * if (reason === "io server disconnect") {
15668
- * // the disconnection was initiated by the server, you need to manually reconnect
15669
- * console.log(socket.active); // false
15670
- * }
15671
- * // else the socket will automatically try to reconnect
15672
- * console.log(socket.active); // true
15673
- * });
15674
- */
15675
- get active() {
15676
- return !!this.subs;
15677
- }
15678
- /**
15679
- * "Opens" the socket.
15680
- *
15681
- * @example
15682
- * const socket = io({
15683
- * autoConnect: false
15684
- * });
15685
- *
15686
- * socket.connect();
15687
- */
15688
- connect() {
15689
- if (this.connected)
15690
- return this;
15691
- this.subEvents();
15692
- if (!this.io["_reconnecting"])
15693
- this.io.open(); // ensure open
15694
- if ("open" === this.io._readyState)
15695
- this.onopen();
15696
- return this;
15697
- }
15698
- /**
15699
- * Alias for {@link connect()}.
15700
- */
15701
- open() {
15702
- return this.connect();
15703
- }
15704
- /**
15705
- * Sends a `message` event.
15706
- *
15707
- * This method mimics the WebSocket.send() method.
15708
- *
15709
- * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
15710
- *
15711
- * @example
15712
- * socket.send("hello");
15713
- *
15714
- * // this is equivalent to
15715
- * socket.emit("message", "hello");
15716
- *
15717
- * @return self
15718
- */
15719
- send(...args) {
15720
- args.unshift("message");
15721
- this.emit.apply(this, args);
15722
- return this;
15723
- }
15724
- /**
15725
- * Override `emit`.
15726
- * If the event is in `events`, it's emitted normally.
15727
- *
15728
- * @example
15729
- * socket.emit("hello", "world");
15730
- *
15731
- * // all serializable datastructures are supported (no need to call JSON.stringify)
15732
- * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
15733
- *
15734
- * // with an acknowledgement from the server
15735
- * socket.emit("hello", "world", (val) => {
15736
- * // ...
15737
- * });
15738
- *
15739
- * @return self
15740
- */
15741
- emit(ev, ...args) {
15742
- var _a, _b, _c;
15743
- if (RESERVED_EVENTS.hasOwnProperty(ev)) {
15744
- throw new Error('"' + ev.toString() + '" is a reserved event name');
15745
- }
15746
- args.unshift(ev);
15747
- if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
15748
- this._addToQueue(args);
15749
- return this;
15750
- }
15751
- const packet = {
15752
- type: PacketType.EVENT,
15753
- data: args,
15754
- };
15755
- packet.options = {};
15756
- packet.options.compress = this.flags.compress !== false;
15757
- // event ack callback
15758
- if ("function" === typeof args[args.length - 1]) {
15759
- const id = this.ids++;
15760
- const ack = args.pop();
15761
- this._registerAckCallback(id, ack);
15762
- packet.id = id;
15763
- }
15764
- const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
15765
- const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
15766
- const discardPacket = this.flags.volatile && !isTransportWritable;
15767
- if (discardPacket) ;
15768
- else if (isConnected) {
15769
- this.notifyOutgoingListeners(packet);
15770
- this.packet(packet);
15771
- }
15772
- else {
15773
- this.sendBuffer.push(packet);
15774
- }
15775
- this.flags = {};
15776
- return this;
15777
- }
15778
- /**
15779
- * @private
15780
- */
15781
- _registerAckCallback(id, ack) {
15782
- var _a;
15783
- const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
15784
- if (timeout === undefined) {
15785
- this.acks[id] = ack;
15786
- return;
15787
- }
15788
- // @ts-ignore
15789
- const timer = this.io.setTimeoutFn(() => {
15790
- delete this.acks[id];
15791
- for (let i = 0; i < this.sendBuffer.length; i++) {
15792
- if (this.sendBuffer[i].id === id) {
15793
- this.sendBuffer.splice(i, 1);
15794
- }
15795
- }
15796
- ack.call(this, new Error("operation has timed out"));
15797
- }, timeout);
15798
- const fn = (...args) => {
15799
- // @ts-ignore
15800
- this.io.clearTimeoutFn(timer);
15801
- ack.apply(this, args);
15802
- };
15803
- fn.withError = true;
15804
- this.acks[id] = fn;
15805
- }
15806
- /**
15807
- * Emits an event and waits for an acknowledgement
15808
- *
15809
- * @example
15810
- * // without timeout
15811
- * const response = await socket.emitWithAck("hello", "world");
15812
- *
15813
- * // with a specific timeout
15814
- * try {
15815
- * const response = await socket.timeout(1000).emitWithAck("hello", "world");
15816
- * } catch (err) {
15817
- * // the server did not acknowledge the event in the given delay
15818
- * }
15819
- *
15820
- * @return a Promise that will be fulfilled when the server acknowledges the event
15821
- */
15822
- emitWithAck(ev, ...args) {
15823
- return new Promise((resolve, reject) => {
15824
- const fn = (arg1, arg2) => {
15825
- return arg1 ? reject(arg1) : resolve(arg2);
15826
- };
15827
- fn.withError = true;
15828
- args.push(fn);
15829
- this.emit(ev, ...args);
15830
- });
15831
- }
15832
- /**
15833
- * Add the packet to the queue.
15834
- * @param args
15835
- * @private
15836
- */
15837
- _addToQueue(args) {
15838
- let ack;
15839
- if (typeof args[args.length - 1] === "function") {
15840
- ack = args.pop();
15841
- }
15842
- const packet = {
15843
- id: this._queueSeq++,
15844
- tryCount: 0,
15845
- pending: false,
15846
- args,
15847
- flags: Object.assign({ fromQueue: true }, this.flags),
15848
- };
15849
- args.push((err, ...responseArgs) => {
15850
- if (packet !== this._queue[0]) {
15851
- // the packet has already been acknowledged
15852
- return;
15853
- }
15854
- const hasError = err !== null;
15855
- if (hasError) {
15856
- if (packet.tryCount > this._opts.retries) {
15857
- this._queue.shift();
15858
- if (ack) {
15859
- ack(err);
15860
- }
15861
- }
15862
- }
15863
- else {
15864
- this._queue.shift();
15865
- if (ack) {
15866
- ack(null, ...responseArgs);
15867
- }
15868
- }
15869
- packet.pending = false;
15870
- return this._drainQueue();
15871
- });
15872
- this._queue.push(packet);
15873
- this._drainQueue();
15874
- }
15875
- /**
15876
- * Send the first packet of the queue, and wait for an acknowledgement from the server.
15877
- * @param force - whether to resend a packet that has not been acknowledged yet
15878
- *
15879
- * @private
15880
- */
15881
- _drainQueue(force = false) {
15882
- if (!this.connected || this._queue.length === 0) {
15883
- return;
15884
- }
15885
- const packet = this._queue[0];
15886
- if (packet.pending && !force) {
15887
- return;
15888
- }
15889
- packet.pending = true;
15890
- packet.tryCount++;
15891
- this.flags = packet.flags;
15892
- this.emit.apply(this, packet.args);
15893
- }
15894
- /**
15895
- * Sends a packet.
15896
- *
15897
- * @param packet
15898
- * @private
15899
- */
15900
- packet(packet) {
15901
- packet.nsp = this.nsp;
15902
- this.io._packet(packet);
15903
- }
15904
- /**
15905
- * Called upon engine `open`.
15906
- *
15907
- * @private
15908
- */
15909
- onopen() {
15910
- if (typeof this.auth == "function") {
15911
- this.auth((data) => {
15912
- this._sendConnectPacket(data);
15913
- });
15914
- }
15915
- else {
15916
- this._sendConnectPacket(this.auth);
15917
- }
15918
- }
15919
- /**
15920
- * Sends a CONNECT packet to initiate the Socket.IO session.
15921
- *
15922
- * @param data
15923
- * @private
15924
- */
15925
- _sendConnectPacket(data) {
15926
- this.packet({
15927
- type: PacketType.CONNECT,
15928
- data: this._pid
15929
- ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data)
15930
- : data,
15931
- });
15932
- }
15933
- /**
15934
- * Called upon engine or manager `error`.
15935
- *
15936
- * @param err
15937
- * @private
15938
- */
15939
- onerror(err) {
15940
- if (!this.connected) {
15941
- this.emitReserved("connect_error", err);
15942
- }
15943
- }
15944
- /**
15945
- * Called upon engine `close`.
15946
- *
15947
- * @param reason
15948
- * @param description
15949
- * @private
15950
- */
15951
- onclose(reason, description) {
15952
- this.connected = false;
15953
- delete this.id;
15954
- this.emitReserved("disconnect", reason, description);
15955
- this._clearAcks();
15956
- }
15957
- /**
15958
- * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
15959
- * the server.
15960
- *
15961
- * @private
15962
- */
15963
- _clearAcks() {
15964
- Object.keys(this.acks).forEach((id) => {
15965
- const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
15966
- if (!isBuffered) {
15967
- // note: handlers that do not accept an error as first argument are ignored here
15968
- const ack = this.acks[id];
15969
- delete this.acks[id];
15970
- if (ack.withError) {
15971
- ack.call(this, new Error("socket has been disconnected"));
15972
- }
15973
- }
15974
- });
15975
- }
15976
- /**
15977
- * Called with socket packet.
15978
- *
15979
- * @param packet
15980
- * @private
15981
- */
15982
- onpacket(packet) {
15983
- const sameNamespace = packet.nsp === this.nsp;
15984
- if (!sameNamespace)
15985
- return;
15986
- switch (packet.type) {
15987
- case PacketType.CONNECT:
15988
- if (packet.data && packet.data.sid) {
15989
- this.onconnect(packet.data.sid, packet.data.pid);
15990
- }
15991
- else {
15992
- this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
15993
- }
15994
- break;
15995
- case PacketType.EVENT:
15996
- case PacketType.BINARY_EVENT:
15997
- this.onevent(packet);
15998
- break;
15999
- case PacketType.ACK:
16000
- case PacketType.BINARY_ACK:
16001
- this.onack(packet);
16002
- break;
16003
- case PacketType.DISCONNECT:
16004
- this.ondisconnect();
16005
- break;
16006
- case PacketType.CONNECT_ERROR:
16007
- this.destroy();
16008
- const err = new Error(packet.data.message);
16009
- // @ts-ignore
16010
- err.data = packet.data.data;
16011
- this.emitReserved("connect_error", err);
16012
- break;
16013
- }
16014
- }
16015
- /**
16016
- * Called upon a server event.
16017
- *
16018
- * @param packet
16019
- * @private
16020
- */
16021
- onevent(packet) {
16022
- const args = packet.data || [];
16023
- if (null != packet.id) {
16024
- args.push(this.ack(packet.id));
16025
- }
16026
- if (this.connected) {
16027
- this.emitEvent(args);
16028
- }
16029
- else {
16030
- this.receiveBuffer.push(Object.freeze(args));
16031
- }
16032
- }
16033
- emitEvent(args) {
16034
- if (this._anyListeners && this._anyListeners.length) {
16035
- const listeners = this._anyListeners.slice();
16036
- for (const listener of listeners) {
16037
- listener.apply(this, args);
16038
- }
16039
- }
16040
- super.emit.apply(this, args);
16041
- if (this._pid && args.length && typeof args[args.length - 1] === "string") {
16042
- this._lastOffset = args[args.length - 1];
16043
- }
16044
- }
16045
- /**
16046
- * Produces an ack callback to emit with an event.
16047
- *
16048
- * @private
16049
- */
16050
- ack(id) {
16051
- const self = this;
16052
- let sent = false;
16053
- return function (...args) {
16054
- // prevent double callbacks
16055
- if (sent)
16056
- return;
16057
- sent = true;
16058
- self.packet({
16059
- type: PacketType.ACK,
16060
- id: id,
16061
- data: args,
16062
- });
16063
- };
16064
- }
16065
- /**
16066
- * Called upon a server acknowledgement.
16067
- *
16068
- * @param packet
16069
- * @private
16070
- */
16071
- onack(packet) {
16072
- const ack = this.acks[packet.id];
16073
- if (typeof ack !== "function") {
16074
- return;
16075
- }
16076
- delete this.acks[packet.id];
16077
- // @ts-ignore FIXME ack is incorrectly inferred as 'never'
16078
- if (ack.withError) {
16079
- packet.data.unshift(null);
16080
- }
16081
- // @ts-ignore
16082
- ack.apply(this, packet.data);
16083
- }
16084
- /**
16085
- * Called upon server connect.
16086
- *
16087
- * @private
16088
- */
16089
- onconnect(id, pid) {
16090
- this.id = id;
16091
- this.recovered = pid && this._pid === pid;
16092
- this._pid = pid; // defined only if connection state recovery is enabled
16093
- this.connected = true;
16094
- this.emitBuffered();
16095
- this.emitReserved("connect");
16096
- this._drainQueue(true);
16097
- }
16098
- /**
16099
- * Emit buffered events (received and emitted).
16100
- *
16101
- * @private
16102
- */
16103
- emitBuffered() {
16104
- this.receiveBuffer.forEach((args) => this.emitEvent(args));
16105
- this.receiveBuffer = [];
16106
- this.sendBuffer.forEach((packet) => {
16107
- this.notifyOutgoingListeners(packet);
16108
- this.packet(packet);
16109
- });
16110
- this.sendBuffer = [];
16111
- }
16112
- /**
16113
- * Called upon server disconnect.
16114
- *
16115
- * @private
16116
- */
16117
- ondisconnect() {
16118
- this.destroy();
16119
- this.onclose("io server disconnect");
16120
- }
16121
- /**
16122
- * Called upon forced client/server side disconnections,
16123
- * this method ensures the manager stops tracking us and
16124
- * that reconnections don't get triggered for this.
16125
- *
16126
- * @private
16127
- */
16128
- destroy() {
16129
- if (this.subs) {
16130
- // clean subscriptions to avoid reconnections
16131
- this.subs.forEach((subDestroy) => subDestroy());
16132
- this.subs = undefined;
16133
- }
16134
- this.io["_destroy"](this);
16135
- }
16136
- /**
16137
- * Disconnects the socket manually. In that case, the socket will not try to reconnect.
16138
- *
16139
- * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
16140
- *
16141
- * @example
16142
- * const socket = io();
16143
- *
16144
- * socket.on("disconnect", (reason) => {
16145
- * // console.log(reason); prints "io client disconnect"
16146
- * });
16147
- *
16148
- * socket.disconnect();
16149
- *
16150
- * @return self
16151
- */
16152
- disconnect() {
16153
- if (this.connected) {
16154
- this.packet({ type: PacketType.DISCONNECT });
16155
- }
16156
- // remove socket from pool
16157
- this.destroy();
16158
- if (this.connected) {
16159
- // fire events
16160
- this.onclose("io client disconnect");
16161
- }
16162
- return this;
16163
- }
16164
- /**
16165
- * Alias for {@link disconnect()}.
16166
- *
16167
- * @return self
16168
- */
16169
- close() {
16170
- return this.disconnect();
16171
- }
16172
- /**
16173
- * Sets the compress flag.
16174
- *
16175
- * @example
16176
- * socket.compress(false).emit("hello");
16177
- *
16178
- * @param compress - if `true`, compresses the sending data
16179
- * @return self
16180
- */
16181
- compress(compress) {
16182
- this.flags.compress = compress;
16183
- return this;
16184
- }
16185
- /**
16186
- * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
16187
- * ready to send messages.
16188
- *
16189
- * @example
16190
- * socket.volatile.emit("hello"); // the server may or may not receive it
16191
- *
16192
- * @returns self
16193
- */
16194
- get volatile() {
16195
- this.flags.volatile = true;
16196
- return this;
16197
- }
16198
- /**
16199
- * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
16200
- * given number of milliseconds have elapsed without an acknowledgement from the server:
16201
- *
16202
- * @example
16203
- * socket.timeout(5000).emit("my-event", (err) => {
16204
- * if (err) {
16205
- * // the server did not acknowledge the event in the given delay
16206
- * }
16207
- * });
16208
- *
16209
- * @returns self
16210
- */
16211
- timeout(timeout) {
16212
- this.flags.timeout = timeout;
16213
- return this;
16214
- }
16215
- /**
16216
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
16217
- * callback.
16218
- *
16219
- * @example
16220
- * socket.onAny((event, ...args) => {
16221
- * console.log(`got ${event}`);
16222
- * });
16223
- *
16224
- * @param listener
16225
- */
16226
- onAny(listener) {
16227
- this._anyListeners = this._anyListeners || [];
16228
- this._anyListeners.push(listener);
16229
- return this;
16230
- }
16231
- /**
16232
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
16233
- * callback. The listener is added to the beginning of the listeners array.
16234
- *
16235
- * @example
16236
- * socket.prependAny((event, ...args) => {
16237
- * console.log(`got event ${event}`);
16238
- * });
16239
- *
16240
- * @param listener
16241
- */
16242
- prependAny(listener) {
16243
- this._anyListeners = this._anyListeners || [];
16244
- this._anyListeners.unshift(listener);
16245
- return this;
16246
- }
16247
- /**
16248
- * Removes the listener that will be fired when any event is emitted.
16249
- *
16250
- * @example
16251
- * const catchAllListener = (event, ...args) => {
16252
- * console.log(`got event ${event}`);
16253
- * }
16254
- *
16255
- * socket.onAny(catchAllListener);
16256
- *
16257
- * // remove a specific listener
16258
- * socket.offAny(catchAllListener);
16259
- *
16260
- * // or remove all listeners
16261
- * socket.offAny();
16262
- *
16263
- * @param listener
16264
- */
16265
- offAny(listener) {
16266
- if (!this._anyListeners) {
16267
- return this;
16268
- }
16269
- if (listener) {
16270
- const listeners = this._anyListeners;
16271
- for (let i = 0; i < listeners.length; i++) {
16272
- if (listener === listeners[i]) {
16273
- listeners.splice(i, 1);
16274
- return this;
16275
- }
16276
- }
16277
- }
16278
- else {
16279
- this._anyListeners = [];
16280
- }
16281
- return this;
16282
- }
16283
- /**
16284
- * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
16285
- * e.g. to remove listeners.
16286
- */
16287
- listenersAny() {
16288
- return this._anyListeners || [];
16289
- }
16290
- /**
16291
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
16292
- * callback.
16293
- *
16294
- * Note: acknowledgements sent to the server are not included.
16295
- *
16296
- * @example
16297
- * socket.onAnyOutgoing((event, ...args) => {
16298
- * console.log(`sent event ${event}`);
16299
- * });
16300
- *
16301
- * @param listener
16302
- */
16303
- onAnyOutgoing(listener) {
16304
- this._anyOutgoingListeners = this._anyOutgoingListeners || [];
16305
- this._anyOutgoingListeners.push(listener);
16306
- return this;
16307
- }
16308
- /**
16309
- * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
16310
- * callback. The listener is added to the beginning of the listeners array.
16311
- *
16312
- * Note: acknowledgements sent to the server are not included.
16313
- *
16314
- * @example
16315
- * socket.prependAnyOutgoing((event, ...args) => {
16316
- * console.log(`sent event ${event}`);
16317
- * });
16318
- *
16319
- * @param listener
16320
- */
16321
- prependAnyOutgoing(listener) {
16322
- this._anyOutgoingListeners = this._anyOutgoingListeners || [];
16323
- this._anyOutgoingListeners.unshift(listener);
16324
- return this;
16325
- }
16326
- /**
16327
- * Removes the listener that will be fired when any event is emitted.
16328
- *
16329
- * @example
16330
- * const catchAllListener = (event, ...args) => {
16331
- * console.log(`sent event ${event}`);
16332
- * }
16333
- *
16334
- * socket.onAnyOutgoing(catchAllListener);
16335
- *
16336
- * // remove a specific listener
16337
- * socket.offAnyOutgoing(catchAllListener);
16338
- *
16339
- * // or remove all listeners
16340
- * socket.offAnyOutgoing();
16341
- *
16342
- * @param [listener] - the catch-all listener (optional)
16343
- */
16344
- offAnyOutgoing(listener) {
16345
- if (!this._anyOutgoingListeners) {
16346
- return this;
16347
- }
16348
- if (listener) {
16349
- const listeners = this._anyOutgoingListeners;
16350
- for (let i = 0; i < listeners.length; i++) {
16351
- if (listener === listeners[i]) {
16352
- listeners.splice(i, 1);
16353
- return this;
16354
- }
16355
- }
16356
- }
16357
- else {
16358
- this._anyOutgoingListeners = [];
16359
- }
16360
- return this;
16361
- }
16362
- /**
16363
- * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
16364
- * e.g. to remove listeners.
16365
- */
16366
- listenersAnyOutgoing() {
16367
- return this._anyOutgoingListeners || [];
16368
- }
16369
- /**
16370
- * Notify the listeners for each packet sent
16371
- *
16372
- * @param packet
16373
- *
16374
- * @private
16375
- */
16376
- notifyOutgoingListeners(packet) {
16377
- if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
16378
- const listeners = this._anyOutgoingListeners.slice();
16379
- for (const listener of listeners) {
16380
- listener.apply(this, packet.data);
16381
- }
16382
- }
16383
- }
16384
- }
16385
-
16386
- /**
16387
- * Initialize backoff timer with `opts`.
16388
- *
16389
- * - `min` initial timeout in milliseconds [100]
16390
- * - `max` max timeout [10000]
16391
- * - `jitter` [0]
16392
- * - `factor` [2]
16393
- *
16394
- * @param {Object} opts
16395
- * @api public
16396
- */
16397
- function Backoff(opts) {
16398
- opts = opts || {};
16399
- this.ms = opts.min || 100;
16400
- this.max = opts.max || 10000;
16401
- this.factor = opts.factor || 2;
16402
- this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
16403
- this.attempts = 0;
16404
- }
16405
- /**
16406
- * Return the backoff duration.
16407
- *
16408
- * @return {Number}
16409
- * @api public
16410
- */
16411
- Backoff.prototype.duration = function () {
16412
- var ms = this.ms * Math.pow(this.factor, this.attempts++);
16413
- if (this.jitter) {
16414
- var rand = Math.random();
16415
- var deviation = Math.floor(rand * this.jitter * ms);
16416
- ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
16417
- }
16418
- return Math.min(ms, this.max) | 0;
16419
- };
16420
- /**
16421
- * Reset the number of attempts.
16422
- *
16423
- * @api public
16424
- */
16425
- Backoff.prototype.reset = function () {
16426
- this.attempts = 0;
16427
- };
16428
- /**
16429
- * Set the minimum duration
16430
- *
16431
- * @api public
16432
- */
16433
- Backoff.prototype.setMin = function (min) {
16434
- this.ms = min;
16435
- };
16436
- /**
16437
- * Set the maximum duration
16438
- *
16439
- * @api public
16440
- */
16441
- Backoff.prototype.setMax = function (max) {
16442
- this.max = max;
16443
- };
16444
- /**
16445
- * Set the jitter
16446
- *
16447
- * @api public
16448
- */
16449
- Backoff.prototype.setJitter = function (jitter) {
16450
- this.jitter = jitter;
16451
- };
16452
-
16453
- class Manager extends Emitter {
16454
- constructor(uri, opts) {
16455
- var _a;
16456
- super();
16457
- this.nsps = {};
16458
- this.subs = [];
16459
- if (uri && "object" === typeof uri) {
16460
- opts = uri;
16461
- uri = undefined;
16462
- }
16463
- opts = opts || {};
16464
- opts.path = opts.path || "/socket.io";
16465
- this.opts = opts;
16466
- installTimerFunctions(this, opts);
16467
- this.reconnection(opts.reconnection !== false);
16468
- this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
16469
- this.reconnectionDelay(opts.reconnectionDelay || 1000);
16470
- this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
16471
- this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
16472
- this.backoff = new Backoff({
16473
- min: this.reconnectionDelay(),
16474
- max: this.reconnectionDelayMax(),
16475
- jitter: this.randomizationFactor(),
16476
- });
16477
- this.timeout(null == opts.timeout ? 20000 : opts.timeout);
16478
- this._readyState = "closed";
16479
- this.uri = uri;
16480
- const _parser = opts.parser || parser;
16481
- this.encoder = new _parser.Encoder();
16482
- this.decoder = new _parser.Decoder();
16483
- this._autoConnect = opts.autoConnect !== false;
16484
- if (this._autoConnect)
16485
- this.open();
16486
- }
16487
- reconnection(v) {
16488
- if (!arguments.length)
16489
- return this._reconnection;
16490
- this._reconnection = !!v;
16491
- if (!v) {
16492
- this.skipReconnect = true;
16493
- }
16494
- return this;
16495
- }
16496
- reconnectionAttempts(v) {
16497
- if (v === undefined)
16498
- return this._reconnectionAttempts;
16499
- this._reconnectionAttempts = v;
16500
- return this;
16501
- }
16502
- reconnectionDelay(v) {
16503
- var _a;
16504
- if (v === undefined)
16505
- return this._reconnectionDelay;
16506
- this._reconnectionDelay = v;
16507
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
16508
- return this;
16509
- }
16510
- randomizationFactor(v) {
16511
- var _a;
16512
- if (v === undefined)
16513
- return this._randomizationFactor;
16514
- this._randomizationFactor = v;
16515
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
16516
- return this;
16517
- }
16518
- reconnectionDelayMax(v) {
16519
- var _a;
16520
- if (v === undefined)
16521
- return this._reconnectionDelayMax;
16522
- this._reconnectionDelayMax = v;
16523
- (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
16524
- return this;
16525
- }
16526
- timeout(v) {
16527
- if (!arguments.length)
16528
- return this._timeout;
16529
- this._timeout = v;
16530
- return this;
16531
- }
16532
- /**
16533
- * Starts trying to reconnect if reconnection is enabled and we have not
16534
- * started reconnecting yet
16535
- *
16536
- * @private
16537
- */
16538
- maybeReconnectOnOpen() {
16539
- // Only try to reconnect if it's the first time we're connecting
16540
- if (!this._reconnecting &&
16541
- this._reconnection &&
16542
- this.backoff.attempts === 0) {
16543
- // keeps reconnection from firing twice for the same reconnection loop
16544
- this.reconnect();
16545
- }
16546
- }
16547
- /**
16548
- * Sets the current transport `socket`.
16549
- *
16550
- * @param {Function} fn - optional, callback
16551
- * @return self
16552
- * @public
16553
- */
16554
- open(fn) {
16555
- if (~this._readyState.indexOf("open"))
16556
- return this;
16557
- this.engine = new Socket$1(this.uri, this.opts);
16558
- const socket = this.engine;
16559
- const self = this;
16560
- this._readyState = "opening";
16561
- this.skipReconnect = false;
16562
- // emit `open`
16563
- const openSubDestroy = on(socket, "open", function () {
16564
- self.onopen();
16565
- fn && fn();
16566
- });
16567
- const onError = (err) => {
16568
- this.cleanup();
16569
- this._readyState = "closed";
16570
- this.emitReserved("error", err);
16571
- if (fn) {
16572
- fn(err);
16573
- }
16574
- else {
16575
- // Only do this if there is no fn to handle the error
16576
- this.maybeReconnectOnOpen();
16577
- }
16578
- };
16579
- // emit `error`
16580
- const errorSub = on(socket, "error", onError);
16581
- if (false !== this._timeout) {
16582
- const timeout = this._timeout;
16583
- // set timer
16584
- const timer = this.setTimeoutFn(() => {
16585
- openSubDestroy();
16586
- onError(new Error("timeout"));
16587
- socket.close();
16588
- }, timeout);
16589
- if (this.opts.autoUnref) {
16590
- timer.unref();
16591
- }
16592
- this.subs.push(() => {
16593
- this.clearTimeoutFn(timer);
16594
- });
16595
- }
16596
- this.subs.push(openSubDestroy);
16597
- this.subs.push(errorSub);
16598
- return this;
16599
- }
16600
- /**
16601
- * Alias for open()
16602
- *
16603
- * @return self
16604
- * @public
16605
- */
16606
- connect(fn) {
16607
- return this.open(fn);
16608
- }
16609
- /**
16610
- * Called upon transport open.
16611
- *
16612
- * @private
16613
- */
16614
- onopen() {
16615
- // clear old subs
16616
- this.cleanup();
16617
- // mark as open
16618
- this._readyState = "open";
16619
- this.emitReserved("open");
16620
- // add new subs
16621
- const socket = this.engine;
16622
- this.subs.push(on(socket, "ping", this.onping.bind(this)), on(socket, "data", this.ondata.bind(this)), on(socket, "error", this.onerror.bind(this)), on(socket, "close", this.onclose.bind(this)),
16623
- // @ts-ignore
16624
- on(this.decoder, "decoded", this.ondecoded.bind(this)));
16625
- }
16626
- /**
16627
- * Called upon a ping.
16628
- *
16629
- * @private
16630
- */
16631
- onping() {
16632
- this.emitReserved("ping");
16633
- }
16634
- /**
16635
- * Called with data.
16636
- *
16637
- * @private
16638
- */
16639
- ondata(data) {
16640
- try {
16641
- this.decoder.add(data);
16642
- }
16643
- catch (e) {
16644
- this.onclose("parse error", e);
16645
- }
16646
- }
16647
- /**
16648
- * Called when parser fully decodes a packet.
16649
- *
16650
- * @private
16651
- */
16652
- ondecoded(packet) {
16653
- // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
16654
- nextTick(() => {
16655
- this.emitReserved("packet", packet);
16656
- }, this.setTimeoutFn);
16657
- }
16658
- /**
16659
- * Called upon socket error.
16660
- *
16661
- * @private
16662
- */
16663
- onerror(err) {
16664
- this.emitReserved("error", err);
16665
- }
16666
- /**
16667
- * Creates a new socket for the given `nsp`.
16668
- *
16669
- * @return {Socket}
16670
- * @public
16671
- */
16672
- socket(nsp, opts) {
16673
- let socket = this.nsps[nsp];
16674
- if (!socket) {
16675
- socket = new Socket(this, nsp, opts);
16676
- this.nsps[nsp] = socket;
16677
- }
16678
- else if (this._autoConnect && !socket.active) {
16679
- socket.connect();
16680
- }
16681
- return socket;
16682
- }
16683
- /**
16684
- * Called upon a socket close.
16685
- *
16686
- * @param socket
16687
- * @private
16688
- */
16689
- _destroy(socket) {
16690
- const nsps = Object.keys(this.nsps);
16691
- for (const nsp of nsps) {
16692
- const socket = this.nsps[nsp];
16693
- if (socket.active) {
16694
- return;
16695
- }
16696
- }
16697
- this._close();
16698
- }
16699
- /**
16700
- * Writes a packet.
16701
- *
16702
- * @param packet
16703
- * @private
16704
- */
16705
- _packet(packet) {
16706
- const encodedPackets = this.encoder.encode(packet);
16707
- for (let i = 0; i < encodedPackets.length; i++) {
16708
- this.engine.write(encodedPackets[i], packet.options);
16709
- }
16710
- }
16711
- /**
16712
- * Clean up transport subscriptions and packet buffer.
16713
- *
16714
- * @private
16715
- */
16716
- cleanup() {
16717
- this.subs.forEach((subDestroy) => subDestroy());
16718
- this.subs.length = 0;
16719
- this.decoder.destroy();
16720
- }
16721
- /**
16722
- * Close the current socket.
16723
- *
16724
- * @private
16725
- */
16726
- _close() {
16727
- this.skipReconnect = true;
16728
- this._reconnecting = false;
16729
- this.onclose("forced close");
16730
- }
16731
- /**
16732
- * Alias for close()
16733
- *
16734
- * @private
16735
- */
16736
- disconnect() {
16737
- return this._close();
16738
- }
16739
- /**
16740
- * Called when:
16741
- *
16742
- * - the low-level engine is closed
16743
- * - the parser encountered a badly formatted packet
16744
- * - all sockets are disconnected
16745
- *
16746
- * @private
16747
- */
16748
- onclose(reason, description) {
16749
- var _a;
16750
- this.cleanup();
16751
- (_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
16752
- this.backoff.reset();
16753
- this._readyState = "closed";
16754
- this.emitReserved("close", reason, description);
16755
- if (this._reconnection && !this.skipReconnect) {
16756
- this.reconnect();
16757
- }
16758
- }
16759
- /**
16760
- * Attempt a reconnection.
16761
- *
16762
- * @private
16763
- */
16764
- reconnect() {
16765
- if (this._reconnecting || this.skipReconnect)
16766
- return this;
16767
- const self = this;
16768
- if (this.backoff.attempts >= this._reconnectionAttempts) {
16769
- this.backoff.reset();
16770
- this.emitReserved("reconnect_failed");
16771
- this._reconnecting = false;
16772
- }
16773
- else {
16774
- const delay = this.backoff.duration();
16775
- this._reconnecting = true;
16776
- const timer = this.setTimeoutFn(() => {
16777
- if (self.skipReconnect)
16778
- return;
16779
- this.emitReserved("reconnect_attempt", self.backoff.attempts);
16780
- // check again for the case socket closed in above events
16781
- if (self.skipReconnect)
16782
- return;
16783
- self.open((err) => {
16784
- if (err) {
16785
- self._reconnecting = false;
16786
- self.reconnect();
16787
- this.emitReserved("reconnect_error", err);
16788
- }
16789
- else {
16790
- self.onreconnect();
16791
- }
16792
- });
16793
- }, delay);
16794
- if (this.opts.autoUnref) {
16795
- timer.unref();
16796
- }
16797
- this.subs.push(() => {
16798
- this.clearTimeoutFn(timer);
16799
- });
16800
- }
16801
- }
16802
- /**
16803
- * Called upon successful reconnect.
16804
- *
16805
- * @private
16806
- */
16807
- onreconnect() {
16808
- const attempt = this.backoff.attempts;
16809
- this._reconnecting = false;
16810
- this.backoff.reset();
16811
- this.emitReserved("reconnect", attempt);
16812
- }
16813
- }
16814
-
16815
- /**
16816
- * Managers cache.
16817
- */
16818
- const cache = {};
16819
- function lookup(uri, opts) {
16820
- if (typeof uri === "object") {
16821
- opts = uri;
16822
- uri = undefined;
16823
- }
16824
- opts = opts || {};
16825
- const parsed = url(uri, opts.path || "/socket.io");
16826
- const source = parsed.source;
16827
- const id = parsed.id;
16828
- const path = parsed.path;
16829
- const sameNamespace = cache[id] && path in cache[id]["nsps"];
16830
- const newConnection = opts.forceNew ||
16831
- opts["force new connection"] ||
16832
- false === opts.multiplex ||
16833
- sameNamespace;
16834
- let io;
16835
- if (newConnection) {
16836
- io = new Manager(source, opts);
16837
- }
16838
- else {
16839
- if (!cache[id]) {
16840
- cache[id] = new Manager(source, opts);
16841
- }
16842
- io = cache[id];
16843
- }
16844
- if (parsed.query && !opts.query) {
16845
- opts.query = parsed.queryKey;
16846
- }
16847
- return io.socket(parsed.path, opts);
16848
- }
16849
- // so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
16850
- // namespace (e.g. `io.connect(...)`), for backward compatibility
16851
- Object.assign(lookup, {
16852
- Manager,
16853
- Socket,
16854
- io: lookup,
16855
- connect: lookup,
16856
- });
16857
-
16858
- var index = /*#__PURE__*/Object.freeze({
16859
- __proto__: null,
16860
- Manager: Manager,
16861
- NodeWebSocket: WS,
16862
- NodeXHR: XHR,
16863
- Socket: Socket,
16864
- WebSocket: WS,
16865
- WebTransport: WT,
16866
- XHR: XHR,
16867
- connect: lookup,
16868
- default: lookup,
16869
- io: lookup,
16870
- protocol: protocol
16871
- });
16872
-
16873
12739
  exports.Zaplier = Zaplier;
16874
12740
  exports.ZaplierSDK = ZaplierSDK;
16875
12741
  exports.analyzeUserAgent = analyzeUserAgent;