"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.objectToURLSearchParams = exports.stripHexPrefix = exports.isHexPrefixed = exports.safeUrl = exports.getInitialURL = exports.getClientHeaders = exports.addParamsToURL = exports.isWalletAPIERC20TokenCurrency = exports.isWalletAPITokenCurrency = exports.isWalletAPICryptoCurrency = exports.isWalletAPISupportedCurrency = void 0;
const currencies_1 = require("../currencies");
const constants_1 = require("./constants");
const helpers_1 = require("../helpers");
const manifestDomainUtils_1 = require("./manifestDomainUtils");
function isWalletAPISupportedCurrency(currency) {
    if ((0, currencies_1.isCryptoCurrency)(currency)) {
        return (0, helpers_1.includes)(constants_1.WALLET_API_FAMILIES, currency.family);
    }
    if ((0, currencies_1.isTokenCurrency)(currency)) {
        return (0, helpers_1.includes)(constants_1.WALLET_API_FAMILIES, currency.parentCurrency.family);
    }
    return false;
}
exports.isWalletAPISupportedCurrency = isWalletAPISupportedCurrency;
function isWalletAPICryptoCurrency(currency) {
    return currency.type === "CryptoCurrency";
}
exports.isWalletAPICryptoCurrency = isWalletAPICryptoCurrency;
function isWalletAPITokenCurrency(currency) {
    return currency.type === "TokenCurrency";
}
exports.isWalletAPITokenCurrency = isWalletAPITokenCurrency;
function isWalletAPIERC20TokenCurrency(currency) {
    return currency.type === "TokenCurrency" && currency.standard === "ERC20";
}
exports.isWalletAPIERC20TokenCurrency = isWalletAPIERC20TokenCurrency;
function addParamsToURL(url, inputs) {
    if (inputs) {
        const keys = Object.keys(inputs);
        for (let i = 0; i < keys.length; i++) {
            const key = keys[i];
            const value = inputs[key];
            if (value !== undefined) {
                url.searchParams.set(key, String(value));
            }
        }
    }
}
exports.addParamsToURL = addParamsToURL;
function getClientHeaders(params) {
    return {
        "x-ledger-host": params.client,
        "x-ledger-host-theme": params.theme,
    };
}
exports.getClientHeaders = getClientHeaders;
/**
 * Validates a URL by checking if it's on the same domain as the manifest URL.
 * Only HTTPS URLs are allowed.
 * @param url - The URL to validate
 * @param manifestUrl - The manifest URL to check same domain against
 * @returns true if the URL is valid and is on the same domain as manifestUrl
 */
const isWhitelistedDomain = (url, manifestUrl) => {
    try {
        // Parse the URL
        const parsedUrl = new URL(url);
        // Only allow HTTPS scheme
        if (parsedUrl.protocol !== "https:") {
            console.error(`#isWhitelistedDomain:: invalid URL: non-HTTPS scheme '${parsedUrl.protocol}' is not allowed`);
            return false;
        }
        // Check if URL is on the same domain as manifest URL
        if (!(0, manifestDomainUtils_1.isSameDomain)(url, manifestUrl)) {
            console.error(`#isWhitelistedDomain:: invalid URL: not on the same domain as manifest URL`);
            return false;
        }
        return true;
    }
    catch (error) {
        // Invalid URL format
        console.error(`#isWhitelistedDomain:: invalid URL format: ${error}`);
        return false;
    }
};
const getInitialURL = (inputs, manifest) => {
    try {
        if (typeof inputs?.goToURL === "string" &&
            isWhitelistedDomain(inputs.goToURL, manifest.url.toString())) {
            return inputs?.goToURL;
        }
        const url = new URL(manifest.url.toString());
        // Filter out goToURL from inputs to prevent it from being added as a query parameter
        // when validation fails
        const { goToURL, ...filteredInputs } = inputs || {};
        addParamsToURL(url, filteredInputs);
        if (manifest.params) {
            url.searchParams.set("params", JSON.stringify(manifest.params));
        }
        return url.toString();
    }
    catch (e) {
        if (e instanceof Error)
            console.error(e.message);
        return manifest.url.toString();
    }
};
exports.getInitialURL = getInitialURL;
const safeUrl = (url) => {
    try {
        return new URL(url);
    }
    catch {
        return null;
    }
};
exports.safeUrl = safeUrl;
// Copied from https://www.npmjs.com/package/ethereumjs-util
const isHexPrefixed = (str) => {
    if (typeof str !== "string") {
        throw new Error(`[isHexPrefixed] input must be type 'string', received type ${typeof str}`);
    }
    return str[0] === "0" && str[1] === "x";
};
exports.isHexPrefixed = isHexPrefixed;
// Copied from https://www.npmjs.com/package/ethereumjs-util
const stripHexPrefix = (str) => {
    if (typeof str !== "string")
        throw new Error(`[stripHexPrefix] input must be type 'string', received ${typeof str}`);
    return (0, exports.isHexPrefixed)(str) ? str.slice(2) : str;
};
exports.stripHexPrefix = stripHexPrefix;
function objectToURLSearchParams(obj) {
    const searchParams = new URLSearchParams();
    Object.entries(obj).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
            if (typeof value === "object") {
                searchParams.append(key, JSON.stringify(value));
            }
            else {
                searchParams.append(key, String(value));
            }
        }
    });
    return searchParams;
}
exports.objectToURLSearchParams = objectToURLSearchParams;
//# sourceMappingURL=helpers.js.map