/*! @azure/msal-common v11.0.0 2023-03-07 */
'use strict';
import { __awaiter, __generator } from '../_virtual/_tslib.js';
import { RegionDiscoverySources, ResponseCodes, Constants } from '../utils/Constants.js';
import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.js';

/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
var RegionDiscovery = /** @class */ (function () {
    function RegionDiscovery(networkInterface, performanceClient, correlationId) {
        this.networkInterface = networkInterface;
        this.performanceClient = performanceClient;
        this.correlationId = correlationId;
    }
    /**
     * Detect the region from the application's environment.
     *
     * @returns Promise<string | null>
     */
    RegionDiscovery.prototype.detectRegion = function (environmentRegion, regionDiscoveryMetadata) {
        var _a, _b, _c, _d;
        return __awaiter(this, void 0, void 0, function () {
            var autodetectedRegionName, options, localIMDSVersionResponse, currentIMDSVersion, currentIMDSVersionResponse;
            return __generator(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        (_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.RegionDiscoveryDetectRegion, this.correlationId);
                        autodetectedRegionName = environmentRegion;
                        if (!!autodetectedRegionName) return [3 /*break*/, 8];
                        options = RegionDiscovery.IMDS_OPTIONS;
                        _e.label = 1;
                    case 1:
                        _e.trys.push([1, 6, , 7]);
                        (_b = this.performanceClient) === null || _b === void 0 ? void 0 : _b.setPreQueueTime(PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.correlationId);
                        return [4 /*yield*/, this.getRegionFromIMDS(Constants.IMDS_VERSION, options)];
                    case 2:
                        localIMDSVersionResponse = _e.sent();
                        if (localIMDSVersionResponse.status === ResponseCodes.httpSuccess) {
                            autodetectedRegionName = localIMDSVersionResponse.body;
                            regionDiscoveryMetadata.region_source = RegionDiscoverySources.IMDS;
                        }
                        if (!(localIMDSVersionResponse.status === ResponseCodes.httpBadRequest)) return [3 /*break*/, 5];
                        (_c = this.performanceClient) === null || _c === void 0 ? void 0 : _c.setPreQueueTime(PerformanceEvents.RegionDiscoveryGetCurrentVersion, this.correlationId);
                        return [4 /*yield*/, this.getCurrentVersion(options)];
                    case 3:
                        currentIMDSVersion = _e.sent();
                        if (!currentIMDSVersion) {
                            regionDiscoveryMetadata.region_source = RegionDiscoverySources.FAILED_AUTO_DETECTION;
                            return [2 /*return*/, null];
                        }
                        (_d = this.performanceClient) === null || _d === void 0 ? void 0 : _d.setPreQueueTime(PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.correlationId);
                        return [4 /*yield*/, this.getRegionFromIMDS(currentIMDSVersion, options)];
                    case 4:
                        currentIMDSVersionResponse = _e.sent();
                        if (currentIMDSVersionResponse.status === ResponseCodes.httpSuccess) {
                            autodetectedRegionName = currentIMDSVersionResponse.body;
                            regionDiscoveryMetadata.region_source = RegionDiscoverySources.IMDS;
                        }
                        _e.label = 5;
                    case 5: return [3 /*break*/, 7];
                    case 6:
                        _e.sent();
                        regionDiscoveryMetadata.region_source = RegionDiscoverySources.FAILED_AUTO_DETECTION;
                        return [2 /*return*/, null];
                    case 7: return [3 /*break*/, 9];
                    case 8:
                        regionDiscoveryMetadata.region_source = RegionDiscoverySources.ENVIRONMENT_VARIABLE;
                        _e.label = 9;
                    case 9:
                        // If no region was auto detected from the environment or from the IMDS endpoint, mark the attempt as a FAILED_AUTO_DETECTION
                        if (!autodetectedRegionName) {
                            regionDiscoveryMetadata.region_source = RegionDiscoverySources.FAILED_AUTO_DETECTION;
                        }
                        return [2 /*return*/, autodetectedRegionName || null];
                }
            });
        });
    };
    /**
     * Make the call to the IMDS endpoint
     *
     * @param imdsEndpointUrl
     * @returns Promise<NetworkResponse<string>>
     */
    RegionDiscovery.prototype.getRegionFromIMDS = function (version, options) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_b) {
                (_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.correlationId);
                return [2 /*return*/, this.networkInterface.sendGetRequestAsync(Constants.IMDS_ENDPOINT + "?api-version=" + version + "&format=text", options, Constants.IMDS_TIMEOUT)];
            });
        });
    };
    /**
     * Get the most recent version of the IMDS endpoint available
     *
     * @returns Promise<string | null>
     */
    RegionDiscovery.prototype.getCurrentVersion = function (options) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        (_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.RegionDiscoveryGetCurrentVersion, this.correlationId);
                        _b.label = 1;
                    case 1:
                        _b.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.networkInterface.sendGetRequestAsync(Constants.IMDS_ENDPOINT + "?format=json", options)];
                    case 2:
                        response = _b.sent();
                        // When IMDS endpoint is called without the api version query param, bad request response comes back with latest version.
                        if (response.status === ResponseCodes.httpBadRequest && response.body && response.body["newest-versions"] && response.body["newest-versions"].length > 0) {
                            return [2 /*return*/, response.body["newest-versions"][0]];
                        }
                        return [2 /*return*/, null];
                    case 3:
                        _b.sent();
                        return [2 /*return*/, null];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    // Options for the IMDS endpoint request
    RegionDiscovery.IMDS_OPTIONS = {
        headers: {
            Metadata: "true",
        },
    };
    return RegionDiscovery;
}());

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