/*! firebase-admin v10.3.0 */
"use strict";
/*!
 * @license
 * Copyright 2022 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventarcApiClient = void 0;
var validator = require("../utils/validator");
var eventarc_utils_1 = require("./eventarc-utils");
var api_request_1 = require("../utils/api-request");
var utils = require("../utils");
var error_1 = require("../utils/error");
var EVENTARC_API = 'https://eventarcpublishing.googleapis.com/v1';
var FIREBASE_VERSION_HEADER = {
    'X-Firebase-Client': "fire-admin-node/" + utils.getSdkVersion(),
};
var CHANNEL_NAME_REGEX = /^(projects\/([^/]+)\/)?locations\/([^/]+)\/channels\/([^/]+)$/;
var DEFAULT_CHANNEL_REGION = 'us-central1';
/**
 * Class that facilitates sending requests to the Eventarc backend API.
 *
 * @internal
 */
var EventarcApiClient = /** @class */ (function () {
    function EventarcApiClient(app, channel) {
        this.app = app;
        this.channel = channel;
        if (!validator.isNonNullObject(app) || !('options' in app)) {
            throw new eventarc_utils_1.FirebaseEventarcError('invalid-argument', 'First argument passed to Channel() must be a valid Eventarc service instance.');
        }
        this.httpClient = new api_request_1.AuthorizedHttpClient(app);
        this.resolvedChannelName = this.resolveChannelName(channel.name);
    }
    EventarcApiClient.prototype.getProjectId = function () {
        var _this = this;
        if (this.projectId) {
            return Promise.resolve(this.projectId);
        }
        return utils.findProjectId(this.app)
            .then(function (projectId) {
            if (!validator.isNonEmptyString(projectId)) {
                throw new eventarc_utils_1.FirebaseEventarcError('unknown-error', 'Failed to determine project ID. Initialize the '
                    + 'SDK with service account credentials or set project ID as an app option. '
                    + 'Alternatively, set the GOOGLE_CLOUD_PROJECT environment variable.');
            }
            _this.projectId = projectId;
            return projectId;
        });
    };
    /**
     * Publishes provided events to this channel. If channel was created with `allowedEventsTypes` and event type
     * is not on that list, the event is ignored.
     *
     * The following CloudEvent fields are auto-populated if not set:
     *  * specversion - `1.0`
     *  * id - uuidv4()
     *  * source - populated with `process.env.EVENTARC_CLOUD_EVENT_SOURCE` and
     *             if not set an error is thrown.
     *
     * @param events - CloudEvent to publish to the channel.
     */
    EventarcApiClient.prototype.publish = function (events) {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            var _this = this;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!Array.isArray(events)) {
                            events = [events];
                        }
                        _a = this.publishToEventarcApi;
                        return [4 /*yield*/, this.resolvedChannelName];
                    case 1: return [2 /*return*/, _a.apply(this, [_b.sent(),
                            events
                                .filter(function (e) { return typeof _this.channel.allowedEventTypes === 'undefined' ||
                                _this.channel.allowedEventTypes.includes(e.type); })
                                .map(eventarc_utils_1.toCloudEventProtoFormat)])];
                }
            });
        });
    };
    EventarcApiClient.prototype.publishToEventarcApi = function (channel, events) {
        return __awaiter(this, void 0, void 0, function () {
            var request;
            return __generator(this, function (_a) {
                if (events.length === 0) {
                    return [2 /*return*/];
                }
                request = {
                    method: 'POST',
                    url: this.getEventarcHost() + "/" + channel + ":publishEvents",
                    data: JSON.stringify({ events: events }),
                };
                return [2 /*return*/, this.sendRequest(request)];
            });
        });
    };
    EventarcApiClient.prototype.sendRequest = function (request) {
        var _this = this;
        request.headers = FIREBASE_VERSION_HEADER;
        return this.httpClient.send(request)
            .then(function () { return undefined; })
            .catch(function (err) {
            throw _this.toFirebaseError(err);
        });
    };
    EventarcApiClient.prototype.toFirebaseError = function (err) {
        if (err instanceof error_1.PrefixedFirebaseError) {
            return err;
        }
        var response = err.response;
        return new eventarc_utils_1.FirebaseEventarcError('unknown-error', "Unexpected response with status: " + response.status + " and body: " + response.text);
    };
    EventarcApiClient.prototype.resolveChannelName = function (name) {
        if (!name.includes('/')) {
            var location = DEFAULT_CHANNEL_REGION;
            var channelId = name;
            return this.resolveChannelNameProjectId(location, channelId);
        }
        else {
            var match = CHANNEL_NAME_REGEX.exec(name);
            if (match === null || match.length < 4) {
                throw new eventarc_utils_1.FirebaseEventarcError('invalid-argument', 'Invalid channel name format.');
            }
            var projectId = match[2];
            var location = match[3];
            var channelId = match[4];
            if (validator.isNonEmptyString(projectId)) {
                return Promise.resolve("projects/" + projectId + "/locations/" + location + "/channels/" + channelId);
            }
            else {
                return this.resolveChannelNameProjectId(location, channelId);
            }
        }
    };
    EventarcApiClient.prototype.resolveChannelNameProjectId = function (location, channelId) {
        return __awaiter(this, void 0, void 0, function () {
            var projectId;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.getProjectId()];
                    case 1:
                        projectId = _a.sent();
                        return [2 /*return*/, "projects/" + projectId + "/locations/" + location + "/channels/" + channelId];
                }
            });
        });
    };
    EventarcApiClient.prototype.getEventarcHost = function () {
        var _a;
        return (_a = process.env.CLOUD_EVENTARC_EMULATOR_HOST) !== null && _a !== void 0 ? _a : EVENTARC_API;
    };
    return EventarcApiClient;
}());
exports.EventarcApiClient = EventarcApiClient;
