text: "use strict";
  Object.defineProperty(exports, "__esModule", { value: true });
  const graphql_1 = require("graphql");
  const cross_fetch_1 = require("cross-fetch");
  // github:owner/name#ref:path/to/file
  function extractData(pointer) {
      const [repo, file] = pointer.split('#');
      const [owner, name] = repo.split(':')[1].split('/');
      const [ref, path] = file.split(':');
      return {
          owner,
          name,
          ref,
          path,
      };
  }
  class GithubLoader {
      loaderId() {
          return 'github-loader';
      }
      async canLoad(pointer) {
          return typeof pointer === 'string' && pointer.toLowerCase().startsWith('github:');
      }
      async load(pointer, options) {
          const { owner, name, ref, path } = extractData(pointer);
          const request = await cross_fetch_1.fetch('https://api.github.com/graphql', {
              method: 'POST',
              headers: {
                  'Content-Type': 'application/json; charset=utf-8',
                  Authorization: `bearer ${options.token}`,
              },
              body: JSON.stringify({
                  query: `
            query GetGraphQLSchemaForGraphQLToolkit($owner: String!, $name: String!, $expression: String!) {
              repository(owner: $owner, name: $name) {
                object(expression: $expression) {
                  ... on Blob {
                    text
                  }
                }
              }
            }
          `,
                  variables: {
                      owner,
                      name,
                      expression: ref + ':' + path,
                  },
                  operationName: 'GetGraphQLSchemaForGraphQLToolkit',
              }),
          });
          const response = await request.json();
          let errorMessage = null;
          if (response.errors && response.errors.length > 0) {
              errorMessage = response.errors.map((item) => item.message).join(', ');
          }
          else if (!response.data) {
              errorMessage = response;
          }
          if (errorMessage) {
              throw new Error('Unable to download schema from github: ' + errorMessage);
          }
          const schemaString = response.data.repository.object.text;
          let document;
          if (/\.(gql|graphql)s?$/i.test(path)) {
              document = graphql_1.parse(schemaString);
          }
          if (/\.json$/i.test(path)) {
              document = graphql_1.parse(graphql_1.printSchema(graphql_1.buildClientSchema(JSON.parse(schemaString))));
          }
          if (!document) {
              throw new Error('Unable to build schema from GitHub');
          }
          return {
              location: pointer,
              document,
          };
      }
  }
  exports.GithubLoader = GithubLoader;
  //# sourceMappingURL=index.js.map