printLocation.mjs 2.2 KB

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