clove/code4dyslexia
src/ecmascript_adapter.cjs
// src/ecmascript_adapter.cjs
const fs = require("node:fs");
const ts = require(process.env.C4D_TYPESCRIPT || "typescript");
const anchors = new Set([
ts.SyntaxKind.OpenBraceToken,
ts.SyntaxKind.OpenBracketToken,
ts.SyntaxKind.OpenParenToken,
]);
const closers = new Set([
ts.SyntaxKind.CloseBraceToken,
ts.SyntaxKind.CloseBracketToken,
ts.SyntaxKind.CloseParenToken,
]);
function logical(node) {
return ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)
|| ts.isInterfaceDeclaration(node) || ts.isEnumDeclaration(node)
|| ts.isModuleDeclaration(node) || ts.isBlock(node)
|| ts.isIfStatement(node) || ts.isIterationStatement(node, false)
|| ts.isSwitchStatement(node) || ts.isTryStatement(node);
}
function inspect(tree) {
const shape = [];
const tokens = [];
function walk(node) {
if (ts.isJSDoc(node)) return;
const children = node.getChildren(tree);
shape.push(node.kind);
if (children.length) {
for (const child of children) walk(child);
} else if (node.kind !== ts.SyntaxKind.EndOfFileToken) {
shape.push(node.getText(tree));
tokens.push(node);
}
shape.push(-1);
}
walk(tree);
return { shape: JSON.stringify(shape), tokens };
}
function analyze(request) {
const { source, path } = request;
const scriptKind = /\.[cm]?ts$/i.test(path) ? ts.ScriptKind.TS : ts.ScriptKind.JS;
const parse = (text) => ts.createSourceFile(path, text, ts.ScriptTarget.Latest, false, scriptKind);
const tree = parse(source);
const bytes = (position) => Buffer.byteLength(source.slice(0, position));
if (tree.parseDiagnostics.length) {
const error = tree.parseDiagnostics[0];
return {
error: ts.flattenDiagnosticMessageText(error.messageText, "\n"),
offset: bytes(error.start || 0),
};
}
const { tokens, shape } = inspect(tree);
const edits = [];
const names = [];
const starts = tree.getLineStarts();
const line = (offset) => tree.getLineAndCharacterOfPosition(offset).line;
const bom = source.startsWith("\uFEFF") ? 1 : 0;
const edit = (start, end, replacement, key, message) => {
edits.push({ start, end, replacement, rule: `formatting.${key}`, message });
};
if (request.indent) {
let depth = 0;
let previous = -1;
for (const token of tokens) {
const start = token.getStart(tree);
const row = line(start);
if (closers.has(token.kind)) depth = Math.max(0, depth - 1);
if (row !== previous) {
const prefixStart = Math.max(bom, starts[row]);
const prefix = source.slice(prefixStart, start);
const width = depth * request.indent;
const wanted = " ".repeat(width);
if (prefix !== wanted && /^[ \t]*$/.test(prefix)) {
edit(prefixStart, start, wanted, "indentSize", `Expected ${width} space(s) of indentation`);
}
}
previous = row;
if (anchors.has(token.kind)) depth++;
}
}
function checkName(name, group) {
if (!name) return;
if (ts.isIdentifier(name)) {
names.push([name.getStart(tree), group, name.text]);
} else if (ts.isBindingPattern(name)) {
for (const element of name.elements) {
if (ts.isBindingElement(element)) checkName(element.name, group);
}
}
}
function visit(node) {
if (request.names) {
if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node)) {
checkName(node.name, "functions");
} else if (ts.isClassLike(node)) {
checkName(node.name, "classes");
} else if (ts.isVariableDeclaration(node) || ts.isParameter(node)) {
checkName(node.name, "variables");
}
}
if (request.newlines && (ts.isSourceFile(node) || ts.isBlock(node) || ts.isModuleBlock(node)
|| ts.isCaseClause(node) || ts.isDefaultClause(node))) {
for (let index = 1; index < node.statements.length; index++) {
const left = node.statements[index - 1];
const right = node.statements[index];
if (!logical(left) && !logical(right)) continue;
const end = starts[line(right.getStart(tree))];
const gap = source.slice(left.end, end);
if (!/^[ \t\r\n]+$/.test(gap)) continue;
const breaks = gap.match(/\r\n|\r|\n/g);
if (breaks && breaks.length !== request.newlines) {
edit(left.end, end, breaks[0].repeat(request.newlines), "newLineSize",
`Expected ${request.newlines} newline character(s) between logical blocks`);
}
}
}
ts.forEachChild(node, visit);
}
visit(tree);
if (request.header) {
const comment = "// " + path;
const firstBreak = source.match(/\r\n|\r|\n/);
const shebang = source.startsWith("#!", bom);
const position = shebang ? (firstBreak ? firstBreak.index + firstBreak[0].length : source.length) : bom;
const leading = source.slice(position).match(/^(?:\s|\/\/[^\r\n]*|\/\*[\s\S]*?\*\/)*/)[0];
if (!leading.split(/\r\n|\r|\n/).some((line) => line.trim() === comment)) {
const ending = firstBreak?.[0] || "\n";
edit(position, position, (shebang && !firstBreak ? ending : "") + comment + ending,
"filePathHeader", `Expected file path header ${comment}`);
}
}
edits.sort((left, right) => left.start - right.start || left.end - right.end
|| Number(right.rule.endsWith("Header")) - Number(left.rule.endsWith("Header")));
let cursor = 0;
const chunks = [];
for (const change of edits) {
if (change.start < cursor) return { error: "Formatting produced overlapping edits" };
chunks.push(source.slice(cursor, change.start), change.replacement);
cursor = change.end;
}
chunks.push(source.slice(cursor));
const formatted = chunks.join("");
if (edits.length) {
const proposed = parse(formatted);
if (proposed.parseDiagnostics.length || inspect(proposed).shape !== shape) {
return { error: "Formatting would change the JavaScript or TypeScript syntax tree" };
}
}
const positions = [...new Set([...edits.map((entry) => entry.start), ...names.map(([start]) => start)])]
.sort((left, right) => left - right);
const offsets = new Map();
let previous = 0;
let offset = 0;
for (const position of positions) {
offset += Buffer.byteLength(source.slice(previous, position));
offsets.set(position, offset);
previous = position;
}
return {
formatted,
issues: edits.map(({ start, rule, message }) => ({ offset: offsets.get(start), rule, message })),
names: names.map(([start, group, name]) => [offsets.get(start), group, name]),
};
}
process.stdout.write(JSON.stringify(analyze(JSON.parse(fs.readFileSync(0, "utf8")))));