index.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var picocolors = require('picocolors');
  4. var jsTokens = require('js-tokens');
  5. var helperValidatorIdentifier = require('@babel/helper-validator-identifier');
  6. function isColorSupported() {
  7. return (typeof process === "object" && (process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") ? false : picocolors.isColorSupported
  8. );
  9. }
  10. const compose = (f, g) => v => f(g(v));
  11. function buildDefs(colors) {
  12. return {
  13. keyword: colors.cyan,
  14. capitalized: colors.yellow,
  15. jsxIdentifier: colors.yellow,
  16. punctuator: colors.yellow,
  17. number: colors.magenta,
  18. string: colors.green,
  19. regex: colors.magenta,
  20. comment: colors.gray,
  21. invalid: compose(compose(colors.white, colors.bgRed), colors.bold),
  22. gutter: colors.gray,
  23. marker: compose(colors.red, colors.bold),
  24. message: compose(colors.red, colors.bold),
  25. reset: colors.reset
  26. };
  27. }
  28. const defsOn = buildDefs(picocolors.createColors(true));
  29. const defsOff = buildDefs(picocolors.createColors(false));
  30. function getDefs(enabled) {
  31. return enabled ? defsOn : defsOff;
  32. }
  33. const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]);
  34. const NEWLINE$1 = /\r\n|[\n\r\u2028\u2029]/;
  35. const BRACKET = /^[()[\]{}]$/;
  36. let tokenize;
  37. {
  38. const JSX_TAG = /^[a-z][\w-]*$/i;
  39. const getTokenType = function (token, offset, text) {
  40. if (token.type === "name") {
  41. if (helperValidatorIdentifier.isKeyword(token.value) || helperValidatorIdentifier.isStrictReservedWord(token.value, true) || sometimesKeywords.has(token.value)) {
  42. return "keyword";
  43. }
  44. if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) === "</")) {
  45. return "jsxIdentifier";
  46. }
  47. if (token.value[0] !== token.value[0].toLowerCase()) {
  48. return "capitalized";
  49. }
  50. }
  51. if (token.type === "punctuator" && BRACKET.test(token.value)) {
  52. return "bracket";
  53. }
  54. if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
  55. return "punctuator";
  56. }
  57. return token.type;
  58. };
  59. tokenize = function* (text) {
  60. let match;
  61. while (match = jsTokens.default.exec(text)) {
  62. const token = jsTokens.matchToToken(match);
  63. yield {
  64. type: getTokenType(token, match.index, text),
  65. value: token.value
  66. };
  67. }
  68. };
  69. }
  70. function highlight(text) {
  71. if (text === "") return "";
  72. const defs = getDefs(true);
  73. let highlighted = "";
  74. for (const {
  75. type,
  76. value
  77. } of tokenize(text)) {
  78. if (type in defs) {
  79. highlighted += value.split(NEWLINE$1).map(str => defs[type](str)).join("\n");
  80. } else {
  81. highlighted += value;
  82. }
  83. }
  84. return highlighted;
  85. }
  86. let deprecationWarningShown = false;
  87. const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
  88. function getMarkerLines(loc, source, opts) {
  89. const startLoc = Object.assign({
  90. column: 0,
  91. line: -1
  92. }, loc.start);
  93. const endLoc = Object.assign({}, startLoc, loc.end);
  94. const {
  95. linesAbove = 2,
  96. linesBelow = 3
  97. } = opts || {};
  98. const startLine = startLoc.line;
  99. const startColumn = startLoc.column;
  100. const endLine = endLoc.line;
  101. const endColumn = endLoc.column;
  102. let start = Math.max(startLine - (linesAbove + 1), 0);
  103. let end = Math.min(source.length, endLine + linesBelow);
  104. if (startLine === -1) {
  105. start = 0;
  106. }
  107. if (endLine === -1) {
  108. end = source.length;
  109. }
  110. const lineDiff = endLine - startLine;
  111. const markerLines = {};
  112. if (lineDiff) {
  113. for (let i = 0; i <= lineDiff; i++) {
  114. const lineNumber = i + startLine;
  115. if (!startColumn) {
  116. markerLines[lineNumber] = true;
  117. } else if (i === 0) {
  118. const sourceLength = source[lineNumber - 1].length;
  119. markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
  120. } else if (i === lineDiff) {
  121. markerLines[lineNumber] = [0, endColumn];
  122. } else {
  123. const sourceLength = source[lineNumber - i].length;
  124. markerLines[lineNumber] = [0, sourceLength];
  125. }
  126. }
  127. } else {
  128. if (startColumn === endColumn) {
  129. if (startColumn) {
  130. markerLines[startLine] = [startColumn, 0];
  131. } else {
  132. markerLines[startLine] = true;
  133. }
  134. } else {
  135. markerLines[startLine] = [startColumn, endColumn - startColumn];
  136. }
  137. }
  138. return {
  139. start,
  140. end,
  141. markerLines
  142. };
  143. }
  144. function codeFrameColumns(rawLines, loc, opts = {}) {
  145. const shouldHighlight = opts.forceColor || isColorSupported() && opts.highlightCode;
  146. const defs = getDefs(shouldHighlight);
  147. const lines = rawLines.split(NEWLINE);
  148. const {
  149. start,
  150. end,
  151. markerLines
  152. } = getMarkerLines(loc, lines, opts);
  153. const hasColumns = loc.start && typeof loc.start.column === "number";
  154. const numberMaxWidth = String(end).length;
  155. const highlightedLines = shouldHighlight ? highlight(rawLines) : rawLines;
  156. let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => {
  157. const number = start + 1 + index;
  158. const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
  159. const gutter = ` ${paddedNumber} |`;
  160. const hasMarker = markerLines[number];
  161. const lastMarkerLine = !markerLines[number + 1];
  162. if (hasMarker) {
  163. let markerLine = "";
  164. if (Array.isArray(hasMarker)) {
  165. const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
  166. const numberOfMarkers = hasMarker[1] || 1;
  167. markerLine = ["\n ", defs.gutter(gutter.replace(/\d/g, " ")), " ", markerSpacing, defs.marker("^").repeat(numberOfMarkers)].join("");
  168. if (lastMarkerLine && opts.message) {
  169. markerLine += " " + defs.message(opts.message);
  170. }
  171. }
  172. return [defs.marker(">"), defs.gutter(gutter), line.length > 0 ? ` ${line}` : "", markerLine].join("");
  173. } else {
  174. return ` ${defs.gutter(gutter)}${line.length > 0 ? ` ${line}` : ""}`;
  175. }
  176. }).join("\n");
  177. if (opts.message && !hasColumns) {
  178. frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
  179. }
  180. if (shouldHighlight) {
  181. return defs.reset(frame);
  182. } else {
  183. return frame;
  184. }
  185. }
  186. function index (rawLines, lineNumber, colNumber, opts = {}) {
  187. if (!deprecationWarningShown) {
  188. deprecationWarningShown = true;
  189. const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
  190. if (process.emitWarning) {
  191. process.emitWarning(message, "DeprecationWarning");
  192. } else {
  193. const deprecationError = new Error(message);
  194. deprecationError.name = "DeprecationWarning";
  195. console.warn(new Error(message));
  196. }
  197. }
  198. colNumber = Math.max(colNumber, 0);
  199. const location = {
  200. start: {
  201. column: colNumber,
  202. line: lineNumber
  203. }
  204. };
  205. return codeFrameColumns(rawLines, location, opts);
  206. }
  207. exports.codeFrameColumns = codeFrameColumns;
  208. exports.default = index;
  209. exports.highlight = highlight;
  210. //# sourceMappingURL=index.js.map