@idomatic/parser-html 1.1.1 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/formats.js +208 -0
- package/idGen.js +5 -0
- package/index.js +7 -20
- package/package.json +21 -2
- package/utils/index.js +144 -38
- package/utils/mask.js +56 -0
- package/utils/pug.js +168 -0
package/formats.js
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { TEMPLATE_REGEX } from "./consts/index.js";
|
|
2
|
+
import { processTemplate, existingIdsIn } from "./utils/index.js";
|
|
3
|
+
import { createIdFactory } from "./idGen.js";
|
|
4
|
+
import { processPug } from "./utils/pug.js";
|
|
5
|
+
import { maskPattern, maskBalanced, composeMasks } from "./utils/mask.js";
|
|
6
|
+
|
|
7
|
+
/** Handlebars comments: `{{!-- ... --}}` and `{{! ... }}`. */
|
|
8
|
+
const maskHandlebarsComments = (c) =>
|
|
9
|
+
maskPattern(maskPattern(c, /\{\{!--[\s\S]*?--\}\}/g), /\{\{![\s\S]*?\}\}/g);
|
|
10
|
+
|
|
11
|
+
/** PHP blocks: `<?php ... ?>`, `<?= ... ?>`, and an unclosed one at the end. */
|
|
12
|
+
const maskPhp = (c) => maskPattern(c, /<\?(?:php|=)?[\s\S]*?(?:\?>|$(?![\s\S]))/g);
|
|
13
|
+
|
|
14
|
+
/** Blade: comments, `@php ... @endphp`, inline `@php(...)`, and raw PHP. */
|
|
15
|
+
const maskBlade = composeMasks(
|
|
16
|
+
(c) => maskPattern(c, /\{\{--[\s\S]*?--\}\}/g),
|
|
17
|
+
(c) => maskPattern(c, /@php\b(?!\s*\()[\s\S]*?@endphp\b/g),
|
|
18
|
+
(c) => maskBalanced(c, /@php\s*/, "(", ")"),
|
|
19
|
+
maskPhp
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
/** Twig, Jinja, Nunjucks and Django comments: `{# ... #}`. */
|
|
23
|
+
const maskHashComments = (c) => maskPattern(c, /\{#[\s\S]*?#\}/g);
|
|
24
|
+
|
|
25
|
+
/** ERB and EJS: everything between `<%` and `%>`. */
|
|
26
|
+
const maskErb = (c) => maskPattern(c, /<%[\s\S]*?%>/g);
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Razor (.cshtml) and Blazor (.razor): comments, code blocks, explicit
|
|
30
|
+
* expressions, the parenthesised part of `@if (...)`/`@foreach (...)`, and
|
|
31
|
+
* directive lines whose generics (`@model List<Product>`) look like tags.
|
|
32
|
+
*/
|
|
33
|
+
const maskRazor = composeMasks(
|
|
34
|
+
(c) => maskPattern(c, /@\*[\s\S]*?\*@/g),
|
|
35
|
+
(c) => maskPattern(c, /^[ \t]*@(?:model|using|inject|inherits|page|typeparam|attribute|implements|layout|namespace|addTagHelper|removeTagHelper|preservewhitespace|rendermode)\b[^\n]*/gm),
|
|
36
|
+
(c) => maskBalanced(c, /@(?:code|functions)?\s*(?=\{)/),
|
|
37
|
+
(c) => maskBalanced(c, /@[\w.]*\s*(?=\()/, "(", ")")
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
// Blazor built-ins that pass unknown attributes through to their element.
|
|
41
|
+
const BLAZOR_PASS_THROUGH = new Set([
|
|
42
|
+
"EditForm", "InputText", "InputTextArea", "InputNumber", "InputCheckbox",
|
|
43
|
+
"InputDate", "InputSelect", "InputFile", "InputRadio", "NavLink",
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
// Tag helpers and Razor markers that render no element of their own.
|
|
47
|
+
const RAZOR_NON_RENDERING = new Set([
|
|
48
|
+
"text", "partial", "environment", "cache", "distributed-cache", "component",
|
|
49
|
+
]);
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* MDX: code and links that only look like tags. Fenced code blocks, inline
|
|
53
|
+
* code, ESM import/export blocks, JSX comments (slash-star inside braces)
|
|
54
|
+
* and `<https://...>` autolinks.
|
|
55
|
+
*/
|
|
56
|
+
const maskMdx = composeMasks(
|
|
57
|
+
(c) => maskPattern(c, /^[ \t]*(`{3,}|~{3,})[^\n]*\n[\s\S]*?^[ \t]*\1[ \t]*$/gm),
|
|
58
|
+
(c) => maskPattern(c, /(`+)[^`\n][\s\S]*?\1/g),
|
|
59
|
+
(c) => maskPattern(c, /^(?:import|export)\b[\s\S]*?(?=\n[ \t]*\n|(?![\s\S]))/gm),
|
|
60
|
+
(c) => maskPattern(c, /\{\/\*[\s\S]*?\*\/\}/g),
|
|
61
|
+
(c) => maskPattern(c, /<(?:https?|mailto|ftp):[^\s>]*>/g)
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
/** Runs `process` on the part after a leading `---` fence (Astro, MDX). */
|
|
65
|
+
function afterFrontmatter(content, process) {
|
|
66
|
+
const fence = /^\s*---\r?\n[\s\S]*?\r?\n---/.exec(content);
|
|
67
|
+
if (!fence) return process(content);
|
|
68
|
+
return fence[0] + process(content.slice(fence[0].length));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Each format says which files it handles and how to process them. The first
|
|
73
|
+
* matching entry wins, so more specific suffixes (`.blade.php`) come first.
|
|
74
|
+
*/
|
|
75
|
+
export const formats = [
|
|
76
|
+
{
|
|
77
|
+
name: "blade",
|
|
78
|
+
test: (file) => file.endsWith(".blade.php"),
|
|
79
|
+
process: (content, config) =>
|
|
80
|
+
processTemplate(content, config, {
|
|
81
|
+
mask: maskBlade,
|
|
82
|
+
// <x-slot> and <x-slot:name> only pass content into a component.
|
|
83
|
+
skipTag: (tag) => tag === "x-slot" || tag.startsWith("x-slot:"),
|
|
84
|
+
}),
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
name: "php",
|
|
88
|
+
test: (file) => file.endsWith(".php") || file.endsWith(".phtml"),
|
|
89
|
+
process: (content, config) =>
|
|
90
|
+
processTemplate(content, config, { mask: maskPhp }),
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
name: "twig",
|
|
94
|
+
test: (file) => file.endsWith(".twig"),
|
|
95
|
+
process: (content, config) =>
|
|
96
|
+
processTemplate(content, config, { mask: maskHashComments }),
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
name: "jinja",
|
|
100
|
+
test: (file) => /\.(jinja2?|j2|njk)$/.test(file),
|
|
101
|
+
process: (content, config) =>
|
|
102
|
+
processTemplate(content, config, { mask: maskHashComments }),
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
name: "erb",
|
|
106
|
+
test: (file) => file.endsWith(".erb") || file.endsWith(".ejs"),
|
|
107
|
+
process: (content, config) =>
|
|
108
|
+
processTemplate(content, config, { mask: maskErb }),
|
|
109
|
+
},
|
|
110
|
+
{
|
|
111
|
+
name: "razor",
|
|
112
|
+
test: (file) => file.endsWith(".cshtml") || file.endsWith(".razor"),
|
|
113
|
+
process: (content, config, file) =>
|
|
114
|
+
processTemplate(content, config, {
|
|
115
|
+
mask: maskRazor,
|
|
116
|
+
skipTag: (tag) =>
|
|
117
|
+
RAZOR_NON_RENDERING.has(tag) ||
|
|
118
|
+
tag.startsWith("vc:") ||
|
|
119
|
+
// A Blazor component throws on a parameter it doesn't declare.
|
|
120
|
+
(file.endsWith(".razor") && /^[A-Z]/.test(tag) && !BLAZOR_PASS_THROUGH.has(tag)),
|
|
121
|
+
}),
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
name: "ember-gjs",
|
|
125
|
+
test: (file) => file.endsWith(".gjs") || file.endsWith(".gts"),
|
|
126
|
+
process: (content, config) => {
|
|
127
|
+
const blocks = /<template>([\s\S]*?)<\/template>/g;
|
|
128
|
+
const existing = [...content.matchAll(blocks)].flatMap((m) =>
|
|
129
|
+
existingIdsIn(m[1], config, maskHandlebarsComments)
|
|
130
|
+
);
|
|
131
|
+
// One factory for the whole file, so two components never share an id.
|
|
132
|
+
const makeId = createIdFactory(config, existing);
|
|
133
|
+
return content.replace(
|
|
134
|
+
blocks,
|
|
135
|
+
(_, body) =>
|
|
136
|
+
`<template>${processTemplate(body, config, {
|
|
137
|
+
mask: maskHandlebarsComments,
|
|
138
|
+
makeId,
|
|
139
|
+
})}</template>`
|
|
140
|
+
);
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
name: "mdx",
|
|
145
|
+
test: (file) => file.endsWith(".mdx"),
|
|
146
|
+
process: (content, config) =>
|
|
147
|
+
afterFrontmatter(content, (c) =>
|
|
148
|
+
processTemplate(c, config, { mask: maskMdx })
|
|
149
|
+
),
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
name: "pug",
|
|
153
|
+
test: (file) => file.endsWith(".pug") || file.endsWith(".jade"),
|
|
154
|
+
process: (content, config) => processPug(content, config),
|
|
155
|
+
},
|
|
156
|
+
{
|
|
157
|
+
name: "vue",
|
|
158
|
+
test: (file) => file.endsWith(".vue"),
|
|
159
|
+
process: (content, config) => {
|
|
160
|
+
const match = content.match(TEMPLATE_REGEX);
|
|
161
|
+
if (!match) return content;
|
|
162
|
+
const updated = processTemplate(match[1], config);
|
|
163
|
+
return content.replace(TEMPLATE_REGEX, () => `<template>${updated}</template>`);
|
|
164
|
+
},
|
|
165
|
+
},
|
|
166
|
+
{
|
|
167
|
+
name: "svelte",
|
|
168
|
+
test: (file) => file.endsWith(".svelte"),
|
|
169
|
+
process: (content, config) =>
|
|
170
|
+
processTemplate(content, config, { component: true }),
|
|
171
|
+
},
|
|
172
|
+
{
|
|
173
|
+
name: "astro",
|
|
174
|
+
test: (file) => file.endsWith(".astro"),
|
|
175
|
+
process: (content, config) =>
|
|
176
|
+
afterFrontmatter(content, (c) =>
|
|
177
|
+
processTemplate(c, config, { component: true })
|
|
178
|
+
),
|
|
179
|
+
},
|
|
180
|
+
{
|
|
181
|
+
name: "handlebars",
|
|
182
|
+
test: (file) => file.endsWith(".hbs") || file.endsWith(".handlebars"),
|
|
183
|
+
process: (content, config) =>
|
|
184
|
+
processTemplate(content, config, { mask: maskHandlebarsComments }),
|
|
185
|
+
},
|
|
186
|
+
{
|
|
187
|
+
name: "html",
|
|
188
|
+
test: (file) => file.endsWith(".html") || file.endsWith(".htm"),
|
|
189
|
+
// Django and Jinja templates are often plain .html; if a file uses
|
|
190
|
+
// {% %} tags, its {# #} comments are skipped too.
|
|
191
|
+
process: (content, config) =>
|
|
192
|
+
processTemplate(content, config, {
|
|
193
|
+
mask: content.includes("{%") ? maskHashComments : undefined,
|
|
194
|
+
}),
|
|
195
|
+
},
|
|
196
|
+
];
|
|
197
|
+
|
|
198
|
+
export function formatFor(filePath) {
|
|
199
|
+
const file = filePath.toLowerCase();
|
|
200
|
+
const format = formats.find((f) => f.test(file));
|
|
201
|
+
return (
|
|
202
|
+
format && {
|
|
203
|
+
...format,
|
|
204
|
+
process: (content, config) => format.process(content, config, file),
|
|
205
|
+
}
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
|
package/idGen.js
CHANGED
|
@@ -19,6 +19,11 @@ export function slugify(str, maxLen = MAX_SLUG_LENGTH) {
|
|
|
19
19
|
return String(str)
|
|
20
20
|
.trim()
|
|
21
21
|
.toLowerCase()
|
|
22
|
+
// "ćao" → "cao", not "ao": strip accents before dropping other characters.
|
|
23
|
+
.normalize("NFKD")
|
|
24
|
+
.replace(/[\u0300-\u036f]/g, "")
|
|
25
|
+
.replace(/đ/g, "d")
|
|
26
|
+
.replace(/ß/g, "ss")
|
|
22
27
|
.replace(/[^a-z0-9]+/g, "-")
|
|
23
28
|
.replace(/-{2,}/g, "-")
|
|
24
29
|
.replace(/^-+|-+$/g, "")
|
package/index.js
CHANGED
|
@@ -1,34 +1,21 @@
|
|
|
1
1
|
import fs from "fs";
|
|
2
|
-
import
|
|
3
|
-
import { TEMPLATE_REGEX as templateRegex } from "./consts/index.js";
|
|
4
|
-
import { processHtmlContent, processVueTemplate } from "./utils/index.js";
|
|
2
|
+
import { formatFor } from "./formats.js";
|
|
5
3
|
|
|
6
4
|
/**
|
|
7
|
-
*
|
|
5
|
+
* Adds unique ids to a markup file. Supported formats are listed in
|
|
6
|
+
* ./formats.js.
|
|
8
7
|
*
|
|
9
8
|
* @param {string} filePath - The path to the file.
|
|
10
9
|
* @param {object} config - The configuration object.
|
|
11
10
|
* @param {boolean} dry - If true, does not write changes back to disk.
|
|
12
11
|
* @returns {boolean} - Returns true if changes were made.
|
|
13
12
|
*/
|
|
14
|
-
|
|
15
13
|
export default async function parseHTML(filePath, config, dry = false) {
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
let updatedContent = originalContent;
|
|
14
|
+
const format = formatFor(filePath);
|
|
15
|
+
if (!format) return false;
|
|
19
16
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
if (match) {
|
|
23
|
-
const newTemplate = processVueTemplate(match[1], config);
|
|
24
|
-
updatedContent = originalContent.replace(
|
|
25
|
-
templateRegex,
|
|
26
|
-
`<template>${newTemplate}</template>`
|
|
27
|
-
);
|
|
28
|
-
}
|
|
29
|
-
} else if (ext === ".html" || ext === ".ng.html") {
|
|
30
|
-
updatedContent = processHtmlContent(originalContent, config);
|
|
31
|
-
}
|
|
17
|
+
const originalContent = fs.readFileSync(filePath, "utf-8");
|
|
18
|
+
const updatedContent = format.process(originalContent, config);
|
|
32
19
|
|
|
33
20
|
if (updatedContent !== originalContent) {
|
|
34
21
|
if (!dry) {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@idomatic/parser-html",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "1.3.1",
|
|
4
|
+
"description": "Markup parser for idomatic: HTML, Vue, Angular, Svelte, Astro, Handlebars, Ember, Blade, PHP, Twig, Jinja, Django, ERB, EJS, Razor, Blazor, Pug and MDX",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
"main": "index.js",
|
|
16
16
|
"files": [
|
|
17
17
|
"index.js",
|
|
18
|
+
"formats.js",
|
|
18
19
|
"idGen.js",
|
|
19
20
|
"utils",
|
|
20
21
|
"consts",
|
|
@@ -29,6 +30,24 @@
|
|
|
29
30
|
"html",
|
|
30
31
|
"vue",
|
|
31
32
|
"angular",
|
|
33
|
+
"svelte",
|
|
34
|
+
"astro",
|
|
35
|
+
"handlebars",
|
|
36
|
+
"ember",
|
|
37
|
+
"blade",
|
|
38
|
+
"laravel",
|
|
39
|
+
"php",
|
|
40
|
+
"twig",
|
|
41
|
+
"jinja",
|
|
42
|
+
"django",
|
|
43
|
+
"nunjucks",
|
|
44
|
+
"erb",
|
|
45
|
+
"rails",
|
|
46
|
+
"ejs",
|
|
47
|
+
"razor",
|
|
48
|
+
"blazor",
|
|
49
|
+
"pug",
|
|
50
|
+
"mdx",
|
|
32
51
|
"data-testid",
|
|
33
52
|
"test-automation",
|
|
34
53
|
"playwright",
|
package/utils/index.js
CHANGED
|
@@ -13,15 +13,91 @@ const DESCRIPTIVE_ATTRS = [
|
|
|
13
13
|
"type",
|
|
14
14
|
];
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
// Elements whose content is raw text, never markup.
|
|
17
|
+
const RAW_TEXT_TAGS = new Set(["script", "style", "textarea", "title"]);
|
|
18
|
+
|
|
19
|
+
// Elements that render nothing of their own or reject attributes in
|
|
20
|
+
// component templates (Svelte, Astro), so an id there is wrong or a no-op.
|
|
21
|
+
const NON_RENDERING_TAGS = new Set(["slot", "Fragment", "script", "style"]);
|
|
17
22
|
|
|
18
23
|
function escapeRegExp(str) {
|
|
19
24
|
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
20
25
|
}
|
|
21
26
|
|
|
27
|
+
/**
|
|
28
|
+
* Walks markup and returns every opening tag. Unlike a single regex, it treats
|
|
29
|
+
* quoted strings and `{...}`, `{{...}}` and `(...)` inside a tag as opaque, so
|
|
30
|
+
* `onclick={() => a > b}` (Svelte, Astro), `{{#if x}}class="a"{{/if}}`
|
|
31
|
+
* (Handlebars) or `@if($a > $b)` (Blade) do not end the tag early. Comments
|
|
32
|
+
* and raw-text element bodies (script, style, ...) are skipped.
|
|
33
|
+
*/
|
|
34
|
+
function findOpeningTags(content) {
|
|
35
|
+
const tags = [];
|
|
36
|
+
let i = 0;
|
|
37
|
+
|
|
38
|
+
while (i < content.length) {
|
|
39
|
+
const lt = content.indexOf("<", i);
|
|
40
|
+
if (lt === -1) break;
|
|
41
|
+
|
|
42
|
+
if (content.startsWith("<!--", lt)) {
|
|
43
|
+
const end = content.indexOf("-->", lt + 4);
|
|
44
|
+
i = end === -1 ? content.length : end + 3;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const nameMatch = /^<([a-zA-Z][\w:.-]*)/.exec(content.slice(lt, lt + 200));
|
|
49
|
+
if (!nameMatch) {
|
|
50
|
+
i = lt + 1;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const tagName = nameMatch[1];
|
|
55
|
+
let j = lt + nameMatch[0].length;
|
|
56
|
+
let quote = null;
|
|
57
|
+
let depth = 0;
|
|
58
|
+
|
|
59
|
+
for (; j < content.length; j++) {
|
|
60
|
+
const ch = content[j];
|
|
61
|
+
if (quote) {
|
|
62
|
+
if (ch === quote) quote = null;
|
|
63
|
+
} else if (ch === '"' || ch === "'" || (ch === "`" && depth > 0)) {
|
|
64
|
+
quote = ch;
|
|
65
|
+
} else if (ch === "{" || ch === "(") {
|
|
66
|
+
depth++;
|
|
67
|
+
} else if (ch === "}" || ch === ")") {
|
|
68
|
+
depth = Math.max(0, depth - 1);
|
|
69
|
+
} else if (ch === ">" && depth === 0) {
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (j >= content.length) break; // unterminated tag
|
|
75
|
+
|
|
76
|
+
const selfClosing = content[j - 1] === "/";
|
|
77
|
+
const attrsStart = lt + nameMatch[0].length;
|
|
78
|
+
const attributesStr = content.slice(attrsStart, selfClosing ? j - 1 : j);
|
|
79
|
+
tags.push({
|
|
80
|
+
start: lt,
|
|
81
|
+
tagName,
|
|
82
|
+
attributesStr,
|
|
83
|
+
attrsStart,
|
|
84
|
+
attrsEnd: selfClosing ? j - 1 : j,
|
|
85
|
+
});
|
|
86
|
+
i = j + 1;
|
|
87
|
+
|
|
88
|
+
if (RAW_TEXT_TAGS.has(tagName.toLowerCase()) && !selfClosing) {
|
|
89
|
+
const close = new RegExp(`</${escapeRegExp(tagName)}\\s*>`, "i");
|
|
90
|
+
const rest = close.exec(content.slice(i));
|
|
91
|
+
i = rest ? i + rest.index + rest[0].length : content.length;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return tags;
|
|
96
|
+
}
|
|
97
|
+
|
|
22
98
|
function getAttrValue(attributesStr, attrName) {
|
|
23
99
|
const re = new RegExp(
|
|
24
|
-
|
|
100
|
+
`(?:^|\\s)${escapeRegExp(attrName)}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`,
|
|
25
101
|
"i"
|
|
26
102
|
);
|
|
27
103
|
const match = attributesStr.match(re);
|
|
@@ -32,67 +108,97 @@ function getAttrValue(attributesStr, attrName) {
|
|
|
32
108
|
function describe(attributesStr) {
|
|
33
109
|
for (const name of DESCRIPTIVE_ATTRS) {
|
|
34
110
|
const value = getAttrValue(attributesStr, name);
|
|
35
|
-
|
|
111
|
+
// Skip values that are template expressions: "{{label}}", "${label}",
|
|
112
|
+
// or Razor's "@item.Name".
|
|
113
|
+
if (value && !/[{}]/.test(value) && !/^\s*@/.test(value)) return value;
|
|
36
114
|
}
|
|
37
115
|
return "";
|
|
38
116
|
}
|
|
39
117
|
|
|
40
|
-
function
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
);
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
118
|
+
function hasAttribute(attributesStr, attributeName) {
|
|
119
|
+
const name = escapeRegExp(attributeName);
|
|
120
|
+
// `id="x"`, `id={x}`, Vue `:id="x"` / `v-bind:id`, and Svelte shorthand `{id}`.
|
|
121
|
+
return new RegExp(
|
|
122
|
+
`(?:^|\\s)(?::|v-bind:)?${name}\\s*=|\\{\\s*${name}\\s*\\}`
|
|
123
|
+
).test(attributesStr);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function collectExistingIds(tags, attributeName) {
|
|
127
|
+
return tags
|
|
128
|
+
.map((t) => getAttrValue(t.attributesStr, attributeName))
|
|
129
|
+
.filter(Boolean);
|
|
52
130
|
}
|
|
53
131
|
|
|
54
132
|
/**
|
|
55
133
|
* Inserts semantic, unique ids into every eligible tag of an HTML-like string
|
|
56
134
|
* while preserving the original formatting.
|
|
57
135
|
*
|
|
58
|
-
* @param {string} content -
|
|
136
|
+
* @param {string} content - The markup.
|
|
59
137
|
* @param {object} config - The configuration object.
|
|
60
138
|
* @param {string} config.attributeName - The attribute name to add.
|
|
61
139
|
* @param {string} [config.prefix] - The prefix for generated ids.
|
|
62
140
|
* @param {string[]} [config.excludeTags] - Tag names to skip.
|
|
141
|
+
* @param {object} [options]
|
|
142
|
+
* @param {(content: string) => string} [options.mask] - Blanks embedded code
|
|
143
|
+
* (same length) so it is never scanned; see ./mask.js.
|
|
144
|
+
* @param {(tagName: string) => boolean} [options.skipTag] - Format-specific
|
|
145
|
+
* tags that never get an id.
|
|
146
|
+
* @param {boolean} [options.component] - Svelte/Astro: skip `slot`,
|
|
147
|
+
* `Fragment`, `svelte:*` and top-level script/style, and `<svelte:head>` content.
|
|
148
|
+
* @param {(parts: string[]) => string} [options.makeId] - A shared id factory,
|
|
149
|
+
* when several templates in one file must not collide.
|
|
150
|
+
* @param {string} [options.quote] - Quote for the new attribute value; `'`
|
|
151
|
+
* when the template itself sits inside a double-quoted JS string.
|
|
152
|
+
* @param {{ ms: MagicString, offset: number }} [options.target] - Write into
|
|
153
|
+
* an existing MagicString at `offset` instead of a new one, for templates
|
|
154
|
+
* embedded in a larger file (Lit, Angular inline). The return value is then
|
|
155
|
+
* that whole file.
|
|
63
156
|
* @returns {string} - The updated markup.
|
|
64
157
|
*/
|
|
65
|
-
function processTemplate(content, config) {
|
|
158
|
+
export function processTemplate(content, config, options = {}) {
|
|
159
|
+
const { mask, skipTag, component = false, quote = '"' } = options;
|
|
66
160
|
const { attributeName, excludeTags = [] } = config;
|
|
67
|
-
const
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
const
|
|
161
|
+
const scan = mask ? mask(content) : content;
|
|
162
|
+
const ms = options.target ? options.target.ms : new MagicString(content);
|
|
163
|
+
const offset = options.target ? options.target.offset : 0;
|
|
164
|
+
const tags = findOpeningTags(scan);
|
|
165
|
+
const makeId =
|
|
166
|
+
options.makeId ||
|
|
167
|
+
createIdFactory(config, collectExistingIds(tags, attributeName));
|
|
71
168
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
169
|
+
// `<svelte:head>` content goes into document.head, not the rendered page.
|
|
170
|
+
const headRanges = component
|
|
171
|
+
? [...scan.matchAll(/<svelte:head[\s\S]*?<\/svelte:head>/g)].map(
|
|
172
|
+
(m) => [m.index, m.index + m[0].length]
|
|
173
|
+
)
|
|
174
|
+
: [];
|
|
78
175
|
|
|
176
|
+
for (const { start, tagName, attributesStr, attrsStart, attrsEnd } of tags) {
|
|
79
177
|
if (excludeTags.includes(tagName)) continue;
|
|
80
|
-
if (
|
|
178
|
+
if (skipTag && skipTag(tagName)) continue;
|
|
179
|
+
if (headRanges.some(([from, to]) => start > from && start < to)) continue;
|
|
180
|
+
if (
|
|
181
|
+
component &&
|
|
182
|
+
(NON_RENDERING_TAGS.has(tagName) || tagName.startsWith("svelte:"))
|
|
183
|
+
) {
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
if (hasAttribute(attributesStr, attributeName)) continue;
|
|
81
187
|
|
|
82
188
|
const idValue = makeId([tagName, describe(attributesStr)]);
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
189
|
+
// Insert after the last attribute of the *original* text, so spacing
|
|
190
|
+
// before `>` or `/>` is kept (`<input name="a" id="x" />`) and a masked
|
|
191
|
+
// block at the end (`<% end %>`) stays before the new id, not after it.
|
|
192
|
+
const insertAt =
|
|
193
|
+
attrsStart + content.slice(attrsStart, attrsEnd).trimEnd().length;
|
|
194
|
+
ms.appendLeft(offset + insertAt, ` ${attributeName}=${quote}${idValue}${quote}`);
|
|
86
195
|
}
|
|
87
196
|
|
|
88
|
-
TAG_REGEX.lastIndex = 0;
|
|
89
197
|
return ms.toString();
|
|
90
198
|
}
|
|
91
199
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
export function processHtmlContent(htmlContent, config) {
|
|
97
|
-
return processTemplate(htmlContent, config);
|
|
200
|
+
/** Ids already present in a template, for seeding a shared factory. */
|
|
201
|
+
export function existingIdsIn(content, config, mask) {
|
|
202
|
+
const tags = findOpeningTags(mask ? mask(content) : content);
|
|
203
|
+
return collectExistingIds(tags, config.attributeName);
|
|
98
204
|
}
|
package/utils/mask.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Masking: template languages embed code in markup (`<?php ?>`, `<% %>`,
|
|
3
|
+
* `{# #}`, `@{ }`...). That code can contain `<` and `>` that look like tags or
|
|
4
|
+
* end a tag early. Before scanning, those regions are replaced with spaces of
|
|
5
|
+
* the same length (newlines kept), so every index still lines up with the
|
|
6
|
+
* original file and edits land in the right place.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export function blank(str) {
|
|
10
|
+
return str.replace(/[^\n]/g, " ");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Blanks every match of a global regex. */
|
|
14
|
+
export function maskPattern(content, re) {
|
|
15
|
+
return content.replace(re, (m) => blank(m));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Blanks regions that start with `startRe` (which must end right before the
|
|
20
|
+
* opening bracket) and run to the matching closing bracket. Quoted strings
|
|
21
|
+
* inside are skipped so a `}` in a string does not close the block.
|
|
22
|
+
*/
|
|
23
|
+
export function maskBalanced(content, startRe, open = "{", close = "}") {
|
|
24
|
+
const re = new RegExp(startRe.source, startRe.flags.includes("g") ? startRe.flags : startRe.flags + "g");
|
|
25
|
+
let out = content;
|
|
26
|
+
let match;
|
|
27
|
+
while ((match = re.exec(content)) !== null) {
|
|
28
|
+
const from = match.index;
|
|
29
|
+
let i = from + match[0].length;
|
|
30
|
+
if (content[i] !== open) continue;
|
|
31
|
+
let depth = 0;
|
|
32
|
+
let quote = null;
|
|
33
|
+
for (; i < content.length; i++) {
|
|
34
|
+
const ch = content[i];
|
|
35
|
+
if (quote) {
|
|
36
|
+
if (ch === "\\") i++;
|
|
37
|
+
else if (ch === quote) quote = null;
|
|
38
|
+
} else if (ch === '"' || ch === "'" || ch === "`") {
|
|
39
|
+
quote = ch;
|
|
40
|
+
} else if (ch === open) {
|
|
41
|
+
depth++;
|
|
42
|
+
} else if (ch === close && --depth === 0) {
|
|
43
|
+
break;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const to = Math.min(i + 1, content.length);
|
|
47
|
+
out = out.slice(0, from) + blank(content.slice(from, to)) + out.slice(to);
|
|
48
|
+
re.lastIndex = to;
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Applies several masks in order. */
|
|
54
|
+
export function composeMasks(...masks) {
|
|
55
|
+
return (content) => masks.reduce((acc, mask) => mask(acc), content);
|
|
56
|
+
}
|
package/utils/pug.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import MagicString from "magic-string";
|
|
2
|
+
import { createIdFactory } from "../idGen.js";
|
|
3
|
+
|
|
4
|
+
// Lines that start with these words are Pug keywords, not elements.
|
|
5
|
+
const KEYWORDS = new Set([
|
|
6
|
+
"doctype", "include", "extends", "block", "append", "prepend", "mixin",
|
|
7
|
+
"if", "else", "unless", "case", "when", "default", "each", "for", "while",
|
|
8
|
+
"yield",
|
|
9
|
+
]);
|
|
10
|
+
|
|
11
|
+
const DESCRIPTIVE_ATTRS = ["aria-label", "name", "placeholder", "alt", "title", "label", "role", "type"];
|
|
12
|
+
|
|
13
|
+
// tag, then .class / #id shorthands, then optional &attributes(...)
|
|
14
|
+
const ELEMENT = /^([a-zA-Z][\w-]*(?::[\w-]+)*)?((?:[.#][\w-]+)*)/;
|
|
15
|
+
|
|
16
|
+
function escapeRegExp(str) {
|
|
17
|
+
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Index just past the `)` that closes the `(` at `open`, skipping strings. */
|
|
21
|
+
function closingParen(src, open) {
|
|
22
|
+
let depth = 0;
|
|
23
|
+
let quote = null;
|
|
24
|
+
for (let i = open; i < src.length; i++) {
|
|
25
|
+
const ch = src[i];
|
|
26
|
+
if (quote) {
|
|
27
|
+
if (ch === "\\") i++;
|
|
28
|
+
else if (ch === quote) quote = null;
|
|
29
|
+
} else if (ch === '"' || ch === "'" || ch === "`") {
|
|
30
|
+
quote = ch;
|
|
31
|
+
} else if (ch === "(") {
|
|
32
|
+
depth++;
|
|
33
|
+
} else if (ch === ")" && --depth === 0) {
|
|
34
|
+
return i + 1;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return -1;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function attrValue(attrs, name) {
|
|
41
|
+
const m = new RegExp(`(?:^|[\\s,(])${escapeRegExp(name)}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(attrs);
|
|
42
|
+
return m ? m[1] ?? m[2] : "";
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function describe(attrs) {
|
|
46
|
+
for (const name of DESCRIPTIVE_ATTRS) {
|
|
47
|
+
const value = attrValue(attrs, name);
|
|
48
|
+
if (value && !/[{}#]/.test(value)) return value;
|
|
49
|
+
}
|
|
50
|
+
return "";
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Reads one element at `pos` (tag, shorthands, attribute list). Returns where
|
|
55
|
+
* an id would go and where the element ends, or null if this isn't one.
|
|
56
|
+
*/
|
|
57
|
+
function readElement(src, pos) {
|
|
58
|
+
const m = ELEMENT.exec(src.slice(pos));
|
|
59
|
+
if (!m || (!m[1] && !m[2])) return null;
|
|
60
|
+
const tag = m[1] || "div";
|
|
61
|
+
const shorthand = m[2];
|
|
62
|
+
let end = pos + m[0].length;
|
|
63
|
+
let attrs = "";
|
|
64
|
+
let attrsOpen = -1;
|
|
65
|
+
|
|
66
|
+
if (src.startsWith("&attributes", end)) {
|
|
67
|
+
const close = closingParen(src, end + "&attributes".length);
|
|
68
|
+
if (close === -1) return null;
|
|
69
|
+
end = close;
|
|
70
|
+
}
|
|
71
|
+
if (src[end] === "(") {
|
|
72
|
+
const close = closingParen(src, end);
|
|
73
|
+
if (close === -1) return null;
|
|
74
|
+
attrsOpen = end;
|
|
75
|
+
attrs = src.slice(end, close);
|
|
76
|
+
end = close;
|
|
77
|
+
}
|
|
78
|
+
return { tag, shorthand, attrs, attrsOpen, nameEnd: pos + m[0].length, end };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Adds ids to a Pug template.
|
|
83
|
+
*
|
|
84
|
+
* @param {string} content - The .pug source.
|
|
85
|
+
* @param {object} config - attributeName, prefix, excludeTags, idStrategy.
|
|
86
|
+
* @returns {string} - The updated source.
|
|
87
|
+
*/
|
|
88
|
+
export function processPug(content, config) {
|
|
89
|
+
const { attributeName, excludeTags = [] } = config;
|
|
90
|
+
const ms = new MagicString(content);
|
|
91
|
+
const lines = content.split("\n");
|
|
92
|
+
const offsets = [];
|
|
93
|
+
let acc = 0;
|
|
94
|
+
for (const line of lines) {
|
|
95
|
+
offsets.push(acc);
|
|
96
|
+
acc += line.length + 1;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const hasAttr = (el) =>
|
|
100
|
+
new RegExp(`(?:^|[\\s,(])${escapeRegExp(attributeName)}\\s*=`).test(el.attrs) ||
|
|
101
|
+
(attributeName === "id" && /#[\w-]/.test(el.shorthand));
|
|
102
|
+
|
|
103
|
+
// First pass: collect existing ids so new ones never collide.
|
|
104
|
+
const existing = [];
|
|
105
|
+
for (const m of content.matchAll(/(?:^|[\s,(])([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) {
|
|
106
|
+
if (m[1] === attributeName) existing.push(m[2] ?? m[3]);
|
|
107
|
+
}
|
|
108
|
+
if (attributeName === "id") {
|
|
109
|
+
for (const m of content.matchAll(/^[ \t]*[\w-]*(?:\.[\w-]+)*#([\w-]+)/gm)) existing.push(m[1]);
|
|
110
|
+
}
|
|
111
|
+
const makeId = createIdFactory(config, existing);
|
|
112
|
+
|
|
113
|
+
let skipDeeperThan = -1; // indentation of a comment or text block owner
|
|
114
|
+
let resumeAt = 0; // offset past a multi-line attribute list
|
|
115
|
+
|
|
116
|
+
for (let n = 0; n < lines.length; n++) {
|
|
117
|
+
const line = lines[n];
|
|
118
|
+
const start = offsets[n];
|
|
119
|
+
if (start < resumeAt) continue;
|
|
120
|
+
|
|
121
|
+
const body = line.trimStart();
|
|
122
|
+
if (!body) continue;
|
|
123
|
+
const indent = line.length - body.length;
|
|
124
|
+
|
|
125
|
+
if (skipDeeperThan >= 0) {
|
|
126
|
+
if (indent > skipDeeperThan) continue;
|
|
127
|
+
skipDeeperThan = -1;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Comments (and their indented children), code, text, mixin calls,
|
|
131
|
+
// outputs, raw HTML lines and filters.
|
|
132
|
+
if (body.startsWith("//")) {
|
|
133
|
+
skipDeeperThan = indent;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (/^[-|+=!<:]/.test(body)) continue;
|
|
137
|
+
const firstWord = /^[\w-]+/.exec(body)?.[0];
|
|
138
|
+
if (firstWord && KEYWORDS.has(firstWord) && !/^[\w-]+[.#(]/.test(body)) continue;
|
|
139
|
+
|
|
140
|
+
// An element, possibly followed by `: child` block expansion.
|
|
141
|
+
let pos = start + indent;
|
|
142
|
+
while (pos < content.length) {
|
|
143
|
+
const el = readElement(content, pos);
|
|
144
|
+
if (!el) break;
|
|
145
|
+
|
|
146
|
+
if (!excludeTags.includes(el.tag) && !hasAttr(el)) {
|
|
147
|
+
const id = makeId([el.tag, describe(el.attrs)]);
|
|
148
|
+
if (el.attrsOpen >= 0) {
|
|
149
|
+
ms.appendLeft(el.end - 1, ` ${attributeName}="${id}"`);
|
|
150
|
+
} else {
|
|
151
|
+
ms.appendLeft(el.nameEnd, `(${attributeName}="${id}")`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
resumeAt = el.end;
|
|
156
|
+
// `p.` / `script.`: the indented lines below are plain text.
|
|
157
|
+
if (content[el.end] === "." && /\s/.test(content[el.end + 1] ?? "\n")) {
|
|
158
|
+
skipDeeperThan = indent;
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
const expansion = /^:\s+/.exec(content.slice(el.end, el.end + 10));
|
|
162
|
+
if (!expansion) break;
|
|
163
|
+
pos = el.end + expansion[0].length;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return ms.toString();
|
|
168
|
+
}
|