|
| 1 | +import { readFile, writeFile } from "node:fs/promises"; |
| 2 | +import { createWriteStream } from "node:fs"; |
| 3 | +import { parse, latestEcmaVersion } from "espree"; |
| 4 | +import { traverse, Syntax } from "estraverse"; |
| 5 | +import { GetFilesToParse, GetRecursiveFilesToFix } from "./dump_javascript_paths.mjs"; |
| 6 | +import { match } from "node:assert"; |
| 7 | + |
| 8 | +const classRegex = /(\.[a-zA-Z0-9_-]+)/g; |
| 9 | +const files = await GetFilesToParse(); |
| 10 | + |
| 11 | +const classNames = {}; |
| 12 | + |
| 13 | +for (const file of files) { |
| 14 | + try { |
| 15 | + |
| 16 | + const code = await readFile(file); |
| 17 | + const ast = parse(code, { |
| 18 | + ecmaVersion: latestEcmaVersion, |
| 19 | + sourceType: "module", |
| 20 | + loc: true, |
| 21 | + }); |
| 22 | + |
| 23 | + traverse(ast, { |
| 24 | + enter: (node) => { |
| 25 | + // console.log(node); |
| 26 | + if ( |
| 27 | + node.type === Syntax.AssignmentExpression && |
| 28 | + node.left.type === Syntax.MemberExpression && |
| 29 | + node.left.property.type === Syntax.Identifier && |
| 30 | + node.left.property.name === "exports" && |
| 31 | + node.right.type === Syntax.ObjectExpression && |
| 32 | + node.right.properties.constructor === Array |
| 33 | + ) { |
| 34 | + // TODO: store it under a per website value to make sure there's no class colision |
| 35 | + for (const array_node of node.right.properties) { |
| 36 | + if (!isNaN(array_node.value.value)) { |
| 37 | + continue; |
| 38 | + } |
| 39 | + if (!classNames.hasOwnProperty(array_node.value.value)) { |
| 40 | + classNames[array_node.value.value] = [array_node.key.name]; |
| 41 | + } else |
| 42 | + { |
| 43 | + if (!classNames[array_node.value.value].includes(array_node.key.name)) { |
| 44 | + classNames[array_node.value.value].push(array_node.key.name); |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + }, |
| 50 | + }); |
| 51 | + } catch (e) { |
| 52 | + console.error(`Unable to parse "${file}":`, e); |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +for await (const file of GetRecursiveFilesToFix()) { |
| 57 | + try { |
| 58 | + console.log(file); |
| 59 | + let css = (await readFile(file)).toString(); |
| 60 | + const matches = [...new Set (css.match(classRegex))]; |
| 61 | + if (matches) { |
| 62 | + for (const match of matches) { |
| 63 | + if (classNames.hasOwnProperty(match.slice(1))) { |
| 64 | + css = css.replaceAll( match, `.${classNames[match.slice(1)].join("|")}`); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + await writeFile(file, css); |
| 69 | + } catch (e) { |
| 70 | + console.error(`Unable to fix "${file}":`, e); |
| 71 | + } |
| 72 | +} |
0 commit comments