@idomatic/parser-js 1.0.24 → 1.1.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.
Files changed (3) hide show
  1. package/idGen.js +58 -0
  2. package/index.js +71 -8
  3. package/package.json +28 -2
package/idGen.js ADDED
@@ -0,0 +1,58 @@
1
+ import { randomUUID } from "crypto";
2
+
3
+ /**
4
+ * Id generation with a configurable strategy.
5
+ *
6
+ * - "semantic" (default): derive a human-readable slug from the element's tag,
7
+ * descriptive attributes and text content, then guarantee uniqueness by
8
+ * suffixing `-2`, `-3`, ... only on collision.
9
+ * - "random": use `${prefix}${randomUUID()}`.
10
+ *
11
+ * Either way the factory is seeded with ids already present in the file, so
12
+ * re-runs are idempotent: a new element never steals or duplicates an existing id.
13
+ */
14
+
15
+ const MAX_SLUG_LENGTH = 40;
16
+
17
+ export function slugify(str, maxLen = MAX_SLUG_LENGTH) {
18
+ if (!str) return "";
19
+ return String(str)
20
+ .trim()
21
+ .toLowerCase()
22
+ .replace(/[^a-z0-9]+/g, "-")
23
+ .replace(/-{2,}/g, "-")
24
+ .replace(/^-+|-+$/g, "")
25
+ .slice(0, maxLen)
26
+ .replace(/-+$/g, "");
27
+ }
28
+
29
+ /**
30
+ * @param {object} config - iDomatic config (uses `prefix` and `idStrategy`).
31
+ * @param {Iterable<string>} existing - ids already present in the file.
32
+ * @returns {(parts: string[]) => string} - returns a unique id per call.
33
+ */
34
+ export function createIdFactory(config, existing = []) {
35
+ const prefix = config.prefix || "";
36
+ const random = config.idStrategy === "random";
37
+ const taken = new Set(existing);
38
+
39
+ return function makeId(parts) {
40
+ if (random) {
41
+ let candidate = `${prefix}${randomUUID()}`;
42
+ while (taken.has(candidate)) candidate = `${prefix}${randomUUID()}`;
43
+ taken.add(candidate);
44
+ return candidate;
45
+ }
46
+
47
+ const slug =
48
+ slugify(parts.map((p) => slugify(p)).filter(Boolean).join("-")) || "el";
49
+
50
+ let candidate = `${prefix}${slug}`;
51
+ let n = 2;
52
+ while (taken.has(candidate)) {
53
+ candidate = `${prefix}${slug}-${n++}`;
54
+ }
55
+ taken.add(candidate);
56
+ return candidate;
57
+ };
58
+ }
package/index.js CHANGED
@@ -1,11 +1,61 @@
1
1
  import fs from "fs";
2
2
  import { parse, print, types } from "recast";
3
- import { randomUUID } from "crypto";
4
3
  import { createRequire } from "module";
4
+ import { createIdFactory } from "./idGen.js";
5
5
 
6
6
  const require = createRequire(import.meta.url);
7
7
  const b = types.builders;
8
8
 
9
+ // Attributes that describe an element well, in priority order.
10
+ const DESCRIPTIVE_ATTRS = [
11
+ "aria-label",
12
+ "name",
13
+ "placeholder",
14
+ "alt",
15
+ "title",
16
+ "label",
17
+ "role",
18
+ "type",
19
+ ];
20
+
21
+ function getTagName(nameNode) {
22
+ if (!nameNode) return "el";
23
+ if (nameNode.type === "JSXIdentifier") return nameNode.name;
24
+ if (nameNode.type === "JSXMemberExpression") {
25
+ return nameNode.property?.name || "el";
26
+ }
27
+ return "el";
28
+ }
29
+
30
+ function getStringAttr(attributes, attrName) {
31
+ const attr = attributes.find(
32
+ (a) => a.type === "JSXAttribute" && a.name?.name === attrName
33
+ );
34
+ const value = attr?.value;
35
+ if (value?.type === "StringLiteral" || value?.type === "Literal") {
36
+ return typeof value.value === "string" ? value.value : "";
37
+ }
38
+ return "";
39
+ }
40
+
41
+ function getTextContent(el) {
42
+ for (const child of el?.children || []) {
43
+ if (child.type === "JSXText") {
44
+ const text = child.value.trim();
45
+ if (text) return text;
46
+ }
47
+ }
48
+ return "";
49
+ }
50
+
51
+ function describe(opening, el) {
52
+ for (const name of DESCRIPTIVE_ATTRS) {
53
+ const value = getStringAttr(opening.attributes, name);
54
+ if (value) return value;
55
+ }
56
+ return getTextContent(el);
57
+ }
58
+
9
59
  /**
10
60
  * @param {string} filePath - Full path to file
11
61
  * @param {object} config - iDomatic config
@@ -14,28 +64,41 @@ const b = types.builders;
14
64
  */
15
65
  export default function parseJS(filePath, config, dry = false) {
16
66
  const code = fs.readFileSync(filePath, "utf-8");
67
+ const attributeName = config.attributeName;
68
+ const tagsToExclude = config.excludeTags || [];
17
69
  let changed = false;
18
70
 
19
71
  const ast = parse(code, {
20
72
  parser: require("recast/parsers/babel-ts"),
21
73
  });
22
74
 
75
+ // First pass: collect ids already present so new ids never collide with them.
76
+ const existingIds = [];
77
+ types.visit(ast, {
78
+ visitJSXOpeningElement(path) {
79
+ const value = getStringAttr(path.node.attributes, attributeName);
80
+ if (value) existingIds.push(value);
81
+ return false;
82
+ },
83
+ });
84
+
85
+ const makeId = createIdFactory(config, existingIds);
86
+
23
87
  types.visit(ast, {
24
88
  visitJSXOpeningElement(path) {
25
- const tag = path.node.name.name;
26
- const tagsToExclude = config.excludeTags || [];
89
+ const opening = path.node;
90
+ const tag = getTagName(opening.name);
27
91
 
28
92
  if (tagsToExclude.includes(tag)) return false;
29
93
 
30
- const attributeName = config.attributeName;
31
-
32
- const hasId = path.node.attributes.some(
94
+ const hasId = opening.attributes.some(
33
95
  (attr) => attr.name?.name === attributeName
34
96
  );
35
97
 
36
98
  if (!hasId) {
37
- const idValue = `${config.prefix}${randomUUID()}`;
38
- path.node.attributes.push(
99
+ const descriptor = describe(opening, path.parent.node);
100
+ const idValue = makeId([tag, descriptor]);
101
+ opening.attributes.push(
39
102
  b.jsxAttribute(
40
103
  b.jsxIdentifier(attributeName),
41
104
  b.stringLiteral(idValue)
package/package.json CHANGED
@@ -1,9 +1,22 @@
1
1
  {
2
2
  "name": "@idomatic/parser-js",
3
- "version": "1.0.24",
3
+ "version": "1.1.1",
4
4
  "description": "JS/TSX parser for idomatic CLI",
5
5
  "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/AmarSmajlovic/idomatic.git",
9
+ "directory": "packages/parser-js"
10
+ },
11
+ "homepage": "https://www.idomatic.dev",
12
+ "bugs": {
13
+ "url": "https://github.com/AmarSmajlovic/idomatic/issues"
14
+ },
6
15
  "main": "index.js",
16
+ "files": [
17
+ "index.js",
18
+ "idGen.js"
19
+ ],
7
20
  "exports": {
8
21
  ".": {
9
22
  "import": "./index.js",
@@ -16,11 +29,24 @@
16
29
  "js",
17
30
  "tsx",
18
31
  "jsx",
19
- "typescript"
32
+ "typescript",
33
+ "react",
34
+ "data-testid",
35
+ "test-automation",
36
+ "playwright",
37
+ "cypress",
38
+ "testing-library"
20
39
  ],
21
40
  "author": "Amar Smajlovic",
22
41
  "license": "MIT",
42
+ "scripts": {
43
+ "test": "vitest run"
44
+ },
23
45
  "dependencies": {
46
+ "@babel/parser": "^7.22.5",
24
47
  "recast": "^0.23.5"
48
+ },
49
+ "devDependencies": {
50
+ "vitest": "^2.1.8"
25
51
  }
26
52
  }