"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createFetchMultipartSubscription = createFetchMultipartSubscription;
const relay_runtime_1 = require("relay-runtime");
const client_1 = require("@apollo/client");
const globals_1 = require("@apollo/client/utilities/internal/globals");
const parseAndCheckHttpResponse_js_1 = require("../../../link/http/parseAndCheckHttpResponse.cjs");
const selectHttpOptionsAndBody_js_1 = require("../../../link/http/selectHttpOptionsAndBody.cjs");
const backupFetch = (0, globals_1.maybe)(() => fetch);
function createFetchMultipartSubscription(uri, { fetch: preferredFetch, headers } = {}) {
    return function fetchMultipartSubscription(operation, variables) {
        const body = {
            operationName: operation.name,
            variables,
            query: operation.text || "",
        };
        const options = generateOptionsForMultipartSubscription(headers || {});
        return relay_runtime_1.Observable.create((sink) => {
            try {
                options.body = (0, client_1.serializeFetchParameter)(body, "Payload");
            }
            catch (parseError) {
                sink.error(parseError);
            }
            const currentFetch = preferredFetch || (0, globals_1.maybe)(() => fetch) || backupFetch;
            const observerNext = sink.next.bind(sink);
            currentFetch(uri, options)
                .then((response) => {
                const ctype = response.headers?.get("content-type");
                if (ctype !== null && /^multipart\/mixed/i.test(ctype)) {
                    return (0, parseAndCheckHttpResponse_js_1.readMultipartBody)(response, observerNext);
                }
                sink.error(new Error("Expected multipart response"));
            })
                .then(() => {
                sink.complete();
            })
                .catch((err) => {
                sink.error(err);
            });
        });
    };
}
function generateOptionsForMultipartSubscription(headers) {
    const options = {
        ...selectHttpOptionsAndBody_js_1.fallbackHttpConfig.options,
        headers: {
            ...(headers || {}),
            ...selectHttpOptionsAndBody_js_1.fallbackHttpConfig.headers,
            accept: "multipart/mixed;boundary=graphql;subscriptionSpec=1.0,application/json",
        },
    };
    return options;
}
//# sourceMappingURL=index.cjs.map
