import { trace } from '@opentelemetry/api';
import { describe, expect, it, vi } from 'vitest';
import { INTENTIONAL_CLOSE_CODE, ISocket } from './socket.js';
import { ISocketWithClientAuth } from './socketWithClientAuth.js';
const PING_TIMEOUT_CLOSE_REASON = 'Ping timeout';
describe('ISocket', () => {
    it('preserves the transport-close marker when rejecting pending requests with a reason', async () => {
        const ws = {
            addEventListener: vi.fn(),
            close: vi.fn(),
            send: vi.fn()
        };
        const socket = new ISocket(ws, {}, [], { onClose: vi.fn() });
        const pendingRequest = socket.request('editor.ping', {});
        socket.closeAndRejectPendingRequests(PING_TIMEOUT_CLOSE_REASON);
        await expect(pendingRequest).rejects.toMatchObject({
            code: 8,
            message: `[internal] Connection closed: ${PING_TIMEOUT_CLOSE_REASON}`
        });
        expect(ws.close).toHaveBeenCalledWith(INTENTIONAL_CLOSE_CODE, PING_TIMEOUT_CLOSE_REASON);
    });
});
describe('ISocketWithClientAuth', () => {
    it('still sends a refreshed token when an older in-flight request resolves after setAuthorization', async () => {
        let messageHandler;
        const sentMessages = [];
        const ws = {
            addEventListener: vi.fn((event, handler) => {
                if (event === 'message') {
                    messageHandler = handler;
                }
            }),
            close: vi.fn(),
            send: vi.fn((message) => {
                sentMessages.push(JSON.parse(message));
            })
        };
        const socket = new ISocketWithClientAuth(ws, 'Bearer old-token', {}, [], trace.getTracer('test'), { onClose: vi.fn() });
        const firstRequest = socket.request('editor.ping', {});
        expect(sentMessages[0].request.setAuthorization).toBe('Bearer old-token');
        socket.setAuthorization('Bearer new-token');
        messageHandler?.({
            data: JSON.stringify({
                response: { id: 1, payload: undefined, error: null }
            })
        });
        await firstRequest;
        const secondRequest = socket.request('editor.ping', {});
        expect(sentMessages[1].request.setAuthorization).toBe('Bearer new-token');
        messageHandler?.({
            data: JSON.stringify({
                response: { id: 2, payload: undefined, error: null }
            })
        });
        await secondRequest;
    });
});
//# sourceMappingURL=socket.test.js.map