text: "use strict";
  Object.defineProperty(exports, "__esModule", { value: true });
  const api_1 = require("@forge/api");
  const isRequestPayload = (request) => {
      return typeof request.payload === 'object' && request.payload.product && request.payload.fetchUrl;
  };
  const defaultFunctions = {
      __request: async (request) => {
          if (!isRequestPayload(request)) {
              throw new Error('Invalid payload specified for request');
          }
          const { payload } = request;
          const productApis = {
              jira: api_1.asUser().requestJira,
              confluence: api_1.asUser().requestConfluence
          };
          const response = await productApis[payload.product](payload.fetchUrl, payload.fetchOptions);
          let body = await response.text();
          try {
              body = JSON.parse(body);
          }
          catch (e) { }
          return Object.assign(Object.assign({}, response), { body });
      }
  };
  class Resolver {
      constructor() {
          this.functions = Object.assign({}, defaultFunctions);
      }
      define(functionKey, cb) {
          if (!cb || typeof cb !== 'function') {
              throw new Error(`Resolver definition '${functionKey}' callback must be a 'function'. Received '${typeof cb}'.`);
          }
          if (functionKey in this.functions) {
              throw new Error(`Resolver definition '${functionKey}' already exists.`);
          }
          this.functions[functionKey] = cb;
          return this;
      }
      getFunction(functionKey) {
          if (functionKey in this.functions) {
              return this.functions[functionKey];
          }
          throw new Error(`Resolver has no definition for '${functionKey}'.`);
      }
      sanitizeObject(object) {
          return JSON.parse(JSON.stringify(object));
      }
      getDefinitions() {
          const resolve = async ({ call: { functionKey, payload: callPayload }, context }, backendRuntimePayload) => {
              var _a;
              const cb = this.getFunction(functionKey);
              const result = await cb({
                  payload: callPayload || {},
                  context: Object.assign(Object.assign({}, context), { accountId: (_a = backendRuntimePayload === null || backendRuntimePayload === void 0 ? void 0 : backendRuntimePayload.principal) === null || _a === void 0 ? void 0 : _a.accountId, license: backendRuntimePayload === null || backendRuntimePayload === void 0 ? void 0 : backendRuntimePayload.license })
              });
              if (typeof result === 'object') {
                  return this.sanitizeObject(result);
              }
              return result;
          };
          return resolve;
      }
  }
  exports.default = Resolver;
  