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