parse-graphql-sdl.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.isDescribable = exports.transformCommentsToDescriptions = exports.parseGraphQLSDL = void 0;
  4. const graphql_1 = require("graphql");
  5. const comments_js_1 = require("./comments.js");
  6. function parseGraphQLSDL(location, rawSDL, options = {}) {
  7. let document;
  8. try {
  9. if (options.commentDescriptions && rawSDL.includes('#')) {
  10. document = transformCommentsToDescriptions(rawSDL, options);
  11. // If noLocation=true, we need to make sure to print and parse it again, to remove locations,
  12. // since `transformCommentsToDescriptions` must have locations set in order to transform the comments
  13. // into descriptions.
  14. if (options.noLocation) {
  15. document = (0, graphql_1.parse)((0, graphql_1.print)(document), options);
  16. }
  17. }
  18. else {
  19. document = (0, graphql_1.parse)(new graphql_1.Source(rawSDL, location), options);
  20. }
  21. }
  22. catch (e) {
  23. if (e.message.includes('EOF') && rawSDL.replace(/(\#[^*]*)/g, '').trim() === '') {
  24. document = {
  25. kind: graphql_1.Kind.DOCUMENT,
  26. definitions: [],
  27. };
  28. }
  29. else {
  30. throw e;
  31. }
  32. }
  33. return {
  34. location,
  35. document,
  36. };
  37. }
  38. exports.parseGraphQLSDL = parseGraphQLSDL;
  39. function transformCommentsToDescriptions(sourceSdl, options = {}) {
  40. const parsedDoc = (0, graphql_1.parse)(sourceSdl, {
  41. ...options,
  42. noLocation: false,
  43. });
  44. const modifiedDoc = (0, graphql_1.visit)(parsedDoc, {
  45. leave: (node) => {
  46. if (isDescribable(node)) {
  47. const rawValue = (0, comments_js_1.getLeadingCommentBlock)(node);
  48. if (rawValue !== undefined) {
  49. const commentsBlock = (0, comments_js_1.dedentBlockStringValue)('\n' + rawValue);
  50. const isBlock = commentsBlock.includes('\n');
  51. if (!node.description) {
  52. return {
  53. ...node,
  54. description: {
  55. kind: graphql_1.Kind.STRING,
  56. value: commentsBlock,
  57. block: isBlock,
  58. },
  59. };
  60. }
  61. else {
  62. return {
  63. ...node,
  64. description: {
  65. ...node.description,
  66. value: node.description.value + '\n' + commentsBlock,
  67. block: true,
  68. },
  69. };
  70. }
  71. }
  72. }
  73. },
  74. });
  75. return modifiedDoc;
  76. }
  77. exports.transformCommentsToDescriptions = transformCommentsToDescriptions;
  78. function isDescribable(node) {
  79. return ((0, graphql_1.isTypeSystemDefinitionNode)(node) ||
  80. node.kind === graphql_1.Kind.FIELD_DEFINITION ||
  81. node.kind === graphql_1.Kind.INPUT_VALUE_DEFINITION ||
  82. node.kind === graphql_1.Kind.ENUM_VALUE_DEFINITION);
  83. }
  84. exports.isDescribable = isDescribable;