Fix flow estree type definition (#18437)

This commit is contained in:
fisker Cheung authored and GitHub committed 2025-12-07 16:02:13 +08:00
1 parent 94a8634300
commit 576f952997
4 files changed
+176 -91

No files matched your search

@@ -1,4 +1,7 @@
import fs from "node:fs/promises";
import url from "node:url";
import { codeFrameColumns } from "@babel/code-frame";
import * as ts from "typescript";
import * as prettier from "../index.js";
const PROJECT_ROOT = new URL("../", import.meta.url);
@@ -12,11 +15,7 @@ const FLOW_TYPES_DTS = new URL(
);
let text = await fs.readFile(FLOW_TYPES, "utf8");
text = text.replaceAll("'use strict';", " ");
text = text.replaceAll(/(?<=\n) {2,}\+/gu, " ");
text = text.replaceAll("interface {", "{");
text = text.replaceAll(/: interface extends (\w+)/gu, ": $1 & ");
text = toDts(text);
const getRelativePath = (url) =>
new URL(url).href.slice(PROJECT_ROOT.href.length);
@@ -36,3 +35,65 @@ text = await prettier.format(text, {
});
await fs.writeFile(FLOW_TYPES_DTS, text);
const program = ts.createProgram([url.fileURLToPath(FLOW_TYPES_DTS)], {
strict: true,
});
const diagnostics = ts.getPreEmitDiagnostics(program);
if (diagnostics.length > 0) {
await fs.rm(FLOW_TYPES_DTS);
const [diagnostic] = diagnostics;
const { line, character: column } = ts.getLineAndCharacterOfPosition(
diagnostic.file,
diagnostic.start,
);
throw new Error(
diagnostic.messageText +
":\n" +
codeFrameColumns(
text,
{ start: { line: line + 1, column } },
{
message: `TS${diagnostic.code}: ${diagnostic.messageText}`,
},
),
);
}
function toDts(text) {
// Useless directive
text = text.replaceAll("'use strict';", " ");
// `{+foo: string}` -> `{foo: string}`
text = text.replaceAll(/(?<=\n)(?<indention>[ {2}]+)\+/gu, "$<indention>");
// `{foo: interface {}}` -> `{foo: {}}`
text = text.replaceAll(": interface {", ": {");
// `{foo: interface extends T {}}` -> `{foo: T & {}}`
text = text.replaceAll(
/(?<=: )interface extends (?<type>\w+)(?= \{)/gu,
"$<type> & ",
);
// `$ReadOnlyArray<?T>` -> `ReadonlyArray<T | null>`
text = text.replaceAll(
/\$ReadOnlyArray<\?(\w+)>/gu,
"ReadonlyArray<$1 | null>",
);
// `$ReadOnlyArray<T>` -> `ReadonlyArray<T>`
text = text.replaceAll("$ReadOnlyArray<", "ReadonlyArray<");
// `$ReadOnly<T>` -> `Readonly<T>`
text = text.replaceAll("$ReadOnly<", "Readonly<");
// `{[string]: T}` -> `{[key: string]: T}`
text = text.replaceAll(
/(?<=\n)(?<indention>[ {2}]+)\[(?<type>string)\](?=: )/gu,
"$<indention>[key: $<type>]",
);
return text;
}