"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildGraphQLWSExecutor = void 0;
const tslib_1 = require("tslib");
const graphql_1 = require("graphql");
const graphql_ws_1 = require("graphql-ws");
const isomorphic_ws_1 = tslib_1.__importDefault(require("isomorphic-ws"));
const utils_1 = require("@graphql-tools/utils");
function isClient(client) {
    return 'subscribe' in client;
}
function buildGraphQLWSExecutor(clientOptionsOrClient) {
    let graphqlWSClient;
    let executorConnectionParams = {};
    if (isClient(clientOptionsOrClient)) {
        graphqlWSClient = clientOptionsOrClient;
    }
    else {
        graphqlWSClient = (0, graphql_ws_1.createClient)({
            ...clientOptionsOrClient,
            webSocketImpl: isomorphic_ws_1.default,
            lazy: true,
            connectionParams: () => {
                const optionsConnectionParams = (typeof clientOptionsOrClient.connectionParams === 'function'
                    ? clientOptionsOrClient.connectionParams()
                    : clientOptionsOrClient.connectionParams) || {};
                return Object.assign(optionsConnectionParams, executorConnectionParams);
            },
        });
        if (clientOptionsOrClient.onClient) {
            clientOptionsOrClient.onClient(graphqlWSClient);
        }
    }
    return function GraphQLWSExecutor(executionRequest) {
        const { document, variables, operationName, extensions, operationType = (0, utils_1.getOperationASTFromRequest)(executionRequest).operation, } = executionRequest;
        // additional connection params can be supplied through the "connectionParams" field in extensions.
        // TODO: connection params only from the FIRST operation in lazy mode will be used (detect connectionParams changes and reconnect, too implicit?)
        if (extensions?.['connectionParams'] && typeof extensions?.['connectionParams'] === 'object') {
            executorConnectionParams = Object.assign(executorConnectionParams, extensions['connectionParams']);
        }
        const query = (0, graphql_1.print)(document);
        const iterableIterator = graphqlWSClient.iterate({
            query,
            variables,
            operationName,
            extensions,
        });
        if (operationType === 'subscription') {
            return iterableIterator;
        }
        return iterableIterator.next().then(({ value }) => value);
    };
}
exports.buildGraphQLWSExecutor = buildGraphQLWSExecutor;
