import { __assign, __rest } from "tslib";
import * as React from "rehackt";
import { equal } from "@wry/equality";
import { mergeDeepArray } from "../../utilities/index.js";
import { useApolloClient } from "./useApolloClient.js";
import { useSyncExternalStore } from "./useSyncExternalStore.js";
import { useDeepMemo, useLazyRef } from "./internal/index.js";
export function useFragment(options) {
    var cache = useApolloClient(options.client).cache;
    var diffOptions = useDeepMemo(function () {
        var fragment = options.fragment, fragmentName = options.fragmentName, from = options.from, _a = options.optimistic, optimistic = _a === void 0 ? true : _a, rest = __rest(options, ["fragment", "fragmentName", "from", "optimistic"]);
        return __assign(__assign({}, rest), { returnPartialData: true, id: typeof from === "string" ? from : cache.identify(from), query: cache["getFragmentDoc"](fragment, fragmentName), optimistic: optimistic });
    }, [options]);
    var resultRef = useLazyRef(function () {
        return diffToResult(cache.diff(diffOptions));
    });
    // Used for both getSnapshot and getServerSnapshot
    var getSnapshot = React.useCallback(function () { return resultRef.current; }, []);
    return useSyncExternalStore(React.useCallback(function (forceUpdate) {
        var lastTimeout = 0;
        var unsubscribe = cache.watch(__assign(__assign({}, diffOptions), { immediate: true, callback: function (diff) {
                if (!equal(diff.result, resultRef.current.data)) {
                    resultRef.current = diffToResult(diff);
                    // If we get another update before we've re-rendered, bail out of
                    // the update and try again. This ensures that the relative timing
                    // between useQuery and useFragment stays roughly the same as
                    // fixed in https://github.com/apollographql/apollo-client/pull/11083
                    clearTimeout(lastTimeout);
                    lastTimeout = setTimeout(forceUpdate);
                }
            } }));
        return function () {
            unsubscribe();
            clearTimeout(lastTimeout);
        };
    }, [cache, diffOptions]), getSnapshot, getSnapshot);
}
function diffToResult(diff) {
    var result = {
        data: diff.result,
        complete: !!diff.complete,
    };
    if (diff.missing) {
        result.missing = mergeDeepArray(diff.missing.map(function (error) { return error.missing; }));
    }
    return result;
}
//# sourceMappingURL=useFragment.js.map