import { getEnv } from "@ledgerhq/live-env";
import axios, { AxiosError } from "axios";
export const fetchTokensFromCDN = async (filename) => {
    try {
        const { data, headers } = await axios.get(`${getEnv("DYNAMIC_CAL_BASE_URL")}/${filename}`);
        return [data, headers.etag];
    }
    catch (err) {
        const error = err;
        throw new Error(`${error.message} ${getEnv("DYNAMIC_CAL_BASE_URL")}/${filename}`);
    }
};
export const fetchTokensFromCALService = async (chainDetails, output, etag, next) => {
    const ref = getEnv("CAL_REF") || undefined;
    try {
        const { data, headers } = await axios.get(`${getEnv("CAL_SERVICE_URL")}/v1/tokens`, {
            params: {
                ...(next?.cursor ? { cursor: next.cursor } : {}),
                chain_id: chainDetails.chainId,
                standard: chainDetails.standard,
                blockchain_name: chainDetails.blockchain_name,
                output: output.join(),
                ref,
            },
            headers: etag
                ? {
                    "If-None-Match": etag,
                }
                : undefined,
        });
        const cursor = headers["x-ledger-next"];
        if (cursor) {
            return fetchTokensFromCALService({ chainId: chainDetails.chainId, standard: chainDetails.standard }, output, etag, {
                tokens: next?.tokens ? [...next.tokens, ...data] : data,
                cursor,
            });
        }
        const hash = headers["etag"];
        return next?.tokens ? { tokens: [...next.tokens, ...data], hash } : { tokens: data, hash };
    }
    catch (err) {
        if (err instanceof AxiosError) {
            if (err.response?.status === 304) {
                throw err;
            }
            throw new Error(`${err?.message}: ${err?.config?.url}`);
        }
        throw err;
    }
};
//# sourceMappingURL=index.js.map