"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.wrapGraphQLClient = wrapGraphQLClient;
function wrapGraphQLClient(getClient, subscriptionsClient) {
    return {
        get client() {
            return getClient();
        },
        subscriptionsClient,
        async mutate(resolved, options) {
            if (!options)
                options = {};
            if (options.noCache === undefined)
                options.noCache = true;
            const client = getClient();
            const result = await client.resolved(() => resolved(client.mutation), options);
            return result;
        },
        async query(resolved, options) {
            const client = getClient();
            const result = await client.resolved(() => resolved(client.query), options);
            return result;
        },
        subscribe(resolved, onData, onError) {
            if (!subscriptionsClient)
                throw new Error('Subscriptions not enabled');
            let unsub;
            const stop = async () => {
                if (!unsub)
                    return;
                await unsub().catch(() => undefined);
            };
            const client = getClient();
            client.resolved(() => resolved(client.subscription), {
                onSubscription(event) {
                    if (event.unsubscribe)
                        unsub = event.unsubscribe;
                    if (event.type === 'data')
                        onData(event.data, stop);
                    else if (event.type === 'with-errors' && onError)
                        onError(event.error, stop);
                },
            });
            return stop;
        },
    };
}
