/
index.js
337 lines (281 loc) · 8.42 KB
/
index.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
'use strict'
var Parser = require('parse5/lib/parser')
var pos = require('unist-util-position')
var visit = require('unist-util-visit')
var fromParse5 = require('hast-util-from-parse5')
var toParse5 = require('hast-util-to-parse5')
var voids = require('html-void-elements')
var ns = require('web-namespaces')
var zwitch = require('zwitch')
var xtend = require('xtend')
module.exports = wrap
var inTemplateMode = 'IN_TEMPLATE_MODE'
var dataState = 'DATA_STATE'
var characterToken = 'CHARACTER_TOKEN'
var startTagToken = 'START_TAG_TOKEN'
var endTagToken = 'END_TAG_TOKEN'
var commentToken = 'COMMENT_TOKEN'
var doctypeToken = 'DOCTYPE_TOKEN'
var parseOptions = {sourceCodeLocationInfo: true, scriptingEnabled: false}
function wrap(tree, file, options) {
var parser = new Parser(parseOptions)
var one = zwitch('type', {
handlers: {
root: root,
element: element,
text: text,
comment: comment,
doctype: doctype,
raw: raw
},
unknown: unknown
})
var stitches
var tokenizer
var preprocessor
var posTracker
var locationTracker
var result
var index
if (file && !('contents' in file)) {
options = file
file = undefined
}
if (options && options.passThrough) {
index = -1
while (++index < options.passThrough.length) {
one.handlers[options.passThrough[index]] = stitch
}
}
result = fromParse5(documentMode(tree) ? document() : fragment(), file)
if (stitches) {
visit(result, 'comment', mend)
}
// Unpack if possible and when not given a `root`.
if (tree.type !== 'root' && result.children.length === 1) {
return result.children[0]
}
return result
function mend(node, index, parent) {
if (node.value.stitch) {
parent.children[index] = node.value.stitch
return index
}
}
function fragment() {
var context = {
nodeName: 'template',
tagName: 'template',
attrs: [],
namespaceURI: ns.html,
childNodes: []
}
var mock = {
nodeName: 'documentmock',
tagName: 'documentmock',
attrs: [],
namespaceURI: ns.html,
childNodes: []
}
var doc = {nodeName: '#document-fragment', childNodes: []}
parser._bootstrap(mock, context)
parser._pushTmplInsertionMode(inTemplateMode)
parser._initTokenizerForFragmentParsing()
parser._insertFakeRootElement()
parser._resetInsertionMode()
parser._findFormInFragmentContext()
tokenizer = parser.tokenizer
preprocessor = tokenizer.preprocessor
locationTracker = tokenizer.__mixins[0]
posTracker = locationTracker.posTracker
one(tree)
parser._adoptNodes(mock.childNodes[0], doc)
return doc
}
function document() {
var doc = parser.treeAdapter.createDocument()
parser._bootstrap(doc, null)
tokenizer = parser.tokenizer
preprocessor = tokenizer.preprocessor
locationTracker = tokenizer.__mixins[0]
posTracker = locationTracker.posTracker
one(tree)
return doc
}
function all(nodes) {
var index = -1
/* istanbul ignore else - invalid nodes, see rehypejs/rehype-raw#7. */
if (nodes) {
while (++index < nodes.length) {
one(nodes[index])
}
}
}
function root(node) {
all(node.children)
}
function element(node) {
resetTokenizer()
parser._processToken(startTag(node), ns.html)
all(node.children)
if (voids.indexOf(node.tagName) < 0) {
resetTokenizer()
parser._processToken(endTag(node))
}
}
function text(node) {
resetTokenizer()
parser._processToken({
type: characterToken,
chars: node.value,
location: createParse5Location(node)
})
}
function doctype(node) {
var p5 = toParse5(node)
resetTokenizer()
parser._processToken({
type: doctypeToken,
name: p5.name,
forceQuirks: false,
publicId: p5.publicId,
systemId: p5.systemId,
location: createParse5Location(node)
})
}
function comment(node) {
resetTokenizer()
parser._processToken({
type: commentToken,
data: node.value,
location: createParse5Location(node)
})
}
function raw(node) {
var start = pos.start(node)
var line = start.line || 1
var column = start.column || 1
var offset = start.offset || 0
var token
// Reset preprocessor:
// See: <https://github.com/inikulin/parse5/blob/9c683e1/packages/parse5/lib/tokenizer/preprocessor.js>.
preprocessor.html = null
preprocessor.pos = -1
preprocessor.lastGapPos = -1
preprocessor.lastCharPos = -1
preprocessor.gapStack = []
preprocessor.skipNextNewLine = false
preprocessor.lastChunkWritten = false
preprocessor.endOfChunkHit = false
// Reset preprocessor mixin:
// See: <https://github.com/inikulin/parse5/blob/9c683e1/packages/parse5/lib/extensions/position-tracking/preprocessor-mixin.js>.
posTracker.isEol = false
posTracker.lineStartPos = -column + 1 // Looks weird, but ensures we get correct positional info.
posTracker.droppedBufferSize = offset
posTracker.offset = 0
posTracker.col = 1
posTracker.line = line
// Reset location tracker:
// See: <https://github.com/inikulin/parse5/blob/9c683e1/packages/parse5/lib/extensions/location-info/tokenizer-mixin.js>.
locationTracker.currentAttrLocation = null
locationTracker.ctLoc = createParse5Location(node)
// See the code for `parse` and `parseFragment`:
// See: <https://github.com/inikulin/parse5/blob/9c683e1/packages/parse5/lib/parser/index.js#L371>.
tokenizer.write(node.value)
parser._runParsingLoop(null)
// Process final characters if they’re still there after hibernating.
// Similar to:
// See: <https://github.com/inikulin/parse5/blob/9c683e1/packages/parse5/lib/extensions/location-info/tokenizer-mixin.js#L95>.
token = tokenizer.currentCharacterToken
if (token) {
token.location.endLine = posTracker.line
token.location.endCol = posTracker.col + 1
token.location.endOffset = posTracker.offset + 1
parser._processToken(token)
}
}
function stitch(node) {
var clone = Object.assign({}, node)
stitches = true
// Recurse, because to somewhat handle `[<x>]</x>` (where `[]` denotes the
// passed through node).
if (node.children) {
clone.children = wrap(
{type: 'root', children: node.children},
file,
options
).children
}
// Hack: `value` is supposed to be a string, but as none of the tools
// (`parse5` or `hast-util-from-parse5`) looks at it, we can pass nodes
// through.
comment({value: {stitch: clone}})
}
function resetTokenizer() {
// Reset tokenizer:
// See: <https://github.com/inikulin/parse5/blob/9c683e1/packages/parse5/lib/tokenizer/index.js#L218-L234>.
// Especially putting it back in the `data` state is useful: some elements,
// like textareas and iframes, change the state.
// See GH-7.
// But also if broken HTML is in `raw`, and then a correct element is given.
// See GH-11.
tokenizer.tokenQueue = []
tokenizer.state = dataState
tokenizer.returnState = ''
tokenizer.charRefCode = -1
tokenizer.tempBuff = []
tokenizer.lastStartTagName = ''
tokenizer.consumedAfterSnapshot = -1
tokenizer.active = false
tokenizer.currentCharacterToken = null
tokenizer.currentToken = null
tokenizer.currentAttr = null
}
}
function startTag(node) {
var location = createParse5Location(node)
location.startTag = xtend(location)
return {
type: startTagToken,
tagName: node.tagName,
selfClosing: false,
attrs: attributes(node),
location: location
}
}
function attributes(node) {
return toParse5({
tagName: node.tagName,
type: 'element',
properties: node.properties
}).attrs
}
function endTag(node) {
var location = createParse5Location(node)
location.endTag = xtend(location)
return {
type: endTagToken,
tagName: node.tagName,
attrs: [],
location: location
}
}
function unknown(node) {
throw new Error('Cannot compile `' + node.type + '` node')
}
function documentMode(node) {
var head = node.type === 'root' ? node.children[0] : node
return head && (head.type === 'doctype' || head.tagName === 'html')
}
function createParse5Location(node) {
var start = pos.start(node)
var end = pos.end(node)
return {
startLine: start.line,
startCol: start.column,
startOffset: start.offset,
endLine: end.line,
endCol: end.column,
endOffset: end.offset
}
}