"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FetchRoute = void 0;
function _express() {
  const data = require("@teambit/express");
  _express = function () {
    return data;
  };
  return data;
}
function _legacy() {
  const data = require("@teambit/legacy.scope-api");
  _legacy = function () {
    return data;
  };
  return data;
}
function _objectList() {
  const data = require("@teambit/legacy/dist/scope/objects/object-list");
  _objectList = function () {
    return data;
  };
  return data;
}
function _promises() {
  const data = require("stream/promises");
  _promises = function () {
    return data;
  };
  return data;
}
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } // @ts-ignore
class FetchRoute {
  constructor(scope, logger) {
    this.scope = scope;
    this.logger = logger;
    _defineProperty(this, "route", '/scope/fetch');
    _defineProperty(this, "method", 'post');
    _defineProperty(this, "verb", _express().Verb.READ);
    _defineProperty(this, "middlewares", [async (req, res) => {
      req.setTimeout(this.scope.config.httpTimeOut);
      const preFetchHookP = this.scope.preFetchObjects.values().map(fn => fn({
        ids: req.body.ids,
        fetchOptions: req.body.fetchOptions
      }, {
        headers: req.headers
      }));
      Promise.all(preFetchHookP).catch(err => {
        this.logger.error('fatal: onPreFetchObjects encountered an error (this error does not stop the process)', err);
      });
      const readable = await (0, _legacy().fetch)(this.scope.path, req.body.ids, req.body.fetchOptions, req.headers);
      const pack = _objectList().ObjectList.fromObjectStreamToTar(readable, this.scope.name);
      try {
        await (0, _promises().pipeline)(pack, res);
        this.logger.info('fetch.router, the response has been sent successfully to the client', req.headers);
      } catch (err) {
        if (req.aborted) {
          this.logger.warn('FetchRoute, the client aborted the request', err);
        } else {
          this.logger.error(`FetchRoute encountered an error during the pipeline streaming, this should never happen.
make sure the error is caught in fromObjectStreamToTar and it streamed using the name "ERROR".
error: ${err.message}`, err);
        }
      }
    }]);
  }
}
exports.FetchRoute = FetchRoute;

//# sourceMappingURL=fetch.route.js.map