graphql-typescript-definitions
Version:
Generate TypeScript definition files from .graphql documents
825 lines (679 loc) • 32.3 kB
JavaScript
import _regeneratorRuntime from "@babel/runtime/regenerator";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
import { EventEmitter } from 'events';
import { join, resolve } from 'path';
import { parse, Source, concatAST } from 'graphql';
import chalk from 'chalk';
import { mkdirp, readFile, writeFile } from 'fs-extra';
import { watch } from 'chokidar';
import { getGraphQLConfig } from 'graphql-config';
import { getGraphQLProjectIncludedFilePaths, getGraphQLProjectForSchemaPath, getGraphQLProjects, getGraphQLSchemaPaths, resolvePathRelativeToConfig } from 'graphql-config-utilities';
import { compile, isOperation } from 'graphql-tool-utilities';
import { printDocument, generateSchemaTypes as _generateSchemaTypes } from "./print/index.mjs";
import { EnumFormat, ExportFormat } from "./types.mjs";
export { EnumFormat, ExportFormat };
export var Builder = /*#__PURE__*/function (_EventEmitter) {
_inherits(Builder, _EventEmitter);
var _super = _createSuper(Builder);
// workspace graphql configuration
// see: https://github.com/prisma/graphql-config
// projectName -> {filePath -> document}
// NOTE: projectName can be undefined for nameless graphql-config projects
function Builder(_ref) {
var _this;
var cwd = _ref.cwd,
options = _objectWithoutProperties(_ref, ["cwd"]);
_classCallCheck(this, Builder);
_this = _super.call(this);
_this.options = void 0;
_this.config = void 0;
_this.documentMapByProject = new Map();
_this.watchers = [];
_this.options = options;
_this.config = options.config ? options.config : getGraphQLConfig(cwd ? resolve(cwd) : undefined);
return _this;
}
_createClass(Builder, [{
key: "once",
value: function once(event, handler) {
return _get(_getPrototypeOf(Builder.prototype), "once", this).call(this, event, handler);
}
}, {
key: "on",
value: function on(event, handler) {
return _get(_getPrototypeOf(Builder.prototype), "on", this).call(this, event, handler);
}
}, {
key: "emit",
value: function emit(event) {
var _get2;
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return (_get2 = _get(_getPrototypeOf(Builder.prototype), "emit", this)).call.apply(_get2, [this, event].concat(args));
}
}, {
key: "run",
value: function () {
var _run = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
var _this2 = this;
var _ref2,
_ref2$watch,
watchGlobs,
schemaPaths,
_this$watchers,
_args = arguments;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_ref2 = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}, _ref2$watch = _ref2.watch, watchGlobs = _ref2$watch === void 0 ? false : _ref2$watch;
_context.prev = 1;
schemaPaths = getGraphQLSchemaPaths(this.config);
_context.next = 9;
break;
case 5:
_context.prev = 5;
_context.t0 = _context["catch"](1);
this.emit('error', _context.t0);
return _context.abrupt("return");
case 9:
if (!watchGlobs) {
_context.next = 13;
break;
}
(_this$watchers = this.watchers).push.apply(_this$watchers, _toConsumableArray(this.setupDocumentWatchers().concat(this.setupSchemaWatcher()))); // wait for all watchers to be ready
_context.next = 13;
return Promise.all(this.watchers.map(function (watcher) {
return new Promise(function (resolve) {
return watcher.on('ready', function () {
return resolve();
});
});
}));
case 13:
_context.prev = 13;
this.emit('start:schema');
_context.next = 17;
return Promise.all(schemaPaths.map(function (schemaPath) {
return _this2.generateSchemaTypes(schemaPath);
}));
case 17:
this.emit('end:schema');
_context.next = 24;
break;
case 20:
_context.prev = 20;
_context.t1 = _context["catch"](13);
this.emit('error', _context.t1);
return _context.abrupt("return");
case 24:
_context.prev = 24;
_context.next = 27;
return Promise.all(getGraphQLProjects(this.config).map(function (projectConfig) {
return _this2.updateDocumentsForProject(projectConfig);
}));
case 27:
_context.next = 33;
break;
case 29:
_context.prev = 29;
_context.t2 = _context["catch"](24);
this.emit('error', _context.t2);
return _context.abrupt("return");
case 33:
_context.next = 35;
return this.generateDocumentTypes();
case 35:
case "end":
return _context.stop();
}
}
}, _callee, this, [[1, 5], [13, 20], [24, 29]]);
}));
function run() {
return _run.apply(this, arguments);
}
return run;
}()
}, {
key: "stop",
value: function stop() {
this.watchers.forEach(function (watcher) {
watcher.close();
});
this.watchers.length = 0;
}
}, {
key: "setupDocumentWatchers",
value: function setupDocumentWatchers() {
var _this3 = this;
var update = /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(filePath, projectConfig) {
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
_context2.next = 3;
return _this3.updateDocumentForFile(filePath, projectConfig);
case 3:
_context2.next = 9;
break;
case 5:
_context2.prev = 5;
_context2.t0 = _context2["catch"](0);
_this3.emit('error', _context2.t0);
return _context2.abrupt("return");
case 9:
_context2.next = 11;
return _this3.generateDocumentTypes();
case 11:
case "end":
return _context2.stop();
}
}
}, _callee2, null, [[0, 5]]);
}));
return function update(_x, _x2) {
return _ref3.apply(this, arguments);
};
}();
return getGraphQLProjects(this.config).filter(function (_ref4) {
var includes = _ref4.includes;
return includes.length > 0;
}).map(function (projectConfig) {
return watch(projectConfig.includes.map(function (include) {
return resolvePathRelativeToConfig(projectConfig, include);
}), {
ignored: projectConfig.excludes.map(function (exclude) {
return resolvePathRelativeToConfig(projectConfig, exclude);
}),
ignoreInitial: true
}).on('add', function (filePath) {
return update(filePath, projectConfig);
}).on('change', function (filePath) {
return update(filePath, projectConfig);
}).on('unlink', /*#__PURE__*/function () {
var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(filePath) {
var documents;
return _regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
documents = _this3.documentMapByProject.get(projectConfig.projectName);
if (documents) {
documents["delete"](filePath);
}
_context3.next = 4;
return _this3.generateDocumentTypes();
case 4:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return function (_x3) {
return _ref5.apply(this, arguments);
};
}());
});
}
}, {
key: "setupSchemaWatcher",
value: function setupSchemaWatcher() {
var _this4 = this;
var update = /*#__PURE__*/function () {
var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(schemaPath) {
return _regeneratorRuntime.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.prev = 0;
_this4.emit('start:schema');
_context4.next = 4;
return _this4.generateSchemaTypes(schemaPath);
case 4:
_this4.emit('end:schema');
_context4.next = 7;
return _this4.generateDocumentTypes();
case 7:
_context4.next = 11;
break;
case 9:
_context4.prev = 9;
_context4.t0 = _context4["catch"](0);
case 11:
case "end":
return _context4.stop();
}
}
}, _callee4, null, [[0, 9]]);
}));
return function update(_x4) {
return _ref6.apply(this, arguments);
};
}();
return watch(getGraphQLSchemaPaths(this.config), {
ignoreInitial: true
}).on('change', update);
}
}, {
key: "generateSchemaTypes",
value: function () {
var _generateSchemaTypes2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(schemaPath) {
var projectConfig, schemaTypesPath, definitions;
return _regeneratorRuntime.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
projectConfig = getGraphQLProjectForSchemaPath(this.config, schemaPath);
schemaTypesPath = getSchemaTypesPath(projectConfig, this.options);
definitions = _generateSchemaTypes(projectConfig.getSchema(), this.options);
_context5.next = 5;
return mkdirp(schemaTypesPath);
case 5:
_context5.next = 7;
return Promise.all(Array.from(definitions.entries()).map(function (_ref7) {
var _ref8 = _slicedToArray(_ref7, 2),
fileName = _ref8[0],
definition = _ref8[1];
return writeFile(join(schemaTypesPath, fileName), definition);
}));
case 7:
this.emit('build:schema', {
schemaPath: schemaPath,
schemaTypesPath: schemaTypesPath
});
case 8:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function generateSchemaTypes(_x5) {
return _generateSchemaTypes2.apply(this, arguments);
}
return generateSchemaTypes;
}()
}, {
key: "generateDocumentTypes",
value: function () {
var _generateDocumentTypes = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() {
var _this5 = this;
return _regeneratorRuntime.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
this.emit('start:docs');
this.checkForDuplicateOperations();
this.checkForDuplicateFragments();
_context6.next = 5;
return Promise.all(Array.from(this.documentMapByProject.entries()).map(function (_ref9) {
var _ref10 = _slicedToArray(_ref9, 2),
projectName = _ref10[0],
documents = _ref10[1];
return _this5.generateDocumentTypesForProject(_this5.config.getProjectConfig(projectName), documents);
}));
case 5:
this.emit('end:docs');
case 6:
case "end":
return _context6.stop();
}
}
}, _callee6, this);
}));
function generateDocumentTypes() {
return _generateDocumentTypes.apply(this, arguments);
}
return generateDocumentTypes;
}()
}, {
key: "checkForDuplicateOperations",
value: function checkForDuplicateOperations() {
var _this6 = this;
getDuplicateOperations(this.documentMapByProject).forEach(function (_ref11) {
var projectName = _ref11.projectName,
duplicates = _ref11.duplicates;
if (duplicates.length) {
duplicates.forEach(function (_ref12) {
var operationName = _ref12.operationName,
filePaths = _ref12.filePaths;
var message = "GraphQL operations must have a unique name. The operation ".concat(chalk.bold(operationName), " is declared in:\n ").concat(filePaths.sort().join('\n ')).concat(projectName ? " (".concat(chalk.bold(projectName), ")") : '');
_this6.emit('error', new Error(message));
});
}
});
}
}, {
key: "checkForDuplicateFragments",
value: function checkForDuplicateFragments() {
var _this7 = this;
getDuplicateFragments(this.documentMapByProject).forEach(function (_ref13) {
var projectName = _ref13.projectName,
duplicates = _ref13.duplicates;
if (duplicates.length) {
duplicates.forEach(function (_ref14) {
var fragmentName = _ref14.fragmentName,
filePaths = _ref14.filePaths;
var message = "GraphQL fragments must have a unique name. The fragment ".concat(chalk.bold(fragmentName), " is declared in:\n ").concat(filePaths.sort().join('\n ')).concat(projectName ? " (".concat(chalk.bold(projectName), ")") : '');
_this7.emit('error', new Error(message));
});
}
});
}
}, {
key: "generateDocumentTypesForProject",
value: function () {
var _generateDocumentTypesForProject = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(projectConfig, documents) {
var _this8 = this;
var ast;
return _regeneratorRuntime.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
_context7.prev = 0;
ast = compile(projectConfig.getSchema(), concatAST(Array.from(documents.values())));
_context7.next = 8;
break;
case 4:
_context7.prev = 4;
_context7.t0 = _context7["catch"](0);
this.emit('error', _context7.t0);
return _context7.abrupt("return");
case 8:
_context7.prev = 8;
_context7.next = 11;
return Promise.all(Array.from(groupOperationsAndFragmentsByFile(ast).values()).map(function (file) {
return _this8.writeDocumentFile(file, ast, projectConfig);
}));
case 11:
_context7.next = 15;
break;
case 13:
_context7.prev = 13;
_context7.t1 = _context7["catch"](8);
case 15:
case "end":
return _context7.stop();
}
}
}, _callee7, this, [[0, 4], [8, 13]]);
}));
function generateDocumentTypesForProject(_x6, _x7) {
return _generateDocumentTypesForProject.apply(this, arguments);
}
return generateDocumentTypesForProject;
}()
}, {
key: "writeDocumentFile",
value: function () {
var _writeDocumentFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(file, ast, projectConfig) {
var definitionPath;
return _regeneratorRuntime.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
definitionPath = "".concat(file.path, ".d.ts");
_context8.next = 3;
return writeFile(definitionPath, this.getDocumentDefinition(file, ast, projectConfig));
case 3:
this.emit('build:docs', {
documentPath: file.path,
definitionPath: definitionPath,
operation: file.operation,
fragments: file.fragments
});
case 4:
case "end":
return _context8.stop();
}
}
}, _callee8, this);
}));
function writeDocumentFile(_x8, _x9, _x10) {
return _writeDocumentFile.apply(this, arguments);
}
return writeDocumentFile;
}()
}, {
key: "getDocumentDefinition",
value: function getDocumentDefinition(file, ast, projectConfig) {
try {
return printDocument(file, ast, {
enumFormat: this.options.enumFormat,
exportFormat: this.options.exportFormat,
addTypename: this.options.addTypename,
schemaTypesPath: getSchemaTypesPath(projectConfig, this.options)
});
} catch (_ref15) {
var message = _ref15.message;
var _error = new Error("Error in ".concat(file.path, ": ").concat(message[0].toLowerCase()).concat(message.slice(1)));
this.emit('error', _error);
throw _error;
}
}
}, {
key: "updateDocumentsForProject",
value: function () {
var _updateDocumentsForProject = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(projectConfig) {
var _this9 = this;
var filePaths;
return _regeneratorRuntime.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
_context9.next = 2;
return getGraphQLProjectIncludedFilePaths(projectConfig);
case 2:
filePaths = _context9.sent;
return _context9.abrupt("return", Promise.all(filePaths.map(function (filePath) {
return _this9.updateDocumentForFile(filePath, projectConfig);
})));
case 4:
case "end":
return _context9.stop();
}
}
}, _callee9);
}));
function updateDocumentsForProject(_x11) {
return _updateDocumentsForProject.apply(this, arguments);
}
return updateDocumentsForProject;
}()
}, {
key: "updateDocumentForFile",
value: function () {
var _updateDocumentForFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10(filePath, projectConfig) {
var contents;
return _regeneratorRuntime.wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
_context10.next = 2;
return readFile(filePath, 'utf8');
case 2:
contents = _context10.sent;
return _context10.abrupt("return", this.setDocumentForFilePath(filePath, projectConfig, contents));
case 4:
case "end":
return _context10.stop();
}
}
}, _callee10, this);
}));
function updateDocumentForFile(_x12, _x13) {
return _updateDocumentForFile.apply(this, arguments);
}
return updateDocumentForFile;
}()
}, {
key: "setDocumentForFilePath",
value: function setDocumentForFilePath(filePath, projectConfig, contents) {
var documents = this.documentMapByProject.get(projectConfig.projectName);
if (!documents) {
documents = new Map();
this.documentMapByProject.set(projectConfig.projectName, documents);
}
if (contents.trim().length === 0) {
return undefined;
}
var document = parse(new Source(contents, filePath));
documents.set(filePath, document);
return document;
}
}]);
return Builder;
}(EventEmitter);
function getSchemaTypesPath(projectConfig, options) {
if (typeof projectConfig.extensions.schemaTypesPath === 'string') {
return resolvePathRelativeToConfig(projectConfig, projectConfig.extensions.schemaTypesPath);
}
return resolvePathRelativeToConfig(projectConfig, join(options.schemaTypesPath, "".concat(projectConfig.projectName ? "".concat(projectConfig.projectName, "-") : '', "types")));
}
function groupOperationsAndFragmentsByFile(_ref16) {
var operations = _ref16.operations,
fragments = _ref16.fragments;
return Object.values(operations).concat(Object.values(fragments)).reduce(function (map, item) {
if (!item.filePath) {
return map;
}
var file = map.get(item.filePath);
if (!file) {
file = {
path: item.filePath,
operation: undefined,
fragments: []
};
map.set(item.filePath, file);
}
if (isOperation(item)) {
file.operation = item;
} else {
file.fragments.push(item);
}
return map;
}, new Map());
}
function getDuplicateOperations(documentsMapByProject) {
return Array.from(documentsMapByProject.entries()).map(function (_ref17) {
var _ref18 = _slicedToArray(_ref17, 2),
projectName = _ref18[0],
documents = _ref18[1];
return {
projectName: projectName,
duplicates: getDuplicateProjectOperations(documents)
};
});
}
function getDuplicateFragments(documentsMapByProject) {
return Array.from(documentsMapByProject.entries()).map(function (_ref19) {
var _ref20 = _slicedToArray(_ref19, 2),
projectName = _ref20[0],
documents = _ref20[1];
return {
projectName: projectName,
duplicates: getDuplicateProjectFragments(documents)
};
});
}
function getDuplicateProjectOperations(documents) {
var operations = new Map();
Array.from(documents.entries()).forEach(function (_ref21) {
var _ref22 = _slicedToArray(_ref21, 2),
filePath = _ref22[0],
document = _ref22[1];
document.definitions.filter(isOperationDefinition).forEach(function (definition) {
var name = definition.name;
if (name && name.value) {
var map = operations.get(name.value);
if (map) {
map.add(filePath);
} else {
operations.set(name.value, new Set([filePath]));
}
}
});
});
return Array.from(operations.entries()).filter(function (_ref23) {
var _ref24 = _slicedToArray(_ref23, 2),
filePaths = _ref24[1];
return filePaths.size > 1;
}).map(function (_ref25) {
var _ref26 = _slicedToArray(_ref25, 2),
operationName = _ref26[0],
filePath = _ref26[1];
return {
operationName: operationName,
filePaths: Array.from(filePath)
};
});
}
function getDuplicateProjectFragments(documents) {
var fragments = new Map();
Array.from(documents.entries()).forEach(function (_ref27) {
var _ref28 = _slicedToArray(_ref27, 2),
filePath = _ref28[0],
document = _ref28[1];
document.definitions.filter(isFragmentDefinition).forEach(function (definition) {
var name = definition.name;
if (name && name.value) {
var map = fragments.get(name.value);
if (map) {
map.add(filePath);
} else {
fragments.set(name.value, new Set([filePath]));
}
}
});
});
return Array.from(fragments.entries()).filter(function (_ref29) {
var _ref30 = _slicedToArray(_ref29, 2),
filePaths = _ref30[1];
return filePaths.size > 1;
}).map(function (_ref31) {
var _ref32 = _slicedToArray(_ref31, 2),
fragmentName = _ref32[0],
filePath = _ref32[1];
return {
fragmentName: fragmentName,
filePaths: Array.from(filePath)
};
});
}
function isOperationDefinition(definition) {
return definition.kind === 'OperationDefinition';
}
function isFragmentDefinition(definition) {
return definition.kind === 'FragmentDefinition';
}