in src/index.js [117:193]
createSocket() {
// Check if socket exists and is connected
if (this.socket && this.socket.connected) {
logger.debug('โ ๏ธ Socket already connected, skipping creation. ID:', this.socket.id);
return;
}
// Store pending events before cleanup
const pendingEvents = [...this.onEvents];
// If socket exists but disconnected, clean it up
if (this.socket) {
logger.debug('๐งน Cleaning up disconnected socket...');
try {
this.socket.removeAllListeners();
this.socket.close();
} catch (e) {
logger.error('Error cleaning socket:', e);
}
this.socket = null;
}
logger.info('๐ Creating new socket...');
this.socket = socket(
this.url,
this.customData,
this.path,
this.protocol,
this.protocolOptions,
this.onConnectionError
);
this.socket.customData = this.customData;
// We set a function on session_confirm here so as to avoid any race condition
// this will be called first and will set those parameters for everyone to use.
this.socket.on('session_confirm', (sessionObject) => {
this.sessionConfirmed = true;
const newSessionId = (sessionObject && sessionObject.session_id)
? sessionObject.session_id
: sessionObject;
// Check if we have a preserved session ID from reconnection
if (this.socket.preservedSessionId) {
logger.debug('๐ Using preserved session ID:', this.socket.preservedSessionId);
this.sessionId = this.socket.preservedSessionId;
// Store in localStorage for persistence
localStorage.setItem('chat_session_id', this.socket.preservedSessionId);
} else {
// Check if we have a stored session ID
const storedSessionId = localStorage.getItem('chat_session_id');
if (storedSessionId) {
logger.debug('๐ Using stored session ID:', storedSessionId);
this.sessionId = storedSessionId;
} else {
logger.debug('๐ New session ID:', newSessionId);
this.sessionId = newSessionId;
localStorage.setItem('chat_session_id', newSessionId);
}
}
});
// Apply pending events (these were registered via socket.on() before socket was created)
pendingEvents.forEach((event) => {
this.socket.on(event.event, event.callback);
});
// Apply previously registered events from onSocketEvent (includes connect, disconnect, etc.)
Object.keys(this.onSocketEvent).forEach((event) => {
this.socket.on(event, this.onSocketEvent[event]);
});
this.onEvents = [];
logger.debug('โ
Socket created with all event handlers attached');
}