const WebSocket = require('ws'); const http = require('http'); // Mock Data // const TOKEN = "mock_token_for_validation"; // Assuming manual auth is bypassed or working const WS_URL = 'ws://localhost:3000/location-broadcast'; const SESSION_ID = 'debug_room'; function loginAndStart() { // 1. Try Register first (in case user doesn't exist) const registerData = JSON.stringify({ username: 'testuser1', password: 'password123', nickname: 'TestUser' }); const regOptions = { hostname: 'localhost', port: 3000, path: '/auth/register', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': registerData.length } }; const regReq = http.request(regOptions, (res) => { // Regardless of success (maybe already exists), try login performLogin(); }); regReq.on('error', () => performLogin()); // Proceed to login on error regReq.write(registerData); regReq.end(); } function performLogin() { const postData = JSON.stringify({ identifier: 'testuser1', // Using a test account password: 'password123' }); const options = { hostname: 'localhost', port: 3000, path: '/auth/login', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': postData.length } }; const req = http.request(options, (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { if (res.statusCode === 201 || res.statusCode === 200) { const json = JSON.parse(data); const realToken = json.data.access_token; console.log("Got Token:", realToken.substring(0, 10) + "..."); startClients(realToken); } else { console.error("Login Failed:", res.statusCode, data); } }); }); req.on('error', (e) => { console.error(`Login Request Error: ${e.message}`); }); req.write(postData); req.end(); } function startClients(validToken) { console.log("Starting Test Clients..."); createClient('Listener', validToken); setTimeout(() => createClient('Sender', validToken), 1000); } function createClient(name, token) { const ws = new WebSocket(WS_URL); ws.on('open', () => { // console.log(`[${name}] Connected`); setTimeout(() => { // console.log(`[${name}] Sending Join Session...`); const joinMsg = { event: 'join_session', data: { sessionId: SESSION_ID, token: token } }; ws.send(JSON.stringify(joinMsg)); }, 500); }); ws.on('message', (data) => { console.log(`[${name}] Rx: ${data.toString()}`); }); ws.on('close', (code, reason) => { console.log(`[${name}] Closed: ${code} ${reason}`); }); ws.on('error', (err) => { console.error(`[${name}] Error:`, err.message); }); } // Start loginAndStart(); // Timeout setTimeout(() => { console.log("❌ Test Timed Out - No broadcast received."); process.exit(1); }, 15000);