Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 1,291 Bytes
89af3b2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | """Read complete JSX nodes, including nested children and arrow-valued attributes."""
import json
from pathlib import Path
import subprocess
WEB = Path(__file__).resolve().parent
PARSER = r"""
const ts = require('typescript');
const fs = require('fs');
const input = JSON.parse(fs.readFileSync(0, 'utf8'));
const source = ts.createSourceFile('contract.tsx', input.source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const nodes = [];
function visit(node) {
const opening = ts.isJsxElement(node) ? node.openingElement : ts.isJsxSelfClosingElement(node) ? node : null;
if (opening && opening.tagName.getText(source) === input.tag) {
nodes.push({start: node.getStart(source), end: node.end, text: node.getText(source),
opening: opening.getText(source), props: opening.attributes.properties.map(p => p.name?.getText(source) ?? '...')});
}
ts.forEachChild(node, visit);
}
visit(source);
process.stdout.write(JSON.stringify(nodes));
"""
def jsx_elements(source: str, tag: str) -> list[dict]:
result = subprocess.run(["node", "-e", PARSER], cwd=WEB,
input=json.dumps({"source": source, "tag": tag}),
capture_output=True, text=True, encoding="utf-8", timeout=20, check=True)
return json.loads(result.stdout)
|