-
Notifications
You must be signed in to change notification settings - Fork 6
/
utils.js
180 lines (158 loc) · 5.84 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
const _ = require('lodash')
const pugLexer = require('pug-lexer')
const pugParser = require('pug-parser')
const pugWalk = require('pug-walk')
// https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types
const JS_MIME = [
'application/javascript',
'application/ecmascript',
'text/ecmascript',
'text/javascript',
]
const context = {}
class LineCol {
constructor (str) {
this.parseString(str)
}
parseString (str) {
str = _.toString(str)
this.len = str.length
this.indices = []
const re = /\r?\n|\r/g
while (re.test(str)) this.indices.push(re.lastIndex)
this.indices.push(str.length + 1)
}
toPoint (offset) {
if (offset < 0) return { line: 1, column: 1, offset: 0 }
if (offset >= this.len) offset = this.len
const found = _.findIndex(this.indices, v => v > offset)
return { line: found + 1, column: offset - _.get(this, ['indices', found - 1], 0) + 1, offset }
}
toOffset (point) {
const [line, column] = _.map(['line', 'column'], k => _.toSafeInteger(_.get(point, k, 0)))
if (line < 1) return 0
if (line > this.indices.length) return this.len
return _.get(this, ['indices', line - 2], 0) + column - 1
}
}
exports.LineCol = LineCol
exports.isJsNode = node => {
if (node.type !== 'Tag' || node.name !== 'script') return false // not a script tag
if (!node.block.nodes.length) return false // nodes empty
let scriptType = 'text/javascript'
_.each(node.attrs, attr => {
if (attr.name === 'type' && _.isString(attr.val)) scriptType = _.trim(attr.val, '\'" ')
})
return _.includes(JS_MIME, _.toLower(scriptType))
}
exports.originalPoint = (column, orig, indentEnd = true) => {
return [
_.get(orig, 0), // line
(indentEnd || column > 1) ? column + _.get(orig, 1) : column, // column
]
}
exports.parsePug = str => {
return pugParser(pugLexer(str))
}
exports.nodesToOrigsAndText = (ctx, nodes) => {
const origs = []
const lines = []
let lastLine = null
_.each(nodes, (node, i) => {
if (node.val === '\n' || node.line === lastLine) return
lastLine = node.line
origs.push([node.line, node.column - 1])
const indexStart = ctx.linecol.toOffset(node)
const indexEnd = ctx.linecol.toOffset({ line: node.line + 1, column: 1 })
lines.push(ctx.src.substring(indexStart, indexEnd))
})
lines[lines.length - 1] = _.trimEnd(lines[lines.length - 1], '\r\n')
return {
origs,
text: lines.join('')
}
}
exports.preprocess = (src, filename) => {
const ast = exports.parsePug(src)
const ctx = context[filename] = { src, filename, linecol: new LineCol(src), blocks: [] }
pugWalk(ast, jsnode => {
if (!exports.isJsNode(jsnode)) return
// console.log(`jsnode = ${JSON.stringify(jsnode)}`)
const ctxBlocksPush = nodes => {
if (!nodes.length) return
const { origs, text } = exports.nodesToOrigsAndText(ctx, nodes)
// console.log(`ctxBlocksPush = ${JSON.stringify({ nodes, origs, src, text })}`)
ctx.blocks.push({
column: jsnode.column,
filename: '0.js',
fixMultiline: jsnode.line !== _.first(origs)[0],
line: jsnode.line,
origs,
text,
linecol: new LineCol(text),
})
}
let textNodes = []
for (const node of jsnode.block.nodes) {
if (!_.includes(['Text', 'Code'], node.type)) {
ctxBlocksPush(textNodes)
textNodes = []
continue
}
textNodes.push(node)
}
ctxBlocksPush(textNodes)
return false
})
// console.log(`preprocess = ${JSON.stringify(ctx.blocks)}`)
return ctx.blocks
}
exports.addIndentAfterLf = (text, indent) => {
return text.replace(/\r?\n|\r/g, eol => `${eol}${indent}`)
}
exports.transformFix = ({ msg, block, ctx }) => {
const fix = _.cloneDeep(_.get(msg, 'fix'))
if (!fix) return
// because inline script (like `#[script console.log('test')]`) is very difficult to autofix with multiline, so skip
if (!block.fixMultiline && _.find(_.get(fix, 'text'), '\n')) return
// transform range: block offset -> block point -> original point -> original offset
msg.orig = { range: fix.range, line: msg.line, column: msg.column, endLine: msg.endLine, endColumn: msg.endColumn }
const start = block.linecol.toPoint(fix.range[0])
const origStart = block.origs[start.line - 1]
;[start.line, start.column] = exports.originalPoint(start.column, origStart)
const end = block.linecol.toPoint(fix.range[1])
const origEnd = block.origs[end.line - 1] || [_.get(block, 'origs.0.0') + end.line - 1, 0]
;[end.line, end.column] = exports.originalPoint(end.column, origEnd)
fix.range = [
ctx.linecol.toOffset(start),
ctx.linecol.toOffset(end),
]
// add indent to multiline fix.text
const head = ctx.linecol.toOffset({ line: origStart[0], column: origStart[1] + 1 })
const indent = ctx.src.substring(head - origStart[1], head)
// fix lines start with pipeline
fix.text = fix.text.replace(/\r?\n|\r/g, eol => `${eol}${fix.text.substring(fix.range[0] - origStart[1], fix.range[0])}`)
fix.text = exports.addIndentAfterLf(fix.text, indent)
return fix
}
exports.postprocess = (messages, filename) => {
// console.log(`postprocess = ${JSON.stringify({ messages, ctx })}`)
const newMessages = []
const ctx = context[filename]
_.each(messages, (blockMsg, blockIdx) => {
const block = ctx.blocks[blockIdx]
_.each(blockMsg, msg => {
// line and column origin
;[msg.line, msg.column] = exports.originalPoint(msg.column, block.origs[msg.line - 1])
if (msg.endLine && msg.endColumn) {
const origMsgEnd = block.origs[msg.endLine - 1] || [_.get(block, 'origs.0.0') + msg.endLine - 1, 0]
;[msg.endLine, msg.endColumn] = exports.originalPoint(msg.endColumn, origMsgEnd, false)
}
msg.fix = exports.transformFix({ msg, block, ctx })
if (_.isNil(msg.fix)) delete msg.fix
newMessages.push(msg)
})
})
delete context[filename]
return newMessages
}