-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate-tsconfig.mjs
146 lines (142 loc) · 5.53 KB
/
update-tsconfig.mjs
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import fs from "node:fs/promises";
import { relative } from "node:path";
import ts from "typescript";
// eslint-disable-next-line no-extra-parens
const filterTruthy = /** @type {<Type>(value: Type) => value is Exclude<Type, null | undefined>} */(Boolean);
/** @type Record<"references", Record<"path", string>[]> */
const projectConfig =
// eslint-disable-next-line no-new-func
new Function(`return ${await fs.readFile("tsconfig.json", "utf8")}`)();
const projectMap = new Map(await Promise.all(
projectConfig.references.map(async ({ path }) => {
const [ packageJsonText, sourceText ] = await Promise.all([
fs.readFile(`${path}/package.json`, "utf8"),
fs.readFile(`${path}/tsconfig.json`, "utf8"),
]);
/** @type {{ name: string; dependencies?: Record<string, string>, exports?: Record<string, { "types"?: string }> }} */
const packageJson = JSON.parse(packageJsonText);
const tsconfig = ts.parseJsonText("tsconfig.json", sourceText);
// eslint-disable-next-line no-new-func
const tsconfigJson = new Function(`return ${sourceText}`)();
const json = tsconfig.statements[0]?.expression;
const positions = function() {
if (json && ts.isObjectLiteralExpression(json)) {
const compilerOptions = json.properties.find(property =>
property.name && ts.isStringLiteral(property.name) && property.name.text === "compilerOptions");
const references = json.properties.find(property =>
property.name && ts.isStringLiteral(property.name) && property.name.text === "references");
if (
references &&
ts.isPropertyAssignment(references) &&
compilerOptions &&
ts.isPropertyAssignment(compilerOptions) &&
ts.isObjectLiteralExpression(compilerOptions.initializer)
) {
const paths = compilerOptions.initializer.properties.find(property =>
property.name && ts.isStringLiteral(property.name) && property.name.text === "paths");
if (paths) {
return {
references: {
start: references.pos,
end: references.end,
},
paths: {
start: paths.pos,
end: paths.end,
},
};
}
}
}
}();
const moduleResolution = tsconfigJson.compilerOptions?.moduleResolution;
const dependencies = Object.keys(packageJson.dependencies ?? {}).sort();
const { name, exports } = packageJson;
/** @type {string} */
const outDir = tsconfigJson.compilerOptions.outDir;
// eslint-disable-next-line no-extra-parens
const entry = /** @type {const} */ ([
name,
{ ...positions, path, exports, outDir, dependencies, moduleResolution, sourceText },
]);
return entry;
}),
));
await Promise.all(function*() {
for (const [ name, { path, dependencies, moduleResolution, sourceText, paths, references } ] of projectMap) {
if (sourceText.includes("@no-automatic-paths")) {
continue;
}
if (paths && references) {
yield async function() {
const pathsEntries = [
...dependencies.filter(dependency => dependency !== name),
name,
]
// eslint-disable-next-line array-callback-return
.flatMap(dependency => {
const record = projectMap.get(dependency);
if (record) {
const { exports, outDir } = record;
if (exports) {
// eslint-disable-next-line array-callback-return
return Object.entries(exports).map(([ specifier, exports ]) => {
const types = exports.types;
const pattern = types && types.replace(`./${outDir}/`, "").replace(/\.d\.ts$/, ".ts");
if (pattern && specifier.startsWith("./")) {
return {
from: `${dependency}/${specifier.slice(2)}`,
to: [ `${relative(path, record.path) || "."}/${pattern}` ],
};
}
});
} else if (moduleResolution === "node" && name === dependency) {
return {
from: `${dependency}/*`,
to: [ "./*.ts", "./*/index.ts" ],
};
}
}
})
.filter(filterTruthy);
const referencesEntries = dependencies
.filter(dependency => dependency !== name)
.map(dependency => projectMap.get(dependency)?.path)
.filter(filterTruthy);
const slices = [
{
start: paths.start,
/** @param text {string} */
fn: text =>
// eslint-disable-next-line indent
`${text.slice(0, paths.start).replace(/(\s+|\/\/.+)$/, "")}
\t\t// vv Generated dependencies, do not modify vv
\t\t"paths": {
${pathsEntries.map(({ from, to }) => `\t\t\t${JSON.stringify(from)}: [ ${to.map(path => JSON.stringify(path)).join(", ")} ],\n`).join("")}\t\t},
\t\t// ^^ Generated dependencies, do not modify ^^
${text.slice(paths.end).replace(/^[,\s]*\n(?:\s+\/\/.+\n)?/, "")}`,
},
{
start: references.start,
/** @param text {string} */
fn: text =>
// eslint-disable-next-line indent
`${text.slice(0, references.start).replace(/(\s+|\/\/.+)$/, "")}
\t// vv Generated dependencies, do not modify vv
\t"references": [
${referencesEntries.map(refPath => `\t\t{ "path": ${JSON.stringify(relative(path, refPath))} },\n`).join("")}\t],
\t// ^^ Generated dependencies, do not modify ^^
${text.slice(references.end).replace(/^[,\s]*\n(?:\s+\/\/.+\n)?/, "")}`,
},
];
slices.sort((left, right) => right.start - left.start);
const modifiedSourceText = slices.reduce((text, { fn }) => fn(text), sourceText);
if (modifiedSourceText !== sourceText) {
await fs.writeFile(`${path}/tsconfig.json`, modifiedSourceText, "utf8");
}
}();
} else if (dependencies.some(dependency => projectMap.has(dependency))) {
console.warn(`⚠️ ${path} has reference dependencies but no "path" or "references" in tsconfig.json`);
}
}
}());