1 | 'use strict'
|
2 |
|
3 | let { red, bold, gray, options: colorette } = require('colorette')
|
4 |
|
5 | let terminalHighlight = require('./terminal-highlight')
|
6 |
|
7 | class CssSyntaxError extends Error {
|
8 | constructor (message, line, column, source, file, plugin) {
|
9 | super(message)
|
10 | this.name = 'CssSyntaxError'
|
11 | this.reason = message
|
12 |
|
13 | if (file) {
|
14 | this.file = file
|
15 | }
|
16 | if (source) {
|
17 | this.source = source
|
18 | }
|
19 | if (plugin) {
|
20 | this.plugin = plugin
|
21 | }
|
22 | if (typeof line !== 'undefined' && typeof column !== 'undefined') {
|
23 | this.line = line
|
24 | this.column = column
|
25 | }
|
26 |
|
27 | this.setMessage()
|
28 |
|
29 | if (Error.captureStackTrace) {
|
30 | Error.captureStackTrace(this, CssSyntaxError)
|
31 | }
|
32 | }
|
33 |
|
34 | setMessage () {
|
35 | this.message = this.plugin ? this.plugin + ': ' : ''
|
36 | this.message += this.file ? this.file : '<css input>'
|
37 | if (typeof this.line !== 'undefined') {
|
38 | this.message += ':' + this.line + ':' + this.column
|
39 | }
|
40 | this.message += ': ' + this.reason
|
41 | }
|
42 |
|
43 | showSourceCode (color) {
|
44 | if (!this.source) return ''
|
45 |
|
46 | let css = this.source
|
47 | if (color == null) color = colorette.enabled
|
48 | if (terminalHighlight) {
|
49 | if (color) css = terminalHighlight(css)
|
50 | }
|
51 |
|
52 | let lines = css.split(/\r?\n/)
|
53 | let start = Math.max(this.line - 3, 0)
|
54 | let end = Math.min(this.line + 2, lines.length)
|
55 |
|
56 | let maxWidth = String(end).length
|
57 |
|
58 | let mark, aside
|
59 | if (color) {
|
60 | mark = text => bold(red(text))
|
61 | aside = text => gray(text)
|
62 | } else {
|
63 | mark = aside = str => str
|
64 | }
|
65 |
|
66 | return lines
|
67 | .slice(start, end)
|
68 | .map((line, index) => {
|
69 | let number = start + 1 + index
|
70 | let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | '
|
71 | if (number === this.line) {
|
72 | let spacing =
|
73 | aside(gutter.replace(/\d/g, ' ')) +
|
74 | line.slice(0, this.column - 1).replace(/[^\t]/g, ' ')
|
75 | return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^')
|
76 | }
|
77 | return ' ' + aside(gutter) + line
|
78 | })
|
79 | .join('\n')
|
80 | }
|
81 |
|
82 | toString () {
|
83 | let code = this.showSourceCode()
|
84 | if (code) {
|
85 | code = '\n\n' + code + '\n'
|
86 | }
|
87 | return this.name + ': ' + this.message + code
|
88 | }
|
89 | }
|
90 |
|
91 | module.exports = CssSyntaxError
|
92 | CssSyntaxError.default = CssSyntaxError
|