"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeSchemaUrl = exports.validateSchemaUrlNormalized = exports.normalizeProtocolUrl = exports.validateProtocolUrlNormalized = void 0;
const dwn_error_js_1 = require("../core/dwn-error.js");
function validateProtocolUrlNormalized(url) {
    let normalized;
    try {
        normalized = normalizeProtocolUrl(url);
    }
    catch (_a) {
        normalized = undefined;
    }
    if (url !== normalized) {
        throw new dwn_error_js_1.DwnError(dwn_error_js_1.DwnErrorCode.UrlProtocolNotNormalized, `Protocol URI ${url} must be normalized.`);
    }
}
exports.validateProtocolUrlNormalized = validateProtocolUrlNormalized;
function normalizeProtocolUrl(url) {
    // Keeping protocol normalization as a separate function in case
    // protocol and schema normalization diverge in the future
    return normalizeUrl(url);
}
exports.normalizeProtocolUrl = normalizeProtocolUrl;
function validateSchemaUrlNormalized(url) {
    let normalized;
    try {
        normalized = normalizeSchemaUrl(url);
    }
    catch (_a) {
        normalized = undefined;
    }
    if (url !== normalized) {
        throw new dwn_error_js_1.DwnError(dwn_error_js_1.DwnErrorCode.UrlSchemaNotNormalized, `Schema URI ${url} must be normalized.`);
    }
}
exports.validateSchemaUrlNormalized = validateSchemaUrlNormalized;
function normalizeSchemaUrl(url) {
    // Keeping schema normalization as a separate function in case
    // protocol and schema normalization diverge in the future
    return normalizeUrl(url);
}
exports.normalizeSchemaUrl = normalizeSchemaUrl;
function normalizeUrl(url) {
    let fullUrl;
    if (/^[^:]+:(\/{2})?[^\/].*/.test(url)) {
        // if (/^[^:]+:\/\/./.test(url)) {
        fullUrl = url;
    }
    else {
        fullUrl = `http://${url}`;
    }
    try {
        const result = new URL(fullUrl);
        result.search = '';
        result.hash = '';
        return removeTrailingSlash(result.href);
    }
    catch (e) {
        throw new dwn_error_js_1.DwnError(dwn_error_js_1.DwnErrorCode.UrlProtocolNotNormalizable, 'Could not normalize protocol URI');
    }
}
function removeTrailingSlash(str) {
    if (str.endsWith('/')) {
        return str.slice(0, -1);
    }
    else {
        return str;
    }
}
//# sourceMappingURL=url.js.map