@idomatic/parser-js 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/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,7 +1,10 @@
1
1
  import fs from "fs";
2
2
  import { parse, print, types } from "recast";
3
3
  import { createRequire } from "module";
4
+ import MagicString from "magic-string";
4
5
  import { createIdFactory } from "./idGen.js";
6
+ import { processTemplate, existingIdsIn } from "./markup/index.js";
7
+ import { maskBalanced } from "./markup/mask.js";
5
8
 
6
9
  const require = createRequire(import.meta.url);
7
10
  const b = types.builders;
@@ -9,6 +12,7 @@ const b = types.builders;
9
12
  // Attributes that describe an element well, in priority order.
10
13
  const DESCRIPTIVE_ATTRS = [
11
14
  "aria-label",
15
+ "accessibilityLabel", // React Native
12
16
  "name",
13
17
  "placeholder",
14
18
  "alt",
@@ -56,6 +60,60 @@ function describe(opening, el) {
56
60
  return getTextContent(el);
57
61
  }
58
62
 
63
+ const parseCode = (code) =>
64
+ parse(code, { parser: require("recast/parsers/babel-ts") });
65
+
66
+ // `${...}` inside a template: never scanned. A nested html`` template in
67
+ // there is found and processed on its own.
68
+ const maskExpressions = (c) => maskBalanced(c, /\$(?=\{)/);
69
+
70
+ function isComponentDecorator(decorator) {
71
+ const callee = decorator.expression?.callee;
72
+ return callee?.type === "Identifier" && callee.name === "Component";
73
+ }
74
+
75
+ /**
76
+ * Markup that lives inside JS strings: Lit `html`/`svg` tagged templates and
77
+ * Angular `@Component({ template })`. Returns the source range of each
78
+ * template's contents and the quote to use for new attribute values.
79
+ */
80
+ function findTemplates(ast) {
81
+ const templates = [];
82
+ const inner = (node) => ({ start: node.start + 1, end: node.end - 1 });
83
+
84
+ function checkClass(path) {
85
+ for (const decorator of path.node.decorators || []) {
86
+ if (!isComponentDecorator(decorator)) continue;
87
+ const options = decorator.expression.arguments?.[0];
88
+ for (const prop of options?.properties || []) {
89
+ const key = prop.key?.name ?? prop.key?.value;
90
+ const value = prop.value;
91
+ if (key !== "template") continue;
92
+ if (value?.type === "TemplateLiteral") {
93
+ templates.push({ ...inner(value), quote: '"' });
94
+ } else if (value?.type === "StringLiteral") {
95
+ const delimiter = value.extra?.raw?.[0];
96
+ templates.push({ ...inner(value), quote: delimiter === '"' ? "'" : '"' });
97
+ }
98
+ }
99
+ }
100
+ this.traverse(path);
101
+ }
102
+
103
+ types.visit(ast, {
104
+ visitTaggedTemplateExpression(path) {
105
+ const { tag, quasi } = path.node;
106
+ if (tag.type === "Identifier" && (tag.name === "html" || tag.name === "svg")) {
107
+ templates.push({ ...inner(quasi), quote: '"' });
108
+ }
109
+ this.traverse(path);
110
+ },
111
+ visitClassDeclaration: checkClass,
112
+ visitClassExpression: checkClass,
113
+ });
114
+ return templates;
115
+ }
116
+
59
117
  /**
60
118
  * @param {string} filePath - Full path to file
61
119
  * @param {object} config - iDomatic config
@@ -63,33 +121,59 @@ function describe(opening, el) {
63
121
  * @returns {boolean} - True if the file would be (or was) updated
64
122
  */
65
123
  export default function parseJS(filePath, config, dry = false) {
66
- const code = fs.readFileSync(filePath, "utf-8");
124
+ const original = fs.readFileSync(filePath, "utf-8");
67
125
  const attributeName = config.attributeName;
68
126
  const tagsToExclude = config.excludeTags || [];
69
- let changed = false;
70
127
 
71
- const ast = parse(code, {
72
- parser: require("recast/parsers/babel-ts"),
73
- });
128
+ let ast = parseCode(original);
74
129
 
75
- // First pass: collect ids already present so new ids never collide with them.
130
+ // Collect ids already present (JSX and templates) so new ids never collide.
76
131
  const existingIds = [];
77
132
  types.visit(ast, {
78
133
  visitJSXOpeningElement(path) {
79
134
  const value = getStringAttr(path.node.attributes, attributeName);
80
135
  if (value) existingIds.push(value);
81
- return false;
136
+ this.traverse(path);
82
137
  },
83
138
  });
139
+ const templates = findTemplates(ast);
140
+ for (const t of templates) {
141
+ existingIds.push(
142
+ ...existingIdsIn(original.slice(t.start, t.end), config, maskExpressions)
143
+ );
144
+ }
84
145
 
85
146
  const makeId = createIdFactory(config, existingIds);
86
147
 
148
+ // Templates first, as plain text edits on the source.
149
+ let code = original;
150
+ if (templates.length) {
151
+ const ms = new MagicString(original);
152
+ for (const t of templates) {
153
+ processTemplate(original.slice(t.start, t.end), config, {
154
+ mask: maskExpressions,
155
+ makeId,
156
+ quote: t.quote,
157
+ target: { ms, offset: t.start },
158
+ });
159
+ }
160
+ code = ms.toString();
161
+ if (code !== original) ast = parseCode(code);
162
+ }
163
+
164
+ // Then JSX, through the AST.
165
+ let jsxChanged = false;
87
166
  types.visit(ast, {
88
167
  visitJSXOpeningElement(path) {
89
168
  const opening = path.node;
90
169
  const tag = getTagName(opening.name);
91
170
 
92
- if (tagsToExclude.includes(tag)) return false;
171
+ // A Fragment renders no element and only accepts `key`.
172
+ if (tagsToExclude.includes(tag) || tag === "Fragment") {
173
+ // Still visit JSX passed through props, e.g. fallback={<p>...</p>}.
174
+ this.traverse(path);
175
+ return;
176
+ }
93
177
 
94
178
  const hasId = opening.attributes.some(
95
179
  (attr) => attr.name?.name === attributeName
@@ -104,15 +188,16 @@ export default function parseJS(filePath, config, dry = false) {
104
188
  b.stringLiteral(idValue)
105
189
  )
106
190
  );
107
- changed = true;
191
+ jsxChanged = true;
108
192
  }
109
193
 
110
- return false;
194
+ this.traverse(path);
111
195
  },
112
196
  });
113
197
 
198
+ const output = jsxChanged ? print(ast).code : code;
199
+ const changed = output !== original;
114
200
  if (changed && !dry) {
115
- const output = print(ast).code;
116
201
  fs.writeFileSync(filePath, output);
117
202
  }
118
203
 
@@ -0,0 +1,204 @@
1
+ import MagicString from "magic-string";
2
+ import { createIdFactory } from "../idGen.js";
3
+
4
+ // Attributes that describe an element well, in priority order.
5
+ const DESCRIPTIVE_ATTRS = [
6
+ "aria-label",
7
+ "name",
8
+ "placeholder",
9
+ "alt",
10
+ "title",
11
+ "label",
12
+ "role",
13
+ "type",
14
+ ];
15
+
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"]);
22
+
23
+ function escapeRegExp(str) {
24
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
25
+ }
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
+
98
+ function getAttrValue(attributesStr, attrName) {
99
+ const re = new RegExp(
100
+ `(?:^|\\s)${escapeRegExp(attrName)}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`,
101
+ "i"
102
+ );
103
+ const match = attributesStr.match(re);
104
+ if (!match) return "";
105
+ return match[1] ?? match[2] ?? "";
106
+ }
107
+
108
+ function describe(attributesStr) {
109
+ for (const name of DESCRIPTIVE_ATTRS) {
110
+ const value = getAttrValue(attributesStr, name);
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
+ }
115
+ return "";
116
+ }
117
+
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);
130
+ }
131
+
132
+ /**
133
+ * Inserts semantic, unique ids into every eligible tag of an HTML-like string
134
+ * while preserving the original formatting.
135
+ *
136
+ * @param {string} content - The markup.
137
+ * @param {object} config - The configuration object.
138
+ * @param {string} config.attributeName - The attribute name to add.
139
+ * @param {string} [config.prefix] - The prefix for generated ids.
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.
156
+ * @returns {string} - The updated markup.
157
+ */
158
+ export function processTemplate(content, config, options = {}) {
159
+ const { mask, skipTag, component = false, quote = '"' } = options;
160
+ const { attributeName, excludeTags = [] } = config;
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));
168
+
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
+ : [];
175
+
176
+ for (const { start, tagName, attributesStr, attrsStart, attrsEnd } of tags) {
177
+ if (excludeTags.includes(tagName)) continue;
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;
187
+
188
+ const idValue = makeId([tagName, describe(attributesStr)]);
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}`);
195
+ }
196
+
197
+ return ms.toString();
198
+ }
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);
204
+ }
package/markup/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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@idomatic/parser-js",
3
- "version": "1.1.1",
4
- "description": "JS/TSX parser for idomatic CLI",
3
+ "version": "1.3.1",
4
+ "description": "JS/TS parser for idomatic: JSX/TSX (React, React Native, Solid), Lit templates and Angular inline templates",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -15,7 +15,8 @@
15
15
  "main": "index.js",
16
16
  "files": [
17
17
  "index.js",
18
- "idGen.js"
18
+ "idGen.js",
19
+ "markup"
19
20
  ],
20
21
  "exports": {
21
22
  ".": {
@@ -44,6 +45,7 @@
44
45
  },
45
46
  "dependencies": {
46
47
  "@babel/parser": "^7.22.5",
48
+ "magic-string": "^0.30.21",
47
49
  "recast": "^0.23.5"
48
50
  },
49
51
  "devDependencies": {