"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateJsonRpcResponse = exports.checkError = exports.createJsonRpcPayload = exports.InvalidJsonRpcResponseError = exports.JsonRpcError = void 0;
let msgId = 0;
const nextMsgId = () => ++msgId;
class JsonRpcError extends Error {
    constructor(message, code, data) {
        super(message);
        this.code = code;
        this.data = data;
    }
}
exports.JsonRpcError = JsonRpcError;
class InvalidJsonRpcResponseError extends JsonRpcError {
    constructor(message, data) {
        super(`Invalid JSON RPC response: ${message}`, undefined, data);
    }
}
exports.InvalidJsonRpcResponseError = InvalidJsonRpcResponseError;
function createJsonRpcPayload(method, params) {
    return {
        jsonrpc: '2.0',
        id: nextMsgId(),
        method,
        params: params !== null && params !== void 0 ? params : []
    };
}
exports.createJsonRpcPayload = createJsonRpcPayload;
function checkError(msg) {
    if (msg === null || msg === void 0 ? void 0 : msg.error) {
        throw new JsonRpcError(msg.error.message, msg.error.code, msg.error.data);
    }
    if ((msg === null || msg === void 0 ? void 0 : msg.result) == null) {
        throw new JsonRpcError('No result');
    }
}
exports.checkError = checkError;
function validateJsonRpcResponse(response) {
    if (response == null) {
        throw new InvalidJsonRpcResponseError('Response message is null/empty');
    }
    if (Array.isArray(response)) {
        return response.every(validateJsonRpcResponse);
    }
    if (response.jsonrpc !== '2.0') {
        throw new InvalidJsonRpcResponseError(`Invalid jsonrpc value (${response.jsonrpc}) in message`);
    }
    if (!(typeof response.id === 'number' || typeof response.id === 'string')) {
        throw new InvalidJsonRpcResponseError(`Invalid message ID (type: ${typeof response.id}) in message`);
    }
    return true;
}
exports.validateJsonRpcResponse = validateJsonRpcResponse;
