text: "use strict";
  /*
   * The MIT License (MIT)
   *
   * Copyright (c) 2019 Looker Data Sciences, Inc.
   *
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:
   *
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   *
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   */
  var __extends = (this && this.__extends) || (function () {
      var extendStatics = function (d, b) {
          extendStatics = Object.setPrototypeOf ||
              ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
              function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
          return extendStatics(d, b);
      };
      return function (d, b) {
          extendStatics(d, b);
          function __() { this.constructor = d; }
          d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
      };
  })();
  var __assign = (this && this.__assign) || function () {
      __assign = Object.assign || function(t) {
          for (var s, i = 1, n = arguments.length; i < n; i++) {
              s = arguments[i];
              for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                  t[p] = s[p];
          }
          return t;
      };
      return __assign.apply(this, arguments);
  };
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
      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) : new P(function (resolve) { resolve(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 };
      }
  };
  var __importDefault = (this && this.__importDefault) || function (mod) {
      return (mod && mod.__esModule) ? mod : { "default": mod };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  var transport_1 = require("./transport");
  var request_1 = __importDefault(require("request"));
  var request_promise_native_1 = __importDefault(require("request-promise-native"));
  var readable_stream_1 = require("readable-stream");
  var baseTransport_1 = require("./baseTransport");
  var NodeTransport = /** @class */ (function (_super) {
      __extends(NodeTransport, _super);
      function NodeTransport(options) {
          var _this = _super.call(this, options) || this;
          _this.options = options;
          return _this;
      }
      NodeTransport.prototype.request = function (method, path, queryParams, body, authenticator, options) {
          return __awaiter(this, void 0, void 0, function () {
              var init, req, res, resTyped, contentType, parsed, e_1, error;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0: return [4 /*yield*/, this.initRequest(method, path, queryParams, body, authenticator, options)];
                      case 1:
                          init = _a.sent();
                          req = request_promise_native_1.default(init).promise();
                          _a.label = 2;
                      case 2:
                          _a.trys.push([2, 5, , 6]);
                          return [4 /*yield*/, req];
                      case 3:
                          res = _a.sent();
                          resTyped = res;
                          contentType = String(resTyped.headers['content-type']);
                          return [4 /*yield*/, parseResponse(contentType, res)];
                      case 4:
                          parsed = _a.sent();
                          if (this.ok(resTyped)) {
                              return [2 /*return*/, { ok: true, value: parsed }];
                          }
                          else {
                              return [2 /*return*/, { ok: false, error: parsed }];
                          }
                          return [3 /*break*/, 6];
                      case 5:
                          e_1 = _a.sent();
                          error = {
                              type: 'sdk_error',
                              message: typeof e_1.message === 'string'
                                  ? e_1.message
                                  : "The SDK call was not successful. The error was '" + e_1 + "'.",
                          };
                          return [2 /*return*/, { ok: false, error: error }];
                      case 6: return [2 /*return*/];
                  }
              });
          });
      };
      /**
       * Http method dispatcher from general-purpose request properties
       * @param props
       * @returns {request.Request}
       */
      NodeTransport.prototype.requestor = function (props) {
          var method = props.method.toString().toUpperCase();
          switch (method) {
              case 'GET': return request_1.default.get(props);
              case 'PUT': return request_1.default.put(props);
              case 'POST': return request_1.default.post(props);
              case 'PATCH': return request_1.default.patch(props);
              case 'DELETE': return request_1.default.put(props);
              case 'HEAD': return request_1.default.head(props);
              default: return request_1.default.get(props);
          }
      };
      NodeTransport.prototype.stream = function (callback, method, path, queryParams, body, authenticator, options) {
          return __awaiter(this, void 0, void 0, function () {
              var stream, returnPromise, init, streamPromise, results;
              var _this = this;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0:
                          stream = new readable_stream_1.PassThrough();
                          returnPromise = callback(stream);
                          return [4 /*yield*/, this.initRequest(method, path, queryParams, body, authenticator, options)];
                      case 1:
                          init = _a.sent();
                          streamPromise = new Promise(function (resolve, reject) {
                              transport_1.trace("[stream] beginning stream via download url", init);
                              var hasResolved = false;
                              var req = _this.requestor(init);
                              req
                                  .on("error", function (err) {
                                  if (hasResolved && err.code === "ECONNRESET") {
                                      transport_1.trace('ignoring ECONNRESET that occurred after streaming finished', init);
                                  }
                                  else {
                                      transport_1.trace('streaming error', err);
                                      reject(err);
                                  }
                              })
                                  .on("finish", function () {
                                  transport_1.trace("[stream] streaming via download url finished", init);
                              })
                                  .on("socket", function (socket) {
                                  transport_1.trace("[stream] setting keepalive on socket", init);
                                  socket.setKeepAlive(true);
                              })
                                  .on("abort", function () {
                                  transport_1.trace("[stream] streaming via download url aborted", init);
                              })
                                  .on("response", function () {
                                  transport_1.trace("[stream] got response from download url", init);
                              })
                                  .on("close", function () {
                                  transport_1.trace("[stream] request stream closed", init);
                              })
                                  .pipe(stream)
                                  .on("error", function (err) {
                                  transport_1.trace("[stream] PassThrough stream error", err);
                                  reject(err);
                              })
                                  .on("finish", function () {
                                  transport_1.trace("[stream] PassThrough stream finished", init);
                                  resolve();
                                  hasResolved = true;
                              })
                                  .on("close", function () {
                                  transport_1.trace("[stream] PassThrough stream closed", init);
                              });
                          });
                          return [4 /*yield*/, Promise.all([returnPromise, streamPromise])];
                      case 2:
                          results = _a.sent();
                          return [2 /*return*/, results[0]];
                  }
              });
          });
      };
      /**
       * should the request verify SSL?
       * @param {Partial<ITransportSettings>} options Defaults to the instance options values
       * @returns {boolean} true if the request should require full SSL verification
       */
      NodeTransport.prototype.verifySsl = function (options) {
          if (!options)
              options = this.options;
          return 'verify_ssl' in options ? options.verify_ssl : true;
      };
      /**
       * Request timeout in seconds
       * @param {Partial<ITransportSettings>} options Defaults to the instance options values
       * @returns {number | undefined}
       */
      NodeTransport.prototype.timeout = function (options) {
          if (!options)
              options = this.options;
          if ('timeout' in options && options.timeout)
              return options.timeout;
          return transport_1.defaultTimeout;
      };
      NodeTransport.prototype.initRequest = function (method, path, queryParams, body, authenticator, options) {
          return __awaiter(this, void 0, void 0, function () {
              var headers, requestPath, init;
              return __generator(this, function (_a) {
                  switch (_a.label) {
                      case 0:
                          options = options ? __assign({}, this.options, options) : this.options;
                          headers = __assign({ 'User-Agent': transport_1.agentTag }, options.headers);
                          if (body) {
                              headers = __assign({ 'User-Agent': transport_1.agentTag }, options.headers);
                          }
                          requestPath = this.makePath(path, options, queryParams, authenticator);
                          init = {
                              url: requestPath,
                              headers: headers,
                              body: body ? body : undefined,
                              json: !!body,
                              resolveWithFullResponse: true,
                              rejectUnauthorized: this.verifySsl(options),
                              timeout: this.timeout(options) * 1000,
                              encoding: null,
                              method: method,
                          };
                          if ('encoding' in options)
                              init.encoding = options.encoding;
                          if (!authenticator) return [3 /*break*/, 2];
                          return [4 /*yield*/, authenticator(init)];
                      case 1:
                          // Automatic authentication process for the request
                          init = _a.sent();
                          _a.label = 2;
                      case 2: return [2 /*return*/, init];
                  }
              });
          });
      };
      NodeTransport.prototype.ok = function (res) {
          return (res.statusCode >= transport_1.StatusCode.OK && res.statusCode <= transport_1.StatusCode.IMUsed);
      };
      return NodeTransport;
  }(baseTransport_1.BaseTransport));
  exports.NodeTransport = NodeTransport;
  function parseResponse(contentType, res) {
      return __awaiter(this, void 0, void 0, function () {
          var mode, utf8, result;
          return __generator(this, function (_a) {
              switch (_a.label) {
                  case 0:
                      mode = transport_1.responseMode(contentType);
                      utf8 = 'utf8';
                      return [4 /*yield*/, res.body];
                  case 1:
                      result = _a.sent();
                      if (mode === transport_1.ResponseMode.string) {
                          if (contentType.match(/^application\/.*\bjson\b/g)) {
                              try {
                                  if (result instanceof Buffer) {
                                      result = result.toString(utf8);
                                  }
                                  if (result instanceof Object) {
                                      return [2 /*return*/, result];
                                  }
                                  return [2 /*return*/, JSON.parse(result.toString())];
                              }
                              catch (error) {
                                  return [2 /*return*/, Promise.reject(error)];
                              }
                          }
                          // if (!isUtf8(contentType)) {
                          //   // always convert to UTF-8 from whatever it was
                          //   result = if (result instanceof Buffer) result.toString(utf8)
                          // }
                          if (result instanceof Buffer) {
                              result = result.toString(utf8);
                          }
                          return [2 /*return*/, result.toString()];
                      }
                      else {
                          try {
                              // TODO Return ArrayBuffer from buffer without any character encoding?
                              // See https://stackoverflow.com/a/31394257/74137 for more info
                              // return result.buffer.slice(result.byteOffset, result.byteOffset + result.byteLength)
                              return [2 /*return*/, result.toString()];
                          }
                          catch (error) {
                              return [2 /*return*/, Promise.reject(error)];
                          }
                      }
                      return [2 /*return*/];
              }
          });
      });
  }
  