UNPKG

2.82 kBJavaScriptView Raw
1"use strict";
2
3exports.UNDEFINED = -1;
4
5/**
6 * Format the message to be white on red and surrounded by a line.
7 */
8exports.format = function(msg, padding) {
9 if (typeof padding === 'undefined') padding = 1;
10
11 var lines = msg.split('\n');
12 var lineWidth = 0;
13 lines.forEach(function(line) {
14 line = line.trimRight();
15 lineWidth = Math.max(lineWidth, line.length);
16 });
17
18 var ruler = ("+" + fill('-', 2 * padding + lineWidth) + "+").bgRed.white;
19 var result = [ruler];
20 lines.forEach(function(line) {
21 var out = '|' + fill(' ', padding);
22 out += line + fill(' ', padding + lineWidth - line.length) + '|';
23 result.push(out.bgRed.white);
24 });
25 result.push(ruler);
26
27 return result.join('\n');
28};
29
30
31/**
32 * Create a string by repeating `occurences` times the string `char`.
33 */
34function fill(char, occurences) {
35 var out = '';
36 while (occurences-- > 0) {
37 out += char;
38 }
39 return out;
40};
41
42exports.fire = function(msg, id, src) {
43 msg = "" + msg;
44 var ex = Error(msg);
45 ex.fatal = msg;
46 ex.id = id;
47 ex.src = [src];
48 throw ex;
49};
50
51exports.bubble = function(ex, src) {
52 if (typeof src !== 'undefined') {
53 if (!ex.src) {
54 ex.src = [];
55 }
56 ex.src.push(src);
57 }
58 throw ex;
59};
60
61exports.extractCodeAtPos = function(code, pos) {
62 var lines = [],
63 lastLinePos = 0,
64 index = 0,
65 cursor = 0,
66 indexOf,
67 lineNum,
68 out = '',
69 c,
70 k;
71 while (index < pos) {
72 c = code.charAt(index);
73 if (c == '\n') {
74 lines.push(code.substr(cursor, index - cursor));
75 lastLinePos = cursor;
76 cursor = index + 1;
77 }
78 index++;
79 }
80 indexOf = code.indexOf('\n', index);
81 lastLinePos = cursor;
82 if (indexOf < 0) {
83 lines.push(code.substr(cursor));
84 } else {
85 lines.push(code.substr(cursor, indexOf - cursor));
86 }
87 lineNum = Math.max(0, lines.length - 12);
88
89 function pad(txt) {
90 txt = "" + txt;
91 while (txt.length < 6) txt = ' ' + txt;
92 return txt;
93 }
94 while (lineNum < lines.length) {
95 out += pad(lineNum + 1) + ': ' + preventTooLongLine(lines[lineNum], pos - lastLinePos) + "\n";
96 lineNum++;
97 }
98 // position of the hat cursor ('^').
99 var hatPos = pos - lastLinePos;
100 if (hatPos > 119) hatPos = 34;
101 for (k = 0; k < 10 + hatPos; k++) {
102 out += ' ';
103 }
104 out += '^\n';
105 return out;
106};
107
108
109function preventTooLongLine(line, pos) {
110 if (line.length < 120) return line;
111 pos = Math.max(0, (pos || 0) - 30);
112 var subline = line.substr(pos);
113 if (subline.length > 110) subline = subline.substr(0, 110) + " ...".magenta;
114 return (pos > 0 ? "... ".magenta : '') + subline;
115}
\No newline at end of file