@idomatic/parser-js 1.0.0

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 (2) hide show
  1. package/index.js +42 -0
  2. package/package.json +23 -0
package/index.js ADDED
@@ -0,0 +1,42 @@
1
+ import fs from "fs";
2
+ import { parse, print, types } from "recast";
3
+ import { randomUUID } from "crypto";
4
+ import { createRequire } from "module";
5
+
6
+ const require = createRequire(import.meta.url);
7
+ const b = types.builders;
8
+
9
+ export default function parseJS(filePath, config) {
10
+ const code = fs.readFileSync(filePath, "utf-8");
11
+
12
+ const ast = parse(code, {
13
+ parser: require("recast/parsers/babel-ts"),
14
+ });
15
+
16
+ types.visit(ast, {
17
+ visitJSXOpeningElement(path) {
18
+ const tag = path.node.name.name;
19
+
20
+ if (config.skipTags.includes(tag)) return false;
21
+
22
+ const hasId = path.node.attributes.some(
23
+ (attr) => attr.name?.name === "id"
24
+ );
25
+
26
+ if (!hasId) {
27
+ path.node.attributes.push(
28
+ b.jsxAttribute(
29
+ b.jsxIdentifier("id"),
30
+ b.stringLiteral(`${config.prefix}${randomUUID()}`)
31
+ )
32
+ );
33
+ }
34
+
35
+ return false;
36
+ },
37
+ });
38
+
39
+ const output = print(ast).code;
40
+
41
+ fs.writeFileSync(filePath, output);
42
+ }
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@idomatic/parser-js",
3
+ "version": "1.0.0",
4
+ "description": "JS/TSX parser for idomatic CLI",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": {
8
+ "default": "./index.js"
9
+ },
10
+ "keywords": [
11
+ "idomatic",
12
+ "parser",
13
+ "js",
14
+ "tsx",
15
+ "jsx",
16
+ "typescript"
17
+ ],
18
+ "author": "Amar Smajlovic",
19
+ "license": "MIT",
20
+ "dependencies": {
21
+ "recast": "^0.23.5"
22
+ }
23
+ }