import { Observable } from "relay-runtime";
import { serializeFetchParameter } from "@apollo/client";
import { maybe } from "@apollo/client/utilities";
import { handleError, readMultipartBody, } from "../../../link/http/parseAndCheckHttpResponse.js";
import { fallbackHttpConfig } from "../../../link/http/selectHttpOptionsAndBody.js";
const backupFetch = maybe(() => fetch);
export 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 Observable.create((sink) => {
            try {
                options.body = serializeFetchParameter(body, "Payload");
            }
            catch (parseError) {
                sink.error(parseError);
            }
            const currentFetch = preferredFetch || 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 readMultipartBody(response, observerNext);
                }
                sink.error(new Error("Expected multipart response"));
            })
                .then(() => {
                sink.complete();
            })
                .catch((err) => {
                handleError(err, sink);
            });
        });
    };
}
function generateOptionsForMultipartSubscription(headers) {
    const options = {
        ...fallbackHttpConfig.options,
        headers: {
            ...(headers || {}),
            ...fallbackHttpConfig.headers,
            accept: "multipart/mixed;boundary=graphql;subscriptionSpec=1.0,application/json",
        },
    };
    return options;
}
//# sourceMappingURL=index.js.map
