/*! @azure/msal-common v12.0.0 2023-04-03 */
'use strict';
import { ClientConfigurationError } from '../error/ClientConfigurationError.js';
import { HeaderNames, Constants } from '../utils/Constants.js';

/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
/**
 * This is a helper class that parses supported HTTP response authentication headers to extract and return
 * header challenge values that can be used outside the basic authorization flows.
 */
var AuthenticationHeaderParser = /** @class */ (function () {
    function AuthenticationHeaderParser(headers) {
        this.headers = headers;
    }
    /**
     * This method parses the SHR nonce value out of either the Authentication-Info or WWW-Authenticate authentication headers.
     * @returns
     */
    AuthenticationHeaderParser.prototype.getShrNonce = function () {
        // Attempt to parse nonce from Authentiacation-Info
        var authenticationInfo = this.headers[HeaderNames.AuthenticationInfo];
        if (authenticationInfo) {
            var authenticationInfoChallenges = this.parseChallenges(authenticationInfo);
            if (authenticationInfoChallenges.nextnonce) {
                return authenticationInfoChallenges.nextnonce;
            }
            throw ClientConfigurationError.createInvalidAuthenticationHeaderError(HeaderNames.AuthenticationInfo, "nextnonce challenge is missing.");
        }
        // Attempt to parse nonce from WWW-Authenticate
        var wwwAuthenticate = this.headers[HeaderNames.WWWAuthenticate];
        if (wwwAuthenticate) {
            var wwwAuthenticateChallenges = this.parseChallenges(wwwAuthenticate);
            if (wwwAuthenticateChallenges.nonce) {
                return wwwAuthenticateChallenges.nonce;
            }
            throw ClientConfigurationError.createInvalidAuthenticationHeaderError(HeaderNames.WWWAuthenticate, "nonce challenge is missing.");
        }
        // If neither header is present, throw missing headers error
        throw ClientConfigurationError.createMissingNonceAuthenticationHeadersError();
    };
    /**
     * Parses an HTTP header's challenge set into a key/value map.
     * @param header
     * @returns
     */
    AuthenticationHeaderParser.prototype.parseChallenges = function (header) {
        var schemeSeparator = header.indexOf(" ");
        var challenges = header.substr(schemeSeparator + 1).split(",");
        var challengeMap = {};
        challenges.forEach(function (challenge) {
            var _a = challenge.split("="), key = _a[0], value = _a[1];
            // Remove escaped quotation marks (', ") from challenge string to keep only the challenge value
            challengeMap[key] = unescape(value.replace(/['"]+/g, Constants.EMPTY_STRING));
        });
        return challengeMap;
    };
    return AuthenticationHeaderParser;
}());

export { AuthenticationHeaderParser };
//# sourceMappingURL=AuthenticationHeaderParser.js.map
