@autobe/compiler
Version:
AI backend server code generator
68 lines (63 loc) • 1.79 kB
text/typescript
import sortImport from "@trivago/prettier-plugin-sort-imports";
import import2 from "import2";
import { format } from "prettier";
import ts from "typescript";
export namespace FilePrinter {
export const description = <Node extends ts.Node>(
node: Node,
comment: string,
): Node => {
if (comment.length === 0) return node;
ts.addSyntheticLeadingComment(
node,
ts.SyntaxKind.MultiLineCommentTrivia,
[
"*",
...comment
.split("\r\n")
.join("\n")
.split("\n")
.map(
(str) =>
` * ${str.split("*/").join("*\\\\/").split("*\\/").join("*\\\\/")}`,
),
"",
].join("\n"),
true,
);
return node;
};
export const newLine = () =>
ts.factory.createExpressionStatement(ts.factory.createIdentifier("\n"));
export const write = (props: {
statements: ts.Statement[];
top?: string;
}): string => {
const script: string = ts
.createPrinter({
newLine: ts.NewLineKind.LineFeed,
})
.printFile(
ts.factory.createSourceFile(
props.statements,
ts.factory.createToken(ts.SyntaxKind.EndOfFileToken),
ts.NodeFlags.None,
),
);
return (props.top ?? "") + script;
};
export const beautify = async (script: string): Promise<string> => {
try {
return await format(script, {
parser: "typescript",
plugins: [sortImport, await import2("prettier-plugin-jsdoc")],
importOrder: ["<THIRD_PARTY_MODULES>", "^[./]"],
importOrderSeparation: true,
importOrderSortSpecifiers: true,
importOrderParserPlugins: ["decorators-legacy", "typescript", "jsx"],
});
} catch {
return script;
}
};
}