@idomatic/parser-html 1.2.0 → 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 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,17 +1,9 @@
1
1
  import fs from "fs";
2
- import path from "path";
3
- import { TEMPLATE_REGEX as templateRegex } from "./consts/index.js";
4
- import {
5
- processComponentContent,
6
- processHtmlContent,
7
- processVueTemplate,
8
- } from "./utils/index.js";
9
-
10
- const COMPONENT_EXTS = new Set([".svelte", ".astro"]);
11
- const MARKUP_EXTS = new Set([".html", ".hbs", ".handlebars"]);
2
+ import { formatFor } from "./formats.js";
12
3
 
13
4
  /**
14
- * Parses an HTML, Vue, Svelte, Astro or Handlebars file and adds unique ids.
5
+ * Adds unique ids to a markup file. Supported formats are listed in
6
+ * ./formats.js.
15
7
  *
16
8
  * @param {string} filePath - The path to the file.
17
9
  * @param {object} config - The configuration object.
@@ -19,24 +11,11 @@ const MARKUP_EXTS = new Set([".html", ".hbs", ".handlebars"]);
19
11
  * @returns {boolean} - Returns true if changes were made.
20
12
  */
21
13
  export default async function parseHTML(filePath, config, dry = false) {
22
- const ext = path.extname(filePath).toLowerCase();
23
- const originalContent = fs.readFileSync(filePath, "utf-8");
24
- let updatedContent = originalContent;
14
+ const format = formatFor(filePath);
15
+ if (!format) return false;
25
16
 
26
- if (ext === ".vue") {
27
- const match = originalContent.match(templateRegex);
28
- if (match) {
29
- const newTemplate = processVueTemplate(match[1], config);
30
- updatedContent = originalContent.replace(
31
- templateRegex,
32
- () => `<template>${newTemplate}</template>`
33
- );
34
- }
35
- } else if (COMPONENT_EXTS.has(ext)) {
36
- updatedContent = processComponentContent(originalContent, config);
37
- } else if (MARKUP_EXTS.has(ext)) {
38
- updatedContent = processHtmlContent(originalContent, config);
39
- }
17
+ const originalContent = fs.readFileSync(filePath, "utf-8");
18
+ const updatedContent = format.process(originalContent, config);
40
19
 
41
20
  if (updatedContent !== originalContent) {
42
21
  if (!dry) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@idomatic/parser-html",
3
- "version": "1.2.0",
4
- "description": "HTML, Vue, Angular, Svelte, Astro and Handlebars parser for idomatic CLI",
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",
@@ -32,6 +33,21 @@
32
33
  "svelte",
33
34
  "astro",
34
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",
35
51
  "data-testid",
36
52
  "test-automation",
37
53
  "playwright",
package/utils/index.js CHANGED
@@ -26,10 +26,10 @@ function escapeRegExp(str) {
26
26
 
27
27
  /**
28
28
  * Walks markup and returns every opening tag. Unlike a single regex, it treats
29
- * quoted strings and `{...}` / `{{...}}` expressions inside a tag as opaque, so
30
- * `onclick={() => a > b}` (Svelte, Astro) or `{{#if x}}class="a"{{/if}}`
31
- * (Handlebars) do not end the tag early. Comments and raw-text element bodies
32
- * (script, style, ...) are skipped.
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
33
  */
34
34
  function findOpeningTags(content) {
35
35
  const tags = [];
@@ -62,9 +62,9 @@ function findOpeningTags(content) {
62
62
  if (ch === quote) quote = null;
63
63
  } else if (ch === '"' || ch === "'" || (ch === "`" && depth > 0)) {
64
64
  quote = ch;
65
- } else if (ch === "{") {
65
+ } else if (ch === "{" || ch === "(") {
66
66
  depth++;
67
- } else if (ch === "}") {
67
+ } else if (ch === "}" || ch === ")") {
68
68
  depth = Math.max(0, depth - 1);
69
69
  } else if (ch === ">" && depth === 0) {
70
70
  break;
@@ -76,13 +76,12 @@ function findOpeningTags(content) {
76
76
  const selfClosing = content[j - 1] === "/";
77
77
  const attrsStart = lt + nameMatch[0].length;
78
78
  const attributesStr = content.slice(attrsStart, selfClosing ? j - 1 : j);
79
- // Insert right after the last attribute so existing spacing before `>` or
80
- // `/>` is kept: `<input name="a" />` -> `<input name="a" id="x" />`.
81
79
  tags.push({
82
80
  start: lt,
83
81
  tagName,
84
82
  attributesStr,
85
- insertAt: attrsStart + attributesStr.trimEnd().length,
83
+ attrsStart,
84
+ attrsEnd: selfClosing ? j - 1 : j,
86
85
  });
87
86
  i = j + 1;
88
87
 
@@ -109,8 +108,9 @@ function getAttrValue(attributesStr, attrName) {
109
108
  function describe(attributesStr) {
110
109
  for (const name of DESCRIPTIVE_ATTRS) {
111
110
  const value = getAttrValue(attributesStr, name);
112
- // Skip values that are template expressions, e.g. "{{label}}".
113
- if (value && !/[{}]/.test(value)) return value;
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;
114
114
  }
115
115
  return "";
116
116
  }
@@ -133,34 +133,49 @@ function collectExistingIds(tags, attributeName) {
133
133
  * Inserts semantic, unique ids into every eligible tag of an HTML-like string
134
134
  * while preserving the original formatting.
135
135
  *
136
- * @param {string} content - Markup (HTML, Vue template, Svelte, Astro, Handlebars).
136
+ * @param {string} content - The markup.
137
137
  * @param {object} config - The configuration object.
138
138
  * @param {string} config.attributeName - The attribute name to add.
139
139
  * @param {string} [config.prefix] - The prefix for generated ids.
140
140
  * @param {string[]} [config.excludeTags] - Tag names to skip.
141
141
  * @param {object} [options]
142
- * @param {boolean} [options.component] - Skip non-rendering component tags
143
- * (`slot`, `Fragment`, `svelte:*`) and top-level script/style blocks.
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.
144
156
  * @returns {string} - The updated markup.
145
157
  */
146
- function processTemplate(content, config, { component = false } = {}) {
158
+ export function processTemplate(content, config, options = {}) {
159
+ const { mask, skipTag, component = false, quote = '"' } = options;
147
160
  const { attributeName, excludeTags = [] } = config;
148
- const ms = new MagicString(content);
149
- const tags = findOpeningTags(content);
150
- const makeId = createIdFactory(
151
- config,
152
- collectExistingIds(tags, attributeName)
153
- );
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));
154
168
 
155
169
  // `<svelte:head>` content goes into document.head, not the rendered page.
156
170
  const headRanges = component
157
- ? [...content.matchAll(/<svelte:head[\s\S]*?<\/svelte:head>/g)].map(
171
+ ? [...scan.matchAll(/<svelte:head[\s\S]*?<\/svelte:head>/g)].map(
158
172
  (m) => [m.index, m.index + m[0].length]
159
173
  )
160
174
  : [];
161
175
 
162
- for (const { start, tagName, attributesStr, insertAt } of tags) {
176
+ for (const { start, tagName, attributesStr, attrsStart, attrsEnd } of tags) {
163
177
  if (excludeTags.includes(tagName)) continue;
178
+ if (skipTag && skipTag(tagName)) continue;
164
179
  if (headRanges.some(([from, to]) => start > from && start < to)) continue;
165
180
  if (
166
181
  component &&
@@ -171,30 +186,19 @@ function processTemplate(content, config, { component = false } = {}) {
171
186
  if (hasAttribute(attributesStr, attributeName)) continue;
172
187
 
173
188
  const idValue = makeId([tagName, describe(attributesStr)]);
174
- ms.appendLeft(insertAt, ` ${attributeName}="${idValue}"`);
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}`);
175
195
  }
176
196
 
177
197
  return ms.toString();
178
198
  }
179
199
 
180
- export function processVueTemplate(templateContent, config) {
181
- return processTemplate(templateContent, config);
182
- }
183
-
184
- export function processHtmlContent(htmlContent, config) {
185
- return processTemplate(htmlContent, config);
186
- }
187
-
188
- /**
189
- * Svelte and Astro components: markup plus script/style blocks (and, for
190
- * Astro, a `---` frontmatter fence). Only the markup is touched.
191
- */
192
- export function processComponentContent(content, config) {
193
- const frontmatter = /^\s*---\r?\n[\s\S]*?\r?\n---/.exec(content);
194
- if (!frontmatter) return processTemplate(content, config, { component: true });
195
-
196
- const head = frontmatter[0];
197
- return (
198
- head + processTemplate(content.slice(head.length), config, { component: true })
199
- );
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);
200
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
+ }