source: trip-planner-front/node_modules/socket.io/dist/socket.js@ 6a80231

Last change on this file since 6a80231 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 15.1 KB
Line 
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.Socket = exports.RESERVED_EVENTS = void 0;
7const events_1 = require("events");
8const socket_io_parser_1 = require("socket.io-parser");
9const url = require("url");
10const debug_1 = __importDefault(require("debug"));
11const base64id_1 = __importDefault(require("base64id"));
12const debug = debug_1.default("socket.io:socket");
13exports.RESERVED_EVENTS = new Set([
14 "connect",
15 "connect_error",
16 "disconnect",
17 "disconnecting",
18 // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
19 "newListener",
20 "removeListener",
21]);
22class Socket extends events_1.EventEmitter {
23 /**
24 * Interface to a `Client` for a given `Namespace`.
25 *
26 * @param {Namespace} nsp
27 * @param {Client} client
28 * @param {Object} auth
29 * @package
30 */
31 constructor(nsp, client, auth) {
32 super();
33 this.nsp = nsp;
34 this.client = client;
35 this.acks = new Map();
36 this.fns = [];
37 this.flags = {};
38 this._rooms = new Set();
39 this.server = nsp.server;
40 this.adapter = this.nsp.adapter;
41 if (client.conn.protocol === 3) {
42 // @ts-ignore
43 this.id = nsp.name !== "/" ? nsp.name + "#" + client.id : client.id;
44 }
45 else {
46 this.id = base64id_1.default.generateId(); // don't reuse the Engine.IO id because it's sensitive information
47 }
48 this.connected = true;
49 this.disconnected = false;
50 this.handshake = this.buildHandshake(auth);
51 }
52 /**
53 * Builds the `handshake` BC object
54 *
55 * @private
56 */
57 buildHandshake(auth) {
58 return {
59 headers: this.request.headers,
60 time: new Date() + "",
61 address: this.conn.remoteAddress,
62 xdomain: !!this.request.headers.origin,
63 // @ts-ignore
64 secure: !!this.request.connection.encrypted,
65 issued: +new Date(),
66 url: this.request.url,
67 query: url.parse(this.request.url, true).query,
68 auth,
69 };
70 }
71 /**
72 * Emits to this client.
73 *
74 * @return Always returns `true`.
75 * @public
76 */
77 emit(ev, ...args) {
78 if (exports.RESERVED_EVENTS.has(ev)) {
79 throw new Error(`"${ev}" is a reserved event name`);
80 }
81 args.unshift(ev);
82 const packet = {
83 type: socket_io_parser_1.PacketType.EVENT,
84 data: args,
85 };
86 // access last argument to see if it's an ACK callback
87 if (typeof args[args.length - 1] === "function") {
88 if (this._rooms.size || this.flags.broadcast) {
89 throw new Error("Callbacks are not supported when broadcasting");
90 }
91 debug("emitting packet with ack id %d", this.nsp._ids);
92 this.acks.set(this.nsp._ids, args.pop());
93 packet.id = this.nsp._ids++;
94 }
95 const rooms = new Set(this._rooms);
96 const flags = Object.assign({}, this.flags);
97 // reset flags
98 this._rooms.clear();
99 this.flags = {};
100 if (rooms.size || flags.broadcast) {
101 this.adapter.broadcast(packet, {
102 except: new Set([this.id]),
103 rooms: rooms,
104 flags: flags,
105 });
106 }
107 else {
108 // dispatch packet
109 this.packet(packet, flags);
110 }
111 return true;
112 }
113 /**
114 * Targets a room when broadcasting.
115 *
116 * @param name
117 * @return self
118 * @public
119 */
120 to(name) {
121 this._rooms.add(name);
122 return this;
123 }
124 /**
125 * Targets a room when broadcasting.
126 *
127 * @param name
128 * @return self
129 * @public
130 */
131 in(name) {
132 this._rooms.add(name);
133 return this;
134 }
135 /**
136 * Sends a `message` event.
137 *
138 * @return self
139 * @public
140 */
141 send(...args) {
142 this.emit("message", ...args);
143 return this;
144 }
145 /**
146 * Sends a `message` event.
147 *
148 * @return self
149 * @public
150 */
151 write(...args) {
152 this.emit("message", ...args);
153 return this;
154 }
155 /**
156 * Writes a packet.
157 *
158 * @param {Object} packet - packet object
159 * @param {Object} opts - options
160 * @private
161 */
162 packet(packet, opts = {}) {
163 packet.nsp = this.nsp.name;
164 opts.compress = false !== opts.compress;
165 this.client._packet(packet, opts);
166 }
167 /**
168 * Joins a room.
169 *
170 * @param {String|Array} rooms - room or array of rooms
171 * @return a Promise or nothing, depending on the adapter
172 * @public
173 */
174 join(rooms) {
175 debug("join room %s", rooms);
176 return this.adapter.addAll(this.id, new Set(Array.isArray(rooms) ? rooms : [rooms]));
177 }
178 /**
179 * Leaves a room.
180 *
181 * @param {String} room
182 * @return a Promise or nothing, depending on the adapter
183 * @public
184 */
185 leave(room) {
186 debug("leave room %s", room);
187 return this.adapter.del(this.id, room);
188 }
189 /**
190 * Leave all rooms.
191 *
192 * @private
193 */
194 leaveAll() {
195 this.adapter.delAll(this.id);
196 }
197 /**
198 * Called by `Namespace` upon successful
199 * middleware execution (ie: authorization).
200 * Socket is added to namespace array before
201 * call to join, so adapters can access it.
202 *
203 * @private
204 */
205 _onconnect() {
206 debug("socket connected - writing packet");
207 this.join(this.id);
208 if (this.conn.protocol === 3) {
209 this.packet({ type: socket_io_parser_1.PacketType.CONNECT });
210 }
211 else {
212 this.packet({ type: socket_io_parser_1.PacketType.CONNECT, data: { sid: this.id } });
213 }
214 }
215 /**
216 * Called with each packet. Called by `Client`.
217 *
218 * @param {Object} packet
219 * @private
220 */
221 _onpacket(packet) {
222 debug("got packet %j", packet);
223 switch (packet.type) {
224 case socket_io_parser_1.PacketType.EVENT:
225 this.onevent(packet);
226 break;
227 case socket_io_parser_1.PacketType.BINARY_EVENT:
228 this.onevent(packet);
229 break;
230 case socket_io_parser_1.PacketType.ACK:
231 this.onack(packet);
232 break;
233 case socket_io_parser_1.PacketType.BINARY_ACK:
234 this.onack(packet);
235 break;
236 case socket_io_parser_1.PacketType.DISCONNECT:
237 this.ondisconnect();
238 break;
239 case socket_io_parser_1.PacketType.CONNECT_ERROR:
240 this._onerror(new Error(packet.data));
241 }
242 }
243 /**
244 * Called upon event packet.
245 *
246 * @param {Packet} packet - packet object
247 * @private
248 */
249 onevent(packet) {
250 const args = packet.data || [];
251 debug("emitting event %j", args);
252 if (null != packet.id) {
253 debug("attaching ack callback to event");
254 args.push(this.ack(packet.id));
255 }
256 if (this._anyListeners && this._anyListeners.length) {
257 const listeners = this._anyListeners.slice();
258 for (const listener of listeners) {
259 listener.apply(this, args);
260 }
261 }
262 this.dispatch(args);
263 }
264 /**
265 * Produces an ack callback to emit with an event.
266 *
267 * @param {Number} id - packet id
268 * @private
269 */
270 ack(id) {
271 const self = this;
272 let sent = false;
273 return function () {
274 // prevent double callbacks
275 if (sent)
276 return;
277 const args = Array.prototype.slice.call(arguments);
278 debug("sending ack %j", args);
279 self.packet({
280 id: id,
281 type: socket_io_parser_1.PacketType.ACK,
282 data: args,
283 });
284 sent = true;
285 };
286 }
287 /**
288 * Called upon ack packet.
289 *
290 * @private
291 */
292 onack(packet) {
293 const ack = this.acks.get(packet.id);
294 if ("function" == typeof ack) {
295 debug("calling ack %s with %j", packet.id, packet.data);
296 ack.apply(this, packet.data);
297 this.acks.delete(packet.id);
298 }
299 else {
300 debug("bad ack %s", packet.id);
301 }
302 }
303 /**
304 * Called upon client disconnect packet.
305 *
306 * @private
307 */
308 ondisconnect() {
309 debug("got disconnect packet");
310 this._onclose("client namespace disconnect");
311 }
312 /**
313 * Handles a client error.
314 *
315 * @private
316 */
317 _onerror(err) {
318 if (this.listeners("error").length) {
319 super.emit("error", err);
320 }
321 else {
322 console.error("Missing error handler on `socket`.");
323 console.error(err.stack);
324 }
325 }
326 /**
327 * Called upon closing. Called by `Client`.
328 *
329 * @param {String} reason
330 * @throw {Error} optional error object
331 *
332 * @private
333 */
334 _onclose(reason) {
335 if (!this.connected)
336 return this;
337 debug("closing socket - reason %s", reason);
338 super.emit("disconnecting", reason);
339 this.leaveAll();
340 this.nsp._remove(this);
341 this.client._remove(this);
342 this.connected = false;
343 this.disconnected = true;
344 super.emit("disconnect", reason);
345 return;
346 }
347 /**
348 * Produces an `error` packet.
349 *
350 * @param {Object} err - error object
351 *
352 * @private
353 */
354 _error(err) {
355 this.packet({ type: socket_io_parser_1.PacketType.CONNECT_ERROR, data: err });
356 }
357 /**
358 * Disconnects this client.
359 *
360 * @param {Boolean} close - if `true`, closes the underlying connection
361 * @return {Socket} self
362 *
363 * @public
364 */
365 disconnect(close = false) {
366 if (!this.connected)
367 return this;
368 if (close) {
369 this.client._disconnect();
370 }
371 else {
372 this.packet({ type: socket_io_parser_1.PacketType.DISCONNECT });
373 this._onclose("server namespace disconnect");
374 }
375 return this;
376 }
377 /**
378 * Sets the compress flag.
379 *
380 * @param {Boolean} compress - if `true`, compresses the sending data
381 * @return {Socket} self
382 * @public
383 */
384 compress(compress) {
385 this.flags.compress = compress;
386 return this;
387 }
388 /**
389 * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to
390 * receive messages (because of network slowness or other issues, or because they’re connected through long polling
391 * and is in the middle of a request-response cycle).
392 *
393 * @return {Socket} self
394 * @public
395 */
396 get volatile() {
397 this.flags.volatile = true;
398 return this;
399 }
400 /**
401 * Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the
402 * sender.
403 *
404 * @return {Socket} self
405 * @public
406 */
407 get broadcast() {
408 this.flags.broadcast = true;
409 return this;
410 }
411 /**
412 * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
413 *
414 * @return {Socket} self
415 * @public
416 */
417 get local() {
418 this.flags.local = true;
419 return this;
420 }
421 /**
422 * Dispatch incoming event to socket listeners.
423 *
424 * @param {Array} event - event that will get emitted
425 * @private
426 */
427 dispatch(event) {
428 debug("dispatching an event %j", event);
429 this.run(event, (err) => {
430 process.nextTick(() => {
431 if (err) {
432 return this._onerror(err);
433 }
434 if (this.connected) {
435 super.emit.apply(this, event);
436 }
437 else {
438 debug("ignore packet received after disconnection");
439 }
440 });
441 });
442 }
443 /**
444 * Sets up socket middleware.
445 *
446 * @param {Function} fn - middleware function (event, next)
447 * @return {Socket} self
448 * @public
449 */
450 use(fn) {
451 this.fns.push(fn);
452 return this;
453 }
454 /**
455 * Executes the middleware for an incoming event.
456 *
457 * @param {Array} event - event that will get emitted
458 * @param {Function} fn - last fn call in the middleware
459 * @private
460 */
461 run(event, fn) {
462 const fns = this.fns.slice(0);
463 if (!fns.length)
464 return fn(null);
465 function run(i) {
466 fns[i](event, function (err) {
467 // upon error, short-circuit
468 if (err)
469 return fn(err);
470 // if no middleware left, summon callback
471 if (!fns[i + 1])
472 return fn(null);
473 // go on to next
474 run(i + 1);
475 });
476 }
477 run(0);
478 }
479 /**
480 * A reference to the request that originated the underlying Engine.IO Socket.
481 *
482 * @public
483 */
484 get request() {
485 return this.client.request;
486 }
487 /**
488 * A reference to the underlying Client transport connection (Engine.IO Socket object).
489 *
490 * @public
491 */
492 get conn() {
493 return this.client.conn;
494 }
495 /**
496 * @public
497 */
498 get rooms() {
499 return this.adapter.socketRooms(this.id) || new Set();
500 }
501 /**
502 * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
503 * callback.
504 *
505 * @param listener
506 * @public
507 */
508 onAny(listener) {
509 this._anyListeners = this._anyListeners || [];
510 this._anyListeners.push(listener);
511 return this;
512 }
513 /**
514 * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
515 * callback. The listener is added to the beginning of the listeners array.
516 *
517 * @param listener
518 * @public
519 */
520 prependAny(listener) {
521 this._anyListeners = this._anyListeners || [];
522 this._anyListeners.unshift(listener);
523 return this;
524 }
525 /**
526 * Removes the listener that will be fired when any event is emitted.
527 *
528 * @param listener
529 * @public
530 */
531 offAny(listener) {
532 if (!this._anyListeners) {
533 return this;
534 }
535 if (listener) {
536 const listeners = this._anyListeners;
537 for (let i = 0; i < listeners.length; i++) {
538 if (listener === listeners[i]) {
539 listeners.splice(i, 1);
540 return this;
541 }
542 }
543 }
544 else {
545 this._anyListeners = [];
546 }
547 return this;
548 }
549 /**
550 * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
551 * e.g. to remove listeners.
552 *
553 * @public
554 */
555 listenersAny() {
556 return this._anyListeners || [];
557 }
558}
559exports.Socket = Socket;
Note: See TracBrowser for help on using the repository browser.