first commit
This commit is contained in:
commit
e7033775d8
20657 files changed
+1988940
No files matched your search
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014-present Guillermo Rauch and Socket.IO contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
|
||||
# socket.io-client
|
||||
|
||||
[](https://github.com/socketio/socket.io-client/actions)
|
||||
[](https://www.npmjs.com/package/socket.io-client)
|
||||

|
||||
[](http://slack.socket.io)
|
||||
|
||||
[](https://saucelabs.com/u/socket)
|
||||
|
||||
## Documentation
|
||||
|
||||
Please see the documentation [here](https://socket.io/docs/v4/client-initialization/).
|
||||
|
||||
The source code of the website can be found [here](https://github.com/socketio/socket.io-website). Contributions are welcome!
|
||||
|
||||
## Debug / logging
|
||||
|
||||
In order to see all the client debug output, run the following command on the browser console – including the desired scope – and reload your app page:
|
||||
|
||||
```
|
||||
localStorage.debug = '*';
|
||||
```
|
||||
|
||||
And then, filter by the scopes you're interested in. See also: https://socket.io/docs/v4/logging-and-debugging/
|
||||
|
||||
## License
|
||||
|
||||
[MIT](/LICENSE)
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { io } from "./index.js";
|
||||
export default io;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const index_js_1 = require("./index.js");
|
||||
exports.default = index_js_1.io;
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Initialize backoff timer with `opts`.
|
||||
*
|
||||
* - `min` initial timeout in milliseconds [100]
|
||||
* - `max` max timeout [10000]
|
||||
* - `jitter` [0]
|
||||
* - `factor` [2]
|
||||
*
|
||||
* @param {Object} opts
|
||||
* @api public
|
||||
*/
|
||||
export declare function Backoff(opts: any): void;
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
"use strict";
|
||||
/**
|
||||
* Initialize backoff timer with `opts`.
|
||||
*
|
||||
* - `min` initial timeout in milliseconds [100]
|
||||
* - `max` max timeout [10000]
|
||||
* - `jitter` [0]
|
||||
* - `factor` [2]
|
||||
*
|
||||
* @param {Object} opts
|
||||
* @api public
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Backoff = Backoff;
|
||||
function Backoff(opts) {
|
||||
opts = opts || {};
|
||||
this.ms = opts.min || 100;
|
||||
this.max = opts.max || 10000;
|
||||
this.factor = opts.factor || 2;
|
||||
this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
|
||||
this.attempts = 0;
|
||||
}
|
||||
/**
|
||||
* Return the backoff duration.
|
||||
*
|
||||
* @return {Number}
|
||||
* @api public
|
||||
*/
|
||||
Backoff.prototype.duration = function () {
|
||||
var ms = this.ms * Math.pow(this.factor, this.attempts++);
|
||||
if (this.jitter) {
|
||||
var rand = Math.random();
|
||||
var deviation = Math.floor(rand * this.jitter * ms);
|
||||
ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
|
||||
}
|
||||
return Math.min(ms, this.max) | 0;
|
||||
};
|
||||
/**
|
||||
* Reset the number of attempts.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
Backoff.prototype.reset = function () {
|
||||
this.attempts = 0;
|
||||
};
|
||||
/**
|
||||
* Set the minimum duration
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
Backoff.prototype.setMin = function (min) {
|
||||
this.ms = min;
|
||||
};
|
||||
/**
|
||||
* Set the maximum duration
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
Backoff.prototype.setMax = function (max) {
|
||||
this.max = max;
|
||||
};
|
||||
/**
|
||||
* Set the jitter
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
Backoff.prototype.setJitter = function (jitter) {
|
||||
this.jitter = jitter;
|
||||
};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
import { Manager, ManagerOptions } from "./manager.js";
|
||||
import { DisconnectDescription, Socket, SocketOptions } from "./socket.js";
|
||||
/**
|
||||
* Looks up an existing `Manager` for multiplexing.
|
||||
* If the user summons:
|
||||
*
|
||||
* `io('http://localhost/a');`
|
||||
* `io('http://localhost/b');`
|
||||
*
|
||||
* We reuse the existing instance based on same scheme/port/host,
|
||||
* and we initialize sockets for each namespace.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
declare function lookup(opts?: Partial<ManagerOptions & SocketOptions>): Socket;
|
||||
declare function lookup(uri?: string, opts?: Partial<ManagerOptions & SocketOptions>): Socket;
|
||||
/**
|
||||
* Protocol version.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export { protocol } from "socket.io-parser";
|
||||
/**
|
||||
* Expose constructors for standalone build.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export { DisconnectDescription, Manager, ManagerOptions, Socket, SocketOptions, lookup as io, lookup as connect, lookup as default, };
|
||||
export { Fetch, NodeXHR, XHR, NodeWebSocket, WebSocket, WebTransport, } from "engine.io-client";
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.WebTransport = exports.WebSocket = exports.NodeWebSocket = exports.XHR = exports.NodeXHR = exports.Fetch = exports.Socket = exports.Manager = exports.protocol = void 0;
|
||||
exports.io = lookup;
|
||||
exports.connect = lookup;
|
||||
exports.default = lookup;
|
||||
const url_js_1 = require("./url.js");
|
||||
const manager_js_1 = require("./manager.js");
|
||||
Object.defineProperty(exports, "Manager", { enumerable: true, get: function () { return manager_js_1.Manager; } });
|
||||
const socket_js_1 = require("./socket.js");
|
||||
Object.defineProperty(exports, "Socket", { enumerable: true, get: function () { return socket_js_1.Socket; } });
|
||||
const debug_1 = __importDefault(require("debug")); // debug()
|
||||
const debug = (0, debug_1.default)("socket.io-client"); // debug()
|
||||
/**
|
||||
* Managers cache.
|
||||
*/
|
||||
const cache = {};
|
||||
function lookup(uri, opts) {
|
||||
if (typeof uri === "object") {
|
||||
opts = uri;
|
||||
uri = undefined;
|
||||
}
|
||||
opts = opts || {};
|
||||
const parsed = (0, url_js_1.url)(uri, opts.path || "/socket.io");
|
||||
const source = parsed.source;
|
||||
const id = parsed.id;
|
||||
const path = parsed.path;
|
||||
const sameNamespace = cache[id] && path in cache[id]["nsps"];
|
||||
const newConnection = opts.forceNew ||
|
||||
opts["force new connection"] ||
|
||||
false === opts.multiplex ||
|
||||
sameNamespace;
|
||||
let io;
|
||||
if (newConnection) {
|
||||
debug("ignoring socket cache for %s", source);
|
||||
io = new manager_js_1.Manager(source, opts);
|
||||
}
|
||||
else {
|
||||
if (!cache[id]) {
|
||||
debug("new io instance for %s", source);
|
||||
cache[id] = new manager_js_1.Manager(source, opts);
|
||||
}
|
||||
io = cache[id];
|
||||
}
|
||||
if (parsed.query && !opts.query) {
|
||||
opts.query = parsed.queryKey;
|
||||
}
|
||||
return io.socket(parsed.path, opts);
|
||||
}
|
||||
// so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
|
||||
// namespace (e.g. `io.connect(...)`), for backward compatibility
|
||||
Object.assign(lookup, {
|
||||
Manager: manager_js_1.Manager,
|
||||
Socket: socket_js_1.Socket,
|
||||
io: lookup,
|
||||
connect: lookup,
|
||||
});
|
||||
/**
|
||||
* Protocol version.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
var socket_io_parser_1 = require("socket.io-parser");
|
||||
Object.defineProperty(exports, "protocol", { enumerable: true, get: function () { return socket_io_parser_1.protocol; } });
|
||||
var engine_io_client_1 = require("engine.io-client");
|
||||
Object.defineProperty(exports, "Fetch", { enumerable: true, get: function () { return engine_io_client_1.Fetch; } });
|
||||
Object.defineProperty(exports, "NodeXHR", { enumerable: true, get: function () { return engine_io_client_1.NodeXHR; } });
|
||||
Object.defineProperty(exports, "XHR", { enumerable: true, get: function () { return engine_io_client_1.XHR; } });
|
||||
Object.defineProperty(exports, "NodeWebSocket", { enumerable: true, get: function () { return engine_io_client_1.NodeWebSocket; } });
|
||||
Object.defineProperty(exports, "WebSocket", { enumerable: true, get: function () { return engine_io_client_1.WebSocket; } });
|
||||
Object.defineProperty(exports, "WebTransport", { enumerable: true, get: function () { return engine_io_client_1.WebTransport; } });
|
||||
|
||||
module.exports = lookup;
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
import { Socket as Engine, SocketOptions as EngineOptions } from "engine.io-client";
|
||||
import { Socket, SocketOptions, DisconnectDescription } from "./socket.js";
|
||||
import { Packet } from "socket.io-parser";
|
||||
import { DefaultEventsMap, EventsMap, Emitter } from "@socket.io/component-emitter";
|
||||
export interface ManagerOptions extends EngineOptions {
|
||||
/**
|
||||
* Should we force a new Manager for this connection?
|
||||
* @default false
|
||||
*/
|
||||
forceNew: boolean;
|
||||
/**
|
||||
* Should we multiplex our connection (reuse existing Manager) ?
|
||||
* @default true
|
||||
*/
|
||||
multiplex: boolean;
|
||||
/**
|
||||
* The path to get our client file from, in the case of the server
|
||||
* serving it
|
||||
* @default '/socket.io'
|
||||
*/
|
||||
path: string;
|
||||
/**
|
||||
* Should we allow reconnections?
|
||||
* @default true
|
||||
*/
|
||||
reconnection: boolean;
|
||||
/**
|
||||
* How many reconnection attempts should we try?
|
||||
* @default Infinity
|
||||
*/
|
||||
reconnectionAttempts: number;
|
||||
/**
|
||||
* The time delay in milliseconds between reconnection attempts
|
||||
* @default 1000
|
||||
*/
|
||||
reconnectionDelay: number;
|
||||
/**
|
||||
* The max time delay in milliseconds between reconnection attempts
|
||||
* @default 5000
|
||||
*/
|
||||
reconnectionDelayMax: number;
|
||||
/**
|
||||
* Used in the exponential backoff jitter when reconnecting
|
||||
* @default 0.5
|
||||
*/
|
||||
randomizationFactor: number;
|
||||
/**
|
||||
* The timeout in milliseconds for our connection attempt
|
||||
* @default 20000
|
||||
*/
|
||||
timeout: number;
|
||||
/**
|
||||
* Should we automatically connect?
|
||||
* @default true
|
||||
*/
|
||||
autoConnect: boolean;
|
||||
/**
|
||||
* the parser to use. Defaults to an instance of the Parser that ships with socket.io.
|
||||
*/
|
||||
parser: any;
|
||||
}
|
||||
interface ManagerReservedEvents {
|
||||
open: () => void;
|
||||
error: (err: Error) => void;
|
||||
ping: () => void;
|
||||
packet: (packet: Packet) => void;
|
||||
close: (reason: string, description?: DisconnectDescription) => void;
|
||||
reconnect_failed: () => void;
|
||||
reconnect_attempt: (attempt: number) => void;
|
||||
reconnect_error: (err: Error) => void;
|
||||
reconnect: (attempt: number) => void;
|
||||
}
|
||||
export declare class Manager<ListenEvents extends EventsMap = DefaultEventsMap, EmitEvents extends EventsMap = ListenEvents> extends Emitter<{}, {}, ManagerReservedEvents> {
|
||||
/**
|
||||
* The Engine.IO client instance
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
engine: Engine;
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
_autoConnect: boolean;
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
_readyState: "opening" | "open" | "closed";
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
_reconnecting: boolean;
|
||||
private readonly uri;
|
||||
opts: Partial<ManagerOptions>;
|
||||
private nsps;
|
||||
private subs;
|
||||
private backoff;
|
||||
private setTimeoutFn;
|
||||
private clearTimeoutFn;
|
||||
private _reconnection;
|
||||
private _reconnectionAttempts;
|
||||
private _reconnectionDelay;
|
||||
private _randomizationFactor;
|
||||
private _reconnectionDelayMax;
|
||||
private _timeout;
|
||||
private encoder;
|
||||
private decoder;
|
||||
private skipReconnect;
|
||||
/**
|
||||
* `Manager` constructor.
|
||||
*
|
||||
* @param uri - engine instance or engine uri/opts
|
||||
* @param opts - options
|
||||
* @public
|
||||
*/
|
||||
constructor(opts: Partial<ManagerOptions>);
|
||||
constructor(uri?: string, opts?: Partial<ManagerOptions>);
|
||||
constructor(uri?: string | Partial<ManagerOptions>, opts?: Partial<ManagerOptions>);
|
||||
/**
|
||||
* Sets the `reconnection` config.
|
||||
*
|
||||
* @param {Boolean} v - true/false if it should automatically reconnect
|
||||
* @return {Manager} self or value
|
||||
* @public
|
||||
*/
|
||||
reconnection(v: boolean): this;
|
||||
reconnection(): boolean;
|
||||
reconnection(v?: boolean): this | boolean;
|
||||
/**
|
||||
* Sets the reconnection attempts config.
|
||||
*
|
||||
* @param {Number} v - max reconnection attempts before giving up
|
||||
* @return {Manager} self or value
|
||||
* @public
|
||||
*/
|
||||
reconnectionAttempts(v: number): this;
|
||||
reconnectionAttempts(): number;
|
||||
reconnectionAttempts(v?: number): this | number;
|
||||
/**
|
||||
* Sets the delay between reconnections.
|
||||
*
|
||||
* @param {Number} v - delay
|
||||
* @return {Manager} self or value
|
||||
* @public
|
||||
*/
|
||||
reconnectionDelay(v: number): this;
|
||||
reconnectionDelay(): number;
|
||||
reconnectionDelay(v?: number): this | number;
|
||||
/**
|
||||
* Sets the randomization factor
|
||||
*
|
||||
* @param v - the randomization factor
|
||||
* @return self or value
|
||||
* @public
|
||||
*/
|
||||
randomizationFactor(v: number): this;
|
||||
randomizationFactor(): number;
|
||||
randomizationFactor(v?: number): this | number;
|
||||
/**
|
||||
* Sets the maximum delay between reconnections.
|
||||
*
|
||||
* @param v - delay
|
||||
* @return self or value
|
||||
* @public
|
||||
*/
|
||||
reconnectionDelayMax(v: number): this;
|
||||
reconnectionDelayMax(): number;
|
||||
reconnectionDelayMax(v?: number): this | number;
|
||||
/**
|
||||
* Sets the connection timeout. `false` to disable
|
||||
*
|
||||
* @param v - connection timeout
|
||||
* @return self or value
|
||||
* @public
|
||||
*/
|
||||
timeout(v: number | boolean): this;
|
||||
timeout(): number | boolean;
|
||||
timeout(v?: number | boolean): this | number | boolean;
|
||||
/**
|
||||
* Starts trying to reconnect if reconnection is enabled and we have not
|
||||
* started reconnecting yet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private maybeReconnectOnOpen;
|
||||
/**
|
||||
* Sets the current transport `socket`.
|
||||
*
|
||||
* @param {Function} fn - optional, callback
|
||||
* @return self
|
||||
* @public
|
||||
*/
|
||||
open(fn?: (err?: Error) => void): this;
|
||||
/**
|
||||
* Alias for open()
|
||||
*
|
||||
* @return self
|
||||
* @public
|
||||
*/
|
||||
connect(fn?: (err?: Error) => void): this;
|
||||
/**
|
||||
* Called upon transport open.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onopen;
|
||||
/**
|
||||
* Called upon a ping.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onping;
|
||||
/**
|
||||
* Called with data.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private ondata;
|
||||
/**
|
||||
* Called when parser fully decodes a packet.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private ondecoded;
|
||||
/**
|
||||
* Called upon socket error.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onerror;
|
||||
/**
|
||||
* Creates a new socket for the given `nsp`.
|
||||
*
|
||||
* @return {Socket}
|
||||
* @public
|
||||
*/
|
||||
socket(nsp: string, opts?: Partial<SocketOptions>): Socket;
|
||||
/**
|
||||
* Called upon a socket close.
|
||||
*
|
||||
* @param socket
|
||||
* @private
|
||||
*/
|
||||
_destroy(socket: Socket): void;
|
||||
/**
|
||||
* Writes a packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
_packet(packet: Partial<Packet & {
|
||||
query: string;
|
||||
options: any;
|
||||
}>): void;
|
||||
/**
|
||||
* Clean up transport subscriptions and packet buffer.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private cleanup;
|
||||
/**
|
||||
* Close the current socket.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_close(): void;
|
||||
/**
|
||||
* Alias for close()
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private disconnect;
|
||||
/**
|
||||
* Called when:
|
||||
*
|
||||
* - the low-level engine is closed
|
||||
* - the parser encountered a badly formatted packet
|
||||
* - all sockets are disconnected
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onclose;
|
||||
/**
|
||||
* Attempt a reconnection.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private reconnect;
|
||||
/**
|
||||
* Called upon successful reconnect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onreconnect;
|
||||
}
|
||||
export {};
|
||||
+416
@@ -0,0 +1,416 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Manager = void 0;
|
||||
const engine_io_client_1 = require("engine.io-client");
|
||||
const socket_js_1 = require("./socket.js");
|
||||
const parser = __importStar(require("socket.io-parser"));
|
||||
const on_js_1 = require("./on.js");
|
||||
const backo2_js_1 = require("./contrib/backo2.js");
|
||||
const component_emitter_1 = require("@socket.io/component-emitter");
|
||||
const debug_1 = __importDefault(require("debug")); // debug()
|
||||
const debug = (0, debug_1.default)("socket.io-client:manager"); // debug()
|
||||
class Manager extends component_emitter_1.Emitter {
|
||||
constructor(uri, opts) {
|
||||
var _a;
|
||||
super();
|
||||
this.nsps = {};
|
||||
this.subs = [];
|
||||
if (uri && "object" === typeof uri) {
|
||||
opts = uri;
|
||||
uri = undefined;
|
||||
}
|
||||
opts = opts || {};
|
||||
opts.path = opts.path || "/socket.io";
|
||||
this.opts = opts;
|
||||
(0, engine_io_client_1.installTimerFunctions)(this, opts);
|
||||
this.reconnection(opts.reconnection !== false);
|
||||
this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
|
||||
this.reconnectionDelay(opts.reconnectionDelay || 1000);
|
||||
this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
|
||||
this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
|
||||
this.backoff = new backo2_js_1.Backoff({
|
||||
min: this.reconnectionDelay(),
|
||||
max: this.reconnectionDelayMax(),
|
||||
jitter: this.randomizationFactor(),
|
||||
});
|
||||
this.timeout(null == opts.timeout ? 20000 : opts.timeout);
|
||||
this._readyState = "closed";
|
||||
this.uri = uri;
|
||||
const _parser = opts.parser || parser;
|
||||
this.encoder = new _parser.Encoder();
|
||||
this.decoder = new _parser.Decoder();
|
||||
this._autoConnect = opts.autoConnect !== false;
|
||||
if (this._autoConnect)
|
||||
this.open();
|
||||
}
|
||||
reconnection(v) {
|
||||
if (!arguments.length)
|
||||
return this._reconnection;
|
||||
this._reconnection = !!v;
|
||||
if (!v) {
|
||||
this.skipReconnect = true;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
reconnectionAttempts(v) {
|
||||
if (v === undefined)
|
||||
return this._reconnectionAttempts;
|
||||
this._reconnectionAttempts = v;
|
||||
return this;
|
||||
}
|
||||
reconnectionDelay(v) {
|
||||
var _a;
|
||||
if (v === undefined)
|
||||
return this._reconnectionDelay;
|
||||
this._reconnectionDelay = v;
|
||||
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
|
||||
return this;
|
||||
}
|
||||
randomizationFactor(v) {
|
||||
var _a;
|
||||
if (v === undefined)
|
||||
return this._randomizationFactor;
|
||||
this._randomizationFactor = v;
|
||||
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
|
||||
return this;
|
||||
}
|
||||
reconnectionDelayMax(v) {
|
||||
var _a;
|
||||
if (v === undefined)
|
||||
return this._reconnectionDelayMax;
|
||||
this._reconnectionDelayMax = v;
|
||||
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
|
||||
return this;
|
||||
}
|
||||
timeout(v) {
|
||||
if (!arguments.length)
|
||||
return this._timeout;
|
||||
this._timeout = v;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Starts trying to reconnect if reconnection is enabled and we have not
|
||||
* started reconnecting yet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
maybeReconnectOnOpen() {
|
||||
// Only try to reconnect if it's the first time we're connecting
|
||||
if (!this._reconnecting &&
|
||||
this._reconnection &&
|
||||
this.backoff.attempts === 0) {
|
||||
// keeps reconnection from firing twice for the same reconnection loop
|
||||
this.reconnect();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Sets the current transport `socket`.
|
||||
*
|
||||
* @param {Function} fn - optional, callback
|
||||
* @return self
|
||||
* @public
|
||||
*/
|
||||
open(fn) {
|
||||
debug("readyState %s", this._readyState);
|
||||
if (~this._readyState.indexOf("open"))
|
||||
return this;
|
||||
debug("opening %s", this.uri);
|
||||
this.engine = new engine_io_client_1.Socket(this.uri, this.opts);
|
||||
const socket = this.engine;
|
||||
const self = this;
|
||||
this._readyState = "opening";
|
||||
this.skipReconnect = false;
|
||||
// emit `open`
|
||||
const openSubDestroy = (0, on_js_1.on)(socket, "open", function () {
|
||||
self.onopen();
|
||||
fn && fn();
|
||||
});
|
||||
const onError = (err) => {
|
||||
debug("error");
|
||||
this.cleanup();
|
||||
this._readyState = "closed";
|
||||
this.emitReserved("error", err);
|
||||
if (fn) {
|
||||
fn(err);
|
||||
}
|
||||
else {
|
||||
// Only do this if there is no fn to handle the error
|
||||
this.maybeReconnectOnOpen();
|
||||
}
|
||||
};
|
||||
// emit `error`
|
||||
const errorSub = (0, on_js_1.on)(socket, "error", onError);
|
||||
if (false !== this._timeout) {
|
||||
const timeout = this._timeout;
|
||||
debug("connect attempt will timeout after %d", timeout);
|
||||
// set timer
|
||||
const timer = this.setTimeoutFn(() => {
|
||||
debug("connect attempt timed out after %d", timeout);
|
||||
openSubDestroy();
|
||||
onError(new Error("timeout"));
|
||||
socket.close();
|
||||
}, timeout);
|
||||
if (this.opts.autoUnref) {
|
||||
timer.unref();
|
||||
}
|
||||
this.subs.push(() => {
|
||||
this.clearTimeoutFn(timer);
|
||||
});
|
||||
}
|
||||
this.subs.push(openSubDestroy);
|
||||
this.subs.push(errorSub);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Alias for open()
|
||||
*
|
||||
* @return self
|
||||
* @public
|
||||
*/
|
||||
connect(fn) {
|
||||
return this.open(fn);
|
||||
}
|
||||
/**
|
||||
* Called upon transport open.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onopen() {
|
||||
debug("open");
|
||||
// clear old subs
|
||||
this.cleanup();
|
||||
// mark as open
|
||||
this._readyState = "open";
|
||||
this.emitReserved("open");
|
||||
// add new subs
|
||||
const socket = this.engine;
|
||||
this.subs.push((0, on_js_1.on)(socket, "ping", this.onping.bind(this)), (0, on_js_1.on)(socket, "data", this.ondata.bind(this)), (0, on_js_1.on)(socket, "error", this.onerror.bind(this)), (0, on_js_1.on)(socket, "close", this.onclose.bind(this)),
|
||||
// @ts-ignore
|
||||
(0, on_js_1.on)(this.decoder, "decoded", this.ondecoded.bind(this)));
|
||||
}
|
||||
/**
|
||||
* Called upon a ping.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onping() {
|
||||
this.emitReserved("ping");
|
||||
}
|
||||
/**
|
||||
* Called with data.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
ondata(data) {
|
||||
try {
|
||||
this.decoder.add(data);
|
||||
}
|
||||
catch (e) {
|
||||
this.onclose("parse error", e);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Called when parser fully decodes a packet.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
ondecoded(packet) {
|
||||
// the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
|
||||
(0, engine_io_client_1.nextTick)(() => {
|
||||
this.emitReserved("packet", packet);
|
||||
}, this.setTimeoutFn);
|
||||
}
|
||||
/**
|
||||
* Called upon socket error.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onerror(err) {
|
||||
debug("error", err);
|
||||
this.emitReserved("error", err);
|
||||
}
|
||||
/**
|
||||
* Creates a new socket for the given `nsp`.
|
||||
*
|
||||
* @return {Socket}
|
||||
* @public
|
||||
*/
|
||||
socket(nsp, opts) {
|
||||
let socket = this.nsps[nsp];
|
||||
if (!socket) {
|
||||
socket = new socket_js_1.Socket(this, nsp, opts);
|
||||
this.nsps[nsp] = socket;
|
||||
}
|
||||
else if (this._autoConnect && !socket.active) {
|
||||
socket.connect();
|
||||
}
|
||||
return socket;
|
||||
}
|
||||
/**
|
||||
* Called upon a socket close.
|
||||
*
|
||||
* @param socket
|
||||
* @private
|
||||
*/
|
||||
_destroy(socket) {
|
||||
const nsps = Object.keys(this.nsps);
|
||||
for (const nsp of nsps) {
|
||||
const socket = this.nsps[nsp];
|
||||
if (socket.active) {
|
||||
debug("socket %s is still active, skipping close", nsp);
|
||||
return;
|
||||
}
|
||||
}
|
||||
this._close();
|
||||
}
|
||||
/**
|
||||
* Writes a packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
_packet(packet) {
|
||||
debug("writing packet %j", packet);
|
||||
const encodedPackets = this.encoder.encode(packet);
|
||||
for (let i = 0; i < encodedPackets.length; i++) {
|
||||
this.engine.write(encodedPackets[i], packet.options);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Clean up transport subscriptions and packet buffer.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
cleanup() {
|
||||
debug("cleanup");
|
||||
this.subs.forEach((subDestroy) => subDestroy());
|
||||
this.subs.length = 0;
|
||||
this.decoder.destroy();
|
||||
}
|
||||
/**
|
||||
* Close the current socket.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_close() {
|
||||
debug("disconnect");
|
||||
this.skipReconnect = true;
|
||||
this._reconnecting = false;
|
||||
this.onclose("forced close");
|
||||
}
|
||||
/**
|
||||
* Alias for close()
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
disconnect() {
|
||||
return this._close();
|
||||
}
|
||||
/**
|
||||
* Called when:
|
||||
*
|
||||
* - the low-level engine is closed
|
||||
* - the parser encountered a badly formatted packet
|
||||
* - all sockets are disconnected
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onclose(reason, description) {
|
||||
var _a;
|
||||
debug("closed due to %s", reason);
|
||||
this.cleanup();
|
||||
(_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
|
||||
this.backoff.reset();
|
||||
this._readyState = "closed";
|
||||
this.emitReserved("close", reason, description);
|
||||
if (this._reconnection && !this.skipReconnect) {
|
||||
this.reconnect();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Attempt a reconnection.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
reconnect() {
|
||||
if (this._reconnecting || this.skipReconnect)
|
||||
return this;
|
||||
const self = this;
|
||||
if (this.backoff.attempts >= this._reconnectionAttempts) {
|
||||
debug("reconnect failed");
|
||||
this.backoff.reset();
|
||||
this.emitReserved("reconnect_failed");
|
||||
this._reconnecting = false;
|
||||
}
|
||||
else {
|
||||
const delay = this.backoff.duration();
|
||||
debug("will wait %dms before reconnect attempt", delay);
|
||||
this._reconnecting = true;
|
||||
const timer = this.setTimeoutFn(() => {
|
||||
if (self.skipReconnect)
|
||||
return;
|
||||
debug("attempting reconnect");
|
||||
this.emitReserved("reconnect_attempt", self.backoff.attempts);
|
||||
// check again for the case socket closed in above events
|
||||
if (self.skipReconnect)
|
||||
return;
|
||||
self.open((err) => {
|
||||
if (err) {
|
||||
debug("reconnect attempt error");
|
||||
self._reconnecting = false;
|
||||
self.reconnect();
|
||||
this.emitReserved("reconnect_error", err);
|
||||
}
|
||||
else {
|
||||
debug("reconnect success");
|
||||
self.onreconnect();
|
||||
}
|
||||
});
|
||||
}, delay);
|
||||
if (this.opts.autoUnref) {
|
||||
timer.unref();
|
||||
}
|
||||
this.subs.push(() => {
|
||||
this.clearTimeoutFn(timer);
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Called upon successful reconnect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onreconnect() {
|
||||
const attempt = this.backoff.attempts;
|
||||
this._reconnecting = false;
|
||||
this.backoff.reset();
|
||||
this.emitReserved("reconnect", attempt);
|
||||
}
|
||||
}
|
||||
exports.Manager = Manager;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { Emitter } from "@socket.io/component-emitter";
|
||||
export declare function on(obj: Emitter<any, any>, ev: string, fn: (err?: any) => any): VoidFunction;
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.on = on;
|
||||
function on(obj, ev, fn) {
|
||||
obj.on(ev, fn);
|
||||
return function subDestroy() {
|
||||
obj.off(ev, fn);
|
||||
};
|
||||
}
|
||||
+593
@@ -0,0 +1,593 @@
|
||||
import { Packet } from "socket.io-parser";
|
||||
import { Manager } from "./manager.js";
|
||||
import { DefaultEventsMap, EventNames, EventParams, EventsMap, Emitter } from "@socket.io/component-emitter";
|
||||
type PrependTimeoutError<T extends any[]> = {
|
||||
[K in keyof T]: T[K] extends (...args: infer Params) => infer Result ? (err: Error, ...args: Params) => Result : T[K];
|
||||
};
|
||||
/**
|
||||
* Utility type to decorate the acknowledgement callbacks with a timeout error.
|
||||
*
|
||||
* This is needed because the timeout() flag breaks the symmetry between the sender and the receiver:
|
||||
*
|
||||
* @example
|
||||
* interface Events {
|
||||
* "my-event": (val: string) => void;
|
||||
* }
|
||||
*
|
||||
* socket.on("my-event", (cb) => {
|
||||
* cb("123"); // one single argument here
|
||||
* });
|
||||
*
|
||||
* socket.timeout(1000).emit("my-event", (err, val) => {
|
||||
* // two arguments there (the "err" argument is not properly typed)
|
||||
* });
|
||||
*
|
||||
*/
|
||||
export type DecorateAcknowledgements<E> = {
|
||||
[K in keyof E]: E[K] extends (...args: infer Params) => infer Result ? (...args: PrependTimeoutError<Params>) => Result : E[K];
|
||||
};
|
||||
export type Last<T extends any[]> = T extends [...infer H, infer L] ? L : any;
|
||||
export type AllButLast<T extends any[]> = T extends [...infer H, infer L] ? H : any[];
|
||||
export type FirstArg<T> = T extends (arg: infer Param) => infer Result ? Param : any;
|
||||
export interface SocketOptions {
|
||||
/**
|
||||
* the authentication payload sent when connecting to the Namespace
|
||||
*/
|
||||
auth?: {
|
||||
[key: string]: any;
|
||||
} | ((cb: (data: object) => void) => void);
|
||||
/**
|
||||
* The maximum number of retries. Above the limit, the packet will be discarded.
|
||||
*
|
||||
* Using `Infinity` means the delivery guarantee is "at-least-once" (instead of "at-most-once" by default), but a
|
||||
* smaller value like 10 should be sufficient in practice.
|
||||
*/
|
||||
retries?: number;
|
||||
/**
|
||||
* The default timeout in milliseconds used when waiting for an acknowledgement.
|
||||
*/
|
||||
ackTimeout?: number;
|
||||
}
|
||||
export type DisconnectDescription = Error | {
|
||||
description: string;
|
||||
context?: unknown;
|
||||
};
|
||||
interface SocketReservedEvents {
|
||||
connect: () => void;
|
||||
connect_error: (err: Error) => void;
|
||||
disconnect: (reason: Socket.DisconnectReason, description?: DisconnectDescription) => void;
|
||||
}
|
||||
/**
|
||||
* A Socket is the fundamental class for interacting with the server.
|
||||
*
|
||||
* A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log("connected");
|
||||
* });
|
||||
*
|
||||
* // send an event to the server
|
||||
* socket.emit("foo", "bar");
|
||||
*
|
||||
* socket.on("foobar", () => {
|
||||
* // an event was received from the server
|
||||
* });
|
||||
*
|
||||
* // upon disconnection
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* console.log(`disconnected due to ${reason}`);
|
||||
* });
|
||||
*/
|
||||
export declare class Socket<ListenEvents extends EventsMap = DefaultEventsMap, EmitEvents extends EventsMap = ListenEvents> extends Emitter<ListenEvents, EmitEvents, SocketReservedEvents> {
|
||||
readonly io: Manager<ListenEvents, EmitEvents>;
|
||||
/**
|
||||
* A unique identifier for the session. `undefined` when the socket is not connected.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* console.log(socket.id); // undefined
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log(socket.id); // "G5p5..."
|
||||
* });
|
||||
*/
|
||||
id: string | undefined;
|
||||
/**
|
||||
* The session ID used for connection state recovery, which must not be shared (unlike {@link id}).
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private _pid;
|
||||
/**
|
||||
* The offset of the last received packet, which will be sent upon reconnection to allow for the recovery of the connection state.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private _lastOffset;
|
||||
/**
|
||||
* Whether the socket is currently connected to the server.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log(socket.connected); // true
|
||||
* });
|
||||
*
|
||||
* socket.on("disconnect", () => {
|
||||
* console.log(socket.connected); // false
|
||||
* });
|
||||
*/
|
||||
connected: boolean;
|
||||
/**
|
||||
* Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
|
||||
* be transmitted by the server.
|
||||
*/
|
||||
recovered: boolean;
|
||||
/**
|
||||
* Credentials that are sent when accessing a namespace.
|
||||
*
|
||||
* @example
|
||||
* const socket = io({
|
||||
* auth: {
|
||||
* token: "abcd"
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* // or with a function
|
||||
* const socket = io({
|
||||
* auth: (cb) => {
|
||||
* cb({ token: localStorage.token })
|
||||
* }
|
||||
* });
|
||||
*/
|
||||
auth: {
|
||||
[key: string]: any;
|
||||
} | ((cb: (data: object) => void) => void);
|
||||
/**
|
||||
* Buffer for packets received before the CONNECT packet
|
||||
*/
|
||||
receiveBuffer: Array<ReadonlyArray<any>>;
|
||||
/**
|
||||
* Buffer for packets that will be sent once the socket is connected
|
||||
*/
|
||||
sendBuffer: Array<Packet>;
|
||||
/**
|
||||
* The queue of packets to be sent with retry in case of failure.
|
||||
*
|
||||
* Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
|
||||
* @private
|
||||
*/
|
||||
private _queue;
|
||||
/**
|
||||
* A sequence to generate the ID of the {@link QueuedPacket}.
|
||||
* @private
|
||||
*/
|
||||
private _queueSeq;
|
||||
private readonly nsp;
|
||||
private readonly _opts;
|
||||
private ids;
|
||||
/**
|
||||
* A map containing acknowledgement handlers.
|
||||
*
|
||||
* The `withError` attribute is used to differentiate handlers that accept an error as first argument:
|
||||
*
|
||||
* - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
|
||||
* - `socket.timeout(5000).emit("test", (err, value) => { ... })`
|
||||
* - `const value = await socket.emitWithAck("test")`
|
||||
*
|
||||
* From those that don't:
|
||||
*
|
||||
* - `socket.emit("test", (value) => { ... });`
|
||||
*
|
||||
* In the first case, the handlers will be called with an error when:
|
||||
*
|
||||
* - the timeout is reached
|
||||
* - the socket gets disconnected
|
||||
*
|
||||
* In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
|
||||
* an acknowledgement from the server.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private acks;
|
||||
private flags;
|
||||
private subs?;
|
||||
private _anyListeners;
|
||||
private _anyOutgoingListeners;
|
||||
/**
|
||||
* `Socket` constructor.
|
||||
*/
|
||||
constructor(io: Manager, nsp: string, opts?: Partial<SocketOptions>);
|
||||
/**
|
||||
* Whether the socket is currently disconnected
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log(socket.disconnected); // false
|
||||
* });
|
||||
*
|
||||
* socket.on("disconnect", () => {
|
||||
* console.log(socket.disconnected); // true
|
||||
* });
|
||||
*/
|
||||
get disconnected(): boolean;
|
||||
/**
|
||||
* Subscribe to open, close and packet events
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private subEvents;
|
||||
/**
|
||||
* Whether the Socket will try to reconnect when its Manager connects or reconnects.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* console.log(socket.active); // true
|
||||
*
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* if (reason === "io server disconnect") {
|
||||
* // the disconnection was initiated by the server, you need to manually reconnect
|
||||
* console.log(socket.active); // false
|
||||
* }
|
||||
* // else the socket will automatically try to reconnect
|
||||
* console.log(socket.active); // true
|
||||
* });
|
||||
*/
|
||||
get active(): boolean;
|
||||
/**
|
||||
* "Opens" the socket.
|
||||
*
|
||||
* @example
|
||||
* const socket = io({
|
||||
* autoConnect: false
|
||||
* });
|
||||
*
|
||||
* socket.connect();
|
||||
*/
|
||||
connect(): this;
|
||||
/**
|
||||
* Alias for {@link connect()}.
|
||||
*/
|
||||
open(): this;
|
||||
/**
|
||||
* Sends a `message` event.
|
||||
*
|
||||
* This method mimics the WebSocket.send() method.
|
||||
*
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
|
||||
*
|
||||
* @example
|
||||
* socket.send("hello");
|
||||
*
|
||||
* // this is equivalent to
|
||||
* socket.emit("message", "hello");
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
send(...args: any[]): this;
|
||||
/**
|
||||
* Override `emit`.
|
||||
* If the event is in `events`, it's emitted normally.
|
||||
*
|
||||
* @example
|
||||
* socket.emit("hello", "world");
|
||||
*
|
||||
* // all serializable datastructures are supported (no need to call JSON.stringify)
|
||||
* socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
|
||||
*
|
||||
* // with an acknowledgement from the server
|
||||
* socket.emit("hello", "world", (val) => {
|
||||
* // ...
|
||||
* });
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
emit<Ev extends EventNames<EmitEvents>>(ev: Ev, ...args: EventParams<EmitEvents, Ev>): this;
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
private _registerAckCallback;
|
||||
/**
|
||||
* Emits an event and waits for an acknowledgement
|
||||
*
|
||||
* @example
|
||||
* // without timeout
|
||||
* const response = await socket.emitWithAck("hello", "world");
|
||||
*
|
||||
* // with a specific timeout
|
||||
* try {
|
||||
* const response = await socket.timeout(1000).emitWithAck("hello", "world");
|
||||
* } catch (err) {
|
||||
* // the server did not acknowledge the event in the given delay
|
||||
* }
|
||||
*
|
||||
* @return a Promise that will be fulfilled when the server acknowledges the event
|
||||
*/
|
||||
emitWithAck<Ev extends EventNames<EmitEvents>>(ev: Ev, ...args: AllButLast<EventParams<EmitEvents, Ev>>): Promise<FirstArg<Last<EventParams<EmitEvents, Ev>>>>;
|
||||
/**
|
||||
* Add the packet to the queue.
|
||||
* @param args
|
||||
* @private
|
||||
*/
|
||||
private _addToQueue;
|
||||
/**
|
||||
* Send the first packet of the queue, and wait for an acknowledgement from the server.
|
||||
* @param force - whether to resend a packet that has not been acknowledged yet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private _drainQueue;
|
||||
/**
|
||||
* Sends a packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
private packet;
|
||||
/**
|
||||
* Called upon engine `open`.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onopen;
|
||||
/**
|
||||
* Sends a CONNECT packet to initiate the Socket.IO session.
|
||||
*
|
||||
* @param data
|
||||
* @private
|
||||
*/
|
||||
private _sendConnectPacket;
|
||||
/**
|
||||
* Called upon engine or manager `error`.
|
||||
*
|
||||
* @param err
|
||||
* @private
|
||||
*/
|
||||
private onerror;
|
||||
/**
|
||||
* Called upon engine `close`.
|
||||
*
|
||||
* @param reason
|
||||
* @param description
|
||||
* @private
|
||||
*/
|
||||
private onclose;
|
||||
/**
|
||||
* Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
|
||||
* the server.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private _clearAcks;
|
||||
/**
|
||||
* Called with socket packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
private onpacket;
|
||||
/**
|
||||
* Called upon a server event.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
private onevent;
|
||||
private emitEvent;
|
||||
/**
|
||||
* Produces an ack callback to emit with an event.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private ack;
|
||||
/**
|
||||
* Called upon a server acknowledgement.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
private onack;
|
||||
/**
|
||||
* Called upon server connect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onconnect;
|
||||
/**
|
||||
* Emit buffered events (received and emitted).
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private emitBuffered;
|
||||
/**
|
||||
* Called upon server disconnect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private ondisconnect;
|
||||
/**
|
||||
* Called upon forced client/server side disconnections,
|
||||
* this method ensures the manager stops tracking us and
|
||||
* that reconnections don't get triggered for this.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private destroy;
|
||||
/**
|
||||
* Disconnects the socket manually. In that case, the socket will not try to reconnect.
|
||||
*
|
||||
* If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* // console.log(reason); prints "io client disconnect"
|
||||
* });
|
||||
*
|
||||
* socket.disconnect();
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
disconnect(): this;
|
||||
/**
|
||||
* Alias for {@link disconnect()}.
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
close(): this;
|
||||
/**
|
||||
* Sets the compress flag.
|
||||
*
|
||||
* @example
|
||||
* socket.compress(false).emit("hello");
|
||||
*
|
||||
* @param compress - if `true`, compresses the sending data
|
||||
* @return self
|
||||
*/
|
||||
compress(compress: boolean): this;
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
|
||||
* ready to send messages.
|
||||
*
|
||||
* @example
|
||||
* socket.volatile.emit("hello"); // the server may or may not receive it
|
||||
*
|
||||
* @returns self
|
||||
*/
|
||||
get volatile(): this;
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the callback will be called with an error when the
|
||||
* given number of milliseconds have elapsed without an acknowledgement from the server:
|
||||
*
|
||||
* @example
|
||||
* socket.timeout(5000).emit("my-event", (err) => {
|
||||
* if (err) {
|
||||
* // the server did not acknowledge the event in the given delay
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* @returns self
|
||||
*/
|
||||
timeout(timeout: number): Socket<ListenEvents, DecorateAcknowledgements<EmitEvents>>;
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback.
|
||||
*
|
||||
* @example
|
||||
* socket.onAny((event, ...args) => {
|
||||
* console.log(`got ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
onAny(listener: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback. The listener is added to the beginning of the listeners array.
|
||||
*
|
||||
* @example
|
||||
* socket.prependAny((event, ...args) => {
|
||||
* console.log(`got event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
prependAny(listener: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Removes the listener that will be fired when any event is emitted.
|
||||
*
|
||||
* @example
|
||||
* const catchAllListener = (event, ...args) => {
|
||||
* console.log(`got event ${event}`);
|
||||
* }
|
||||
*
|
||||
* socket.onAny(catchAllListener);
|
||||
*
|
||||
* // remove a specific listener
|
||||
* socket.offAny(catchAllListener);
|
||||
*
|
||||
* // or remove all listeners
|
||||
* socket.offAny();
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
offAny(listener?: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
|
||||
* e.g. to remove listeners.
|
||||
*/
|
||||
listenersAny(): ((...args: any[]) => void)[];
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback.
|
||||
*
|
||||
* Note: acknowledgements sent to the server are not included.
|
||||
*
|
||||
* @example
|
||||
* socket.onAnyOutgoing((event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
onAnyOutgoing(listener: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback. The listener is added to the beginning of the listeners array.
|
||||
*
|
||||
* Note: acknowledgements sent to the server are not included.
|
||||
*
|
||||
* @example
|
||||
* socket.prependAnyOutgoing((event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
prependAnyOutgoing(listener: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Removes the listener that will be fired when any event is emitted.
|
||||
*
|
||||
* @example
|
||||
* const catchAllListener = (event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* }
|
||||
*
|
||||
* socket.onAnyOutgoing(catchAllListener);
|
||||
*
|
||||
* // remove a specific listener
|
||||
* socket.offAnyOutgoing(catchAllListener);
|
||||
*
|
||||
* // or remove all listeners
|
||||
* socket.offAnyOutgoing();
|
||||
*
|
||||
* @param [listener] - the catch-all listener (optional)
|
||||
*/
|
||||
offAnyOutgoing(listener?: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
|
||||
* e.g. to remove listeners.
|
||||
*/
|
||||
listenersAnyOutgoing(): ((...args: any[]) => void)[];
|
||||
/**
|
||||
* Notify the listeners for each packet sent
|
||||
*
|
||||
* @param packet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private notifyOutgoingListeners;
|
||||
}
|
||||
export declare namespace Socket {
|
||||
type DisconnectReason = "io server disconnect" | "io client disconnect" | "ping timeout" | "transport close" | "transport error" | "parse error";
|
||||
}
|
||||
export {};
|
||||
+909
@@ -0,0 +1,909 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Socket = void 0;
|
||||
const socket_io_parser_1 = require("socket.io-parser");
|
||||
const on_js_1 = require("./on.js");
|
||||
const component_emitter_1 = require("@socket.io/component-emitter");
|
||||
const debug_1 = __importDefault(require("debug")); // debug()
|
||||
const debug = (0, debug_1.default)("socket.io-client:socket"); // debug()
|
||||
/**
|
||||
* Internal events.
|
||||
* These events can't be emitted by the user.
|
||||
*/
|
||||
const RESERVED_EVENTS = Object.freeze({
|
||||
connect: 1,
|
||||
connect_error: 1,
|
||||
disconnect: 1,
|
||||
disconnecting: 1,
|
||||
// EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
|
||||
newListener: 1,
|
||||
removeListener: 1,
|
||||
});
|
||||
/**
|
||||
* A Socket is the fundamental class for interacting with the server.
|
||||
*
|
||||
* A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log("connected");
|
||||
* });
|
||||
*
|
||||
* // send an event to the server
|
||||
* socket.emit("foo", "bar");
|
||||
*
|
||||
* socket.on("foobar", () => {
|
||||
* // an event was received from the server
|
||||
* });
|
||||
*
|
||||
* // upon disconnection
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* console.log(`disconnected due to ${reason}`);
|
||||
* });
|
||||
*/
|
||||
class Socket extends component_emitter_1.Emitter {
|
||||
/**
|
||||
* `Socket` constructor.
|
||||
*/
|
||||
constructor(io, nsp, opts) {
|
||||
super();
|
||||
/**
|
||||
* Whether the socket is currently connected to the server.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log(socket.connected); // true
|
||||
* });
|
||||
*
|
||||
* socket.on("disconnect", () => {
|
||||
* console.log(socket.connected); // false
|
||||
* });
|
||||
*/
|
||||
this.connected = false;
|
||||
/**
|
||||
* Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
|
||||
* be transmitted by the server.
|
||||
*/
|
||||
this.recovered = false;
|
||||
/**
|
||||
* Buffer for packets received before the CONNECT packet
|
||||
*/
|
||||
this.receiveBuffer = [];
|
||||
/**
|
||||
* Buffer for packets that will be sent once the socket is connected
|
||||
*/
|
||||
this.sendBuffer = [];
|
||||
/**
|
||||
* The queue of packets to be sent with retry in case of failure.
|
||||
*
|
||||
* Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
|
||||
* @private
|
||||
*/
|
||||
this._queue = [];
|
||||
/**
|
||||
* A sequence to generate the ID of the {@link QueuedPacket}.
|
||||
* @private
|
||||
*/
|
||||
this._queueSeq = 0;
|
||||
this.ids = 0;
|
||||
/**
|
||||
* A map containing acknowledgement handlers.
|
||||
*
|
||||
* The `withError` attribute is used to differentiate handlers that accept an error as first argument:
|
||||
*
|
||||
* - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
|
||||
* - `socket.timeout(5000).emit("test", (err, value) => { ... })`
|
||||
* - `const value = await socket.emitWithAck("test")`
|
||||
*
|
||||
* From those that don't:
|
||||
*
|
||||
* - `socket.emit("test", (value) => { ... });`
|
||||
*
|
||||
* In the first case, the handlers will be called with an error when:
|
||||
*
|
||||
* - the timeout is reached
|
||||
* - the socket gets disconnected
|
||||
*
|
||||
* In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
|
||||
* an acknowledgement from the server.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
this.acks = {};
|
||||
this.flags = {};
|
||||
this.io = io;
|
||||
this.nsp = nsp;
|
||||
if (opts && opts.auth) {
|
||||
this.auth = opts.auth;
|
||||
}
|
||||
this._opts = Object.assign({}, opts);
|
||||
if (this.io._autoConnect)
|
||||
this.open();
|
||||
}
|
||||
/**
|
||||
* Whether the socket is currently disconnected
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log(socket.disconnected); // false
|
||||
* });
|
||||
*
|
||||
* socket.on("disconnect", () => {
|
||||
* console.log(socket.disconnected); // true
|
||||
* });
|
||||
*/
|
||||
get disconnected() {
|
||||
return !this.connected;
|
||||
}
|
||||
/**
|
||||
* Subscribe to open, close and packet events
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
subEvents() {
|
||||
if (this.subs)
|
||||
return;
|
||||
const io = this.io;
|
||||
this.subs = [
|
||||
(0, on_js_1.on)(io, "open", this.onopen.bind(this)),
|
||||
(0, on_js_1.on)(io, "packet", this.onpacket.bind(this)),
|
||||
(0, on_js_1.on)(io, "error", this.onerror.bind(this)),
|
||||
(0, on_js_1.on)(io, "close", this.onclose.bind(this)),
|
||||
];
|
||||
}
|
||||
/**
|
||||
* Whether the Socket will try to reconnect when its Manager connects or reconnects.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* console.log(socket.active); // true
|
||||
*
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* if (reason === "io server disconnect") {
|
||||
* // the disconnection was initiated by the server, you need to manually reconnect
|
||||
* console.log(socket.active); // false
|
||||
* }
|
||||
* // else the socket will automatically try to reconnect
|
||||
* console.log(socket.active); // true
|
||||
* });
|
||||
*/
|
||||
get active() {
|
||||
return !!this.subs;
|
||||
}
|
||||
/**
|
||||
* "Opens" the socket.
|
||||
*
|
||||
* @example
|
||||
* const socket = io({
|
||||
* autoConnect: false
|
||||
* });
|
||||
*
|
||||
* socket.connect();
|
||||
*/
|
||||
connect() {
|
||||
if (this.connected)
|
||||
return this;
|
||||
this.subEvents();
|
||||
if (!this.io["_reconnecting"])
|
||||
this.io.open(); // ensure open
|
||||
if ("open" === this.io._readyState)
|
||||
this.onopen();
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Alias for {@link connect()}.
|
||||
*/
|
||||
open() {
|
||||
return this.connect();
|
||||
}
|
||||
/**
|
||||
* Sends a `message` event.
|
||||
*
|
||||
* This method mimics the WebSocket.send() method.
|
||||
*
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
|
||||
*
|
||||
* @example
|
||||
* socket.send("hello");
|
||||
*
|
||||
* // this is equivalent to
|
||||
* socket.emit("message", "hello");
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
send(...args) {
|
||||
args.unshift("message");
|
||||
this.emit.apply(this, args);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Override `emit`.
|
||||
* If the event is in `events`, it's emitted normally.
|
||||
*
|
||||
* @example
|
||||
* socket.emit("hello", "world");
|
||||
*
|
||||
* // all serializable datastructures are supported (no need to call JSON.stringify)
|
||||
* socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
|
||||
*
|
||||
* // with an acknowledgement from the server
|
||||
* socket.emit("hello", "world", (val) => {
|
||||
* // ...
|
||||
* });
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
emit(ev, ...args) {
|
||||
var _a, _b, _c;
|
||||
if (RESERVED_EVENTS.hasOwnProperty(ev)) {
|
||||
throw new Error('"' + ev.toString() + '" is a reserved event name');
|
||||
}
|
||||
args.unshift(ev);
|
||||
if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
|
||||
this._addToQueue(args);
|
||||
return this;
|
||||
}
|
||||
const packet = {
|
||||
type: socket_io_parser_1.PacketType.EVENT,
|
||||
data: args,
|
||||
};
|
||||
packet.options = {};
|
||||
packet.options.compress = this.flags.compress !== false;
|
||||
// event ack callback
|
||||
if ("function" === typeof args[args.length - 1]) {
|
||||
const id = this.ids++;
|
||||
debug("emitting packet with ack id %d", id);
|
||||
const ack = args.pop();
|
||||
this._registerAckCallback(id, ack);
|
||||
packet.id = id;
|
||||
}
|
||||
const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
|
||||
const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
|
||||
const discardPacket = this.flags.volatile && !isTransportWritable;
|
||||
if (discardPacket) {
|
||||
debug("discard packet as the transport is not currently writable");
|
||||
}
|
||||
else if (isConnected) {
|
||||
this.notifyOutgoingListeners(packet);
|
||||
this.packet(packet);
|
||||
}
|
||||
else {
|
||||
this.sendBuffer.push(packet);
|
||||
}
|
||||
this.flags = {};
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
_registerAckCallback(id, ack) {
|
||||
var _a;
|
||||
const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
|
||||
if (timeout === undefined) {
|
||||
this.acks[id] = ack;
|
||||
return;
|
||||
}
|
||||
// @ts-ignore
|
||||
const timer = this.io.setTimeoutFn(() => {
|
||||
delete this.acks[id];
|
||||
for (let i = 0; i < this.sendBuffer.length; i++) {
|
||||
if (this.sendBuffer[i].id === id) {
|
||||
debug("removing packet with ack id %d from the buffer", id);
|
||||
this.sendBuffer.splice(i, 1);
|
||||
}
|
||||
}
|
||||
debug("event with ack id %d has timed out after %d ms", id, timeout);
|
||||
ack.call(this, new Error("operation has timed out"));
|
||||
}, timeout);
|
||||
const fn = (...args) => {
|
||||
// @ts-ignore
|
||||
this.io.clearTimeoutFn(timer);
|
||||
ack.apply(this, args);
|
||||
};
|
||||
fn.withError = true;
|
||||
this.acks[id] = fn;
|
||||
}
|
||||
/**
|
||||
* Emits an event and waits for an acknowledgement
|
||||
*
|
||||
* @example
|
||||
* // without timeout
|
||||
* const response = await socket.emitWithAck("hello", "world");
|
||||
*
|
||||
* // with a specific timeout
|
||||
* try {
|
||||
* const response = await socket.timeout(1000).emitWithAck("hello", "world");
|
||||
* } catch (err) {
|
||||
* // the server did not acknowledge the event in the given delay
|
||||
* }
|
||||
*
|
||||
* @return a Promise that will be fulfilled when the server acknowledges the event
|
||||
*/
|
||||
emitWithAck(ev, ...args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const fn = (arg1, arg2) => {
|
||||
return arg1 ? reject(arg1) : resolve(arg2);
|
||||
};
|
||||
fn.withError = true;
|
||||
args.push(fn);
|
||||
this.emit(ev, ...args);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Add the packet to the queue.
|
||||
* @param args
|
||||
* @private
|
||||
*/
|
||||
_addToQueue(args) {
|
||||
let ack;
|
||||
if (typeof args[args.length - 1] === "function") {
|
||||
ack = args.pop();
|
||||
}
|
||||
const packet = {
|
||||
id: this._queueSeq++,
|
||||
tryCount: 0,
|
||||
pending: false,
|
||||
args,
|
||||
flags: Object.assign({ fromQueue: true }, this.flags),
|
||||
};
|
||||
args.push((err, ...responseArgs) => {
|
||||
if (packet !== this._queue[0]) {
|
||||
return debug("packet [%d] already acknowledged", packet.id);
|
||||
}
|
||||
const hasError = err !== null;
|
||||
if (hasError) {
|
||||
if (packet.tryCount > this._opts.retries) {
|
||||
debug("packet [%d] is discarded after %d tries", packet.id, packet.tryCount);
|
||||
this._queue.shift();
|
||||
if (ack) {
|
||||
ack(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
debug("packet [%d] was successfully sent", packet.id);
|
||||
this._queue.shift();
|
||||
if (ack) {
|
||||
ack(null, ...responseArgs);
|
||||
}
|
||||
}
|
||||
packet.pending = false;
|
||||
return this._drainQueue();
|
||||
});
|
||||
this._queue.push(packet);
|
||||
this._drainQueue();
|
||||
}
|
||||
/**
|
||||
* Send the first packet of the queue, and wait for an acknowledgement from the server.
|
||||
* @param force - whether to resend a packet that has not been acknowledged yet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_drainQueue(force = false) {
|
||||
debug("draining queue");
|
||||
if (!this.connected || this._queue.length === 0) {
|
||||
return;
|
||||
}
|
||||
const packet = this._queue[0];
|
||||
if (packet.pending && !force) {
|
||||
debug("packet [%d] has already been sent and is waiting for an ack", packet.id);
|
||||
return;
|
||||
}
|
||||
packet.pending = true;
|
||||
packet.tryCount++;
|
||||
debug("sending packet [%d] (try n°%d)", packet.id, packet.tryCount);
|
||||
this.flags = packet.flags;
|
||||
this.emit.apply(this, packet.args);
|
||||
}
|
||||
/**
|
||||
* Sends a packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
packet(packet) {
|
||||
packet.nsp = this.nsp;
|
||||
this.io._packet(packet);
|
||||
}
|
||||
/**
|
||||
* Called upon engine `open`.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onopen() {
|
||||
debug("transport is open - connecting");
|
||||
if (typeof this.auth == "function") {
|
||||
this.auth((data) => {
|
||||
this._sendConnectPacket(data);
|
||||
});
|
||||
}
|
||||
else {
|
||||
this._sendConnectPacket(this.auth);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Sends a CONNECT packet to initiate the Socket.IO session.
|
||||
*
|
||||
* @param data
|
||||
* @private
|
||||
*/
|
||||
_sendConnectPacket(data) {
|
||||
this.packet({
|
||||
type: socket_io_parser_1.PacketType.CONNECT,
|
||||
data: this._pid
|
||||
? Object.assign({ pid: this._pid, offset: this._lastOffset }, data)
|
||||
: data,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Called upon engine or manager `error`.
|
||||
*
|
||||
* @param err
|
||||
* @private
|
||||
*/
|
||||
onerror(err) {
|
||||
if (!this.connected) {
|
||||
this.emitReserved("connect_error", err);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Called upon engine `close`.
|
||||
*
|
||||
* @param reason
|
||||
* @param description
|
||||
* @private
|
||||
*/
|
||||
onclose(reason, description) {
|
||||
debug("close (%s)", reason);
|
||||
this.connected = false;
|
||||
delete this.id;
|
||||
this.emitReserved("disconnect", reason, description);
|
||||
this._clearAcks();
|
||||
}
|
||||
/**
|
||||
* Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
|
||||
* the server.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_clearAcks() {
|
||||
Object.keys(this.acks).forEach((id) => {
|
||||
const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
|
||||
if (!isBuffered) {
|
||||
// note: handlers that do not accept an error as first argument are ignored here
|
||||
const ack = this.acks[id];
|
||||
delete this.acks[id];
|
||||
if (ack.withError) {
|
||||
ack.call(this, new Error("socket has been disconnected"));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Called with socket packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
onpacket(packet) {
|
||||
const sameNamespace = packet.nsp === this.nsp;
|
||||
if (!sameNamespace)
|
||||
return;
|
||||
switch (packet.type) {
|
||||
case socket_io_parser_1.PacketType.CONNECT:
|
||||
if (packet.data && packet.data.sid) {
|
||||
this.onconnect(packet.data.sid, packet.data.pid);
|
||||
}
|
||||
else {
|
||||
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/)"));
|
||||
}
|
||||
break;
|
||||
case socket_io_parser_1.PacketType.EVENT:
|
||||
case socket_io_parser_1.PacketType.BINARY_EVENT:
|
||||
this.onevent(packet);
|
||||
break;
|
||||
case socket_io_parser_1.PacketType.ACK:
|
||||
case socket_io_parser_1.PacketType.BINARY_ACK:
|
||||
this.onack(packet);
|
||||
break;
|
||||
case socket_io_parser_1.PacketType.DISCONNECT:
|
||||
this.ondisconnect();
|
||||
break;
|
||||
case socket_io_parser_1.PacketType.CONNECT_ERROR:
|
||||
this.destroy();
|
||||
const err = new Error(packet.data.message);
|
||||
// @ts-ignore
|
||||
err.data = packet.data.data;
|
||||
this.emitReserved("connect_error", err);
|
||||
break;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Called upon a server event.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
onevent(packet) {
|
||||
const args = packet.data || [];
|
||||
debug("emitting event %j", args);
|
||||
if (null != packet.id) {
|
||||
debug("attaching ack callback to event");
|
||||
args.push(this.ack(packet.id));
|
||||
}
|
||||
if (this.connected) {
|
||||
this.emitEvent(args);
|
||||
}
|
||||
else {
|
||||
this.receiveBuffer.push(Object.freeze(args));
|
||||
}
|
||||
}
|
||||
emitEvent(args) {
|
||||
if (this._anyListeners && this._anyListeners.length) {
|
||||
const listeners = this._anyListeners.slice();
|
||||
for (const listener of listeners) {
|
||||
listener.apply(this, args);
|
||||
}
|
||||
}
|
||||
super.emit.apply(this, args);
|
||||
if (this._pid && args.length && typeof args[args.length - 1] === "string") {
|
||||
this._lastOffset = args[args.length - 1];
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Produces an ack callback to emit with an event.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
ack(id) {
|
||||
const self = this;
|
||||
let sent = false;
|
||||
return function (...args) {
|
||||
// prevent double callbacks
|
||||
if (sent)
|
||||
return;
|
||||
sent = true;
|
||||
debug("sending ack %j", args);
|
||||
self.packet({
|
||||
type: socket_io_parser_1.PacketType.ACK,
|
||||
id: id,
|
||||
data: args,
|
||||
});
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Called upon a server acknowledgement.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
onack(packet) {
|
||||
const ack = this.acks[packet.id];
|
||||
if (typeof ack !== "function") {
|
||||
debug("bad ack %s", packet.id);
|
||||
return;
|
||||
}
|
||||
delete this.acks[packet.id];
|
||||
debug("calling ack %s with %j", packet.id, packet.data);
|
||||
// @ts-ignore FIXME ack is incorrectly inferred as 'never'
|
||||
if (ack.withError) {
|
||||
packet.data.unshift(null);
|
||||
}
|
||||
// @ts-ignore
|
||||
ack.apply(this, packet.data);
|
||||
}
|
||||
/**
|
||||
* Called upon server connect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onconnect(id, pid) {
|
||||
debug("socket connected with id %s", id);
|
||||
this.id = id;
|
||||
this.recovered = pid && this._pid === pid;
|
||||
this._pid = pid; // defined only if connection state recovery is enabled
|
||||
this.connected = true;
|
||||
this.emitBuffered();
|
||||
this._drainQueue(true);
|
||||
this.emitReserved("connect");
|
||||
}
|
||||
/**
|
||||
* Emit buffered events (received and emitted).
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
emitBuffered() {
|
||||
this.receiveBuffer.forEach((args) => this.emitEvent(args));
|
||||
this.receiveBuffer = [];
|
||||
this.sendBuffer.forEach((packet) => {
|
||||
this.notifyOutgoingListeners(packet);
|
||||
this.packet(packet);
|
||||
});
|
||||
this.sendBuffer = [];
|
||||
}
|
||||
/**
|
||||
* Called upon server disconnect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
ondisconnect() {
|
||||
debug("server disconnect (%s)", this.nsp);
|
||||
this.destroy();
|
||||
this.onclose("io server disconnect");
|
||||
}
|
||||
/**
|
||||
* Called upon forced client/server side disconnections,
|
||||
* this method ensures the manager stops tracking us and
|
||||
* that reconnections don't get triggered for this.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
destroy() {
|
||||
if (this.subs) {
|
||||
// clean subscriptions to avoid reconnections
|
||||
this.subs.forEach((subDestroy) => subDestroy());
|
||||
this.subs = undefined;
|
||||
}
|
||||
this.io["_destroy"](this);
|
||||
}
|
||||
/**
|
||||
* Disconnects the socket manually. In that case, the socket will not try to reconnect.
|
||||
*
|
||||
* If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* // console.log(reason); prints "io client disconnect"
|
||||
* });
|
||||
*
|
||||
* socket.disconnect();
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
disconnect() {
|
||||
if (this.connected) {
|
||||
debug("performing disconnect (%s)", this.nsp);
|
||||
this.packet({ type: socket_io_parser_1.PacketType.DISCONNECT });
|
||||
}
|
||||
// remove socket from pool
|
||||
this.destroy();
|
||||
if (this.connected) {
|
||||
// fire events
|
||||
this.onclose("io client disconnect");
|
||||
}
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Alias for {@link disconnect()}.
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
close() {
|
||||
return this.disconnect();
|
||||
}
|
||||
/**
|
||||
* Sets the compress flag.
|
||||
*
|
||||
* @example
|
||||
* socket.compress(false).emit("hello");
|
||||
*
|
||||
* @param compress - if `true`, compresses the sending data
|
||||
* @return self
|
||||
*/
|
||||
compress(compress) {
|
||||
this.flags.compress = compress;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
|
||||
* ready to send messages.
|
||||
*
|
||||
* @example
|
||||
* socket.volatile.emit("hello"); // the server may or may not receive it
|
||||
*
|
||||
* @returns self
|
||||
*/
|
||||
get volatile() {
|
||||
this.flags.volatile = true;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the callback will be called with an error when the
|
||||
* given number of milliseconds have elapsed without an acknowledgement from the server:
|
||||
*
|
||||
* @example
|
||||
* socket.timeout(5000).emit("my-event", (err) => {
|
||||
* if (err) {
|
||||
* // the server did not acknowledge the event in the given delay
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* @returns self
|
||||
*/
|
||||
timeout(timeout) {
|
||||
this.flags.timeout = timeout;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback.
|
||||
*
|
||||
* @example
|
||||
* socket.onAny((event, ...args) => {
|
||||
* console.log(`got ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
onAny(listener) {
|
||||
this._anyListeners = this._anyListeners || [];
|
||||
this._anyListeners.push(listener);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback. The listener is added to the beginning of the listeners array.
|
||||
*
|
||||
* @example
|
||||
* socket.prependAny((event, ...args) => {
|
||||
* console.log(`got event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
prependAny(listener) {
|
||||
this._anyListeners = this._anyListeners || [];
|
||||
this._anyListeners.unshift(listener);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Removes the listener that will be fired when any event is emitted.
|
||||
*
|
||||
* @example
|
||||
* const catchAllListener = (event, ...args) => {
|
||||
* console.log(`got event ${event}`);
|
||||
* }
|
||||
*
|
||||
* socket.onAny(catchAllListener);
|
||||
*
|
||||
* // remove a specific listener
|
||||
* socket.offAny(catchAllListener);
|
||||
*
|
||||
* // or remove all listeners
|
||||
* socket.offAny();
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
offAny(listener) {
|
||||
if (!this._anyListeners) {
|
||||
return this;
|
||||
}
|
||||
if (listener) {
|
||||
const listeners = this._anyListeners;
|
||||
for (let i = 0; i < listeners.length; i++) {
|
||||
if (listener === listeners[i]) {
|
||||
listeners.splice(i, 1);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
this._anyListeners = [];
|
||||
}
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
|
||||
* e.g. to remove listeners.
|
||||
*/
|
||||
listenersAny() {
|
||||
return this._anyListeners || [];
|
||||
}
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback.
|
||||
*
|
||||
* Note: acknowledgements sent to the server are not included.
|
||||
*
|
||||
* @example
|
||||
* socket.onAnyOutgoing((event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
onAnyOutgoing(listener) {
|
||||
this._anyOutgoingListeners = this._anyOutgoingListeners || [];
|
||||
this._anyOutgoingListeners.push(listener);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback. The listener is added to the beginning of the listeners array.
|
||||
*
|
||||
* Note: acknowledgements sent to the server are not included.
|
||||
*
|
||||
* @example
|
||||
* socket.prependAnyOutgoing((event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
prependAnyOutgoing(listener) {
|
||||
this._anyOutgoingListeners = this._anyOutgoingListeners || [];
|
||||
this._anyOutgoingListeners.unshift(listener);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Removes the listener that will be fired when any event is emitted.
|
||||
*
|
||||
* @example
|
||||
* const catchAllListener = (event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* }
|
||||
*
|
||||
* socket.onAnyOutgoing(catchAllListener);
|
||||
*
|
||||
* // remove a specific listener
|
||||
* socket.offAnyOutgoing(catchAllListener);
|
||||
*
|
||||
* // or remove all listeners
|
||||
* socket.offAnyOutgoing();
|
||||
*
|
||||
* @param [listener] - the catch-all listener (optional)
|
||||
*/
|
||||
offAnyOutgoing(listener) {
|
||||
if (!this._anyOutgoingListeners) {
|
||||
return this;
|
||||
}
|
||||
if (listener) {
|
||||
const listeners = this._anyOutgoingListeners;
|
||||
for (let i = 0; i < listeners.length; i++) {
|
||||
if (listener === listeners[i]) {
|
||||
listeners.splice(i, 1);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
this._anyOutgoingListeners = [];
|
||||
}
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
|
||||
* e.g. to remove listeners.
|
||||
*/
|
||||
listenersAnyOutgoing() {
|
||||
return this._anyOutgoingListeners || [];
|
||||
}
|
||||
/**
|
||||
* Notify the listeners for each packet sent
|
||||
*
|
||||
* @param packet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
notifyOutgoingListeners(packet) {
|
||||
if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
|
||||
const listeners = this._anyOutgoingListeners.slice();
|
||||
for (const listener of listeners) {
|
||||
listener.apply(this, packet.data);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.Socket = Socket;
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
type ParsedUrl = {
|
||||
source: string;
|
||||
protocol: string;
|
||||
authority: string;
|
||||
userInfo: string;
|
||||
user: string;
|
||||
password: string;
|
||||
host: string;
|
||||
port: string;
|
||||
relative: string;
|
||||
path: string;
|
||||
directory: string;
|
||||
file: string;
|
||||
query: string;
|
||||
anchor: string;
|
||||
pathNames: Array<string>;
|
||||
queryKey: {
|
||||
[key: string]: string;
|
||||
};
|
||||
id: string;
|
||||
href: string;
|
||||
};
|
||||
/**
|
||||
* URL parser.
|
||||
*
|
||||
* @param uri - url
|
||||
* @param path - the request path of the connection
|
||||
* @param loc - An object meant to mimic window.location.
|
||||
* Defaults to window.location.
|
||||
* @public
|
||||
*/
|
||||
export declare function url(uri: string | ParsedUrl, path?: string, loc?: Location): ParsedUrl;
|
||||
export {};
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.url = url;
|
||||
const engine_io_client_1 = require("engine.io-client");
|
||||
const debug_1 = __importDefault(require("debug")); // debug()
|
||||
const debug = (0, debug_1.default)("socket.io-client:url"); // debug()
|
||||
/**
|
||||
* URL parser.
|
||||
*
|
||||
* @param uri - url
|
||||
* @param path - the request path of the connection
|
||||
* @param loc - An object meant to mimic window.location.
|
||||
* Defaults to window.location.
|
||||
* @public
|
||||
*/
|
||||
function url(uri, path = "", loc) {
|
||||
let obj = uri;
|
||||
// default to window.location
|
||||
loc = loc || (typeof location !== "undefined" && location);
|
||||
if (null == uri)
|
||||
uri = loc.protocol + "//" + loc.host;
|
||||
// relative path support
|
||||
if (typeof uri === "string") {
|
||||
if ("/" === uri.charAt(0)) {
|
||||
if ("/" === uri.charAt(1)) {
|
||||
uri = loc.protocol + uri;
|
||||
}
|
||||
else {
|
||||
uri = loc.host + uri;
|
||||
}
|
||||
}
|
||||
if (!/^(https?|wss?):\/\//.test(uri)) {
|
||||
debug("protocol-less url %s", uri);
|
||||
if ("undefined" !== typeof loc) {
|
||||
uri = loc.protocol + "//" + uri;
|
||||
}
|
||||
else {
|
||||
uri = "https://" + uri;
|
||||
}
|
||||
}
|
||||
// parse
|
||||
debug("parse %s", uri);
|
||||
obj = (0, engine_io_client_1.parse)(uri);
|
||||
}
|
||||
// make sure we treat `localhost:80` and `localhost` equally
|
||||
if (!obj.port) {
|
||||
if (/^(http|ws)$/.test(obj.protocol)) {
|
||||
obj.port = "80";
|
||||
}
|
||||
else if (/^(http|ws)s$/.test(obj.protocol)) {
|
||||
obj.port = "443";
|
||||
}
|
||||
}
|
||||
obj.path = obj.path || "/";
|
||||
const ipv6 = obj.host.indexOf(":") !== -1;
|
||||
const host = ipv6 ? "[" + obj.host + "]" : obj.host;
|
||||
// define unique id
|
||||
obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
|
||||
// define href
|
||||
obj.href =
|
||||
obj.protocol +
|
||||
"://" +
|
||||
host +
|
||||
(loc && loc.port === obj.port ? "" : ":" + obj.port);
|
||||
return obj;
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { io } from "./index.js";
|
||||
export default io;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { io } from "./index.js";
|
||||
export default io;
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Initialize backoff timer with `opts`.
|
||||
*
|
||||
* - `min` initial timeout in milliseconds [100]
|
||||
* - `max` max timeout [10000]
|
||||
* - `jitter` [0]
|
||||
* - `factor` [2]
|
||||
*
|
||||
* @param {Object} opts
|
||||
* @api public
|
||||
*/
|
||||
export declare function Backoff(opts: any): void;
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Initialize backoff timer with `opts`.
|
||||
*
|
||||
* - `min` initial timeout in milliseconds [100]
|
||||
* - `max` max timeout [10000]
|
||||
* - `jitter` [0]
|
||||
* - `factor` [2]
|
||||
*
|
||||
* @param {Object} opts
|
||||
* @api public
|
||||
*/
|
||||
export function Backoff(opts) {
|
||||
opts = opts || {};
|
||||
this.ms = opts.min || 100;
|
||||
this.max = opts.max || 10000;
|
||||
this.factor = opts.factor || 2;
|
||||
this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
|
||||
this.attempts = 0;
|
||||
}
|
||||
/**
|
||||
* Return the backoff duration.
|
||||
*
|
||||
* @return {Number}
|
||||
* @api public
|
||||
*/
|
||||
Backoff.prototype.duration = function () {
|
||||
var ms = this.ms * Math.pow(this.factor, this.attempts++);
|
||||
if (this.jitter) {
|
||||
var rand = Math.random();
|
||||
var deviation = Math.floor(rand * this.jitter * ms);
|
||||
ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
|
||||
}
|
||||
return Math.min(ms, this.max) | 0;
|
||||
};
|
||||
/**
|
||||
* Reset the number of attempts.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
Backoff.prototype.reset = function () {
|
||||
this.attempts = 0;
|
||||
};
|
||||
/**
|
||||
* Set the minimum duration
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
Backoff.prototype.setMin = function (min) {
|
||||
this.ms = min;
|
||||
};
|
||||
/**
|
||||
* Set the maximum duration
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
Backoff.prototype.setMax = function (max) {
|
||||
this.max = max;
|
||||
};
|
||||
/**
|
||||
* Set the jitter
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
Backoff.prototype.setJitter = function (jitter) {
|
||||
this.jitter = jitter;
|
||||
};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
import { Manager, ManagerOptions } from "./manager.js";
|
||||
import { DisconnectDescription, Socket, SocketOptions } from "./socket.js";
|
||||
/**
|
||||
* Looks up an existing `Manager` for multiplexing.
|
||||
* If the user summons:
|
||||
*
|
||||
* `io('http://localhost/a');`
|
||||
* `io('http://localhost/b');`
|
||||
*
|
||||
* We reuse the existing instance based on same scheme/port/host,
|
||||
* and we initialize sockets for each namespace.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
declare function lookup(opts?: Partial<ManagerOptions & SocketOptions>): Socket;
|
||||
declare function lookup(uri?: string, opts?: Partial<ManagerOptions & SocketOptions>): Socket;
|
||||
/**
|
||||
* Protocol version.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export { protocol } from "socket.io-parser";
|
||||
/**
|
||||
* Expose constructors for standalone build.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export { DisconnectDescription, Manager, ManagerOptions, Socket, SocketOptions, lookup as io, lookup as connect, lookup as default, };
|
||||
export { Fetch, NodeXHR, XHR, NodeWebSocket, WebSocket, WebTransport, } from "engine.io-client";
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import { url } from "./url.js";
|
||||
import { Manager } from "./manager.js";
|
||||
import { Socket } from "./socket.js";
|
||||
import debugModule from "debug"; // debug()
|
||||
const debug = debugModule("socket.io-client"); // debug()
|
||||
/**
|
||||
* Managers cache.
|
||||
*/
|
||||
const cache = {};
|
||||
function lookup(uri, opts) {
|
||||
if (typeof uri === "object") {
|
||||
opts = uri;
|
||||
uri = undefined;
|
||||
}
|
||||
opts = opts || {};
|
||||
const parsed = url(uri, opts.path || "/socket.io");
|
||||
const source = parsed.source;
|
||||
const id = parsed.id;
|
||||
const path = parsed.path;
|
||||
const sameNamespace = cache[id] && path in cache[id]["nsps"];
|
||||
const newConnection = opts.forceNew ||
|
||||
opts["force new connection"] ||
|
||||
false === opts.multiplex ||
|
||||
sameNamespace;
|
||||
let io;
|
||||
if (newConnection) {
|
||||
debug("ignoring socket cache for %s", source);
|
||||
io = new Manager(source, opts);
|
||||
}
|
||||
else {
|
||||
if (!cache[id]) {
|
||||
debug("new io instance for %s", source);
|
||||
cache[id] = new Manager(source, opts);
|
||||
}
|
||||
io = cache[id];
|
||||
}
|
||||
if (parsed.query && !opts.query) {
|
||||
opts.query = parsed.queryKey;
|
||||
}
|
||||
return io.socket(parsed.path, opts);
|
||||
}
|
||||
// so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
|
||||
// namespace (e.g. `io.connect(...)`), for backward compatibility
|
||||
Object.assign(lookup, {
|
||||
Manager,
|
||||
Socket,
|
||||
io: lookup,
|
||||
connect: lookup,
|
||||
});
|
||||
/**
|
||||
* Protocol version.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export { protocol } from "socket.io-parser";
|
||||
/**
|
||||
* Expose constructors for standalone build.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export { Manager, Socket, lookup as io, lookup as connect, lookup as default, };
|
||||
export { Fetch, NodeXHR, XHR, NodeWebSocket, WebSocket, WebTransport, } from "engine.io-client";
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
import { Socket as Engine, SocketOptions as EngineOptions } from "engine.io-client";
|
||||
import { Socket, SocketOptions, DisconnectDescription } from "./socket.js";
|
||||
import { Packet } from "socket.io-parser";
|
||||
import { DefaultEventsMap, EventsMap, Emitter } from "@socket.io/component-emitter";
|
||||
export interface ManagerOptions extends EngineOptions {
|
||||
/**
|
||||
* Should we force a new Manager for this connection?
|
||||
* @default false
|
||||
*/
|
||||
forceNew: boolean;
|
||||
/**
|
||||
* Should we multiplex our connection (reuse existing Manager) ?
|
||||
* @default true
|
||||
*/
|
||||
multiplex: boolean;
|
||||
/**
|
||||
* The path to get our client file from, in the case of the server
|
||||
* serving it
|
||||
* @default '/socket.io'
|
||||
*/
|
||||
path: string;
|
||||
/**
|
||||
* Should we allow reconnections?
|
||||
* @default true
|
||||
*/
|
||||
reconnection: boolean;
|
||||
/**
|
||||
* How many reconnection attempts should we try?
|
||||
* @default Infinity
|
||||
*/
|
||||
reconnectionAttempts: number;
|
||||
/**
|
||||
* The time delay in milliseconds between reconnection attempts
|
||||
* @default 1000
|
||||
*/
|
||||
reconnectionDelay: number;
|
||||
/**
|
||||
* The max time delay in milliseconds between reconnection attempts
|
||||
* @default 5000
|
||||
*/
|
||||
reconnectionDelayMax: number;
|
||||
/**
|
||||
* Used in the exponential backoff jitter when reconnecting
|
||||
* @default 0.5
|
||||
*/
|
||||
randomizationFactor: number;
|
||||
/**
|
||||
* The timeout in milliseconds for our connection attempt
|
||||
* @default 20000
|
||||
*/
|
||||
timeout: number;
|
||||
/**
|
||||
* Should we automatically connect?
|
||||
* @default true
|
||||
*/
|
||||
autoConnect: boolean;
|
||||
/**
|
||||
* the parser to use. Defaults to an instance of the Parser that ships with socket.io.
|
||||
*/
|
||||
parser: any;
|
||||
}
|
||||
interface ManagerReservedEvents {
|
||||
open: () => void;
|
||||
error: (err: Error) => void;
|
||||
ping: () => void;
|
||||
packet: (packet: Packet) => void;
|
||||
close: (reason: string, description?: DisconnectDescription) => void;
|
||||
reconnect_failed: () => void;
|
||||
reconnect_attempt: (attempt: number) => void;
|
||||
reconnect_error: (err: Error) => void;
|
||||
reconnect: (attempt: number) => void;
|
||||
}
|
||||
export declare class Manager<ListenEvents extends EventsMap = DefaultEventsMap, EmitEvents extends EventsMap = ListenEvents> extends Emitter<{}, {}, ManagerReservedEvents> {
|
||||
/**
|
||||
* The Engine.IO client instance
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
engine: Engine;
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
_autoConnect: boolean;
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
_readyState: "opening" | "open" | "closed";
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
_reconnecting: boolean;
|
||||
private readonly uri;
|
||||
opts: Partial<ManagerOptions>;
|
||||
private nsps;
|
||||
private subs;
|
||||
private backoff;
|
||||
private setTimeoutFn;
|
||||
private clearTimeoutFn;
|
||||
private _reconnection;
|
||||
private _reconnectionAttempts;
|
||||
private _reconnectionDelay;
|
||||
private _randomizationFactor;
|
||||
private _reconnectionDelayMax;
|
||||
private _timeout;
|
||||
private encoder;
|
||||
private decoder;
|
||||
private skipReconnect;
|
||||
/**
|
||||
* `Manager` constructor.
|
||||
*
|
||||
* @param uri - engine instance or engine uri/opts
|
||||
* @param opts - options
|
||||
* @public
|
||||
*/
|
||||
constructor(opts: Partial<ManagerOptions>);
|
||||
constructor(uri?: string, opts?: Partial<ManagerOptions>);
|
||||
constructor(uri?: string | Partial<ManagerOptions>, opts?: Partial<ManagerOptions>);
|
||||
/**
|
||||
* Sets the `reconnection` config.
|
||||
*
|
||||
* @param {Boolean} v - true/false if it should automatically reconnect
|
||||
* @return {Manager} self or value
|
||||
* @public
|
||||
*/
|
||||
reconnection(v: boolean): this;
|
||||
reconnection(): boolean;
|
||||
reconnection(v?: boolean): this | boolean;
|
||||
/**
|
||||
* Sets the reconnection attempts config.
|
||||
*
|
||||
* @param {Number} v - max reconnection attempts before giving up
|
||||
* @return {Manager} self or value
|
||||
* @public
|
||||
*/
|
||||
reconnectionAttempts(v: number): this;
|
||||
reconnectionAttempts(): number;
|
||||
reconnectionAttempts(v?: number): this | number;
|
||||
/**
|
||||
* Sets the delay between reconnections.
|
||||
*
|
||||
* @param {Number} v - delay
|
||||
* @return {Manager} self or value
|
||||
* @public
|
||||
*/
|
||||
reconnectionDelay(v: number): this;
|
||||
reconnectionDelay(): number;
|
||||
reconnectionDelay(v?: number): this | number;
|
||||
/**
|
||||
* Sets the randomization factor
|
||||
*
|
||||
* @param v - the randomization factor
|
||||
* @return self or value
|
||||
* @public
|
||||
*/
|
||||
randomizationFactor(v: number): this;
|
||||
randomizationFactor(): number;
|
||||
randomizationFactor(v?: number): this | number;
|
||||
/**
|
||||
* Sets the maximum delay between reconnections.
|
||||
*
|
||||
* @param v - delay
|
||||
* @return self or value
|
||||
* @public
|
||||
*/
|
||||
reconnectionDelayMax(v: number): this;
|
||||
reconnectionDelayMax(): number;
|
||||
reconnectionDelayMax(v?: number): this | number;
|
||||
/**
|
||||
* Sets the connection timeout. `false` to disable
|
||||
*
|
||||
* @param v - connection timeout
|
||||
* @return self or value
|
||||
* @public
|
||||
*/
|
||||
timeout(v: number | boolean): this;
|
||||
timeout(): number | boolean;
|
||||
timeout(v?: number | boolean): this | number | boolean;
|
||||
/**
|
||||
* Starts trying to reconnect if reconnection is enabled and we have not
|
||||
* started reconnecting yet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private maybeReconnectOnOpen;
|
||||
/**
|
||||
* Sets the current transport `socket`.
|
||||
*
|
||||
* @param {Function} fn - optional, callback
|
||||
* @return self
|
||||
* @public
|
||||
*/
|
||||
open(fn?: (err?: Error) => void): this;
|
||||
/**
|
||||
* Alias for open()
|
||||
*
|
||||
* @return self
|
||||
* @public
|
||||
*/
|
||||
connect(fn?: (err?: Error) => void): this;
|
||||
/**
|
||||
* Called upon transport open.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onopen;
|
||||
/**
|
||||
* Called upon a ping.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onping;
|
||||
/**
|
||||
* Called with data.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private ondata;
|
||||
/**
|
||||
* Called when parser fully decodes a packet.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private ondecoded;
|
||||
/**
|
||||
* Called upon socket error.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onerror;
|
||||
/**
|
||||
* Creates a new socket for the given `nsp`.
|
||||
*
|
||||
* @return {Socket}
|
||||
* @public
|
||||
*/
|
||||
socket(nsp: string, opts?: Partial<SocketOptions>): Socket;
|
||||
/**
|
||||
* Called upon a socket close.
|
||||
*
|
||||
* @param socket
|
||||
* @private
|
||||
*/
|
||||
_destroy(socket: Socket): void;
|
||||
/**
|
||||
* Writes a packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
_packet(packet: Partial<Packet & {
|
||||
query: string;
|
||||
options: any;
|
||||
}>): void;
|
||||
/**
|
||||
* Clean up transport subscriptions and packet buffer.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private cleanup;
|
||||
/**
|
||||
* Close the current socket.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_close(): void;
|
||||
/**
|
||||
* Alias for close()
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private disconnect;
|
||||
/**
|
||||
* Called when:
|
||||
*
|
||||
* - the low-level engine is closed
|
||||
* - the parser encountered a badly formatted packet
|
||||
* - all sockets are disconnected
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onclose;
|
||||
/**
|
||||
* Attempt a reconnection.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private reconnect;
|
||||
/**
|
||||
* Called upon successful reconnect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onreconnect;
|
||||
}
|
||||
export {};
|
||||
+386
@@ -0,0 +1,386 @@
|
||||
import { Socket as Engine, installTimerFunctions, nextTick, } from "engine.io-client";
|
||||
import { Socket } from "./socket.js";
|
||||
import * as parser from "socket.io-parser";
|
||||
import { on } from "./on.js";
|
||||
import { Backoff } from "./contrib/backo2.js";
|
||||
import { Emitter, } from "@socket.io/component-emitter";
|
||||
import debugModule from "debug"; // debug()
|
||||
const debug = debugModule("socket.io-client:manager"); // debug()
|
||||
export class Manager extends Emitter {
|
||||
constructor(uri, opts) {
|
||||
var _a;
|
||||
super();
|
||||
this.nsps = {};
|
||||
this.subs = [];
|
||||
if (uri && "object" === typeof uri) {
|
||||
opts = uri;
|
||||
uri = undefined;
|
||||
}
|
||||
opts = opts || {};
|
||||
opts.path = opts.path || "/socket.io";
|
||||
this.opts = opts;
|
||||
installTimerFunctions(this, opts);
|
||||
this.reconnection(opts.reconnection !== false);
|
||||
this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
|
||||
this.reconnectionDelay(opts.reconnectionDelay || 1000);
|
||||
this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
|
||||
this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
|
||||
this.backoff = new Backoff({
|
||||
min: this.reconnectionDelay(),
|
||||
max: this.reconnectionDelayMax(),
|
||||
jitter: this.randomizationFactor(),
|
||||
});
|
||||
this.timeout(null == opts.timeout ? 20000 : opts.timeout);
|
||||
this._readyState = "closed";
|
||||
this.uri = uri;
|
||||
const _parser = opts.parser || parser;
|
||||
this.encoder = new _parser.Encoder();
|
||||
this.decoder = new _parser.Decoder();
|
||||
this._autoConnect = opts.autoConnect !== false;
|
||||
if (this._autoConnect)
|
||||
this.open();
|
||||
}
|
||||
reconnection(v) {
|
||||
if (!arguments.length)
|
||||
return this._reconnection;
|
||||
this._reconnection = !!v;
|
||||
if (!v) {
|
||||
this.skipReconnect = true;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
reconnectionAttempts(v) {
|
||||
if (v === undefined)
|
||||
return this._reconnectionAttempts;
|
||||
this._reconnectionAttempts = v;
|
||||
return this;
|
||||
}
|
||||
reconnectionDelay(v) {
|
||||
var _a;
|
||||
if (v === undefined)
|
||||
return this._reconnectionDelay;
|
||||
this._reconnectionDelay = v;
|
||||
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
|
||||
return this;
|
||||
}
|
||||
randomizationFactor(v) {
|
||||
var _a;
|
||||
if (v === undefined)
|
||||
return this._randomizationFactor;
|
||||
this._randomizationFactor = v;
|
||||
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
|
||||
return this;
|
||||
}
|
||||
reconnectionDelayMax(v) {
|
||||
var _a;
|
||||
if (v === undefined)
|
||||
return this._reconnectionDelayMax;
|
||||
this._reconnectionDelayMax = v;
|
||||
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
|
||||
return this;
|
||||
}
|
||||
timeout(v) {
|
||||
if (!arguments.length)
|
||||
return this._timeout;
|
||||
this._timeout = v;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Starts trying to reconnect if reconnection is enabled and we have not
|
||||
* started reconnecting yet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
maybeReconnectOnOpen() {
|
||||
// Only try to reconnect if it's the first time we're connecting
|
||||
if (!this._reconnecting &&
|
||||
this._reconnection &&
|
||||
this.backoff.attempts === 0) {
|
||||
// keeps reconnection from firing twice for the same reconnection loop
|
||||
this.reconnect();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Sets the current transport `socket`.
|
||||
*
|
||||
* @param {Function} fn - optional, callback
|
||||
* @return self
|
||||
* @public
|
||||
*/
|
||||
open(fn) {
|
||||
debug("readyState %s", this._readyState);
|
||||
if (~this._readyState.indexOf("open"))
|
||||
return this;
|
||||
debug("opening %s", this.uri);
|
||||
this.engine = new Engine(this.uri, this.opts);
|
||||
const socket = this.engine;
|
||||
const self = this;
|
||||
this._readyState = "opening";
|
||||
this.skipReconnect = false;
|
||||
// emit `open`
|
||||
const openSubDestroy = on(socket, "open", function () {
|
||||
self.onopen();
|
||||
fn && fn();
|
||||
});
|
||||
const onError = (err) => {
|
||||
debug("error");
|
||||
this.cleanup();
|
||||
this._readyState = "closed";
|
||||
this.emitReserved("error", err);
|
||||
if (fn) {
|
||||
fn(err);
|
||||
}
|
||||
else {
|
||||
// Only do this if there is no fn to handle the error
|
||||
this.maybeReconnectOnOpen();
|
||||
}
|
||||
};
|
||||
// emit `error`
|
||||
const errorSub = on(socket, "error", onError);
|
||||
if (false !== this._timeout) {
|
||||
const timeout = this._timeout;
|
||||
debug("connect attempt will timeout after %d", timeout);
|
||||
// set timer
|
||||
const timer = this.setTimeoutFn(() => {
|
||||
debug("connect attempt timed out after %d", timeout);
|
||||
openSubDestroy();
|
||||
onError(new Error("timeout"));
|
||||
socket.close();
|
||||
}, timeout);
|
||||
if (this.opts.autoUnref) {
|
||||
timer.unref();
|
||||
}
|
||||
this.subs.push(() => {
|
||||
this.clearTimeoutFn(timer);
|
||||
});
|
||||
}
|
||||
this.subs.push(openSubDestroy);
|
||||
this.subs.push(errorSub);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Alias for open()
|
||||
*
|
||||
* @return self
|
||||
* @public
|
||||
*/
|
||||
connect(fn) {
|
||||
return this.open(fn);
|
||||
}
|
||||
/**
|
||||
* Called upon transport open.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onopen() {
|
||||
debug("open");
|
||||
// clear old subs
|
||||
this.cleanup();
|
||||
// mark as open
|
||||
this._readyState = "open";
|
||||
this.emitReserved("open");
|
||||
// add new subs
|
||||
const socket = this.engine;
|
||||
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)),
|
||||
// @ts-ignore
|
||||
on(this.decoder, "decoded", this.ondecoded.bind(this)));
|
||||
}
|
||||
/**
|
||||
* Called upon a ping.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onping() {
|
||||
this.emitReserved("ping");
|
||||
}
|
||||
/**
|
||||
* Called with data.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
ondata(data) {
|
||||
try {
|
||||
this.decoder.add(data);
|
||||
}
|
||||
catch (e) {
|
||||
this.onclose("parse error", e);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Called when parser fully decodes a packet.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
ondecoded(packet) {
|
||||
// the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
|
||||
nextTick(() => {
|
||||
this.emitReserved("packet", packet);
|
||||
}, this.setTimeoutFn);
|
||||
}
|
||||
/**
|
||||
* Called upon socket error.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onerror(err) {
|
||||
debug("error", err);
|
||||
this.emitReserved("error", err);
|
||||
}
|
||||
/**
|
||||
* Creates a new socket for the given `nsp`.
|
||||
*
|
||||
* @return {Socket}
|
||||
* @public
|
||||
*/
|
||||
socket(nsp, opts) {
|
||||
let socket = this.nsps[nsp];
|
||||
if (!socket) {
|
||||
socket = new Socket(this, nsp, opts);
|
||||
this.nsps[nsp] = socket;
|
||||
}
|
||||
else if (this._autoConnect && !socket.active) {
|
||||
socket.connect();
|
||||
}
|
||||
return socket;
|
||||
}
|
||||
/**
|
||||
* Called upon a socket close.
|
||||
*
|
||||
* @param socket
|
||||
* @private
|
||||
*/
|
||||
_destroy(socket) {
|
||||
const nsps = Object.keys(this.nsps);
|
||||
for (const nsp of nsps) {
|
||||
const socket = this.nsps[nsp];
|
||||
if (socket.active) {
|
||||
debug("socket %s is still active, skipping close", nsp);
|
||||
return;
|
||||
}
|
||||
}
|
||||
this._close();
|
||||
}
|
||||
/**
|
||||
* Writes a packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
_packet(packet) {
|
||||
debug("writing packet %j", packet);
|
||||
const encodedPackets = this.encoder.encode(packet);
|
||||
for (let i = 0; i < encodedPackets.length; i++) {
|
||||
this.engine.write(encodedPackets[i], packet.options);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Clean up transport subscriptions and packet buffer.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
cleanup() {
|
||||
debug("cleanup");
|
||||
this.subs.forEach((subDestroy) => subDestroy());
|
||||
this.subs.length = 0;
|
||||
this.decoder.destroy();
|
||||
}
|
||||
/**
|
||||
* Close the current socket.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_close() {
|
||||
debug("disconnect");
|
||||
this.skipReconnect = true;
|
||||
this._reconnecting = false;
|
||||
this.onclose("forced close");
|
||||
}
|
||||
/**
|
||||
* Alias for close()
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
disconnect() {
|
||||
return this._close();
|
||||
}
|
||||
/**
|
||||
* Called when:
|
||||
*
|
||||
* - the low-level engine is closed
|
||||
* - the parser encountered a badly formatted packet
|
||||
* - all sockets are disconnected
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onclose(reason, description) {
|
||||
var _a;
|
||||
debug("closed due to %s", reason);
|
||||
this.cleanup();
|
||||
(_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
|
||||
this.backoff.reset();
|
||||
this._readyState = "closed";
|
||||
this.emitReserved("close", reason, description);
|
||||
if (this._reconnection && !this.skipReconnect) {
|
||||
this.reconnect();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Attempt a reconnection.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
reconnect() {
|
||||
if (this._reconnecting || this.skipReconnect)
|
||||
return this;
|
||||
const self = this;
|
||||
if (this.backoff.attempts >= this._reconnectionAttempts) {
|
||||
debug("reconnect failed");
|
||||
this.backoff.reset();
|
||||
this.emitReserved("reconnect_failed");
|
||||
this._reconnecting = false;
|
||||
}
|
||||
else {
|
||||
const delay = this.backoff.duration();
|
||||
debug("will wait %dms before reconnect attempt", delay);
|
||||
this._reconnecting = true;
|
||||
const timer = this.setTimeoutFn(() => {
|
||||
if (self.skipReconnect)
|
||||
return;
|
||||
debug("attempting reconnect");
|
||||
this.emitReserved("reconnect_attempt", self.backoff.attempts);
|
||||
// check again for the case socket closed in above events
|
||||
if (self.skipReconnect)
|
||||
return;
|
||||
self.open((err) => {
|
||||
if (err) {
|
||||
debug("reconnect attempt error");
|
||||
self._reconnecting = false;
|
||||
self.reconnect();
|
||||
this.emitReserved("reconnect_error", err);
|
||||
}
|
||||
else {
|
||||
debug("reconnect success");
|
||||
self.onreconnect();
|
||||
}
|
||||
});
|
||||
}, delay);
|
||||
if (this.opts.autoUnref) {
|
||||
timer.unref();
|
||||
}
|
||||
this.subs.push(() => {
|
||||
this.clearTimeoutFn(timer);
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Called upon successful reconnect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onreconnect() {
|
||||
const attempt = this.backoff.attempts;
|
||||
this._reconnecting = false;
|
||||
this.backoff.reset();
|
||||
this.emitReserved("reconnect", attempt);
|
||||
}
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { Emitter } from "@socket.io/component-emitter";
|
||||
export declare function on(obj: Emitter<any, any>, ev: string, fn: (err?: any) => any): VoidFunction;
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
export function on(obj, ev, fn) {
|
||||
obj.on(ev, fn);
|
||||
return function subDestroy() {
|
||||
obj.off(ev, fn);
|
||||
};
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "socket.io-client",
|
||||
"version": "4.8.3",
|
||||
"type": "module"
|
||||
}
|
||||
+593
@@ -0,0 +1,593 @@
|
||||
import { Packet } from "socket.io-parser";
|
||||
import { Manager } from "./manager.js";
|
||||
import { DefaultEventsMap, EventNames, EventParams, EventsMap, Emitter } from "@socket.io/component-emitter";
|
||||
type PrependTimeoutError<T extends any[]> = {
|
||||
[K in keyof T]: T[K] extends (...args: infer Params) => infer Result ? (err: Error, ...args: Params) => Result : T[K];
|
||||
};
|
||||
/**
|
||||
* Utility type to decorate the acknowledgement callbacks with a timeout error.
|
||||
*
|
||||
* This is needed because the timeout() flag breaks the symmetry between the sender and the receiver:
|
||||
*
|
||||
* @example
|
||||
* interface Events {
|
||||
* "my-event": (val: string) => void;
|
||||
* }
|
||||
*
|
||||
* socket.on("my-event", (cb) => {
|
||||
* cb("123"); // one single argument here
|
||||
* });
|
||||
*
|
||||
* socket.timeout(1000).emit("my-event", (err, val) => {
|
||||
* // two arguments there (the "err" argument is not properly typed)
|
||||
* });
|
||||
*
|
||||
*/
|
||||
export type DecorateAcknowledgements<E> = {
|
||||
[K in keyof E]: E[K] extends (...args: infer Params) => infer Result ? (...args: PrependTimeoutError<Params>) => Result : E[K];
|
||||
};
|
||||
export type Last<T extends any[]> = T extends [...infer H, infer L] ? L : any;
|
||||
export type AllButLast<T extends any[]> = T extends [...infer H, infer L] ? H : any[];
|
||||
export type FirstArg<T> = T extends (arg: infer Param) => infer Result ? Param : any;
|
||||
export interface SocketOptions {
|
||||
/**
|
||||
* the authentication payload sent when connecting to the Namespace
|
||||
*/
|
||||
auth?: {
|
||||
[key: string]: any;
|
||||
} | ((cb: (data: object) => void) => void);
|
||||
/**
|
||||
* The maximum number of retries. Above the limit, the packet will be discarded.
|
||||
*
|
||||
* Using `Infinity` means the delivery guarantee is "at-least-once" (instead of "at-most-once" by default), but a
|
||||
* smaller value like 10 should be sufficient in practice.
|
||||
*/
|
||||
retries?: number;
|
||||
/**
|
||||
* The default timeout in milliseconds used when waiting for an acknowledgement.
|
||||
*/
|
||||
ackTimeout?: number;
|
||||
}
|
||||
export type DisconnectDescription = Error | {
|
||||
description: string;
|
||||
context?: unknown;
|
||||
};
|
||||
interface SocketReservedEvents {
|
||||
connect: () => void;
|
||||
connect_error: (err: Error) => void;
|
||||
disconnect: (reason: Socket.DisconnectReason, description?: DisconnectDescription) => void;
|
||||
}
|
||||
/**
|
||||
* A Socket is the fundamental class for interacting with the server.
|
||||
*
|
||||
* A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log("connected");
|
||||
* });
|
||||
*
|
||||
* // send an event to the server
|
||||
* socket.emit("foo", "bar");
|
||||
*
|
||||
* socket.on("foobar", () => {
|
||||
* // an event was received from the server
|
||||
* });
|
||||
*
|
||||
* // upon disconnection
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* console.log(`disconnected due to ${reason}`);
|
||||
* });
|
||||
*/
|
||||
export declare class Socket<ListenEvents extends EventsMap = DefaultEventsMap, EmitEvents extends EventsMap = ListenEvents> extends Emitter<ListenEvents, EmitEvents, SocketReservedEvents> {
|
||||
readonly io: Manager<ListenEvents, EmitEvents>;
|
||||
/**
|
||||
* A unique identifier for the session. `undefined` when the socket is not connected.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* console.log(socket.id); // undefined
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log(socket.id); // "G5p5..."
|
||||
* });
|
||||
*/
|
||||
id: string | undefined;
|
||||
/**
|
||||
* The session ID used for connection state recovery, which must not be shared (unlike {@link id}).
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private _pid;
|
||||
/**
|
||||
* The offset of the last received packet, which will be sent upon reconnection to allow for the recovery of the connection state.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private _lastOffset;
|
||||
/**
|
||||
* Whether the socket is currently connected to the server.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log(socket.connected); // true
|
||||
* });
|
||||
*
|
||||
* socket.on("disconnect", () => {
|
||||
* console.log(socket.connected); // false
|
||||
* });
|
||||
*/
|
||||
connected: boolean;
|
||||
/**
|
||||
* Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
|
||||
* be transmitted by the server.
|
||||
*/
|
||||
recovered: boolean;
|
||||
/**
|
||||
* Credentials that are sent when accessing a namespace.
|
||||
*
|
||||
* @example
|
||||
* const socket = io({
|
||||
* auth: {
|
||||
* token: "abcd"
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* // or with a function
|
||||
* const socket = io({
|
||||
* auth: (cb) => {
|
||||
* cb({ token: localStorage.token })
|
||||
* }
|
||||
* });
|
||||
*/
|
||||
auth: {
|
||||
[key: string]: any;
|
||||
} | ((cb: (data: object) => void) => void);
|
||||
/**
|
||||
* Buffer for packets received before the CONNECT packet
|
||||
*/
|
||||
receiveBuffer: Array<ReadonlyArray<any>>;
|
||||
/**
|
||||
* Buffer for packets that will be sent once the socket is connected
|
||||
*/
|
||||
sendBuffer: Array<Packet>;
|
||||
/**
|
||||
* The queue of packets to be sent with retry in case of failure.
|
||||
*
|
||||
* Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
|
||||
* @private
|
||||
*/
|
||||
private _queue;
|
||||
/**
|
||||
* A sequence to generate the ID of the {@link QueuedPacket}.
|
||||
* @private
|
||||
*/
|
||||
private _queueSeq;
|
||||
private readonly nsp;
|
||||
private readonly _opts;
|
||||
private ids;
|
||||
/**
|
||||
* A map containing acknowledgement handlers.
|
||||
*
|
||||
* The `withError` attribute is used to differentiate handlers that accept an error as first argument:
|
||||
*
|
||||
* - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
|
||||
* - `socket.timeout(5000).emit("test", (err, value) => { ... })`
|
||||
* - `const value = await socket.emitWithAck("test")`
|
||||
*
|
||||
* From those that don't:
|
||||
*
|
||||
* - `socket.emit("test", (value) => { ... });`
|
||||
*
|
||||
* In the first case, the handlers will be called with an error when:
|
||||
*
|
||||
* - the timeout is reached
|
||||
* - the socket gets disconnected
|
||||
*
|
||||
* In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
|
||||
* an acknowledgement from the server.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private acks;
|
||||
private flags;
|
||||
private subs?;
|
||||
private _anyListeners;
|
||||
private _anyOutgoingListeners;
|
||||
/**
|
||||
* `Socket` constructor.
|
||||
*/
|
||||
constructor(io: Manager, nsp: string, opts?: Partial<SocketOptions>);
|
||||
/**
|
||||
* Whether the socket is currently disconnected
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log(socket.disconnected); // false
|
||||
* });
|
||||
*
|
||||
* socket.on("disconnect", () => {
|
||||
* console.log(socket.disconnected); // true
|
||||
* });
|
||||
*/
|
||||
get disconnected(): boolean;
|
||||
/**
|
||||
* Subscribe to open, close and packet events
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private subEvents;
|
||||
/**
|
||||
* Whether the Socket will try to reconnect when its Manager connects or reconnects.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* console.log(socket.active); // true
|
||||
*
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* if (reason === "io server disconnect") {
|
||||
* // the disconnection was initiated by the server, you need to manually reconnect
|
||||
* console.log(socket.active); // false
|
||||
* }
|
||||
* // else the socket will automatically try to reconnect
|
||||
* console.log(socket.active); // true
|
||||
* });
|
||||
*/
|
||||
get active(): boolean;
|
||||
/**
|
||||
* "Opens" the socket.
|
||||
*
|
||||
* @example
|
||||
* const socket = io({
|
||||
* autoConnect: false
|
||||
* });
|
||||
*
|
||||
* socket.connect();
|
||||
*/
|
||||
connect(): this;
|
||||
/**
|
||||
* Alias for {@link connect()}.
|
||||
*/
|
||||
open(): this;
|
||||
/**
|
||||
* Sends a `message` event.
|
||||
*
|
||||
* This method mimics the WebSocket.send() method.
|
||||
*
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
|
||||
*
|
||||
* @example
|
||||
* socket.send("hello");
|
||||
*
|
||||
* // this is equivalent to
|
||||
* socket.emit("message", "hello");
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
send(...args: any[]): this;
|
||||
/**
|
||||
* Override `emit`.
|
||||
* If the event is in `events`, it's emitted normally.
|
||||
*
|
||||
* @example
|
||||
* socket.emit("hello", "world");
|
||||
*
|
||||
* // all serializable datastructures are supported (no need to call JSON.stringify)
|
||||
* socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
|
||||
*
|
||||
* // with an acknowledgement from the server
|
||||
* socket.emit("hello", "world", (val) => {
|
||||
* // ...
|
||||
* });
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
emit<Ev extends EventNames<EmitEvents>>(ev: Ev, ...args: EventParams<EmitEvents, Ev>): this;
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
private _registerAckCallback;
|
||||
/**
|
||||
* Emits an event and waits for an acknowledgement
|
||||
*
|
||||
* @example
|
||||
* // without timeout
|
||||
* const response = await socket.emitWithAck("hello", "world");
|
||||
*
|
||||
* // with a specific timeout
|
||||
* try {
|
||||
* const response = await socket.timeout(1000).emitWithAck("hello", "world");
|
||||
* } catch (err) {
|
||||
* // the server did not acknowledge the event in the given delay
|
||||
* }
|
||||
*
|
||||
* @return a Promise that will be fulfilled when the server acknowledges the event
|
||||
*/
|
||||
emitWithAck<Ev extends EventNames<EmitEvents>>(ev: Ev, ...args: AllButLast<EventParams<EmitEvents, Ev>>): Promise<FirstArg<Last<EventParams<EmitEvents, Ev>>>>;
|
||||
/**
|
||||
* Add the packet to the queue.
|
||||
* @param args
|
||||
* @private
|
||||
*/
|
||||
private _addToQueue;
|
||||
/**
|
||||
* Send the first packet of the queue, and wait for an acknowledgement from the server.
|
||||
* @param force - whether to resend a packet that has not been acknowledged yet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private _drainQueue;
|
||||
/**
|
||||
* Sends a packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
private packet;
|
||||
/**
|
||||
* Called upon engine `open`.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onopen;
|
||||
/**
|
||||
* Sends a CONNECT packet to initiate the Socket.IO session.
|
||||
*
|
||||
* @param data
|
||||
* @private
|
||||
*/
|
||||
private _sendConnectPacket;
|
||||
/**
|
||||
* Called upon engine or manager `error`.
|
||||
*
|
||||
* @param err
|
||||
* @private
|
||||
*/
|
||||
private onerror;
|
||||
/**
|
||||
* Called upon engine `close`.
|
||||
*
|
||||
* @param reason
|
||||
* @param description
|
||||
* @private
|
||||
*/
|
||||
private onclose;
|
||||
/**
|
||||
* Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
|
||||
* the server.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private _clearAcks;
|
||||
/**
|
||||
* Called with socket packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
private onpacket;
|
||||
/**
|
||||
* Called upon a server event.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
private onevent;
|
||||
private emitEvent;
|
||||
/**
|
||||
* Produces an ack callback to emit with an event.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private ack;
|
||||
/**
|
||||
* Called upon a server acknowledgement.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
private onack;
|
||||
/**
|
||||
* Called upon server connect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onconnect;
|
||||
/**
|
||||
* Emit buffered events (received and emitted).
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private emitBuffered;
|
||||
/**
|
||||
* Called upon server disconnect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private ondisconnect;
|
||||
/**
|
||||
* Called upon forced client/server side disconnections,
|
||||
* this method ensures the manager stops tracking us and
|
||||
* that reconnections don't get triggered for this.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private destroy;
|
||||
/**
|
||||
* Disconnects the socket manually. In that case, the socket will not try to reconnect.
|
||||
*
|
||||
* If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* // console.log(reason); prints "io client disconnect"
|
||||
* });
|
||||
*
|
||||
* socket.disconnect();
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
disconnect(): this;
|
||||
/**
|
||||
* Alias for {@link disconnect()}.
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
close(): this;
|
||||
/**
|
||||
* Sets the compress flag.
|
||||
*
|
||||
* @example
|
||||
* socket.compress(false).emit("hello");
|
||||
*
|
||||
* @param compress - if `true`, compresses the sending data
|
||||
* @return self
|
||||
*/
|
||||
compress(compress: boolean): this;
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
|
||||
* ready to send messages.
|
||||
*
|
||||
* @example
|
||||
* socket.volatile.emit("hello"); // the server may or may not receive it
|
||||
*
|
||||
* @returns self
|
||||
*/
|
||||
get volatile(): this;
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the callback will be called with an error when the
|
||||
* given number of milliseconds have elapsed without an acknowledgement from the server:
|
||||
*
|
||||
* @example
|
||||
* socket.timeout(5000).emit("my-event", (err) => {
|
||||
* if (err) {
|
||||
* // the server did not acknowledge the event in the given delay
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* @returns self
|
||||
*/
|
||||
timeout(timeout: number): Socket<ListenEvents, DecorateAcknowledgements<EmitEvents>>;
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback.
|
||||
*
|
||||
* @example
|
||||
* socket.onAny((event, ...args) => {
|
||||
* console.log(`got ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
onAny(listener: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback. The listener is added to the beginning of the listeners array.
|
||||
*
|
||||
* @example
|
||||
* socket.prependAny((event, ...args) => {
|
||||
* console.log(`got event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
prependAny(listener: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Removes the listener that will be fired when any event is emitted.
|
||||
*
|
||||
* @example
|
||||
* const catchAllListener = (event, ...args) => {
|
||||
* console.log(`got event ${event}`);
|
||||
* }
|
||||
*
|
||||
* socket.onAny(catchAllListener);
|
||||
*
|
||||
* // remove a specific listener
|
||||
* socket.offAny(catchAllListener);
|
||||
*
|
||||
* // or remove all listeners
|
||||
* socket.offAny();
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
offAny(listener?: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
|
||||
* e.g. to remove listeners.
|
||||
*/
|
||||
listenersAny(): ((...args: any[]) => void)[];
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback.
|
||||
*
|
||||
* Note: acknowledgements sent to the server are not included.
|
||||
*
|
||||
* @example
|
||||
* socket.onAnyOutgoing((event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
onAnyOutgoing(listener: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback. The listener is added to the beginning of the listeners array.
|
||||
*
|
||||
* Note: acknowledgements sent to the server are not included.
|
||||
*
|
||||
* @example
|
||||
* socket.prependAnyOutgoing((event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
prependAnyOutgoing(listener: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Removes the listener that will be fired when any event is emitted.
|
||||
*
|
||||
* @example
|
||||
* const catchAllListener = (event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* }
|
||||
*
|
||||
* socket.onAnyOutgoing(catchAllListener);
|
||||
*
|
||||
* // remove a specific listener
|
||||
* socket.offAnyOutgoing(catchAllListener);
|
||||
*
|
||||
* // or remove all listeners
|
||||
* socket.offAnyOutgoing();
|
||||
*
|
||||
* @param [listener] - the catch-all listener (optional)
|
||||
*/
|
||||
offAnyOutgoing(listener?: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
|
||||
* e.g. to remove listeners.
|
||||
*/
|
||||
listenersAnyOutgoing(): ((...args: any[]) => void)[];
|
||||
/**
|
||||
* Notify the listeners for each packet sent
|
||||
*
|
||||
* @param packet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private notifyOutgoingListeners;
|
||||
}
|
||||
export declare namespace Socket {
|
||||
type DisconnectReason = "io server disconnect" | "io client disconnect" | "ping timeout" | "transport close" | "transport error" | "parse error";
|
||||
}
|
||||
export {};
|
||||
+902
@@ -0,0 +1,902 @@
|
||||
import { PacketType } from "socket.io-parser";
|
||||
import { on } from "./on.js";
|
||||
import { Emitter, } from "@socket.io/component-emitter";
|
||||
import debugModule from "debug"; // debug()
|
||||
const debug = debugModule("socket.io-client:socket"); // debug()
|
||||
/**
|
||||
* Internal events.
|
||||
* These events can't be emitted by the user.
|
||||
*/
|
||||
const RESERVED_EVENTS = Object.freeze({
|
||||
connect: 1,
|
||||
connect_error: 1,
|
||||
disconnect: 1,
|
||||
disconnecting: 1,
|
||||
// EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
|
||||
newListener: 1,
|
||||
removeListener: 1,
|
||||
});
|
||||
/**
|
||||
* A Socket is the fundamental class for interacting with the server.
|
||||
*
|
||||
* A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log("connected");
|
||||
* });
|
||||
*
|
||||
* // send an event to the server
|
||||
* socket.emit("foo", "bar");
|
||||
*
|
||||
* socket.on("foobar", () => {
|
||||
* // an event was received from the server
|
||||
* });
|
||||
*
|
||||
* // upon disconnection
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* console.log(`disconnected due to ${reason}`);
|
||||
* });
|
||||
*/
|
||||
export class Socket extends Emitter {
|
||||
/**
|
||||
* `Socket` constructor.
|
||||
*/
|
||||
constructor(io, nsp, opts) {
|
||||
super();
|
||||
/**
|
||||
* Whether the socket is currently connected to the server.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log(socket.connected); // true
|
||||
* });
|
||||
*
|
||||
* socket.on("disconnect", () => {
|
||||
* console.log(socket.connected); // false
|
||||
* });
|
||||
*/
|
||||
this.connected = false;
|
||||
/**
|
||||
* Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
|
||||
* be transmitted by the server.
|
||||
*/
|
||||
this.recovered = false;
|
||||
/**
|
||||
* Buffer for packets received before the CONNECT packet
|
||||
*/
|
||||
this.receiveBuffer = [];
|
||||
/**
|
||||
* Buffer for packets that will be sent once the socket is connected
|
||||
*/
|
||||
this.sendBuffer = [];
|
||||
/**
|
||||
* The queue of packets to be sent with retry in case of failure.
|
||||
*
|
||||
* Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
|
||||
* @private
|
||||
*/
|
||||
this._queue = [];
|
||||
/**
|
||||
* A sequence to generate the ID of the {@link QueuedPacket}.
|
||||
* @private
|
||||
*/
|
||||
this._queueSeq = 0;
|
||||
this.ids = 0;
|
||||
/**
|
||||
* A map containing acknowledgement handlers.
|
||||
*
|
||||
* The `withError` attribute is used to differentiate handlers that accept an error as first argument:
|
||||
*
|
||||
* - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
|
||||
* - `socket.timeout(5000).emit("test", (err, value) => { ... })`
|
||||
* - `const value = await socket.emitWithAck("test")`
|
||||
*
|
||||
* From those that don't:
|
||||
*
|
||||
* - `socket.emit("test", (value) => { ... });`
|
||||
*
|
||||
* In the first case, the handlers will be called with an error when:
|
||||
*
|
||||
* - the timeout is reached
|
||||
* - the socket gets disconnected
|
||||
*
|
||||
* In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
|
||||
* an acknowledgement from the server.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
this.acks = {};
|
||||
this.flags = {};
|
||||
this.io = io;
|
||||
this.nsp = nsp;
|
||||
if (opts && opts.auth) {
|
||||
this.auth = opts.auth;
|
||||
}
|
||||
this._opts = Object.assign({}, opts);
|
||||
if (this.io._autoConnect)
|
||||
this.open();
|
||||
}
|
||||
/**
|
||||
* Whether the socket is currently disconnected
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log(socket.disconnected); // false
|
||||
* });
|
||||
*
|
||||
* socket.on("disconnect", () => {
|
||||
* console.log(socket.disconnected); // true
|
||||
* });
|
||||
*/
|
||||
get disconnected() {
|
||||
return !this.connected;
|
||||
}
|
||||
/**
|
||||
* Subscribe to open, close and packet events
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
subEvents() {
|
||||
if (this.subs)
|
||||
return;
|
||||
const io = this.io;
|
||||
this.subs = [
|
||||
on(io, "open", this.onopen.bind(this)),
|
||||
on(io, "packet", this.onpacket.bind(this)),
|
||||
on(io, "error", this.onerror.bind(this)),
|
||||
on(io, "close", this.onclose.bind(this)),
|
||||
];
|
||||
}
|
||||
/**
|
||||
* Whether the Socket will try to reconnect when its Manager connects or reconnects.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* console.log(socket.active); // true
|
||||
*
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* if (reason === "io server disconnect") {
|
||||
* // the disconnection was initiated by the server, you need to manually reconnect
|
||||
* console.log(socket.active); // false
|
||||
* }
|
||||
* // else the socket will automatically try to reconnect
|
||||
* console.log(socket.active); // true
|
||||
* });
|
||||
*/
|
||||
get active() {
|
||||
return !!this.subs;
|
||||
}
|
||||
/**
|
||||
* "Opens" the socket.
|
||||
*
|
||||
* @example
|
||||
* const socket = io({
|
||||
* autoConnect: false
|
||||
* });
|
||||
*
|
||||
* socket.connect();
|
||||
*/
|
||||
connect() {
|
||||
if (this.connected)
|
||||
return this;
|
||||
this.subEvents();
|
||||
if (!this.io["_reconnecting"])
|
||||
this.io.open(); // ensure open
|
||||
if ("open" === this.io._readyState)
|
||||
this.onopen();
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Alias for {@link connect()}.
|
||||
*/
|
||||
open() {
|
||||
return this.connect();
|
||||
}
|
||||
/**
|
||||
* Sends a `message` event.
|
||||
*
|
||||
* This method mimics the WebSocket.send() method.
|
||||
*
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
|
||||
*
|
||||
* @example
|
||||
* socket.send("hello");
|
||||
*
|
||||
* // this is equivalent to
|
||||
* socket.emit("message", "hello");
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
send(...args) {
|
||||
args.unshift("message");
|
||||
this.emit.apply(this, args);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Override `emit`.
|
||||
* If the event is in `events`, it's emitted normally.
|
||||
*
|
||||
* @example
|
||||
* socket.emit("hello", "world");
|
||||
*
|
||||
* // all serializable datastructures are supported (no need to call JSON.stringify)
|
||||
* socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
|
||||
*
|
||||
* // with an acknowledgement from the server
|
||||
* socket.emit("hello", "world", (val) => {
|
||||
* // ...
|
||||
* });
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
emit(ev, ...args) {
|
||||
var _a, _b, _c;
|
||||
if (RESERVED_EVENTS.hasOwnProperty(ev)) {
|
||||
throw new Error('"' + ev.toString() + '" is a reserved event name');
|
||||
}
|
||||
args.unshift(ev);
|
||||
if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
|
||||
this._addToQueue(args);
|
||||
return this;
|
||||
}
|
||||
const packet = {
|
||||
type: PacketType.EVENT,
|
||||
data: args,
|
||||
};
|
||||
packet.options = {};
|
||||
packet.options.compress = this.flags.compress !== false;
|
||||
// event ack callback
|
||||
if ("function" === typeof args[args.length - 1]) {
|
||||
const id = this.ids++;
|
||||
debug("emitting packet with ack id %d", id);
|
||||
const ack = args.pop();
|
||||
this._registerAckCallback(id, ack);
|
||||
packet.id = id;
|
||||
}
|
||||
const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
|
||||
const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
|
||||
const discardPacket = this.flags.volatile && !isTransportWritable;
|
||||
if (discardPacket) {
|
||||
debug("discard packet as the transport is not currently writable");
|
||||
}
|
||||
else if (isConnected) {
|
||||
this.notifyOutgoingListeners(packet);
|
||||
this.packet(packet);
|
||||
}
|
||||
else {
|
||||
this.sendBuffer.push(packet);
|
||||
}
|
||||
this.flags = {};
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
_registerAckCallback(id, ack) {
|
||||
var _a;
|
||||
const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
|
||||
if (timeout === undefined) {
|
||||
this.acks[id] = ack;
|
||||
return;
|
||||
}
|
||||
// @ts-ignore
|
||||
const timer = this.io.setTimeoutFn(() => {
|
||||
delete this.acks[id];
|
||||
for (let i = 0; i < this.sendBuffer.length; i++) {
|
||||
if (this.sendBuffer[i].id === id) {
|
||||
debug("removing packet with ack id %d from the buffer", id);
|
||||
this.sendBuffer.splice(i, 1);
|
||||
}
|
||||
}
|
||||
debug("event with ack id %d has timed out after %d ms", id, timeout);
|
||||
ack.call(this, new Error("operation has timed out"));
|
||||
}, timeout);
|
||||
const fn = (...args) => {
|
||||
// @ts-ignore
|
||||
this.io.clearTimeoutFn(timer);
|
||||
ack.apply(this, args);
|
||||
};
|
||||
fn.withError = true;
|
||||
this.acks[id] = fn;
|
||||
}
|
||||
/**
|
||||
* Emits an event and waits for an acknowledgement
|
||||
*
|
||||
* @example
|
||||
* // without timeout
|
||||
* const response = await socket.emitWithAck("hello", "world");
|
||||
*
|
||||
* // with a specific timeout
|
||||
* try {
|
||||
* const response = await socket.timeout(1000).emitWithAck("hello", "world");
|
||||
* } catch (err) {
|
||||
* // the server did not acknowledge the event in the given delay
|
||||
* }
|
||||
*
|
||||
* @return a Promise that will be fulfilled when the server acknowledges the event
|
||||
*/
|
||||
emitWithAck(ev, ...args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const fn = (arg1, arg2) => {
|
||||
return arg1 ? reject(arg1) : resolve(arg2);
|
||||
};
|
||||
fn.withError = true;
|
||||
args.push(fn);
|
||||
this.emit(ev, ...args);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Add the packet to the queue.
|
||||
* @param args
|
||||
* @private
|
||||
*/
|
||||
_addToQueue(args) {
|
||||
let ack;
|
||||
if (typeof args[args.length - 1] === "function") {
|
||||
ack = args.pop();
|
||||
}
|
||||
const packet = {
|
||||
id: this._queueSeq++,
|
||||
tryCount: 0,
|
||||
pending: false,
|
||||
args,
|
||||
flags: Object.assign({ fromQueue: true }, this.flags),
|
||||
};
|
||||
args.push((err, ...responseArgs) => {
|
||||
if (packet !== this._queue[0]) {
|
||||
return debug("packet [%d] already acknowledged", packet.id);
|
||||
}
|
||||
const hasError = err !== null;
|
||||
if (hasError) {
|
||||
if (packet.tryCount > this._opts.retries) {
|
||||
debug("packet [%d] is discarded after %d tries", packet.id, packet.tryCount);
|
||||
this._queue.shift();
|
||||
if (ack) {
|
||||
ack(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
debug("packet [%d] was successfully sent", packet.id);
|
||||
this._queue.shift();
|
||||
if (ack) {
|
||||
ack(null, ...responseArgs);
|
||||
}
|
||||
}
|
||||
packet.pending = false;
|
||||
return this._drainQueue();
|
||||
});
|
||||
this._queue.push(packet);
|
||||
this._drainQueue();
|
||||
}
|
||||
/**
|
||||
* Send the first packet of the queue, and wait for an acknowledgement from the server.
|
||||
* @param force - whether to resend a packet that has not been acknowledged yet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_drainQueue(force = false) {
|
||||
debug("draining queue");
|
||||
if (!this.connected || this._queue.length === 0) {
|
||||
return;
|
||||
}
|
||||
const packet = this._queue[0];
|
||||
if (packet.pending && !force) {
|
||||
debug("packet [%d] has already been sent and is waiting for an ack", packet.id);
|
||||
return;
|
||||
}
|
||||
packet.pending = true;
|
||||
packet.tryCount++;
|
||||
debug("sending packet [%d] (try n°%d)", packet.id, packet.tryCount);
|
||||
this.flags = packet.flags;
|
||||
this.emit.apply(this, packet.args);
|
||||
}
|
||||
/**
|
||||
* Sends a packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
packet(packet) {
|
||||
packet.nsp = this.nsp;
|
||||
this.io._packet(packet);
|
||||
}
|
||||
/**
|
||||
* Called upon engine `open`.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onopen() {
|
||||
debug("transport is open - connecting");
|
||||
if (typeof this.auth == "function") {
|
||||
this.auth((data) => {
|
||||
this._sendConnectPacket(data);
|
||||
});
|
||||
}
|
||||
else {
|
||||
this._sendConnectPacket(this.auth);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Sends a CONNECT packet to initiate the Socket.IO session.
|
||||
*
|
||||
* @param data
|
||||
* @private
|
||||
*/
|
||||
_sendConnectPacket(data) {
|
||||
this.packet({
|
||||
type: PacketType.CONNECT,
|
||||
data: this._pid
|
||||
? Object.assign({ pid: this._pid, offset: this._lastOffset }, data)
|
||||
: data,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Called upon engine or manager `error`.
|
||||
*
|
||||
* @param err
|
||||
* @private
|
||||
*/
|
||||
onerror(err) {
|
||||
if (!this.connected) {
|
||||
this.emitReserved("connect_error", err);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Called upon engine `close`.
|
||||
*
|
||||
* @param reason
|
||||
* @param description
|
||||
* @private
|
||||
*/
|
||||
onclose(reason, description) {
|
||||
debug("close (%s)", reason);
|
||||
this.connected = false;
|
||||
delete this.id;
|
||||
this.emitReserved("disconnect", reason, description);
|
||||
this._clearAcks();
|
||||
}
|
||||
/**
|
||||
* Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
|
||||
* the server.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_clearAcks() {
|
||||
Object.keys(this.acks).forEach((id) => {
|
||||
const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
|
||||
if (!isBuffered) {
|
||||
// note: handlers that do not accept an error as first argument are ignored here
|
||||
const ack = this.acks[id];
|
||||
delete this.acks[id];
|
||||
if (ack.withError) {
|
||||
ack.call(this, new Error("socket has been disconnected"));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Called with socket packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
onpacket(packet) {
|
||||
const sameNamespace = packet.nsp === this.nsp;
|
||||
if (!sameNamespace)
|
||||
return;
|
||||
switch (packet.type) {
|
||||
case PacketType.CONNECT:
|
||||
if (packet.data && packet.data.sid) {
|
||||
this.onconnect(packet.data.sid, packet.data.pid);
|
||||
}
|
||||
else {
|
||||
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/)"));
|
||||
}
|
||||
break;
|
||||
case PacketType.EVENT:
|
||||
case PacketType.BINARY_EVENT:
|
||||
this.onevent(packet);
|
||||
break;
|
||||
case PacketType.ACK:
|
||||
case PacketType.BINARY_ACK:
|
||||
this.onack(packet);
|
||||
break;
|
||||
case PacketType.DISCONNECT:
|
||||
this.ondisconnect();
|
||||
break;
|
||||
case PacketType.CONNECT_ERROR:
|
||||
this.destroy();
|
||||
const err = new Error(packet.data.message);
|
||||
// @ts-ignore
|
||||
err.data = packet.data.data;
|
||||
this.emitReserved("connect_error", err);
|
||||
break;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Called upon a server event.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
onevent(packet) {
|
||||
const args = packet.data || [];
|
||||
debug("emitting event %j", args);
|
||||
if (null != packet.id) {
|
||||
debug("attaching ack callback to event");
|
||||
args.push(this.ack(packet.id));
|
||||
}
|
||||
if (this.connected) {
|
||||
this.emitEvent(args);
|
||||
}
|
||||
else {
|
||||
this.receiveBuffer.push(Object.freeze(args));
|
||||
}
|
||||
}
|
||||
emitEvent(args) {
|
||||
if (this._anyListeners && this._anyListeners.length) {
|
||||
const listeners = this._anyListeners.slice();
|
||||
for (const listener of listeners) {
|
||||
listener.apply(this, args);
|
||||
}
|
||||
}
|
||||
super.emit.apply(this, args);
|
||||
if (this._pid && args.length && typeof args[args.length - 1] === "string") {
|
||||
this._lastOffset = args[args.length - 1];
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Produces an ack callback to emit with an event.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
ack(id) {
|
||||
const self = this;
|
||||
let sent = false;
|
||||
return function (...args) {
|
||||
// prevent double callbacks
|
||||
if (sent)
|
||||
return;
|
||||
sent = true;
|
||||
debug("sending ack %j", args);
|
||||
self.packet({
|
||||
type: PacketType.ACK,
|
||||
id: id,
|
||||
data: args,
|
||||
});
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Called upon a server acknowledgement.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
onack(packet) {
|
||||
const ack = this.acks[packet.id];
|
||||
if (typeof ack !== "function") {
|
||||
debug("bad ack %s", packet.id);
|
||||
return;
|
||||
}
|
||||
delete this.acks[packet.id];
|
||||
debug("calling ack %s with %j", packet.id, packet.data);
|
||||
// @ts-ignore FIXME ack is incorrectly inferred as 'never'
|
||||
if (ack.withError) {
|
||||
packet.data.unshift(null);
|
||||
}
|
||||
// @ts-ignore
|
||||
ack.apply(this, packet.data);
|
||||
}
|
||||
/**
|
||||
* Called upon server connect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onconnect(id, pid) {
|
||||
debug("socket connected with id %s", id);
|
||||
this.id = id;
|
||||
this.recovered = pid && this._pid === pid;
|
||||
this._pid = pid; // defined only if connection state recovery is enabled
|
||||
this.connected = true;
|
||||
this.emitBuffered();
|
||||
this._drainQueue(true);
|
||||
this.emitReserved("connect");
|
||||
}
|
||||
/**
|
||||
* Emit buffered events (received and emitted).
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
emitBuffered() {
|
||||
this.receiveBuffer.forEach((args) => this.emitEvent(args));
|
||||
this.receiveBuffer = [];
|
||||
this.sendBuffer.forEach((packet) => {
|
||||
this.notifyOutgoingListeners(packet);
|
||||
this.packet(packet);
|
||||
});
|
||||
this.sendBuffer = [];
|
||||
}
|
||||
/**
|
||||
* Called upon server disconnect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
ondisconnect() {
|
||||
debug("server disconnect (%s)", this.nsp);
|
||||
this.destroy();
|
||||
this.onclose("io server disconnect");
|
||||
}
|
||||
/**
|
||||
* Called upon forced client/server side disconnections,
|
||||
* this method ensures the manager stops tracking us and
|
||||
* that reconnections don't get triggered for this.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
destroy() {
|
||||
if (this.subs) {
|
||||
// clean subscriptions to avoid reconnections
|
||||
this.subs.forEach((subDestroy) => subDestroy());
|
||||
this.subs = undefined;
|
||||
}
|
||||
this.io["_destroy"](this);
|
||||
}
|
||||
/**
|
||||
* Disconnects the socket manually. In that case, the socket will not try to reconnect.
|
||||
*
|
||||
* If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* // console.log(reason); prints "io client disconnect"
|
||||
* });
|
||||
*
|
||||
* socket.disconnect();
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
disconnect() {
|
||||
if (this.connected) {
|
||||
debug("performing disconnect (%s)", this.nsp);
|
||||
this.packet({ type: PacketType.DISCONNECT });
|
||||
}
|
||||
// remove socket from pool
|
||||
this.destroy();
|
||||
if (this.connected) {
|
||||
// fire events
|
||||
this.onclose("io client disconnect");
|
||||
}
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Alias for {@link disconnect()}.
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
close() {
|
||||
return this.disconnect();
|
||||
}
|
||||
/**
|
||||
* Sets the compress flag.
|
||||
*
|
||||
* @example
|
||||
* socket.compress(false).emit("hello");
|
||||
*
|
||||
* @param compress - if `true`, compresses the sending data
|
||||
* @return self
|
||||
*/
|
||||
compress(compress) {
|
||||
this.flags.compress = compress;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
|
||||
* ready to send messages.
|
||||
*
|
||||
* @example
|
||||
* socket.volatile.emit("hello"); // the server may or may not receive it
|
||||
*
|
||||
* @returns self
|
||||
*/
|
||||
get volatile() {
|
||||
this.flags.volatile = true;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the callback will be called with an error when the
|
||||
* given number of milliseconds have elapsed without an acknowledgement from the server:
|
||||
*
|
||||
* @example
|
||||
* socket.timeout(5000).emit("my-event", (err) => {
|
||||
* if (err) {
|
||||
* // the server did not acknowledge the event in the given delay
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* @returns self
|
||||
*/
|
||||
timeout(timeout) {
|
||||
this.flags.timeout = timeout;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback.
|
||||
*
|
||||
* @example
|
||||
* socket.onAny((event, ...args) => {
|
||||
* console.log(`got ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
onAny(listener) {
|
||||
this._anyListeners = this._anyListeners || [];
|
||||
this._anyListeners.push(listener);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback. The listener is added to the beginning of the listeners array.
|
||||
*
|
||||
* @example
|
||||
* socket.prependAny((event, ...args) => {
|
||||
* console.log(`got event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
prependAny(listener) {
|
||||
this._anyListeners = this._anyListeners || [];
|
||||
this._anyListeners.unshift(listener);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Removes the listener that will be fired when any event is emitted.
|
||||
*
|
||||
* @example
|
||||
* const catchAllListener = (event, ...args) => {
|
||||
* console.log(`got event ${event}`);
|
||||
* }
|
||||
*
|
||||
* socket.onAny(catchAllListener);
|
||||
*
|
||||
* // remove a specific listener
|
||||
* socket.offAny(catchAllListener);
|
||||
*
|
||||
* // or remove all listeners
|
||||
* socket.offAny();
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
offAny(listener) {
|
||||
if (!this._anyListeners) {
|
||||
return this;
|
||||
}
|
||||
if (listener) {
|
||||
const listeners = this._anyListeners;
|
||||
for (let i = 0; i < listeners.length; i++) {
|
||||
if (listener === listeners[i]) {
|
||||
listeners.splice(i, 1);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
this._anyListeners = [];
|
||||
}
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
|
||||
* e.g. to remove listeners.
|
||||
*/
|
||||
listenersAny() {
|
||||
return this._anyListeners || [];
|
||||
}
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback.
|
||||
*
|
||||
* Note: acknowledgements sent to the server are not included.
|
||||
*
|
||||
* @example
|
||||
* socket.onAnyOutgoing((event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
onAnyOutgoing(listener) {
|
||||
this._anyOutgoingListeners = this._anyOutgoingListeners || [];
|
||||
this._anyOutgoingListeners.push(listener);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback. The listener is added to the beginning of the listeners array.
|
||||
*
|
||||
* Note: acknowledgements sent to the server are not included.
|
||||
*
|
||||
* @example
|
||||
* socket.prependAnyOutgoing((event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
prependAnyOutgoing(listener) {
|
||||
this._anyOutgoingListeners = this._anyOutgoingListeners || [];
|
||||
this._anyOutgoingListeners.unshift(listener);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Removes the listener that will be fired when any event is emitted.
|
||||
*
|
||||
* @example
|
||||
* const catchAllListener = (event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* }
|
||||
*
|
||||
* socket.onAnyOutgoing(catchAllListener);
|
||||
*
|
||||
* // remove a specific listener
|
||||
* socket.offAnyOutgoing(catchAllListener);
|
||||
*
|
||||
* // or remove all listeners
|
||||
* socket.offAnyOutgoing();
|
||||
*
|
||||
* @param [listener] - the catch-all listener (optional)
|
||||
*/
|
||||
offAnyOutgoing(listener) {
|
||||
if (!this._anyOutgoingListeners) {
|
||||
return this;
|
||||
}
|
||||
if (listener) {
|
||||
const listeners = this._anyOutgoingListeners;
|
||||
for (let i = 0; i < listeners.length; i++) {
|
||||
if (listener === listeners[i]) {
|
||||
listeners.splice(i, 1);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
this._anyOutgoingListeners = [];
|
||||
}
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
|
||||
* e.g. to remove listeners.
|
||||
*/
|
||||
listenersAnyOutgoing() {
|
||||
return this._anyOutgoingListeners || [];
|
||||
}
|
||||
/**
|
||||
* Notify the listeners for each packet sent
|
||||
*
|
||||
* @param packet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
notifyOutgoingListeners(packet) {
|
||||
if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
|
||||
const listeners = this._anyOutgoingListeners.slice();
|
||||
for (const listener of listeners) {
|
||||
listener.apply(this, packet.data);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
type ParsedUrl = {
|
||||
source: string;
|
||||
protocol: string;
|
||||
authority: string;
|
||||
userInfo: string;
|
||||
user: string;
|
||||
password: string;
|
||||
host: string;
|
||||
port: string;
|
||||
relative: string;
|
||||
path: string;
|
||||
directory: string;
|
||||
file: string;
|
||||
query: string;
|
||||
anchor: string;
|
||||
pathNames: Array<string>;
|
||||
queryKey: {
|
||||
[key: string]: string;
|
||||
};
|
||||
id: string;
|
||||
href: string;
|
||||
};
|
||||
/**
|
||||
* URL parser.
|
||||
*
|
||||
* @param uri - url
|
||||
* @param path - the request path of the connection
|
||||
* @param loc - An object meant to mimic window.location.
|
||||
* Defaults to window.location.
|
||||
* @public
|
||||
*/
|
||||
export declare function url(uri: string | ParsedUrl, path?: string, loc?: Location): ParsedUrl;
|
||||
export {};
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import { parse } from "engine.io-client";
|
||||
import debugModule from "debug"; // debug()
|
||||
const debug = debugModule("socket.io-client:url"); // debug()
|
||||
/**
|
||||
* URL parser.
|
||||
*
|
||||
* @param uri - url
|
||||
* @param path - the request path of the connection
|
||||
* @param loc - An object meant to mimic window.location.
|
||||
* Defaults to window.location.
|
||||
* @public
|
||||
*/
|
||||
export function url(uri, path = "", loc) {
|
||||
let obj = uri;
|
||||
// default to window.location
|
||||
loc = loc || (typeof location !== "undefined" && location);
|
||||
if (null == uri)
|
||||
uri = loc.protocol + "//" + loc.host;
|
||||
// relative path support
|
||||
if (typeof uri === "string") {
|
||||
if ("/" === uri.charAt(0)) {
|
||||
if ("/" === uri.charAt(1)) {
|
||||
uri = loc.protocol + uri;
|
||||
}
|
||||
else {
|
||||
uri = loc.host + uri;
|
||||
}
|
||||
}
|
||||
if (!/^(https?|wss?):\/\//.test(uri)) {
|
||||
debug("protocol-less url %s", uri);
|
||||
if ("undefined" !== typeof loc) {
|
||||
uri = loc.protocol + "//" + uri;
|
||||
}
|
||||
else {
|
||||
uri = "https://" + uri;
|
||||
}
|
||||
}
|
||||
// parse
|
||||
debug("parse %s", uri);
|
||||
obj = parse(uri);
|
||||
}
|
||||
// make sure we treat `localhost:80` and `localhost` equally
|
||||
if (!obj.port) {
|
||||
if (/^(http|ws)$/.test(obj.protocol)) {
|
||||
obj.port = "80";
|
||||
}
|
||||
else if (/^(http|ws)s$/.test(obj.protocol)) {
|
||||
obj.port = "443";
|
||||
}
|
||||
}
|
||||
obj.path = obj.path || "/";
|
||||
const ipv6 = obj.host.indexOf(":") !== -1;
|
||||
const host = ipv6 ? "[" + obj.host + "]" : obj.host;
|
||||
// define unique id
|
||||
obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
|
||||
// define href
|
||||
obj.href =
|
||||
obj.protocol +
|
||||
"://" +
|
||||
host +
|
||||
(loc && loc.port === obj.port ? "" : ":" + obj.port);
|
||||
return obj;
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { io } from "./index.js";
|
||||
export default io;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { io } from "./index.js";
|
||||
export default io;
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Initialize backoff timer with `opts`.
|
||||
*
|
||||
* - `min` initial timeout in milliseconds [100]
|
||||
* - `max` max timeout [10000]
|
||||
* - `jitter` [0]
|
||||
* - `factor` [2]
|
||||
*
|
||||
* @param {Object} opts
|
||||
* @api public
|
||||
*/
|
||||
export declare function Backoff(opts: any): void;
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Initialize backoff timer with `opts`.
|
||||
*
|
||||
* - `min` initial timeout in milliseconds [100]
|
||||
* - `max` max timeout [10000]
|
||||
* - `jitter` [0]
|
||||
* - `factor` [2]
|
||||
*
|
||||
* @param {Object} opts
|
||||
* @api public
|
||||
*/
|
||||
export function Backoff(opts) {
|
||||
opts = opts || {};
|
||||
this.ms = opts.min || 100;
|
||||
this.max = opts.max || 10000;
|
||||
this.factor = opts.factor || 2;
|
||||
this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
|
||||
this.attempts = 0;
|
||||
}
|
||||
/**
|
||||
* Return the backoff duration.
|
||||
*
|
||||
* @return {Number}
|
||||
* @api public
|
||||
*/
|
||||
Backoff.prototype.duration = function () {
|
||||
var ms = this.ms * Math.pow(this.factor, this.attempts++);
|
||||
if (this.jitter) {
|
||||
var rand = Math.random();
|
||||
var deviation = Math.floor(rand * this.jitter * ms);
|
||||
ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
|
||||
}
|
||||
return Math.min(ms, this.max) | 0;
|
||||
};
|
||||
/**
|
||||
* Reset the number of attempts.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
Backoff.prototype.reset = function () {
|
||||
this.attempts = 0;
|
||||
};
|
||||
/**
|
||||
* Set the minimum duration
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
Backoff.prototype.setMin = function (min) {
|
||||
this.ms = min;
|
||||
};
|
||||
/**
|
||||
* Set the maximum duration
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
Backoff.prototype.setMax = function (max) {
|
||||
this.max = max;
|
||||
};
|
||||
/**
|
||||
* Set the jitter
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
Backoff.prototype.setJitter = function (jitter) {
|
||||
this.jitter = jitter;
|
||||
};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
import { Manager, ManagerOptions } from "./manager.js";
|
||||
import { DisconnectDescription, Socket, SocketOptions } from "./socket.js";
|
||||
/**
|
||||
* Looks up an existing `Manager` for multiplexing.
|
||||
* If the user summons:
|
||||
*
|
||||
* `io('http://localhost/a');`
|
||||
* `io('http://localhost/b');`
|
||||
*
|
||||
* We reuse the existing instance based on same scheme/port/host,
|
||||
* and we initialize sockets for each namespace.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
declare function lookup(opts?: Partial<ManagerOptions & SocketOptions>): Socket;
|
||||
declare function lookup(uri?: string, opts?: Partial<ManagerOptions & SocketOptions>): Socket;
|
||||
/**
|
||||
* Protocol version.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export { protocol } from "socket.io-parser";
|
||||
/**
|
||||
* Expose constructors for standalone build.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export { DisconnectDescription, Manager, ManagerOptions, Socket, SocketOptions, lookup as io, lookup as connect, lookup as default, };
|
||||
export { Fetch, NodeXHR, XHR, NodeWebSocket, WebSocket, WebTransport, } from "engine.io-client";
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
import { url } from "./url.js";
|
||||
import { Manager } from "./manager.js";
|
||||
import { Socket } from "./socket.js";
|
||||
/**
|
||||
* Managers cache.
|
||||
*/
|
||||
const cache = {};
|
||||
function lookup(uri, opts) {
|
||||
if (typeof uri === "object") {
|
||||
opts = uri;
|
||||
uri = undefined;
|
||||
}
|
||||
opts = opts || {};
|
||||
const parsed = url(uri, opts.path || "/socket.io");
|
||||
const source = parsed.source;
|
||||
const id = parsed.id;
|
||||
const path = parsed.path;
|
||||
const sameNamespace = cache[id] && path in cache[id]["nsps"];
|
||||
const newConnection = opts.forceNew ||
|
||||
opts["force new connection"] ||
|
||||
false === opts.multiplex ||
|
||||
sameNamespace;
|
||||
let io;
|
||||
if (newConnection) {
|
||||
io = new Manager(source, opts);
|
||||
}
|
||||
else {
|
||||
if (!cache[id]) {
|
||||
cache[id] = new Manager(source, opts);
|
||||
}
|
||||
io = cache[id];
|
||||
}
|
||||
if (parsed.query && !opts.query) {
|
||||
opts.query = parsed.queryKey;
|
||||
}
|
||||
return io.socket(parsed.path, opts);
|
||||
}
|
||||
// so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
|
||||
// namespace (e.g. `io.connect(...)`), for backward compatibility
|
||||
Object.assign(lookup, {
|
||||
Manager,
|
||||
Socket,
|
||||
io: lookup,
|
||||
connect: lookup,
|
||||
});
|
||||
/**
|
||||
* Protocol version.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export { protocol } from "socket.io-parser";
|
||||
/**
|
||||
* Expose constructors for standalone build.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export { Manager, Socket, lookup as io, lookup as connect, lookup as default, };
|
||||
export { Fetch, NodeXHR, XHR, NodeWebSocket, WebSocket, WebTransport, } from "engine.io-client";
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
import { Socket as Engine, SocketOptions as EngineOptions } from "engine.io-client";
|
||||
import { Socket, SocketOptions, DisconnectDescription } from "./socket.js";
|
||||
import { Packet } from "socket.io-parser";
|
||||
import { DefaultEventsMap, EventsMap, Emitter } from "@socket.io/component-emitter";
|
||||
export interface ManagerOptions extends EngineOptions {
|
||||
/**
|
||||
* Should we force a new Manager for this connection?
|
||||
* @default false
|
||||
*/
|
||||
forceNew: boolean;
|
||||
/**
|
||||
* Should we multiplex our connection (reuse existing Manager) ?
|
||||
* @default true
|
||||
*/
|
||||
multiplex: boolean;
|
||||
/**
|
||||
* The path to get our client file from, in the case of the server
|
||||
* serving it
|
||||
* @default '/socket.io'
|
||||
*/
|
||||
path: string;
|
||||
/**
|
||||
* Should we allow reconnections?
|
||||
* @default true
|
||||
*/
|
||||
reconnection: boolean;
|
||||
/**
|
||||
* How many reconnection attempts should we try?
|
||||
* @default Infinity
|
||||
*/
|
||||
reconnectionAttempts: number;
|
||||
/**
|
||||
* The time delay in milliseconds between reconnection attempts
|
||||
* @default 1000
|
||||
*/
|
||||
reconnectionDelay: number;
|
||||
/**
|
||||
* The max time delay in milliseconds between reconnection attempts
|
||||
* @default 5000
|
||||
*/
|
||||
reconnectionDelayMax: number;
|
||||
/**
|
||||
* Used in the exponential backoff jitter when reconnecting
|
||||
* @default 0.5
|
||||
*/
|
||||
randomizationFactor: number;
|
||||
/**
|
||||
* The timeout in milliseconds for our connection attempt
|
||||
* @default 20000
|
||||
*/
|
||||
timeout: number;
|
||||
/**
|
||||
* Should we automatically connect?
|
||||
* @default true
|
||||
*/
|
||||
autoConnect: boolean;
|
||||
/**
|
||||
* the parser to use. Defaults to an instance of the Parser that ships with socket.io.
|
||||
*/
|
||||
parser: any;
|
||||
}
|
||||
interface ManagerReservedEvents {
|
||||
open: () => void;
|
||||
error: (err: Error) => void;
|
||||
ping: () => void;
|
||||
packet: (packet: Packet) => void;
|
||||
close: (reason: string, description?: DisconnectDescription) => void;
|
||||
reconnect_failed: () => void;
|
||||
reconnect_attempt: (attempt: number) => void;
|
||||
reconnect_error: (err: Error) => void;
|
||||
reconnect: (attempt: number) => void;
|
||||
}
|
||||
export declare class Manager<ListenEvents extends EventsMap = DefaultEventsMap, EmitEvents extends EventsMap = ListenEvents> extends Emitter<{}, {}, ManagerReservedEvents> {
|
||||
/**
|
||||
* The Engine.IO client instance
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
engine: Engine;
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
_autoConnect: boolean;
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
_readyState: "opening" | "open" | "closed";
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
_reconnecting: boolean;
|
||||
private readonly uri;
|
||||
opts: Partial<ManagerOptions>;
|
||||
private nsps;
|
||||
private subs;
|
||||
private backoff;
|
||||
private setTimeoutFn;
|
||||
private clearTimeoutFn;
|
||||
private _reconnection;
|
||||
private _reconnectionAttempts;
|
||||
private _reconnectionDelay;
|
||||
private _randomizationFactor;
|
||||
private _reconnectionDelayMax;
|
||||
private _timeout;
|
||||
private encoder;
|
||||
private decoder;
|
||||
private skipReconnect;
|
||||
/**
|
||||
* `Manager` constructor.
|
||||
*
|
||||
* @param uri - engine instance or engine uri/opts
|
||||
* @param opts - options
|
||||
* @public
|
||||
*/
|
||||
constructor(opts: Partial<ManagerOptions>);
|
||||
constructor(uri?: string, opts?: Partial<ManagerOptions>);
|
||||
constructor(uri?: string | Partial<ManagerOptions>, opts?: Partial<ManagerOptions>);
|
||||
/**
|
||||
* Sets the `reconnection` config.
|
||||
*
|
||||
* @param {Boolean} v - true/false if it should automatically reconnect
|
||||
* @return {Manager} self or value
|
||||
* @public
|
||||
*/
|
||||
reconnection(v: boolean): this;
|
||||
reconnection(): boolean;
|
||||
reconnection(v?: boolean): this | boolean;
|
||||
/**
|
||||
* Sets the reconnection attempts config.
|
||||
*
|
||||
* @param {Number} v - max reconnection attempts before giving up
|
||||
* @return {Manager} self or value
|
||||
* @public
|
||||
*/
|
||||
reconnectionAttempts(v: number): this;
|
||||
reconnectionAttempts(): number;
|
||||
reconnectionAttempts(v?: number): this | number;
|
||||
/**
|
||||
* Sets the delay between reconnections.
|
||||
*
|
||||
* @param {Number} v - delay
|
||||
* @return {Manager} self or value
|
||||
* @public
|
||||
*/
|
||||
reconnectionDelay(v: number): this;
|
||||
reconnectionDelay(): number;
|
||||
reconnectionDelay(v?: number): this | number;
|
||||
/**
|
||||
* Sets the randomization factor
|
||||
*
|
||||
* @param v - the randomization factor
|
||||
* @return self or value
|
||||
* @public
|
||||
*/
|
||||
randomizationFactor(v: number): this;
|
||||
randomizationFactor(): number;
|
||||
randomizationFactor(v?: number): this | number;
|
||||
/**
|
||||
* Sets the maximum delay between reconnections.
|
||||
*
|
||||
* @param v - delay
|
||||
* @return self or value
|
||||
* @public
|
||||
*/
|
||||
reconnectionDelayMax(v: number): this;
|
||||
reconnectionDelayMax(): number;
|
||||
reconnectionDelayMax(v?: number): this | number;
|
||||
/**
|
||||
* Sets the connection timeout. `false` to disable
|
||||
*
|
||||
* @param v - connection timeout
|
||||
* @return self or value
|
||||
* @public
|
||||
*/
|
||||
timeout(v: number | boolean): this;
|
||||
timeout(): number | boolean;
|
||||
timeout(v?: number | boolean): this | number | boolean;
|
||||
/**
|
||||
* Starts trying to reconnect if reconnection is enabled and we have not
|
||||
* started reconnecting yet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private maybeReconnectOnOpen;
|
||||
/**
|
||||
* Sets the current transport `socket`.
|
||||
*
|
||||
* @param {Function} fn - optional, callback
|
||||
* @return self
|
||||
* @public
|
||||
*/
|
||||
open(fn?: (err?: Error) => void): this;
|
||||
/**
|
||||
* Alias for open()
|
||||
*
|
||||
* @return self
|
||||
* @public
|
||||
*/
|
||||
connect(fn?: (err?: Error) => void): this;
|
||||
/**
|
||||
* Called upon transport open.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onopen;
|
||||
/**
|
||||
* Called upon a ping.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onping;
|
||||
/**
|
||||
* Called with data.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private ondata;
|
||||
/**
|
||||
* Called when parser fully decodes a packet.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private ondecoded;
|
||||
/**
|
||||
* Called upon socket error.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onerror;
|
||||
/**
|
||||
* Creates a new socket for the given `nsp`.
|
||||
*
|
||||
* @return {Socket}
|
||||
* @public
|
||||
*/
|
||||
socket(nsp: string, opts?: Partial<SocketOptions>): Socket;
|
||||
/**
|
||||
* Called upon a socket close.
|
||||
*
|
||||
* @param socket
|
||||
* @private
|
||||
*/
|
||||
_destroy(socket: Socket): void;
|
||||
/**
|
||||
* Writes a packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
_packet(packet: Partial<Packet & {
|
||||
query: string;
|
||||
options: any;
|
||||
}>): void;
|
||||
/**
|
||||
* Clean up transport subscriptions and packet buffer.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private cleanup;
|
||||
/**
|
||||
* Close the current socket.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_close(): void;
|
||||
/**
|
||||
* Alias for close()
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private disconnect;
|
||||
/**
|
||||
* Called when:
|
||||
*
|
||||
* - the low-level engine is closed
|
||||
* - the parser encountered a badly formatted packet
|
||||
* - all sockets are disconnected
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onclose;
|
||||
/**
|
||||
* Attempt a reconnection.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private reconnect;
|
||||
/**
|
||||
* Called upon successful reconnect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onreconnect;
|
||||
}
|
||||
export {};
|
||||
+367
@@ -0,0 +1,367 @@
|
||||
import { Socket as Engine, installTimerFunctions, nextTick, } from "engine.io-client";
|
||||
import { Socket } from "./socket.js";
|
||||
import * as parser from "socket.io-parser";
|
||||
import { on } from "./on.js";
|
||||
import { Backoff } from "./contrib/backo2.js";
|
||||
import { Emitter, } from "@socket.io/component-emitter";
|
||||
export class Manager extends Emitter {
|
||||
constructor(uri, opts) {
|
||||
var _a;
|
||||
super();
|
||||
this.nsps = {};
|
||||
this.subs = [];
|
||||
if (uri && "object" === typeof uri) {
|
||||
opts = uri;
|
||||
uri = undefined;
|
||||
}
|
||||
opts = opts || {};
|
||||
opts.path = opts.path || "/socket.io";
|
||||
this.opts = opts;
|
||||
installTimerFunctions(this, opts);
|
||||
this.reconnection(opts.reconnection !== false);
|
||||
this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
|
||||
this.reconnectionDelay(opts.reconnectionDelay || 1000);
|
||||
this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
|
||||
this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
|
||||
this.backoff = new Backoff({
|
||||
min: this.reconnectionDelay(),
|
||||
max: this.reconnectionDelayMax(),
|
||||
jitter: this.randomizationFactor(),
|
||||
});
|
||||
this.timeout(null == opts.timeout ? 20000 : opts.timeout);
|
||||
this._readyState = "closed";
|
||||
this.uri = uri;
|
||||
const _parser = opts.parser || parser;
|
||||
this.encoder = new _parser.Encoder();
|
||||
this.decoder = new _parser.Decoder();
|
||||
this._autoConnect = opts.autoConnect !== false;
|
||||
if (this._autoConnect)
|
||||
this.open();
|
||||
}
|
||||
reconnection(v) {
|
||||
if (!arguments.length)
|
||||
return this._reconnection;
|
||||
this._reconnection = !!v;
|
||||
if (!v) {
|
||||
this.skipReconnect = true;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
reconnectionAttempts(v) {
|
||||
if (v === undefined)
|
||||
return this._reconnectionAttempts;
|
||||
this._reconnectionAttempts = v;
|
||||
return this;
|
||||
}
|
||||
reconnectionDelay(v) {
|
||||
var _a;
|
||||
if (v === undefined)
|
||||
return this._reconnectionDelay;
|
||||
this._reconnectionDelay = v;
|
||||
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
|
||||
return this;
|
||||
}
|
||||
randomizationFactor(v) {
|
||||
var _a;
|
||||
if (v === undefined)
|
||||
return this._randomizationFactor;
|
||||
this._randomizationFactor = v;
|
||||
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
|
||||
return this;
|
||||
}
|
||||
reconnectionDelayMax(v) {
|
||||
var _a;
|
||||
if (v === undefined)
|
||||
return this._reconnectionDelayMax;
|
||||
this._reconnectionDelayMax = v;
|
||||
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
|
||||
return this;
|
||||
}
|
||||
timeout(v) {
|
||||
if (!arguments.length)
|
||||
return this._timeout;
|
||||
this._timeout = v;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Starts trying to reconnect if reconnection is enabled and we have not
|
||||
* started reconnecting yet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
maybeReconnectOnOpen() {
|
||||
// Only try to reconnect if it's the first time we're connecting
|
||||
if (!this._reconnecting &&
|
||||
this._reconnection &&
|
||||
this.backoff.attempts === 0) {
|
||||
// keeps reconnection from firing twice for the same reconnection loop
|
||||
this.reconnect();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Sets the current transport `socket`.
|
||||
*
|
||||
* @param {Function} fn - optional, callback
|
||||
* @return self
|
||||
* @public
|
||||
*/
|
||||
open(fn) {
|
||||
if (~this._readyState.indexOf("open"))
|
||||
return this;
|
||||
this.engine = new Engine(this.uri, this.opts);
|
||||
const socket = this.engine;
|
||||
const self = this;
|
||||
this._readyState = "opening";
|
||||
this.skipReconnect = false;
|
||||
// emit `open`
|
||||
const openSubDestroy = on(socket, "open", function () {
|
||||
self.onopen();
|
||||
fn && fn();
|
||||
});
|
||||
const onError = (err) => {
|
||||
this.cleanup();
|
||||
this._readyState = "closed";
|
||||
this.emitReserved("error", err);
|
||||
if (fn) {
|
||||
fn(err);
|
||||
}
|
||||
else {
|
||||
// Only do this if there is no fn to handle the error
|
||||
this.maybeReconnectOnOpen();
|
||||
}
|
||||
};
|
||||
// emit `error`
|
||||
const errorSub = on(socket, "error", onError);
|
||||
if (false !== this._timeout) {
|
||||
const timeout = this._timeout;
|
||||
// set timer
|
||||
const timer = this.setTimeoutFn(() => {
|
||||
openSubDestroy();
|
||||
onError(new Error("timeout"));
|
||||
socket.close();
|
||||
}, timeout);
|
||||
if (this.opts.autoUnref) {
|
||||
timer.unref();
|
||||
}
|
||||
this.subs.push(() => {
|
||||
this.clearTimeoutFn(timer);
|
||||
});
|
||||
}
|
||||
this.subs.push(openSubDestroy);
|
||||
this.subs.push(errorSub);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Alias for open()
|
||||
*
|
||||
* @return self
|
||||
* @public
|
||||
*/
|
||||
connect(fn) {
|
||||
return this.open(fn);
|
||||
}
|
||||
/**
|
||||
* Called upon transport open.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onopen() {
|
||||
// clear old subs
|
||||
this.cleanup();
|
||||
// mark as open
|
||||
this._readyState = "open";
|
||||
this.emitReserved("open");
|
||||
// add new subs
|
||||
const socket = this.engine;
|
||||
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)),
|
||||
// @ts-ignore
|
||||
on(this.decoder, "decoded", this.ondecoded.bind(this)));
|
||||
}
|
||||
/**
|
||||
* Called upon a ping.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onping() {
|
||||
this.emitReserved("ping");
|
||||
}
|
||||
/**
|
||||
* Called with data.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
ondata(data) {
|
||||
try {
|
||||
this.decoder.add(data);
|
||||
}
|
||||
catch (e) {
|
||||
this.onclose("parse error", e);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Called when parser fully decodes a packet.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
ondecoded(packet) {
|
||||
// the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
|
||||
nextTick(() => {
|
||||
this.emitReserved("packet", packet);
|
||||
}, this.setTimeoutFn);
|
||||
}
|
||||
/**
|
||||
* Called upon socket error.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onerror(err) {
|
||||
this.emitReserved("error", err);
|
||||
}
|
||||
/**
|
||||
* Creates a new socket for the given `nsp`.
|
||||
*
|
||||
* @return {Socket}
|
||||
* @public
|
||||
*/
|
||||
socket(nsp, opts) {
|
||||
let socket = this.nsps[nsp];
|
||||
if (!socket) {
|
||||
socket = new Socket(this, nsp, opts);
|
||||
this.nsps[nsp] = socket;
|
||||
}
|
||||
else if (this._autoConnect && !socket.active) {
|
||||
socket.connect();
|
||||
}
|
||||
return socket;
|
||||
}
|
||||
/**
|
||||
* Called upon a socket close.
|
||||
*
|
||||
* @param socket
|
||||
* @private
|
||||
*/
|
||||
_destroy(socket) {
|
||||
const nsps = Object.keys(this.nsps);
|
||||
for (const nsp of nsps) {
|
||||
const socket = this.nsps[nsp];
|
||||
if (socket.active) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
this._close();
|
||||
}
|
||||
/**
|
||||
* Writes a packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
_packet(packet) {
|
||||
const encodedPackets = this.encoder.encode(packet);
|
||||
for (let i = 0; i < encodedPackets.length; i++) {
|
||||
this.engine.write(encodedPackets[i], packet.options);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Clean up transport subscriptions and packet buffer.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
cleanup() {
|
||||
this.subs.forEach((subDestroy) => subDestroy());
|
||||
this.subs.length = 0;
|
||||
this.decoder.destroy();
|
||||
}
|
||||
/**
|
||||
* Close the current socket.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_close() {
|
||||
this.skipReconnect = true;
|
||||
this._reconnecting = false;
|
||||
this.onclose("forced close");
|
||||
}
|
||||
/**
|
||||
* Alias for close()
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
disconnect() {
|
||||
return this._close();
|
||||
}
|
||||
/**
|
||||
* Called when:
|
||||
*
|
||||
* - the low-level engine is closed
|
||||
* - the parser encountered a badly formatted packet
|
||||
* - all sockets are disconnected
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onclose(reason, description) {
|
||||
var _a;
|
||||
this.cleanup();
|
||||
(_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
|
||||
this.backoff.reset();
|
||||
this._readyState = "closed";
|
||||
this.emitReserved("close", reason, description);
|
||||
if (this._reconnection && !this.skipReconnect) {
|
||||
this.reconnect();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Attempt a reconnection.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
reconnect() {
|
||||
if (this._reconnecting || this.skipReconnect)
|
||||
return this;
|
||||
const self = this;
|
||||
if (this.backoff.attempts >= this._reconnectionAttempts) {
|
||||
this.backoff.reset();
|
||||
this.emitReserved("reconnect_failed");
|
||||
this._reconnecting = false;
|
||||
}
|
||||
else {
|
||||
const delay = this.backoff.duration();
|
||||
this._reconnecting = true;
|
||||
const timer = this.setTimeoutFn(() => {
|
||||
if (self.skipReconnect)
|
||||
return;
|
||||
this.emitReserved("reconnect_attempt", self.backoff.attempts);
|
||||
// check again for the case socket closed in above events
|
||||
if (self.skipReconnect)
|
||||
return;
|
||||
self.open((err) => {
|
||||
if (err) {
|
||||
self._reconnecting = false;
|
||||
self.reconnect();
|
||||
this.emitReserved("reconnect_error", err);
|
||||
}
|
||||
else {
|
||||
self.onreconnect();
|
||||
}
|
||||
});
|
||||
}, delay);
|
||||
if (this.opts.autoUnref) {
|
||||
timer.unref();
|
||||
}
|
||||
this.subs.push(() => {
|
||||
this.clearTimeoutFn(timer);
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Called upon successful reconnect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onreconnect() {
|
||||
const attempt = this.backoff.attempts;
|
||||
this._reconnecting = false;
|
||||
this.backoff.reset();
|
||||
this.emitReserved("reconnect", attempt);
|
||||
}
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { Emitter } from "@socket.io/component-emitter";
|
||||
export declare function on(obj: Emitter<any, any>, ev: string, fn: (err?: any) => any): VoidFunction;
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
export function on(obj, ev, fn) {
|
||||
obj.on(ev, fn);
|
||||
return function subDestroy() {
|
||||
obj.off(ev, fn);
|
||||
};
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "socket.io-client",
|
||||
"version": "4.8.3",
|
||||
"type": "module"
|
||||
}
|
||||
+593
@@ -0,0 +1,593 @@
|
||||
import { Packet } from "socket.io-parser";
|
||||
import { Manager } from "./manager.js";
|
||||
import { DefaultEventsMap, EventNames, EventParams, EventsMap, Emitter } from "@socket.io/component-emitter";
|
||||
type PrependTimeoutError<T extends any[]> = {
|
||||
[K in keyof T]: T[K] extends (...args: infer Params) => infer Result ? (err: Error, ...args: Params) => Result : T[K];
|
||||
};
|
||||
/**
|
||||
* Utility type to decorate the acknowledgement callbacks with a timeout error.
|
||||
*
|
||||
* This is needed because the timeout() flag breaks the symmetry between the sender and the receiver:
|
||||
*
|
||||
* @example
|
||||
* interface Events {
|
||||
* "my-event": (val: string) => void;
|
||||
* }
|
||||
*
|
||||
* socket.on("my-event", (cb) => {
|
||||
* cb("123"); // one single argument here
|
||||
* });
|
||||
*
|
||||
* socket.timeout(1000).emit("my-event", (err, val) => {
|
||||
* // two arguments there (the "err" argument is not properly typed)
|
||||
* });
|
||||
*
|
||||
*/
|
||||
export type DecorateAcknowledgements<E> = {
|
||||
[K in keyof E]: E[K] extends (...args: infer Params) => infer Result ? (...args: PrependTimeoutError<Params>) => Result : E[K];
|
||||
};
|
||||
export type Last<T extends any[]> = T extends [...infer H, infer L] ? L : any;
|
||||
export type AllButLast<T extends any[]> = T extends [...infer H, infer L] ? H : any[];
|
||||
export type FirstArg<T> = T extends (arg: infer Param) => infer Result ? Param : any;
|
||||
export interface SocketOptions {
|
||||
/**
|
||||
* the authentication payload sent when connecting to the Namespace
|
||||
*/
|
||||
auth?: {
|
||||
[key: string]: any;
|
||||
} | ((cb: (data: object) => void) => void);
|
||||
/**
|
||||
* The maximum number of retries. Above the limit, the packet will be discarded.
|
||||
*
|
||||
* Using `Infinity` means the delivery guarantee is "at-least-once" (instead of "at-most-once" by default), but a
|
||||
* smaller value like 10 should be sufficient in practice.
|
||||
*/
|
||||
retries?: number;
|
||||
/**
|
||||
* The default timeout in milliseconds used when waiting for an acknowledgement.
|
||||
*/
|
||||
ackTimeout?: number;
|
||||
}
|
||||
export type DisconnectDescription = Error | {
|
||||
description: string;
|
||||
context?: unknown;
|
||||
};
|
||||
interface SocketReservedEvents {
|
||||
connect: () => void;
|
||||
connect_error: (err: Error) => void;
|
||||
disconnect: (reason: Socket.DisconnectReason, description?: DisconnectDescription) => void;
|
||||
}
|
||||
/**
|
||||
* A Socket is the fundamental class for interacting with the server.
|
||||
*
|
||||
* A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log("connected");
|
||||
* });
|
||||
*
|
||||
* // send an event to the server
|
||||
* socket.emit("foo", "bar");
|
||||
*
|
||||
* socket.on("foobar", () => {
|
||||
* // an event was received from the server
|
||||
* });
|
||||
*
|
||||
* // upon disconnection
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* console.log(`disconnected due to ${reason}`);
|
||||
* });
|
||||
*/
|
||||
export declare class Socket<ListenEvents extends EventsMap = DefaultEventsMap, EmitEvents extends EventsMap = ListenEvents> extends Emitter<ListenEvents, EmitEvents, SocketReservedEvents> {
|
||||
readonly io: Manager<ListenEvents, EmitEvents>;
|
||||
/**
|
||||
* A unique identifier for the session. `undefined` when the socket is not connected.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* console.log(socket.id); // undefined
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log(socket.id); // "G5p5..."
|
||||
* });
|
||||
*/
|
||||
id: string | undefined;
|
||||
/**
|
||||
* The session ID used for connection state recovery, which must not be shared (unlike {@link id}).
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private _pid;
|
||||
/**
|
||||
* The offset of the last received packet, which will be sent upon reconnection to allow for the recovery of the connection state.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private _lastOffset;
|
||||
/**
|
||||
* Whether the socket is currently connected to the server.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log(socket.connected); // true
|
||||
* });
|
||||
*
|
||||
* socket.on("disconnect", () => {
|
||||
* console.log(socket.connected); // false
|
||||
* });
|
||||
*/
|
||||
connected: boolean;
|
||||
/**
|
||||
* Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
|
||||
* be transmitted by the server.
|
||||
*/
|
||||
recovered: boolean;
|
||||
/**
|
||||
* Credentials that are sent when accessing a namespace.
|
||||
*
|
||||
* @example
|
||||
* const socket = io({
|
||||
* auth: {
|
||||
* token: "abcd"
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* // or with a function
|
||||
* const socket = io({
|
||||
* auth: (cb) => {
|
||||
* cb({ token: localStorage.token })
|
||||
* }
|
||||
* });
|
||||
*/
|
||||
auth: {
|
||||
[key: string]: any;
|
||||
} | ((cb: (data: object) => void) => void);
|
||||
/**
|
||||
* Buffer for packets received before the CONNECT packet
|
||||
*/
|
||||
receiveBuffer: Array<ReadonlyArray<any>>;
|
||||
/**
|
||||
* Buffer for packets that will be sent once the socket is connected
|
||||
*/
|
||||
sendBuffer: Array<Packet>;
|
||||
/**
|
||||
* The queue of packets to be sent with retry in case of failure.
|
||||
*
|
||||
* Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
|
||||
* @private
|
||||
*/
|
||||
private _queue;
|
||||
/**
|
||||
* A sequence to generate the ID of the {@link QueuedPacket}.
|
||||
* @private
|
||||
*/
|
||||
private _queueSeq;
|
||||
private readonly nsp;
|
||||
private readonly _opts;
|
||||
private ids;
|
||||
/**
|
||||
* A map containing acknowledgement handlers.
|
||||
*
|
||||
* The `withError` attribute is used to differentiate handlers that accept an error as first argument:
|
||||
*
|
||||
* - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
|
||||
* - `socket.timeout(5000).emit("test", (err, value) => { ... })`
|
||||
* - `const value = await socket.emitWithAck("test")`
|
||||
*
|
||||
* From those that don't:
|
||||
*
|
||||
* - `socket.emit("test", (value) => { ... });`
|
||||
*
|
||||
* In the first case, the handlers will be called with an error when:
|
||||
*
|
||||
* - the timeout is reached
|
||||
* - the socket gets disconnected
|
||||
*
|
||||
* In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
|
||||
* an acknowledgement from the server.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private acks;
|
||||
private flags;
|
||||
private subs?;
|
||||
private _anyListeners;
|
||||
private _anyOutgoingListeners;
|
||||
/**
|
||||
* `Socket` constructor.
|
||||
*/
|
||||
constructor(io: Manager, nsp: string, opts?: Partial<SocketOptions>);
|
||||
/**
|
||||
* Whether the socket is currently disconnected
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log(socket.disconnected); // false
|
||||
* });
|
||||
*
|
||||
* socket.on("disconnect", () => {
|
||||
* console.log(socket.disconnected); // true
|
||||
* });
|
||||
*/
|
||||
get disconnected(): boolean;
|
||||
/**
|
||||
* Subscribe to open, close and packet events
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private subEvents;
|
||||
/**
|
||||
* Whether the Socket will try to reconnect when its Manager connects or reconnects.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* console.log(socket.active); // true
|
||||
*
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* if (reason === "io server disconnect") {
|
||||
* // the disconnection was initiated by the server, you need to manually reconnect
|
||||
* console.log(socket.active); // false
|
||||
* }
|
||||
* // else the socket will automatically try to reconnect
|
||||
* console.log(socket.active); // true
|
||||
* });
|
||||
*/
|
||||
get active(): boolean;
|
||||
/**
|
||||
* "Opens" the socket.
|
||||
*
|
||||
* @example
|
||||
* const socket = io({
|
||||
* autoConnect: false
|
||||
* });
|
||||
*
|
||||
* socket.connect();
|
||||
*/
|
||||
connect(): this;
|
||||
/**
|
||||
* Alias for {@link connect()}.
|
||||
*/
|
||||
open(): this;
|
||||
/**
|
||||
* Sends a `message` event.
|
||||
*
|
||||
* This method mimics the WebSocket.send() method.
|
||||
*
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
|
||||
*
|
||||
* @example
|
||||
* socket.send("hello");
|
||||
*
|
||||
* // this is equivalent to
|
||||
* socket.emit("message", "hello");
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
send(...args: any[]): this;
|
||||
/**
|
||||
* Override `emit`.
|
||||
* If the event is in `events`, it's emitted normally.
|
||||
*
|
||||
* @example
|
||||
* socket.emit("hello", "world");
|
||||
*
|
||||
* // all serializable datastructures are supported (no need to call JSON.stringify)
|
||||
* socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
|
||||
*
|
||||
* // with an acknowledgement from the server
|
||||
* socket.emit("hello", "world", (val) => {
|
||||
* // ...
|
||||
* });
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
emit<Ev extends EventNames<EmitEvents>>(ev: Ev, ...args: EventParams<EmitEvents, Ev>): this;
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
private _registerAckCallback;
|
||||
/**
|
||||
* Emits an event and waits for an acknowledgement
|
||||
*
|
||||
* @example
|
||||
* // without timeout
|
||||
* const response = await socket.emitWithAck("hello", "world");
|
||||
*
|
||||
* // with a specific timeout
|
||||
* try {
|
||||
* const response = await socket.timeout(1000).emitWithAck("hello", "world");
|
||||
* } catch (err) {
|
||||
* // the server did not acknowledge the event in the given delay
|
||||
* }
|
||||
*
|
||||
* @return a Promise that will be fulfilled when the server acknowledges the event
|
||||
*/
|
||||
emitWithAck<Ev extends EventNames<EmitEvents>>(ev: Ev, ...args: AllButLast<EventParams<EmitEvents, Ev>>): Promise<FirstArg<Last<EventParams<EmitEvents, Ev>>>>;
|
||||
/**
|
||||
* Add the packet to the queue.
|
||||
* @param args
|
||||
* @private
|
||||
*/
|
||||
private _addToQueue;
|
||||
/**
|
||||
* Send the first packet of the queue, and wait for an acknowledgement from the server.
|
||||
* @param force - whether to resend a packet that has not been acknowledged yet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private _drainQueue;
|
||||
/**
|
||||
* Sends a packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
private packet;
|
||||
/**
|
||||
* Called upon engine `open`.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onopen;
|
||||
/**
|
||||
* Sends a CONNECT packet to initiate the Socket.IO session.
|
||||
*
|
||||
* @param data
|
||||
* @private
|
||||
*/
|
||||
private _sendConnectPacket;
|
||||
/**
|
||||
* Called upon engine or manager `error`.
|
||||
*
|
||||
* @param err
|
||||
* @private
|
||||
*/
|
||||
private onerror;
|
||||
/**
|
||||
* Called upon engine `close`.
|
||||
*
|
||||
* @param reason
|
||||
* @param description
|
||||
* @private
|
||||
*/
|
||||
private onclose;
|
||||
/**
|
||||
* Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
|
||||
* the server.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private _clearAcks;
|
||||
/**
|
||||
* Called with socket packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
private onpacket;
|
||||
/**
|
||||
* Called upon a server event.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
private onevent;
|
||||
private emitEvent;
|
||||
/**
|
||||
* Produces an ack callback to emit with an event.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private ack;
|
||||
/**
|
||||
* Called upon a server acknowledgement.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
private onack;
|
||||
/**
|
||||
* Called upon server connect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private onconnect;
|
||||
/**
|
||||
* Emit buffered events (received and emitted).
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private emitBuffered;
|
||||
/**
|
||||
* Called upon server disconnect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private ondisconnect;
|
||||
/**
|
||||
* Called upon forced client/server side disconnections,
|
||||
* this method ensures the manager stops tracking us and
|
||||
* that reconnections don't get triggered for this.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private destroy;
|
||||
/**
|
||||
* Disconnects the socket manually. In that case, the socket will not try to reconnect.
|
||||
*
|
||||
* If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* // console.log(reason); prints "io client disconnect"
|
||||
* });
|
||||
*
|
||||
* socket.disconnect();
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
disconnect(): this;
|
||||
/**
|
||||
* Alias for {@link disconnect()}.
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
close(): this;
|
||||
/**
|
||||
* Sets the compress flag.
|
||||
*
|
||||
* @example
|
||||
* socket.compress(false).emit("hello");
|
||||
*
|
||||
* @param compress - if `true`, compresses the sending data
|
||||
* @return self
|
||||
*/
|
||||
compress(compress: boolean): this;
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
|
||||
* ready to send messages.
|
||||
*
|
||||
* @example
|
||||
* socket.volatile.emit("hello"); // the server may or may not receive it
|
||||
*
|
||||
* @returns self
|
||||
*/
|
||||
get volatile(): this;
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the callback will be called with an error when the
|
||||
* given number of milliseconds have elapsed without an acknowledgement from the server:
|
||||
*
|
||||
* @example
|
||||
* socket.timeout(5000).emit("my-event", (err) => {
|
||||
* if (err) {
|
||||
* // the server did not acknowledge the event in the given delay
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* @returns self
|
||||
*/
|
||||
timeout(timeout: number): Socket<ListenEvents, DecorateAcknowledgements<EmitEvents>>;
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback.
|
||||
*
|
||||
* @example
|
||||
* socket.onAny((event, ...args) => {
|
||||
* console.log(`got ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
onAny(listener: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback. The listener is added to the beginning of the listeners array.
|
||||
*
|
||||
* @example
|
||||
* socket.prependAny((event, ...args) => {
|
||||
* console.log(`got event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
prependAny(listener: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Removes the listener that will be fired when any event is emitted.
|
||||
*
|
||||
* @example
|
||||
* const catchAllListener = (event, ...args) => {
|
||||
* console.log(`got event ${event}`);
|
||||
* }
|
||||
*
|
||||
* socket.onAny(catchAllListener);
|
||||
*
|
||||
* // remove a specific listener
|
||||
* socket.offAny(catchAllListener);
|
||||
*
|
||||
* // or remove all listeners
|
||||
* socket.offAny();
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
offAny(listener?: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
|
||||
* e.g. to remove listeners.
|
||||
*/
|
||||
listenersAny(): ((...args: any[]) => void)[];
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback.
|
||||
*
|
||||
* Note: acknowledgements sent to the server are not included.
|
||||
*
|
||||
* @example
|
||||
* socket.onAnyOutgoing((event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
onAnyOutgoing(listener: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback. The listener is added to the beginning of the listeners array.
|
||||
*
|
||||
* Note: acknowledgements sent to the server are not included.
|
||||
*
|
||||
* @example
|
||||
* socket.prependAnyOutgoing((event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
prependAnyOutgoing(listener: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Removes the listener that will be fired when any event is emitted.
|
||||
*
|
||||
* @example
|
||||
* const catchAllListener = (event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* }
|
||||
*
|
||||
* socket.onAnyOutgoing(catchAllListener);
|
||||
*
|
||||
* // remove a specific listener
|
||||
* socket.offAnyOutgoing(catchAllListener);
|
||||
*
|
||||
* // or remove all listeners
|
||||
* socket.offAnyOutgoing();
|
||||
*
|
||||
* @param [listener] - the catch-all listener (optional)
|
||||
*/
|
||||
offAnyOutgoing(listener?: (...args: any[]) => void): this;
|
||||
/**
|
||||
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
|
||||
* e.g. to remove listeners.
|
||||
*/
|
||||
listenersAnyOutgoing(): ((...args: any[]) => void)[];
|
||||
/**
|
||||
* Notify the listeners for each packet sent
|
||||
*
|
||||
* @param packet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
private notifyOutgoingListeners;
|
||||
}
|
||||
export declare namespace Socket {
|
||||
type DisconnectReason = "io server disconnect" | "io client disconnect" | "ping timeout" | "transport close" | "transport error" | "parse error";
|
||||
}
|
||||
export {};
|
||||
+880
@@ -0,0 +1,880 @@
|
||||
import { PacketType } from "socket.io-parser";
|
||||
import { on } from "./on.js";
|
||||
import { Emitter, } from "@socket.io/component-emitter";
|
||||
/**
|
||||
* Internal events.
|
||||
* These events can't be emitted by the user.
|
||||
*/
|
||||
const RESERVED_EVENTS = Object.freeze({
|
||||
connect: 1,
|
||||
connect_error: 1,
|
||||
disconnect: 1,
|
||||
disconnecting: 1,
|
||||
// EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
|
||||
newListener: 1,
|
||||
removeListener: 1,
|
||||
});
|
||||
/**
|
||||
* A Socket is the fundamental class for interacting with the server.
|
||||
*
|
||||
* A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log("connected");
|
||||
* });
|
||||
*
|
||||
* // send an event to the server
|
||||
* socket.emit("foo", "bar");
|
||||
*
|
||||
* socket.on("foobar", () => {
|
||||
* // an event was received from the server
|
||||
* });
|
||||
*
|
||||
* // upon disconnection
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* console.log(`disconnected due to ${reason}`);
|
||||
* });
|
||||
*/
|
||||
export class Socket extends Emitter {
|
||||
/**
|
||||
* `Socket` constructor.
|
||||
*/
|
||||
constructor(io, nsp, opts) {
|
||||
super();
|
||||
/**
|
||||
* Whether the socket is currently connected to the server.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log(socket.connected); // true
|
||||
* });
|
||||
*
|
||||
* socket.on("disconnect", () => {
|
||||
* console.log(socket.connected); // false
|
||||
* });
|
||||
*/
|
||||
this.connected = false;
|
||||
/**
|
||||
* Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
|
||||
* be transmitted by the server.
|
||||
*/
|
||||
this.recovered = false;
|
||||
/**
|
||||
* Buffer for packets received before the CONNECT packet
|
||||
*/
|
||||
this.receiveBuffer = [];
|
||||
/**
|
||||
* Buffer for packets that will be sent once the socket is connected
|
||||
*/
|
||||
this.sendBuffer = [];
|
||||
/**
|
||||
* The queue of packets to be sent with retry in case of failure.
|
||||
*
|
||||
* Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
|
||||
* @private
|
||||
*/
|
||||
this._queue = [];
|
||||
/**
|
||||
* A sequence to generate the ID of the {@link QueuedPacket}.
|
||||
* @private
|
||||
*/
|
||||
this._queueSeq = 0;
|
||||
this.ids = 0;
|
||||
/**
|
||||
* A map containing acknowledgement handlers.
|
||||
*
|
||||
* The `withError` attribute is used to differentiate handlers that accept an error as first argument:
|
||||
*
|
||||
* - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
|
||||
* - `socket.timeout(5000).emit("test", (err, value) => { ... })`
|
||||
* - `const value = await socket.emitWithAck("test")`
|
||||
*
|
||||
* From those that don't:
|
||||
*
|
||||
* - `socket.emit("test", (value) => { ... });`
|
||||
*
|
||||
* In the first case, the handlers will be called with an error when:
|
||||
*
|
||||
* - the timeout is reached
|
||||
* - the socket gets disconnected
|
||||
*
|
||||
* In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
|
||||
* an acknowledgement from the server.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
this.acks = {};
|
||||
this.flags = {};
|
||||
this.io = io;
|
||||
this.nsp = nsp;
|
||||
if (opts && opts.auth) {
|
||||
this.auth = opts.auth;
|
||||
}
|
||||
this._opts = Object.assign({}, opts);
|
||||
if (this.io._autoConnect)
|
||||
this.open();
|
||||
}
|
||||
/**
|
||||
* Whether the socket is currently disconnected
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("connect", () => {
|
||||
* console.log(socket.disconnected); // false
|
||||
* });
|
||||
*
|
||||
* socket.on("disconnect", () => {
|
||||
* console.log(socket.disconnected); // true
|
||||
* });
|
||||
*/
|
||||
get disconnected() {
|
||||
return !this.connected;
|
||||
}
|
||||
/**
|
||||
* Subscribe to open, close and packet events
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
subEvents() {
|
||||
if (this.subs)
|
||||
return;
|
||||
const io = this.io;
|
||||
this.subs = [
|
||||
on(io, "open", this.onopen.bind(this)),
|
||||
on(io, "packet", this.onpacket.bind(this)),
|
||||
on(io, "error", this.onerror.bind(this)),
|
||||
on(io, "close", this.onclose.bind(this)),
|
||||
];
|
||||
}
|
||||
/**
|
||||
* Whether the Socket will try to reconnect when its Manager connects or reconnects.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* console.log(socket.active); // true
|
||||
*
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* if (reason === "io server disconnect") {
|
||||
* // the disconnection was initiated by the server, you need to manually reconnect
|
||||
* console.log(socket.active); // false
|
||||
* }
|
||||
* // else the socket will automatically try to reconnect
|
||||
* console.log(socket.active); // true
|
||||
* });
|
||||
*/
|
||||
get active() {
|
||||
return !!this.subs;
|
||||
}
|
||||
/**
|
||||
* "Opens" the socket.
|
||||
*
|
||||
* @example
|
||||
* const socket = io({
|
||||
* autoConnect: false
|
||||
* });
|
||||
*
|
||||
* socket.connect();
|
||||
*/
|
||||
connect() {
|
||||
if (this.connected)
|
||||
return this;
|
||||
this.subEvents();
|
||||
if (!this.io["_reconnecting"])
|
||||
this.io.open(); // ensure open
|
||||
if ("open" === this.io._readyState)
|
||||
this.onopen();
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Alias for {@link connect()}.
|
||||
*/
|
||||
open() {
|
||||
return this.connect();
|
||||
}
|
||||
/**
|
||||
* Sends a `message` event.
|
||||
*
|
||||
* This method mimics the WebSocket.send() method.
|
||||
*
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
|
||||
*
|
||||
* @example
|
||||
* socket.send("hello");
|
||||
*
|
||||
* // this is equivalent to
|
||||
* socket.emit("message", "hello");
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
send(...args) {
|
||||
args.unshift("message");
|
||||
this.emit.apply(this, args);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Override `emit`.
|
||||
* If the event is in `events`, it's emitted normally.
|
||||
*
|
||||
* @example
|
||||
* socket.emit("hello", "world");
|
||||
*
|
||||
* // all serializable datastructures are supported (no need to call JSON.stringify)
|
||||
* socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
|
||||
*
|
||||
* // with an acknowledgement from the server
|
||||
* socket.emit("hello", "world", (val) => {
|
||||
* // ...
|
||||
* });
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
emit(ev, ...args) {
|
||||
var _a, _b, _c;
|
||||
if (RESERVED_EVENTS.hasOwnProperty(ev)) {
|
||||
throw new Error('"' + ev.toString() + '" is a reserved event name');
|
||||
}
|
||||
args.unshift(ev);
|
||||
if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
|
||||
this._addToQueue(args);
|
||||
return this;
|
||||
}
|
||||
const packet = {
|
||||
type: PacketType.EVENT,
|
||||
data: args,
|
||||
};
|
||||
packet.options = {};
|
||||
packet.options.compress = this.flags.compress !== false;
|
||||
// event ack callback
|
||||
if ("function" === typeof args[args.length - 1]) {
|
||||
const id = this.ids++;
|
||||
const ack = args.pop();
|
||||
this._registerAckCallback(id, ack);
|
||||
packet.id = id;
|
||||
}
|
||||
const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
|
||||
const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
|
||||
const discardPacket = this.flags.volatile && !isTransportWritable;
|
||||
if (discardPacket) {
|
||||
}
|
||||
else if (isConnected) {
|
||||
this.notifyOutgoingListeners(packet);
|
||||
this.packet(packet);
|
||||
}
|
||||
else {
|
||||
this.sendBuffer.push(packet);
|
||||
}
|
||||
this.flags = {};
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
_registerAckCallback(id, ack) {
|
||||
var _a;
|
||||
const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
|
||||
if (timeout === undefined) {
|
||||
this.acks[id] = ack;
|
||||
return;
|
||||
}
|
||||
// @ts-ignore
|
||||
const timer = this.io.setTimeoutFn(() => {
|
||||
delete this.acks[id];
|
||||
for (let i = 0; i < this.sendBuffer.length; i++) {
|
||||
if (this.sendBuffer[i].id === id) {
|
||||
this.sendBuffer.splice(i, 1);
|
||||
}
|
||||
}
|
||||
ack.call(this, new Error("operation has timed out"));
|
||||
}, timeout);
|
||||
const fn = (...args) => {
|
||||
// @ts-ignore
|
||||
this.io.clearTimeoutFn(timer);
|
||||
ack.apply(this, args);
|
||||
};
|
||||
fn.withError = true;
|
||||
this.acks[id] = fn;
|
||||
}
|
||||
/**
|
||||
* Emits an event and waits for an acknowledgement
|
||||
*
|
||||
* @example
|
||||
* // without timeout
|
||||
* const response = await socket.emitWithAck("hello", "world");
|
||||
*
|
||||
* // with a specific timeout
|
||||
* try {
|
||||
* const response = await socket.timeout(1000).emitWithAck("hello", "world");
|
||||
* } catch (err) {
|
||||
* // the server did not acknowledge the event in the given delay
|
||||
* }
|
||||
*
|
||||
* @return a Promise that will be fulfilled when the server acknowledges the event
|
||||
*/
|
||||
emitWithAck(ev, ...args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const fn = (arg1, arg2) => {
|
||||
return arg1 ? reject(arg1) : resolve(arg2);
|
||||
};
|
||||
fn.withError = true;
|
||||
args.push(fn);
|
||||
this.emit(ev, ...args);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Add the packet to the queue.
|
||||
* @param args
|
||||
* @private
|
||||
*/
|
||||
_addToQueue(args) {
|
||||
let ack;
|
||||
if (typeof args[args.length - 1] === "function") {
|
||||
ack = args.pop();
|
||||
}
|
||||
const packet = {
|
||||
id: this._queueSeq++,
|
||||
tryCount: 0,
|
||||
pending: false,
|
||||
args,
|
||||
flags: Object.assign({ fromQueue: true }, this.flags),
|
||||
};
|
||||
args.push((err, ...responseArgs) => {
|
||||
if (packet !== this._queue[0]) {
|
||||
}
|
||||
const hasError = err !== null;
|
||||
if (hasError) {
|
||||
if (packet.tryCount > this._opts.retries) {
|
||||
this._queue.shift();
|
||||
if (ack) {
|
||||
ack(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
this._queue.shift();
|
||||
if (ack) {
|
||||
ack(null, ...responseArgs);
|
||||
}
|
||||
}
|
||||
packet.pending = false;
|
||||
return this._drainQueue();
|
||||
});
|
||||
this._queue.push(packet);
|
||||
this._drainQueue();
|
||||
}
|
||||
/**
|
||||
* Send the first packet of the queue, and wait for an acknowledgement from the server.
|
||||
* @param force - whether to resend a packet that has not been acknowledged yet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_drainQueue(force = false) {
|
||||
if (!this.connected || this._queue.length === 0) {
|
||||
return;
|
||||
}
|
||||
const packet = this._queue[0];
|
||||
if (packet.pending && !force) {
|
||||
return;
|
||||
}
|
||||
packet.pending = true;
|
||||
packet.tryCount++;
|
||||
this.flags = packet.flags;
|
||||
this.emit.apply(this, packet.args);
|
||||
}
|
||||
/**
|
||||
* Sends a packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
packet(packet) {
|
||||
packet.nsp = this.nsp;
|
||||
this.io._packet(packet);
|
||||
}
|
||||
/**
|
||||
* Called upon engine `open`.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onopen() {
|
||||
if (typeof this.auth == "function") {
|
||||
this.auth((data) => {
|
||||
this._sendConnectPacket(data);
|
||||
});
|
||||
}
|
||||
else {
|
||||
this._sendConnectPacket(this.auth);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Sends a CONNECT packet to initiate the Socket.IO session.
|
||||
*
|
||||
* @param data
|
||||
* @private
|
||||
*/
|
||||
_sendConnectPacket(data) {
|
||||
this.packet({
|
||||
type: PacketType.CONNECT,
|
||||
data: this._pid
|
||||
? Object.assign({ pid: this._pid, offset: this._lastOffset }, data)
|
||||
: data,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Called upon engine or manager `error`.
|
||||
*
|
||||
* @param err
|
||||
* @private
|
||||
*/
|
||||
onerror(err) {
|
||||
if (!this.connected) {
|
||||
this.emitReserved("connect_error", err);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Called upon engine `close`.
|
||||
*
|
||||
* @param reason
|
||||
* @param description
|
||||
* @private
|
||||
*/
|
||||
onclose(reason, description) {
|
||||
this.connected = false;
|
||||
delete this.id;
|
||||
this.emitReserved("disconnect", reason, description);
|
||||
this._clearAcks();
|
||||
}
|
||||
/**
|
||||
* Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
|
||||
* the server.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
_clearAcks() {
|
||||
Object.keys(this.acks).forEach((id) => {
|
||||
const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
|
||||
if (!isBuffered) {
|
||||
// note: handlers that do not accept an error as first argument are ignored here
|
||||
const ack = this.acks[id];
|
||||
delete this.acks[id];
|
||||
if (ack.withError) {
|
||||
ack.call(this, new Error("socket has been disconnected"));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Called with socket packet.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
onpacket(packet) {
|
||||
const sameNamespace = packet.nsp === this.nsp;
|
||||
if (!sameNamespace)
|
||||
return;
|
||||
switch (packet.type) {
|
||||
case PacketType.CONNECT:
|
||||
if (packet.data && packet.data.sid) {
|
||||
this.onconnect(packet.data.sid, packet.data.pid);
|
||||
}
|
||||
else {
|
||||
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/)"));
|
||||
}
|
||||
break;
|
||||
case PacketType.EVENT:
|
||||
case PacketType.BINARY_EVENT:
|
||||
this.onevent(packet);
|
||||
break;
|
||||
case PacketType.ACK:
|
||||
case PacketType.BINARY_ACK:
|
||||
this.onack(packet);
|
||||
break;
|
||||
case PacketType.DISCONNECT:
|
||||
this.ondisconnect();
|
||||
break;
|
||||
case PacketType.CONNECT_ERROR:
|
||||
this.destroy();
|
||||
const err = new Error(packet.data.message);
|
||||
// @ts-ignore
|
||||
err.data = packet.data.data;
|
||||
this.emitReserved("connect_error", err);
|
||||
break;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Called upon a server event.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
onevent(packet) {
|
||||
const args = packet.data || [];
|
||||
if (null != packet.id) {
|
||||
args.push(this.ack(packet.id));
|
||||
}
|
||||
if (this.connected) {
|
||||
this.emitEvent(args);
|
||||
}
|
||||
else {
|
||||
this.receiveBuffer.push(Object.freeze(args));
|
||||
}
|
||||
}
|
||||
emitEvent(args) {
|
||||
if (this._anyListeners && this._anyListeners.length) {
|
||||
const listeners = this._anyListeners.slice();
|
||||
for (const listener of listeners) {
|
||||
listener.apply(this, args);
|
||||
}
|
||||
}
|
||||
super.emit.apply(this, args);
|
||||
if (this._pid && args.length && typeof args[args.length - 1] === "string") {
|
||||
this._lastOffset = args[args.length - 1];
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Produces an ack callback to emit with an event.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
ack(id) {
|
||||
const self = this;
|
||||
let sent = false;
|
||||
return function (...args) {
|
||||
// prevent double callbacks
|
||||
if (sent)
|
||||
return;
|
||||
sent = true;
|
||||
self.packet({
|
||||
type: PacketType.ACK,
|
||||
id: id,
|
||||
data: args,
|
||||
});
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Called upon a server acknowledgement.
|
||||
*
|
||||
* @param packet
|
||||
* @private
|
||||
*/
|
||||
onack(packet) {
|
||||
const ack = this.acks[packet.id];
|
||||
if (typeof ack !== "function") {
|
||||
return;
|
||||
}
|
||||
delete this.acks[packet.id];
|
||||
// @ts-ignore FIXME ack is incorrectly inferred as 'never'
|
||||
if (ack.withError) {
|
||||
packet.data.unshift(null);
|
||||
}
|
||||
// @ts-ignore
|
||||
ack.apply(this, packet.data);
|
||||
}
|
||||
/**
|
||||
* Called upon server connect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
onconnect(id, pid) {
|
||||
this.id = id;
|
||||
this.recovered = pid && this._pid === pid;
|
||||
this._pid = pid; // defined only if connection state recovery is enabled
|
||||
this.connected = true;
|
||||
this.emitBuffered();
|
||||
this._drainQueue(true);
|
||||
this.emitReserved("connect");
|
||||
}
|
||||
/**
|
||||
* Emit buffered events (received and emitted).
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
emitBuffered() {
|
||||
this.receiveBuffer.forEach((args) => this.emitEvent(args));
|
||||
this.receiveBuffer = [];
|
||||
this.sendBuffer.forEach((packet) => {
|
||||
this.notifyOutgoingListeners(packet);
|
||||
this.packet(packet);
|
||||
});
|
||||
this.sendBuffer = [];
|
||||
}
|
||||
/**
|
||||
* Called upon server disconnect.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
ondisconnect() {
|
||||
this.destroy();
|
||||
this.onclose("io server disconnect");
|
||||
}
|
||||
/**
|
||||
* Called upon forced client/server side disconnections,
|
||||
* this method ensures the manager stops tracking us and
|
||||
* that reconnections don't get triggered for this.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
destroy() {
|
||||
if (this.subs) {
|
||||
// clean subscriptions to avoid reconnections
|
||||
this.subs.forEach((subDestroy) => subDestroy());
|
||||
this.subs = undefined;
|
||||
}
|
||||
this.io["_destroy"](this);
|
||||
}
|
||||
/**
|
||||
* Disconnects the socket manually. In that case, the socket will not try to reconnect.
|
||||
*
|
||||
* If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
|
||||
*
|
||||
* @example
|
||||
* const socket = io();
|
||||
*
|
||||
* socket.on("disconnect", (reason) => {
|
||||
* // console.log(reason); prints "io client disconnect"
|
||||
* });
|
||||
*
|
||||
* socket.disconnect();
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
disconnect() {
|
||||
if (this.connected) {
|
||||
this.packet({ type: PacketType.DISCONNECT });
|
||||
}
|
||||
// remove socket from pool
|
||||
this.destroy();
|
||||
if (this.connected) {
|
||||
// fire events
|
||||
this.onclose("io client disconnect");
|
||||
}
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Alias for {@link disconnect()}.
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
close() {
|
||||
return this.disconnect();
|
||||
}
|
||||
/**
|
||||
* Sets the compress flag.
|
||||
*
|
||||
* @example
|
||||
* socket.compress(false).emit("hello");
|
||||
*
|
||||
* @param compress - if `true`, compresses the sending data
|
||||
* @return self
|
||||
*/
|
||||
compress(compress) {
|
||||
this.flags.compress = compress;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
|
||||
* ready to send messages.
|
||||
*
|
||||
* @example
|
||||
* socket.volatile.emit("hello"); // the server may or may not receive it
|
||||
*
|
||||
* @returns self
|
||||
*/
|
||||
get volatile() {
|
||||
this.flags.volatile = true;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Sets a modifier for a subsequent event emission that the callback will be called with an error when the
|
||||
* given number of milliseconds have elapsed without an acknowledgement from the server:
|
||||
*
|
||||
* @example
|
||||
* socket.timeout(5000).emit("my-event", (err) => {
|
||||
* if (err) {
|
||||
* // the server did not acknowledge the event in the given delay
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* @returns self
|
||||
*/
|
||||
timeout(timeout) {
|
||||
this.flags.timeout = timeout;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback.
|
||||
*
|
||||
* @example
|
||||
* socket.onAny((event, ...args) => {
|
||||
* console.log(`got ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
onAny(listener) {
|
||||
this._anyListeners = this._anyListeners || [];
|
||||
this._anyListeners.push(listener);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback. The listener is added to the beginning of the listeners array.
|
||||
*
|
||||
* @example
|
||||
* socket.prependAny((event, ...args) => {
|
||||
* console.log(`got event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
prependAny(listener) {
|
||||
this._anyListeners = this._anyListeners || [];
|
||||
this._anyListeners.unshift(listener);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Removes the listener that will be fired when any event is emitted.
|
||||
*
|
||||
* @example
|
||||
* const catchAllListener = (event, ...args) => {
|
||||
* console.log(`got event ${event}`);
|
||||
* }
|
||||
*
|
||||
* socket.onAny(catchAllListener);
|
||||
*
|
||||
* // remove a specific listener
|
||||
* socket.offAny(catchAllListener);
|
||||
*
|
||||
* // or remove all listeners
|
||||
* socket.offAny();
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
offAny(listener) {
|
||||
if (!this._anyListeners) {
|
||||
return this;
|
||||
}
|
||||
if (listener) {
|
||||
const listeners = this._anyListeners;
|
||||
for (let i = 0; i < listeners.length; i++) {
|
||||
if (listener === listeners[i]) {
|
||||
listeners.splice(i, 1);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
this._anyListeners = [];
|
||||
}
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
|
||||
* e.g. to remove listeners.
|
||||
*/
|
||||
listenersAny() {
|
||||
return this._anyListeners || [];
|
||||
}
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback.
|
||||
*
|
||||
* Note: acknowledgements sent to the server are not included.
|
||||
*
|
||||
* @example
|
||||
* socket.onAnyOutgoing((event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
onAnyOutgoing(listener) {
|
||||
this._anyOutgoingListeners = this._anyOutgoingListeners || [];
|
||||
this._anyOutgoingListeners.push(listener);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
|
||||
* callback. The listener is added to the beginning of the listeners array.
|
||||
*
|
||||
* Note: acknowledgements sent to the server are not included.
|
||||
*
|
||||
* @example
|
||||
* socket.prependAnyOutgoing((event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* });
|
||||
*
|
||||
* @param listener
|
||||
*/
|
||||
prependAnyOutgoing(listener) {
|
||||
this._anyOutgoingListeners = this._anyOutgoingListeners || [];
|
||||
this._anyOutgoingListeners.unshift(listener);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Removes the listener that will be fired when any event is emitted.
|
||||
*
|
||||
* @example
|
||||
* const catchAllListener = (event, ...args) => {
|
||||
* console.log(`sent event ${event}`);
|
||||
* }
|
||||
*
|
||||
* socket.onAnyOutgoing(catchAllListener);
|
||||
*
|
||||
* // remove a specific listener
|
||||
* socket.offAnyOutgoing(catchAllListener);
|
||||
*
|
||||
* // or remove all listeners
|
||||
* socket.offAnyOutgoing();
|
||||
*
|
||||
* @param [listener] - the catch-all listener (optional)
|
||||
*/
|
||||
offAnyOutgoing(listener) {
|
||||
if (!this._anyOutgoingListeners) {
|
||||
return this;
|
||||
}
|
||||
if (listener) {
|
||||
const listeners = this._anyOutgoingListeners;
|
||||
for (let i = 0; i < listeners.length; i++) {
|
||||
if (listener === listeners[i]) {
|
||||
listeners.splice(i, 1);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
this._anyOutgoingListeners = [];
|
||||
}
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
|
||||
* e.g. to remove listeners.
|
||||
*/
|
||||
listenersAnyOutgoing() {
|
||||
return this._anyOutgoingListeners || [];
|
||||
}
|
||||
/**
|
||||
* Notify the listeners for each packet sent
|
||||
*
|
||||
* @param packet
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
notifyOutgoingListeners(packet) {
|
||||
if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
|
||||
const listeners = this._anyOutgoingListeners.slice();
|
||||
for (const listener of listeners) {
|
||||
listener.apply(this, packet.data);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
type ParsedUrl = {
|
||||
source: string;
|
||||
protocol: string;
|
||||
authority: string;
|
||||
userInfo: string;
|
||||
user: string;
|
||||
password: string;
|
||||
host: string;
|
||||
port: string;
|
||||
relative: string;
|
||||
path: string;
|
||||
directory: string;
|
||||
file: string;
|
||||
query: string;
|
||||
anchor: string;
|
||||
pathNames: Array<string>;
|
||||
queryKey: {
|
||||
[key: string]: string;
|
||||
};
|
||||
id: string;
|
||||
href: string;
|
||||
};
|
||||
/**
|
||||
* URL parser.
|
||||
*
|
||||
* @param uri - url
|
||||
* @param path - the request path of the connection
|
||||
* @param loc - An object meant to mimic window.location.
|
||||
* Defaults to window.location.
|
||||
* @public
|
||||
*/
|
||||
export declare function url(uri: string | ParsedUrl, path?: string, loc?: Location): ParsedUrl;
|
||||
export {};
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
import { parse } from "engine.io-client";
|
||||
/**
|
||||
* URL parser.
|
||||
*
|
||||
* @param uri - url
|
||||
* @param path - the request path of the connection
|
||||
* @param loc - An object meant to mimic window.location.
|
||||
* Defaults to window.location.
|
||||
* @public
|
||||
*/
|
||||
export function url(uri, path = "", loc) {
|
||||
let obj = uri;
|
||||
// default to window.location
|
||||
loc = loc || (typeof location !== "undefined" && location);
|
||||
if (null == uri)
|
||||
uri = loc.protocol + "//" + loc.host;
|
||||
// relative path support
|
||||
if (typeof uri === "string") {
|
||||
if ("/" === uri.charAt(0)) {
|
||||
if ("/" === uri.charAt(1)) {
|
||||
uri = loc.protocol + uri;
|
||||
}
|
||||
else {
|
||||
uri = loc.host + uri;
|
||||
}
|
||||
}
|
||||
if (!/^(https?|wss?):\/\//.test(uri)) {
|
||||
if ("undefined" !== typeof loc) {
|
||||
uri = loc.protocol + "//" + uri;
|
||||
}
|
||||
else {
|
||||
uri = "https://" + uri;
|
||||
}
|
||||
}
|
||||
// parse
|
||||
obj = parse(uri);
|
||||
}
|
||||
// make sure we treat `localhost:80` and `localhost` equally
|
||||
if (!obj.port) {
|
||||
if (/^(http|ws)$/.test(obj.protocol)) {
|
||||
obj.port = "80";
|
||||
}
|
||||
else if (/^(http|ws)s$/.test(obj.protocol)) {
|
||||
obj.port = "443";
|
||||
}
|
||||
}
|
||||
obj.path = obj.path || "/";
|
||||
const ipv6 = obj.host.indexOf(":") !== -1;
|
||||
const host = ipv6 ? "[" + obj.host + "]" : obj.host;
|
||||
// define unique id
|
||||
obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
|
||||
// define href
|
||||
obj.href =
|
||||
obj.protocol +
|
||||
"://" +
|
||||
host +
|
||||
(loc && loc.port === obj.port ? "" : ":" + obj.port);
|
||||
return obj;
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
/*!
|
||||
* Socket.IO v4.8.3
|
||||
* (c) 2014-2025 Guillermo Rauch
|
||||
* Released under the MIT License.
|
||||
*/
|
||||
const t=Object.create(null);t.open="0",t.close="1",t.ping="2",t.pong="3",t.message="4",t.upgrade="5",t.noop="6";const s=Object.create(null);Object.keys(t).forEach((i=>{s[t[i]]=i}));const i={type:"error",data:"parser error"},e="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),n="function"==typeof ArrayBuffer,r=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,o=({type:s,data:i},o,c)=>e&&i instanceof Blob?o?c(i):h(i,c):n&&(i instanceof ArrayBuffer||r(i))?o?c(i):h(new Blob([i]),c):c(t[s]+(i||"")),h=(t,s)=>{const i=new FileReader;return i.onload=function(){const t=i.result.split(",")[1];s("b"+(t||""))},i.readAsDataURL(t)};function c(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let a;const u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",f="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)f[u.charCodeAt(t)]=t;const l="function"==typeof ArrayBuffer,d=(t,e)=>{if("string"!=typeof t)return{type:"message",data:y(t,e)};const n=t.charAt(0);if("b"===n)return{type:"message",data:p(t.substring(1),e)};return s[n]?t.length>1?{type:s[n],data:t.substring(1)}:{type:s[n]}:i},p=(t,s)=>{if(l){const i=(t=>{let s,i,e,n,r,o=.75*t.length,h=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);const a=new ArrayBuffer(o),u=new Uint8Array(a);for(s=0;s<h;s+=4)i=f[t.charCodeAt(s)],e=f[t.charCodeAt(s+1)],n=f[t.charCodeAt(s+2)],r=f[t.charCodeAt(s+3)],u[c++]=i<<2|e>>4,u[c++]=(15&e)<<4|n>>2,u[c++]=(3&n)<<6|63&r;return a})(t);return y(i,s)}return{base64:!0,data:t}},y=(t,s)=>"blob"===s?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,b=String.fromCharCode(30);function g(){return new TransformStream({transform(t,s){!function(t,s){e&&t.data instanceof Blob?t.data.arrayBuffer().then(c).then(s):n&&(t.data instanceof ArrayBuffer||r(t.data))?s(c(t.data)):o(t,!1,(t=>{a||(a=new TextEncoder),s(a.encode(t))}))}(t,(i=>{const e=i.length;let n;if(e<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,e);else if(e<65536){n=new Uint8Array(3);const t=new DataView(n.buffer);t.setUint8(0,126),t.setUint16(1,e)}else{n=new Uint8Array(9);const t=new DataView(n.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(e))}t.data&&"string"!=typeof t.data&&(n[0]|=128),s.enqueue(n),s.enqueue(i)}))}})}let w;function v(t){return t.reduce(((t,s)=>t+s.length),0)}function m(t,s){if(t[0].length===s)return t.shift();const i=new Uint8Array(s);let e=0;for(let n=0;n<s;n++)i[n]=t[0][e++],e===t[0].length&&(t.shift(),e=0);return t.length&&e<t[0].length&&(t[0]=t[0].slice(e)),i}function k(t){if(t)return function(t){for(var s in k.prototype)t[s]=k.prototype[s];return t}(t)}k.prototype.on=k.prototype.addEventListener=function(t,s){return this.t=this.t||{},(this.t["$"+t]=this.t["$"+t]||[]).push(s),this},k.prototype.once=function(t,s){function i(){this.off(t,i),s.apply(this,arguments)}return i.fn=s,this.on(t,i),this},k.prototype.off=k.prototype.removeListener=k.prototype.removeAllListeners=k.prototype.removeEventListener=function(t,s){if(this.t=this.t||{},0==arguments.length)return this.t={},this;var i,e=this.t["$"+t];if(!e)return this;if(1==arguments.length)return delete this.t["$"+t],this;for(var n=0;n<e.length;n++)if((i=e[n])===s||i.fn===s){e.splice(n,1);break}return 0===e.length&&delete this.t["$"+t],this},k.prototype.emit=function(t){this.t=this.t||{};for(var s=new Array(arguments.length-1),i=this.t["$"+t],e=1;e<arguments.length;e++)s[e-1]=arguments[e];if(i){e=0;for(var n=(i=i.slice(0)).length;e<n;++e)i[e].apply(this,s)}return this},k.prototype.emitReserved=k.prototype.emit,k.prototype.listeners=function(t){return this.t=this.t||{},this.t["$"+t]||[]},k.prototype.hasListeners=function(t){return!!this.listeners(t).length};const A="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,s)=>s(t,0),E="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function O(t,...s){return s.reduce(((s,i)=>(t.hasOwnProperty(i)&&(s[i]=t[i]),s)),{})}const _=E.setTimeout,j=E.clearTimeout;function x(t,s){s.useNativeTimers?(t.setTimeoutFn=_.bind(E),t.clearTimeoutFn=j.bind(E)):(t.setTimeoutFn=E.setTimeout.bind(E),t.clearTimeoutFn=E.clearTimeout.bind(E))}function B(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class C extends Error{constructor(t,s,i){super(t),this.description=s,this.context=i,this.type="TransportError"}}class T extends k{constructor(t){super(),this.writable=!1,x(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,s,i){return super.emitReserved("error",new C(t,s,i)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===thisLine truncated
|
||||
//# sourceMappingURL=socket.io.esm.min.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"socket.io.esm.min.js","sources":["../../engine.io-parser/build/esm/commons.js","../../engine.io-parser/build/esm/encodePacket.browser.js","../../engine.io-parser/build/esm/contrib/base64-arraybuffer.js","../../engine.io-parser/build/esm/decodePacket.browser.js","../../engine.io-parser/build/esm/index.js","../../socket.io-component-emitter/lib/esm/index.js","../../engine.io-client/build/esm/globals.js","../../engine.io-client/build/esm/util.js","../../engine.io-client/build/esm/transport.js","../../engine.io-client/build/esm/contrib/parseqs.js","../../engine.io-client/build/esm/transports/polling.js","../../engine.io-client/build/esm/contrib/has-cors.js","../../engine.io-client/build/esm/transports/polling-xhr.js","../../engine.io-client/build/esm/transports/websocket.js","../../engine.io-client/build/esm/transports/webtransport.js","../../engine.io-client/build/esm/transports/index.js","../../engine.io-client/build/esm/contrib/parseuri.js","../../engine.io-client/build/esm/socket.js","../../engine.io-client/build/esm/transports/polling-fetch.js","../../socket.io-parser/build/esm/is-binary.js","../../socket.io-parser/build/esm/binary.js","../../socket.io-parser/build/esm/index.js","../build/esm/on.js","../build/esm/socket.js","../build/esm/contrib/backo2.js","../build/esm/manager.js","../build/esm/index.js","../build/esm/url.js"],"sourcesContent":["const PACKET_TYPES = Object.create(null); // no Map = no polyfill\nPACKET_TYPES[\"open\"] = \"0\";\nPACKET_TYPES[\"close\"] = \"1\";\nPACKET_TYPES[\"ping\"] = \"2\";\nPACKET_TYPES[\"pong\"] = \"3\";\nPACKET_TYPES[\"message\"] = \"4\";\nPACKET_TYPES[\"upgrade\"] = \"5\";\nPACKET_TYPES[\"noop\"] = \"6\";\nconst PACKET_TYPES_REVERSE = Object.create(null);\nObject.keys(PACKET_TYPES).forEach((key) => {\n PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;\n});\nconst ERROR_PACKET = { type: \"error\", data: \"parser error\" };\nexport { PACKET_TYPES, PACKET_TYPES_REVERSE, ERROR_PACKET };\n","import { PACKET_TYPES } from \"./commons.js\";\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n Object.prototype.toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\n// ArrayBuffer.isView method is not defined in IE10\nconst isView = (obj) => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj && obj.buffer instanceof ArrayBuffer;\n};\nconst encodePacket = ({ type, data }, supportsBinary, callback) => {\n if (withNativeBlob && data instanceof Blob) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(data, callback);\n }\n }\n else if (withNativeArrayBuffer &&\n (data instanceof ArrayBuffer || isView(data))) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(new Blob([data]), callback);\n }\n }\n // plain string\n return callback(PACKET_TYPES[type] + (data || \"\"));\n};\nconst encodeBlobAsBase64 = (data, callback) => {\n const fileReader = new FileReader();\n fileReader.onload = function () {\n const content = fileReader.result.split(\",\")[1];\n callback(\"b\" + (content || \"\"));\n };\n return fileReader.readAsDataURL(data);\n};\nfunction toArray(data) {\n if (data instanceof Uint8Array) {\n return data;\n }\n else if (data instanceof ArrayBuffer) {\n return new Uint8Array(data);\n }\n else {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n }\n}\nlet TEXT_ENCODER;\nexport function encodePacketToBinary(packet, callback) {\n if (withNativeBlob && packet.data instanceof Blob) {\n return packet.data.arrayBuffer().then(toArray).then(callback);\n }\n else if (withNativeArrayBuffer &&\n (packet.data instanceof ArrayBuffer || isView(packet.data))) {\n return callback(toArray(packet.data));\n }\n encodePacket(packet, false, (encoded) => {\n if (!TEXT_ENCODER) {\n TEXT_ENCODER = new TextEncoder();\n }\n callback(TEXT_ENCODER.encode(encoded));\n });\n}\nexport { encodePacket };\n","// imported from https://github.com/socketio/base64-arraybuffer\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nconst lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (let i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nexport const encode = (arraybuffer) => {\n let bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & Line truncated
|
||||
+4955
File diff suppressed because it is too large.
Load diff
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"socket.io.js","sources":["../../engine.io-parser/build/esm/commons.js","../../engine.io-parser/build/esm/encodePacket.browser.js","../../engine.io-parser/build/esm/contrib/base64-arraybuffer.js","../../engine.io-parser/build/esm/decodePacket.browser.js","../../engine.io-parser/build/esm/index.js","../../socket.io-component-emitter/lib/esm/index.js","../../engine.io-client/build/esm/globals.js","../../engine.io-client/build/esm/util.js","../../engine.io-client/build/esm/contrib/parseqs.js","../../engine.io-client/build/esm/transport.js","../../engine.io-client/build/esm/transports/polling.js","../../engine.io-client/build/esm/contrib/has-cors.js","../../engine.io-client/build/esm/transports/polling-xhr.js","../../engine.io-client/build/esm/transports/websocket.js","../../engine.io-client/build/esm/transports/webtransport.js","../../engine.io-client/build/esm/transports/index.js","../../engine.io-client/build/esm/contrib/parseuri.js","../../engine.io-client/build/esm/socket.js","../../engine.io-client/build/esm/index.js","../../../node_modules/ms/index.js","../../../node_modules/debug/src/common.js","../../../node_modules/debug/src/browser.js","../build/esm-debug/url.js","../../socket.io-parser/build/esm/is-binary.js","../../socket.io-parser/build/esm/binary.js","../../socket.io-parser/build/esm/index.js","../build/esm-debug/on.js","../build/esm-debug/socket.js","../build/esm-debug/contrib/backo2.js","../build/esm-debug/manager.js","../build/esm-debug/index.js"],"sourcesContent":["const PACKET_TYPES = Object.create(null); // no Map = no polyfill\nPACKET_TYPES[\"open\"] = \"0\";\nPACKET_TYPES[\"close\"] = \"1\";\nPACKET_TYPES[\"ping\"] = \"2\";\nPACKET_TYPES[\"pong\"] = \"3\";\nPACKET_TYPES[\"message\"] = \"4\";\nPACKET_TYPES[\"upgrade\"] = \"5\";\nPACKET_TYPES[\"noop\"] = \"6\";\nconst PACKET_TYPES_REVERSE = Object.create(null);\nObject.keys(PACKET_TYPES).forEach((key) => {\n PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;\n});\nconst ERROR_PACKET = { type: \"error\", data: \"parser error\" };\nexport { PACKET_TYPES, PACKET_TYPES_REVERSE, ERROR_PACKET };\n","import { PACKET_TYPES } from \"./commons.js\";\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n Object.prototype.toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\n// ArrayBuffer.isView method is not defined in IE10\nconst isView = (obj) => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj && obj.buffer instanceof ArrayBuffer;\n};\nconst encodePacket = ({ type, data }, supportsBinary, callback) => {\n if (withNativeBlob && data instanceof Blob) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(data, callback);\n }\n }\n else if (withNativeArrayBuffer &&\n (data instanceof ArrayBuffer || isView(data))) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(new Blob([data]), callback);\n }\n }\n // plain string\n return callback(PACKET_TYPES[type] + (data || \"\"));\n};\nconst encodeBlobAsBase64 = (data, callback) => {\n const fileReader = new FileReader();\n fileReader.onload = function () {\n const content = fileReader.result.split(\",\")[1];\n callback(\"b\" + (content || \"\"));\n };\n return fileReader.readAsDataURL(data);\n};\nfunction toArray(data) {\n if (data instanceof Uint8Array) {\n return data;\n }\n else if (data instanceof ArrayBuffer) {\n return new Uint8Array(data);\n }\n else {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n }\n}\nlet TEXT_ENCODER;\nexport function encodePacketToBinary(packet, callback) {\n if (withNativeBlob && packet.data instanceof Blob) {\n return packet.data.arrayBuffer().then(toArray).then(callback);\n }\n else if (withNativeArrayBuffer &&\n (packet.data instanceof ArrayBuffer || isView(packet.data))) {\n return callback(toArray(packet.data));\n }\n encodePacket(packet, false, (encoded) => {\n if (!TEXT_ENCODER) {\n TEXT_ENCODER = new TextEncoder();\n }\n callback(TEXT_ENCODER.encode(encoded));\n });\n}\nexport { encodePacket };\n","// imported from https://github.com/socketio/base64-arraybuffer\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nconst lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (let i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nexport const encode = (arraybuffer) => {\n let bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += cLine truncated
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
/*!
|
||||
* Socket.IO v4.8.3
|
||||
* (c) 2014-2025 Guillermo Rauch
|
||||
* Released under the MIT License.
|
||||
*/
|
||||
!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(t="undefined"!=typeof globalThis?globalThis:t||self).io=n()}(this,(function(){"use strict";function t(t,n){(null==n||n>t.length)&&(n=t.length);for(var i=0,r=Array(n);i<n;i++)r[i]=t[i];return r}function n(t,n){for(var i=0;i<n.length;i++){var r=n[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,f(r.key),r)}}function i(t,i,r){return i&&n(t.prototype,i),r&&n(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function r(n,i){var r="undefined"!=typeof Symbol&&n[Symbol.iterator]||n["@@iterator"];if(!r){if(Array.isArray(n)||(r=function(n,i){if(n){if("string"==typeof n)return t(n,i);var r={}.toString.call(n).slice(8,-1);return"Object"===r&&n.constructor&&(r=n.constructor.name),"Map"===r||"Set"===r?Array.from(n):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?t(n,i):void 0}}(n))||i&&n&&"number"==typeof n.length){r&&(n=r);var e=0,o=function(){};return{s:o,n:function(){return e>=n.length?{done:!0}:{done:!1,value:n[e++]}},e:function(t){throw t},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,u=!0,h=!1;return{s:function(){r=r.call(n)},n:function(){var t=r.next();return u=t.done,t},e:function(t){h=!0,s=t},f:function(){try{u||null==r.return||r.return()}finally{if(h)throw s}}}}function e(){return e=Object.assign?Object.assign.bind():function(t){for(var n=1;n<arguments.length;n++){var i=arguments[n];for(var r in i)({}).hasOwnProperty.call(i,r)&&(t[r]=i[r])}return t},e.apply(null,arguments)}function o(t){return o=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},o(t)}function s(t,n){t.prototype=Object.create(n.prototype),t.prototype.constructor=t,h(t,n)}function u(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(u=function(){return!!t})()}function h(t,n){return h=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},h(t,n)}function f(t){var n=function(t,n){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,n||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===n?String:Number)(t)}(t,"string");return"symbol"==typeof n?n:n+""}function c(t){return c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},c(t)}function a(t){var n="function"==typeof Map?new Map:void 0;return a=function(t){if(null===t||!function(t){try{return-1!==Function.toString.call(t).indexOf("[native code]")}catch(n){return"function"==typeof t}}(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==n){if(n.has(t))return n.get(t);n.set(t,i)}function i(){return function(t,n,i){if(u())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,n);var e=new(t.bind.apply(t,r));return i&&h(e,i.prototype),e}(t,arguments,o(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),h(i,t)},a(t)}var v=Object.create(null);v.open="0",v.close="1",v.ping="2",v.pong="3",v.message="4",v.upgrade="5",v.noop="6";var l=Object.create(null);Object.keys(v).forEach((function(t){l[v[t]]=t}));var p,d={type:"error",data:"parser error"},y="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),b="function"==typeof ArrayBuffer,w=function(t){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer},g=function(t,n,i){var r=t.type,e=t.data;return y&&e instanceof Blob?n?i(e):m(e,i):b&&(e instanceof ArrayBuffer||w(e))?n?i(e):m(new Blob([e]),i):i(v[r]+(e||""))},m=function(t,n){var i=new FileReader;return i.onload=function(){var t=i.result.split(",")[1];n("b"+(t||""))},i.readAsDataURL(t)};function k(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}for(var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",j="undefined"==typeof Uint8Array?[]:new Uint8Array(256),E=0;E<64;E++)j[A.charCodeAt(E)]=E;var O,B="function"==typeof ArrayBuffer,S=function(t,n){if("string"!=typeof t)return{type:"message",data:C(t,n)};var i=t.charAt(0);return"b"===i?{type:"message",data:N(t.substring(1),n)}:l[i]?t.length>1?{type:l[i],data:t.substring(1)}:{type:l[i]}:d},N=function(t,n){if(B){var i=function(t){var n,i,r,e,o,s=.75*t.length,u=t.length,h=0;"="===t[t.length-1]&&(s--,"="===t[t.length-2]&&s--);var f=new ArrayBuffer(s),c=new ULine truncated
|
||||
//# sourceMappingURL=socket.io.min.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"socket.io.min.js","sources":["../../engine.io-parser/build/esm/commons.js","../../engine.io-parser/build/esm/encodePacket.browser.js","../../engine.io-parser/build/esm/contrib/base64-arraybuffer.js","../../engine.io-parser/build/esm/index.js","../../engine.io-parser/build/esm/decodePacket.browser.js","../../socket.io-component-emitter/lib/esm/index.js","../../engine.io-client/build/esm/globals.js","../../engine.io-client/build/esm/util.js","../../engine.io-client/build/esm/transport.js","../../engine.io-client/build/esm/contrib/parseqs.js","../../engine.io-client/build/esm/transports/polling.js","../../engine.io-client/build/esm/contrib/has-cors.js","../../engine.io-client/build/esm/transports/polling-xhr.js","../../engine.io-client/build/esm/transports/websocket.js","../../engine.io-client/build/esm/transports/webtransport.js","../../engine.io-client/build/esm/transports/index.js","../../engine.io-client/build/esm/contrib/parseuri.js","../../engine.io-client/build/esm/socket.js","../../engine.io-client/build/esm/index.js","../../socket.io-parser/build/esm/is-binary.js","../../socket.io-parser/build/esm/binary.js","../../socket.io-parser/build/esm/index.js","../build/esm/on.js","../build/esm/socket.js","../build/esm/contrib/backo2.js","../build/esm/manager.js","../build/esm/index.js","../build/esm/url.js"],"sourcesContent":["const PACKET_TYPES = Object.create(null); // no Map = no polyfill\nPACKET_TYPES[\"open\"] = \"0\";\nPACKET_TYPES[\"close\"] = \"1\";\nPACKET_TYPES[\"ping\"] = \"2\";\nPACKET_TYPES[\"pong\"] = \"3\";\nPACKET_TYPES[\"message\"] = \"4\";\nPACKET_TYPES[\"upgrade\"] = \"5\";\nPACKET_TYPES[\"noop\"] = \"6\";\nconst PACKET_TYPES_REVERSE = Object.create(null);\nObject.keys(PACKET_TYPES).forEach((key) => {\n PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;\n});\nconst ERROR_PACKET = { type: \"error\", data: \"parser error\" };\nexport { PACKET_TYPES, PACKET_TYPES_REVERSE, ERROR_PACKET };\n","import { PACKET_TYPES } from \"./commons.js\";\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n Object.prototype.toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\n// ArrayBuffer.isView method is not defined in IE10\nconst isView = (obj) => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj && obj.buffer instanceof ArrayBuffer;\n};\nconst encodePacket = ({ type, data }, supportsBinary, callback) => {\n if (withNativeBlob && data instanceof Blob) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(data, callback);\n }\n }\n else if (withNativeArrayBuffer &&\n (data instanceof ArrayBuffer || isView(data))) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(new Blob([data]), callback);\n }\n }\n // plain string\n return callback(PACKET_TYPES[type] + (data || \"\"));\n};\nconst encodeBlobAsBase64 = (data, callback) => {\n const fileReader = new FileReader();\n fileReader.onload = function () {\n const content = fileReader.result.split(\",\")[1];\n callback(\"b\" + (content || \"\"));\n };\n return fileReader.readAsDataURL(data);\n};\nfunction toArray(data) {\n if (data instanceof Uint8Array) {\n return data;\n }\n else if (data instanceof ArrayBuffer) {\n return new Uint8Array(data);\n }\n else {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n }\n}\nlet TEXT_ENCODER;\nexport function encodePacketToBinary(packet, callback) {\n if (withNativeBlob && packet.data instanceof Blob) {\n return packet.data.arrayBuffer().then(toArray).then(callback);\n }\n else if (withNativeArrayBuffer &&\n (packet.data instanceof ArrayBuffer || isView(packet.data))) {\n return callback(toArray(packet.data));\n }\n encodePacket(packet, false, (encoded) => {\n if (!TEXT_ENCODER) {\n TEXT_ENCODER = new TextEncoder();\n }\n callback(TEXT_ENCODER.encode(encoded));\n });\n}\nexport { encodePacket };\n","// imported from https://github.com/socketio/base64-arraybuffer\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nconst lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (let i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nexport const encode = (arraybuffer) => {\n let bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + Line truncated
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
/*!
|
||||
* Socket.IO v4.8.3
|
||||
* (c) 2014-2025 Guillermo Rauch
|
||||
* Released under the MIT License.
|
||||
*/
|
||||
!function(t,i){"object"==typeof exports&&"undefined"!=typeof module?module.exports=i():"function"==typeof define&&define.amd?define(i):(t="undefined"!=typeof globalThis?globalThis:t||self).io=i()}(this,(function(){"use strict";function t(t,i){return i.forEach((function(i){i&&"string"!=typeof i&&!Array.isArray(i)&&Object.keys(i).forEach((function(n){if("default"!==n&&!(n in t)){var r=Object.getOwnPropertyDescriptor(i,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return i[n]}})}}))})),Object.freeze(t)}function i(t,i){(null==i||i>t.length)&&(i=t.length);for(var n=0,r=Array(i);n<i;n++)r[n]=t[n];return r}function n(t,i){for(var n=0;n<i.length;n++){var r=i[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,c(r.key),r)}}function r(t,i,r){return i&&n(t.prototype,i),r&&n(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function e(t,n){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=function(t,n){if(t){if("string"==typeof t)return i(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?i(t,n):void 0}}(t))||n&&t&&"number"==typeof t.length){r&&(t=r);var e=0,s=function(){};return{s:s,n:function(){return e>=t.length?{done:!0}:{done:!1,value:t[e++]}},e:function(t){throw t},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,h=!0,u=!1;return{s:function(){r=r.call(t)},n:function(){var t=r.next();return h=t.done,t},e:function(t){u=!0,o=t},f:function(){try{h||null==r.return||r.return()}finally{if(u)throw o}}}}function s(){return s=Object.assign?Object.assign.bind():function(t){for(var i=1;i<arguments.length;i++){var n=arguments[i];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},s.apply(null,arguments)}function o(t){return o=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},o(t)}function h(t,i){t.prototype=Object.create(i.prototype),t.prototype.constructor=t,f(t,i)}function u(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(u=function(){return!!t})()}function f(t,i){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,i){return t.__proto__=i,t},f(t,i)}function c(t){var i=function(t,i){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,i||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===i?String:Number)(t)}(t,"string");return"symbol"==typeof i?i:i+""}function a(t){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a(t)}function v(t){var i="function"==typeof Map?new Map:void 0;return v=function(t){if(null===t||!function(t){try{return-1!==Function.toString.call(t).indexOf("[native code]")}catch(i){return"function"==typeof t}}(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==i){if(i.has(t))return i.get(t);i.set(t,n)}function n(){return function(t,i,n){if(u())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,i);var e=new(t.bind.apply(t,r));return n&&f(e,n.prototype),e}(t,arguments,o(this).constructor)}return n.prototype=Object.create(t.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),f(n,t)},v(t)}var l=Object.create(null);l.open="0",l.close="1",l.ping="2",l.pong="3",l.message="4",l.upgrade="5",l.noop="6";var d=Object.create(null);Object.keys(l).forEach((function(t){d[l[t]]=t}));var p,y={type:"error",data:"parser error"},w="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),b="function"==typeof ArrayBuffer,g=function(t){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer},m=function(t,i,n){var r=t.type,e=t.data;return w&&e instanceof Blob?i?n(e):k(e,n):b&&(e instanceof ArrayBuffer||g(e))?i?n(e):k(new Blob([e]),n):n(l[r]+(e||""))},k=function(t,i){var n=new FileReader;return n.onload=function(){var t=n.result.split(",")[1];i("b"+(t||""))},n.readAsDataURL(t)};function A(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}for(var E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",j="undefined"==typeof Uint8Array?[]:new Uint8Array(256),O=0;O<64;O++)j[E.charCodeAt(O)]=O;var M,S="function"==typeof ArrayBuffer,B=function(t,i){if("string"!=typeof t)return{type:"message",data:T(t,i)};var n=Line truncated
|
||||
//# sourceMappingURL=socket.io.msgpack.min.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"socket.io.msgpack.min.js","sources":["../../engine.io-parser/build/esm/commons.js","../../engine.io-parser/build/esm/encodePacket.browser.js","../../engine.io-parser/build/esm/contrib/base64-arraybuffer.js","../../engine.io-parser/build/esm/index.js","../../engine.io-parser/build/esm/decodePacket.browser.js","../../socket.io-component-emitter/lib/esm/index.js","../../engine.io-client/build/esm/globals.js","../../engine.io-client/build/esm/util.js","../../engine.io-client/build/esm/transport.js","../../engine.io-client/build/esm/contrib/parseqs.js","../../engine.io-client/build/esm/transports/polling.js","../../engine.io-client/build/esm/contrib/has-cors.js","../../engine.io-client/build/esm/transports/polling-xhr.js","../../engine.io-client/build/esm/transports/websocket.js","../../engine.io-client/build/esm/transports/webtransport.js","../../engine.io-client/build/esm/transports/index.js","../../engine.io-client/build/esm/contrib/parseuri.js","../../engine.io-client/build/esm/socket.js","../../engine.io-client/build/esm/index.js","../../../node_modules/notepack.io/browser/encode.js","../../../node_modules/notepack.io/browser/decode.js","../../../node_modules/notepack.io/lib/index.js","../../../node_modules/component-emitter/index.js","../../../node_modules/socket.io-msgpack-parser/index.js","../build/esm/on.js","../build/esm/socket.js","../build/esm/contrib/backo2.js","../build/esm/manager.js","../build/esm/index.js","../build/esm/url.js"],"sourcesContent":["const PACKET_TYPES = Object.create(null); // no Map = no polyfill\nPACKET_TYPES[\"open\"] = \"0\";\nPACKET_TYPES[\"close\"] = \"1\";\nPACKET_TYPES[\"ping\"] = \"2\";\nPACKET_TYPES[\"pong\"] = \"3\";\nPACKET_TYPES[\"message\"] = \"4\";\nPACKET_TYPES[\"upgrade\"] = \"5\";\nPACKET_TYPES[\"noop\"] = \"6\";\nconst PACKET_TYPES_REVERSE = Object.create(null);\nObject.keys(PACKET_TYPES).forEach((key) => {\n PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;\n});\nconst ERROR_PACKET = { type: \"error\", data: \"parser error\" };\nexport { PACKET_TYPES, PACKET_TYPES_REVERSE, ERROR_PACKET };\n","import { PACKET_TYPES } from \"./commons.js\";\nconst withNativeBlob = typeof Blob === \"function\" ||\n (typeof Blob !== \"undefined\" &&\n Object.prototype.toString.call(Blob) === \"[object BlobConstructor]\");\nconst withNativeArrayBuffer = typeof ArrayBuffer === \"function\";\n// ArrayBuffer.isView method is not defined in IE10\nconst isView = (obj) => {\n return typeof ArrayBuffer.isView === \"function\"\n ? ArrayBuffer.isView(obj)\n : obj && obj.buffer instanceof ArrayBuffer;\n};\nconst encodePacket = ({ type, data }, supportsBinary, callback) => {\n if (withNativeBlob && data instanceof Blob) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(data, callback);\n }\n }\n else if (withNativeArrayBuffer &&\n (data instanceof ArrayBuffer || isView(data))) {\n if (supportsBinary) {\n return callback(data);\n }\n else {\n return encodeBlobAsBase64(new Blob([data]), callback);\n }\n }\n // plain string\n return callback(PACKET_TYPES[type] + (data || \"\"));\n};\nconst encodeBlobAsBase64 = (data, callback) => {\n const fileReader = new FileReader();\n fileReader.onload = function () {\n const content = fileReader.result.split(\",\")[1];\n callback(\"b\" + (content || \"\"));\n };\n return fileReader.readAsDataURL(data);\n};\nfunction toArray(data) {\n if (data instanceof Uint8Array) {\n return data;\n }\n else if (data instanceof ArrayBuffer) {\n return new Uint8Array(data);\n }\n else {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n }\n}\nlet TEXT_ENCODER;\nexport function encodePacketToBinary(packet, callback) {\n if (withNativeBlob && packet.data instanceof Blob) {\n return packet.data.arrayBuffer().then(toArray).then(callback);\n }\n else if (withNativeArrayBuffer &&\n (packet.data instanceof ArrayBuffer || isView(packet.data))) {\n return callback(toArray(packet.data));\n }\n encodePacket(packet, false, (encoded) => {\n if (!TEXT_ENCODER) {\n TEXT_ENCODER = new TextEncoder();\n }\n callback(TEXT_ENCODER.encode(encoded));\n });\n}\nexport { encodePacket };\n","// imported from https://github.com/socketio/base64-arraybuffer\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nconst lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (let i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nexport const encode = (arraybuffer) => {\n let bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];Line truncated
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
{
|
||||
"name": "socket.io-client",
|
||||
"version": "4.8.3",
|
||||
"description": "Realtime application framework client",
|
||||
"keywords": [
|
||||
"realtime",
|
||||
"framework",
|
||||
"websocket",
|
||||
"tcp",
|
||||
"events",
|
||||
"client"
|
||||
],
|
||||
"files": [
|
||||
"dist/",
|
||||
"build/"
|
||||
],
|
||||
"type": "commonjs",
|
||||
"main": "./build/cjs/index.js",
|
||||
"module": "./build/esm/index.js",
|
||||
"exports": {
|
||||
"./package.json": "./package.json",
|
||||
"./dist/socket.io.js": "./dist/socket.io.js",
|
||||
"./dist/socket.io.js.map": "./dist/socket.io.js.map",
|
||||
".": {
|
||||
"import": {
|
||||
"types": "./build/esm/index.d.ts",
|
||||
"node": "./build/esm-debug/index.js",
|
||||
"default": "./build/esm/index.js"
|
||||
},
|
||||
"require": {
|
||||
"types": "./build/cjs/index.d.ts",
|
||||
"default": "./build/cjs/index.js"
|
||||
}
|
||||
},
|
||||
"./debug": {
|
||||
"import": {
|
||||
"types": "./build/esm/index.d.ts",
|
||||
"default": "./build/esm-debug/index.js"
|
||||
},
|
||||
"require": {
|
||||
"types": "./build/cjs/index.d.ts",
|
||||
"default": "./build/cjs/index.js"
|
||||
}
|
||||
}
|
||||
},
|
||||
"types": "./build/esm/index.d.ts",
|
||||
"dependencies": {
|
||||
"@socket.io/component-emitter": "~3.1.0",
|
||||
"debug": "~4.4.1",
|
||||
"engine.io-client": "~6.6.1",
|
||||
"socket.io-parser": "~4.2.4"
|
||||
},
|
||||
"scripts": {
|
||||
"compile": "rimraf ./build && tsc && tsc -p tsconfig.esm.json && ./postcompile.sh",
|
||||
"test": "npm run format:check && npm run compile && if test \"$BROWSERS\" = \"1\" ; then npm run test:browser; else npm run test:node; fi",
|
||||
"test:node": "mocha --import=tsx --require test/support/hooks.ts --exit test/index.ts",
|
||||
"test:browser": "ts-node test/browser-runner.ts",
|
||||
"test:types": "tsd",
|
||||
"build": "rollup -c support/rollup.config.umd.js && rollup -c support/rollup.config.esm.js && rollup -c support/rollup.config.umd.msgpack.js",
|
||||
"bundle-size": "node support/bundle-size.js",
|
||||
"format:check": "prettier --check \"*.js\" \"lib/**/*.ts\" \"test/**/*.ts\" \"support/**/*.js\"",
|
||||
"format:fix": "prettier --write \"*.js\" \"lib/**/*.ts\" \"test/**/*.ts\" \"support/**/*.js\"",
|
||||
"prepack": "npm run compile"
|
||||
},
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Guillermo Rauch",
|
||||
"email": "rauchg@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "Arnout Kazemier",
|
||||
"email": "info@3rd-eden.com"
|
||||
},
|
||||
{
|
||||
"name": "Vladimir Dronnikov",
|
||||
"email": "dronnikov@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "Einar Otto Stangvik",
|
||||
"email": "einaros@gmail.com"
|
||||
}
|
||||
],
|
||||
"homepage": "https://github.com/socketio/socket.io/tree/main/packages/socket.io-client#readme",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/socketio/socket.io.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/socketio/socket.io/issues"
|
||||
},
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
},
|
||||
"tsd": {
|
||||
"directory": "test"
|
||||
},
|
||||
"browser": {
|
||||
"./test/node.ts": false
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user