forked from OKEAMAH/prettier
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser-html.js
More file actions
449 lines (412 loc) · 12.5 KB
/
parser-html.js
File metadata and controls
449 lines (412 loc) · 12.5 KB
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
import {
getHtmlTagDefinition,
parse as parseHtml,
ParseLocation,
ParseSourceFile,
ParseSourceSpan,
RecursiveVisitor,
TagContentType,
visitAll,
} from "angular-html-parser";
import createError from "../common/parser-create-error.js";
import parseFrontMatter from "../utils/front-matter/parse.js";
import inferParser from "../utils/infer-parser.js";
import isNonEmptyArray from "../utils/is-non-empty-array.js";
import { Node } from "./ast.js";
import { parseIeConditionalComment } from "./conditional-comment.js";
import { locEnd, locStart } from "./loc.js";
import { hasPragma } from "./pragma.js";
import HTML_ELEMENT_ATTRIBUTES from "./utils/html-elements-attributes.evaluate.js";
import HTML_TAGS from "./utils/html-tag-names.evaluate.js";
import isUnknownNamespace from "./utils/is-unknown-namespace.js";
/**
* @typedef {import('angular-html-parser')} AngularHtmlParser
* @typedef {import('angular-html-parser/lib/compiler/src/ml_parser/ast.js').Node} AstNode
* @typedef {import('angular-html-parser/lib/compiler/src/ml_parser/ast.js').Attribute} Attribute
* @typedef {import('angular-html-parser/lib/compiler/src/ml_parser/ast.js').Element} Element
* @typedef {import('angular-html-parser/lib/compiler/src/ml_parser/parser.js').ParseTreeResult} ParserTreeResult
* @typedef {import('angular-html-parser').ParseOptions & {
* name: 'html' | 'angular' | 'vue' | 'lwc';
* normalizeTagName?: boolean;
* normalizeAttributeName?: boolean;
* shouldParseAsRawText?: (tagName: string, prefix: string, hasParent: boolean, attrs: Array<{
* prefix: string;
* name: string;
* value?: string;
* }>) => boolean;
* }} ParseOptions
* @typedef {{filepath?: string}} Options
*/
// `@else if`
function normalizeAngularControlFlowBlock(node) {
if (node.type !== "block") {
return;
}
node.name = node.name.toLowerCase().replaceAll(/\s+/gu, " ").trim();
node.type = "angularControlFlowBlock";
if (!isNonEmptyArray(node.parameters)) {
delete node.parameters;
return;
}
for (const parameter of node.parameters) {
parameter.type = "angularControlFlowBlockParameter";
}
node.parameters = {
type: "angularControlFlowBlockParameters",
children: node.parameters,
sourceSpan: new ParseSourceSpan(
node.parameters[0].sourceSpan.start,
node.parameters.at(-1).sourceSpan.end,
),
};
}
function normalizeAngularIcuExpression(node) {
if (node.type === "plural" || node.type === "select") {
node.clause = node.type;
node.type = "angularIcuExpression";
}
if (node.type === "expansionCase") {
node.type = "angularIcuCase";
}
}
/**
* @param {string} input
* @param {ParseOptions} parseOptions
* @param {Options} options
*/
function ngHtmlParser(input, parseOptions, options) {
const {
name,
canSelfClose = true,
normalizeTagName = false,
normalizeAttributeName = false,
allowHtmComponentClosingTags = false,
isTagNameCaseSensitive = false,
shouldParseAsRawText,
} = parseOptions;
let { rootNodes, errors } = parseHtml(input, {
canSelfClose,
allowHtmComponentClosingTags,
isTagNameCaseSensitive,
getTagContentType: shouldParseAsRawText
? (...args) =>
shouldParseAsRawText(...args) ? TagContentType.RAW_TEXT : undefined
: undefined,
tokenizeAngularBlocks: name === "angular" ? true : undefined,
});
if (name === "vue") {
const isHtml = rootNodes.some(
(node) =>
(node.type === "docType" && node.value === "html") ||
(node.type === "element" && node.name.toLowerCase() === "html"),
);
// If not Vue SFC, treat as html
if (isHtml) {
return ngHtmlParser(input, HTML_PARSE_OPTIONS, options);
}
/** @type {ParserTreeResult | undefined} */
let secondParseResult;
const getHtmlParseResult = () =>
(secondParseResult ??= parseHtml(input, {
canSelfClose,
allowHtmComponentClosingTags,
isTagNameCaseSensitive,
}));
const getNodeWithSameLocation = (node) =>
getHtmlParseResult().rootNodes.find(
({ startSourceSpan }) =>
startSourceSpan &&
startSourceSpan.start.offset === node.startSourceSpan.start.offset,
) ?? node;
for (const [index, node] of rootNodes.entries()) {
const { endSourceSpan, startSourceSpan } = node;
const isVoidElement = endSourceSpan === null;
if (isVoidElement) {
errors = getHtmlParseResult().errors;
rootNodes[index] = getNodeWithSameLocation(node);
} else if (shouldParseVueRootNodeAsHtml(node, options)) {
const error = getHtmlParseResult().errors.find(
(error) =>
error.span.start.offset > startSourceSpan.start.offset &&
error.span.start.offset < endSourceSpan.end.offset,
);
if (error) {
throwParseError(error);
}
rootNodes[index] = getNodeWithSameLocation(node);
}
}
}
if (errors.length > 0) {
throwParseError(errors[0]);
}
/**
* @param {Attribute | Element} node
*/
const restoreName = (node) => {
const namespace = node.name.startsWith(":")
? node.name.slice(1).split(":")[0]
: null;
const rawName = node.nameSpan.toString();
const hasExplicitNamespace =
namespace !== null && rawName.startsWith(`${namespace}:`);
const name = hasExplicitNamespace
? rawName.slice(namespace.length + 1)
: rawName;
node.name = name;
node.namespace = namespace;
node.hasExplicitNamespace = hasExplicitNamespace;
};
/**
* @param {AstNode} node
*/
const restoreNameAndValue = (node) => {
switch (node.type) {
case "element":
restoreName(node);
for (const attr of node.attrs) {
restoreName(attr);
if (!attr.valueSpan) {
attr.value = null;
} else {
attr.value = attr.valueSpan.toString();
if (/["']/u.test(attr.value[0])) {
attr.value = attr.value.slice(1, -1);
}
}
}
break;
case "comment":
node.value = node.sourceSpan
.toString()
.slice("<!--".length, -"-->".length);
break;
case "text":
node.value = node.sourceSpan.toString();
break;
// No default
}
};
const lowerCaseIfFn = (text, fn) => {
const lowerCasedText = text.toLowerCase();
return fn(lowerCasedText) ? lowerCasedText : text;
};
const normalizeName = (node) => {
if (node.type === "element") {
if (
normalizeTagName &&
(!node.namespace ||
node.namespace === node.tagDefinition.implicitNamespacePrefix ||
isUnknownNamespace(node))
) {
node.name = lowerCaseIfFn(node.name, (lowerCasedName) =>
HTML_TAGS.has(lowerCasedName),
);
}
if (normalizeAttributeName) {
for (const attr of node.attrs) {
if (!attr.namespace) {
attr.name = lowerCaseIfFn(
attr.name,
(lowerCasedAttrName) =>
HTML_ELEMENT_ATTRIBUTES.has(node.name) &&
(HTML_ELEMENT_ATTRIBUTES.get("*").has(lowerCasedAttrName) ||
HTML_ELEMENT_ATTRIBUTES.get(node.name).has(
lowerCasedAttrName,
)),
);
}
}
}
}
};
const fixSourceSpan = (node) => {
if (node.sourceSpan && node.endSourceSpan) {
node.sourceSpan = new ParseSourceSpan(
node.sourceSpan.start,
node.endSourceSpan.end,
);
}
};
/**
* @param {AstNode} node
*/
const addTagDefinition = (node) => {
if (node.type === "element") {
const tagDefinition = getHtmlTagDefinition(
isTagNameCaseSensitive ? node.name : node.name.toLowerCase(),
);
if (
!node.namespace ||
node.namespace === tagDefinition.implicitNamespacePrefix ||
isUnknownNamespace(node)
) {
node.tagDefinition = tagDefinition;
} else {
node.tagDefinition = getHtmlTagDefinition(""); // the default one
}
}
};
visitAll(
new (class extends RecursiveVisitor {
// Angular does not visit to the children of expansionCase
// https://github.com/angular/angular/blob/e3a6bf9b6c3bef03df9bfc8f05b817bc875cbad6/packages/compiler/src/ml_parser/ast.ts#L161
visitExpansionCase(ast, context) {
if (name === "angular") {
// @ts-expect-error
this.visitChildren(context, (visit) => {
visit(ast.expression);
});
}
}
visit(node) {
restoreNameAndValue(node);
addTagDefinition(node);
normalizeName(node);
fixSourceSpan(node);
}
})(),
rootNodes,
);
return rootNodes;
}
function shouldParseVueRootNodeAsHtml(node, options) {
if (node.type !== "element" || node.name !== "template") {
return false;
}
const language = node.attrs.find((attr) => attr.name === "lang")?.value;
return !language || inferParser(options, { language }) === "html";
}
function throwParseError(error) {
const {
msg,
span: { start, end },
} = error;
throw createError(msg, {
loc: {
start: { line: start.line + 1, column: start.col + 1 },
end: { line: end.line + 1, column: end.col + 1 },
},
cause: error,
});
}
/**
* @param {string} text
* @param {ParseOptions} parseOptions
* @param {Options} options
* @param {boolean} shouldParseFrontMatter
*/
function parse(
text,
parseOptions,
options = {},
shouldParseFrontMatter = true,
) {
const { frontMatter, content } = shouldParseFrontMatter
? parseFrontMatter(text)
: { frontMatter: null, content: text };
const file = new ParseSourceFile(text, options.filepath);
const start = new ParseLocation(file, 0, 0, 0);
const end = start.moveBy(text.length);
const rawAst = {
type: "root",
sourceSpan: new ParseSourceSpan(start, end),
children: ngHtmlParser(content, parseOptions, options),
};
if (frontMatter) {
const start = new ParseLocation(file, 0, 0, 0);
const end = start.moveBy(frontMatter.raw.length);
frontMatter.sourceSpan = new ParseSourceSpan(start, end);
// @ts-expect-error -- not a real AstNode
rawAst.children.unshift(frontMatter);
}
const ast = new Node(rawAst);
const parseSubHtml = (subContent, startSpan) => {
const { offset } = startSpan;
const fakeContent = text.slice(0, offset).replaceAll(/[^\n\r]/gu, " ");
const realContent = subContent;
const subAst = parse(
fakeContent + realContent,
parseOptions,
options,
false,
);
// @ts-expect-error
subAst.sourceSpan = new ParseSourceSpan(
startSpan,
// @ts-expect-error
subAst.children.at(-1).sourceSpan.end,
);
// @ts-expect-error
const firstText = subAst.children[0];
if (firstText.length === offset) {
/* c8 ignore next */ // @ts-expect-error
subAst.children.shift();
} else {
firstText.sourceSpan = new ParseSourceSpan(
firstText.sourceSpan.start.moveBy(offset),
firstText.sourceSpan.end,
);
firstText.value = firstText.value.slice(offset);
}
return subAst;
};
ast.walk((node) => {
if (node.type === "comment") {
const ieConditionalComment = parseIeConditionalComment(
node,
parseSubHtml,
);
if (ieConditionalComment) {
node.parent.replaceChild(node, ieConditionalComment);
}
}
normalizeAngularControlFlowBlock(node);
normalizeAngularIcuExpression(node);
});
return ast;
}
/**
* @param {ParseOptions} parseOptions
*/
function createParser(parseOptions) {
return {
parse: (text, options) => parse(text, parseOptions, options),
hasPragma,
astFormat: "html",
locStart,
locEnd,
};
}
/** @type {ParseOptions} */
const HTML_PARSE_OPTIONS = {
name: "html",
normalizeTagName: true,
normalizeAttributeName: true,
allowHtmComponentClosingTags: true,
};
// HTML
export const html = createParser(HTML_PARSE_OPTIONS);
// Angular
export const angular = createParser({ name: "angular" });
// Vue
export const vue = createParser({
name: "vue",
isTagNameCaseSensitive: true,
shouldParseAsRawText(tagName, prefix, hasParent, attrs) {
return (
tagName.toLowerCase() !== "html" &&
!hasParent &&
(tagName !== "template" ||
attrs.some(
({ name, value }) =>
name === "lang" &&
value !== "html" &&
value !== "" &&
value !== undefined,
))
);
},
});
// Lightning Web Components
export const lwc = createParser({ name: "lwc", canSelfClose: false });