"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.schemaFromExecutor = void 0;
const graphql_1 = require("graphql");
const value_or_promise_1 = require("value-or-promise");
const utils_1 = require("@graphql-tools/utils");
function getSchemaFromIntrospection(introspectionResult, options) {
    if (introspectionResult?.data?.__schema) {
        return (0, graphql_1.buildClientSchema)(introspectionResult.data, options);
    }
    if (introspectionResult?.errors) {
        const graphqlErrors = introspectionResult.errors.map(error => (0, utils_1.createGraphQLError)(error.message, error));
        if (introspectionResult.errors.length === 1) {
            throw graphqlErrors[0];
        }
        else {
            throw new AggregateError(graphqlErrors, 'Could not obtain introspection result');
        }
    }
    throw (0, utils_1.createGraphQLError)(`Could not obtain introspection result, received the following as response; \n ${(0, utils_1.inspect)(introspectionResult)}`);
}
function schemaFromExecutor(executor, context, options) {
    const parsedIntrospectionQuery = (0, graphql_1.parse)((0, graphql_1.getIntrospectionQuery)(options), options);
    return new value_or_promise_1.ValueOrPromise(() => executor({
        document: parsedIntrospectionQuery,
        context,
    }))
        .then(introspection => {
        if ((0, utils_1.isAsyncIterable)(introspection)) {
            const iterator = introspection[Symbol.asyncIterator]();
            return iterator.next().then(({ value }) => value);
        }
        return introspection;
    })
        .then(introspection => getSchemaFromIntrospection(introspection, options))
        .resolve();
}
exports.schemaFromExecutor = schemaFromExecutor;
