printLocation.mjs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { getLocation } from '../language/location';
  2. /**
  3. * Render a helpful description of the location in the GraphQL Source document.
  4. */
  5. export function printLocation(location) {
  6. return printSourceLocation(location.source, getLocation(location.source, location.start));
  7. }
  8. /**
  9. * Render a helpful description of the location in the GraphQL Source document.
  10. */
  11. export function printSourceLocation(source, sourceLocation) {
  12. var firstLineColumnOffset = source.locationOffset.column - 1;
  13. var body = whitespace(firstLineColumnOffset) + source.body;
  14. var lineIndex = sourceLocation.line - 1;
  15. var lineOffset = source.locationOffset.line - 1;
  16. var lineNum = sourceLocation.line + lineOffset;
  17. var columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;
  18. var columnNum = sourceLocation.column + columnOffset;
  19. var locationStr = "".concat(source.name, ":").concat(lineNum, ":").concat(columnNum, "\n");
  20. var lines = body.split(/\r\n|[\n\r]/g);
  21. var locationLine = lines[lineIndex]; // Special case for minified documents
  22. if (locationLine.length > 120) {
  23. var sublineIndex = Math.floor(columnNum / 80);
  24. var sublineColumnNum = columnNum % 80;
  25. var sublines = [];
  26. for (var i = 0; i < locationLine.length; i += 80) {
  27. sublines.push(locationLine.slice(i, i + 80));
  28. }
  29. return locationStr + printPrefixedLines([["".concat(lineNum), sublines[0]]].concat(sublines.slice(1, sublineIndex + 1).map(function (subline) {
  30. return ['', subline];
  31. }), [[' ', whitespace(sublineColumnNum - 1) + '^'], ['', sublines[sublineIndex + 1]]]));
  32. }
  33. return locationStr + printPrefixedLines([// Lines specified like this: ["prefix", "string"],
  34. ["".concat(lineNum - 1), lines[lineIndex - 1]], ["".concat(lineNum), locationLine], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1), lines[lineIndex + 1]]]);
  35. }
  36. function printPrefixedLines(lines) {
  37. var existingLines = lines.filter(function (_ref) {
  38. var _ = _ref[0],
  39. line = _ref[1];
  40. return line !== undefined;
  41. });
  42. var padLen = Math.max.apply(Math, existingLines.map(function (_ref2) {
  43. var prefix = _ref2[0];
  44. return prefix.length;
  45. }));
  46. return existingLines.map(function (_ref3) {
  47. var prefix = _ref3[0],
  48. line = _ref3[1];
  49. return lpad(padLen, prefix) + (line ? ' | ' + line : ' |');
  50. }).join('\n');
  51. }
  52. function whitespace(len) {
  53. return Array(len + 1).join(' ');
  54. }
  55. function lpad(len, str) {
  56. return whitespace(len - str.length) + str;
  57. }