1 | import { dirname, join } from 'path';
|
---|
2 | import { readFileSync } from 'fs';
|
---|
3 | import hasTypes from 'hastypes';
|
---|
4 | import semver from 'semver';
|
---|
5 | import { execSync } from 'child_process';
|
---|
6 | import { createRequire } from 'module';
|
---|
7 | import { pathToFileURL } from 'url';
|
---|
8 |
|
---|
9 | const packageJSONpath = join(process.cwd(), 'package.json');
|
---|
10 |
|
---|
11 | const require = createRequire(pathToFileURL(packageJSONpath));
|
---|
12 |
|
---|
13 | const { dependencies, devDependencies } = JSON.parse(readFileSync(packageJSONpath));
|
---|
14 |
|
---|
15 | const typesPackagesPresent = Object.entries(devDependencies).filter(([name]) => name.startsWith('@types/'));
|
---|
16 |
|
---|
17 | console.log(`Found ${typesPackagesPresent.length} \`@types/\` packages...`);
|
---|
18 |
|
---|
19 | const typesPackagesToRemove = Promise.all(typesPackagesPresent.filter(([x]) => x !== '@types/node').map(async ([name, version]) => {
|
---|
20 | const actualName = name.replace('@types/', '');
|
---|
21 | let actualVersion;
|
---|
22 | try {
|
---|
23 | actualVersion = JSON.parse(readFileSync(join(process.cwd(), 'node_modules', actualName, 'package.json'))).version;
|
---|
24 | } catch (e) {
|
---|
25 | console.error(e, join(actualName, '/package.json'));
|
---|
26 | return [name, , true];
|
---|
27 | }
|
---|
28 | const expectedVersion = `${semver.major(actualVersion)}.${semver.minor(actualVersion)}`;
|
---|
29 | const specifier = `${actualName}@${expectedVersion}`;
|
---|
30 |
|
---|
31 | return [name, expectedVersion, await hasTypes(specifier)];
|
---|
32 | })).then((x) => x.filter(([, , hasTypes]) => hasTypes === true));// .then((x) => x.map(([name, expectedVersion]) => [name, expectedVersion]));
|
---|
33 |
|
---|
34 | typesPackagesToRemove.then((x) => {
|
---|
35 | console.log(`Found ${x.length} \`@types/\` packages to remove...`);
|
---|
36 | console.log(x);
|
---|
37 | if (x.length > 0) {
|
---|
38 | execSync(`npm uninstall --save ${x.map(([name, version]) => `"${name}@${version}"`).join(' ')}`, { cwd: process.cwd() });
|
---|
39 | }
|
---|
40 | });
|
---|
41 |
|
---|
42 | // const typesPackagesToAdd = Promise.all(
|
---|
43 | // Object.entries(dependencies)
|
---|
44 | // .filter(([name]) => !typesPackagesPresent.includes(`@types/${name}`))
|
---|
45 | // .map(async ([name, version]) => {
|
---|
46 | // const actualVersion = require(`${name}/package.json`).version;
|
---|
47 | // const expectedVersion = `${semver.major(actualVersion)}.${semver.minor(actualVersion)}`;
|
---|
48 | // console.log(specifier);
|
---|
49 | // })
|
---|
50 | // )
|
---|