Skip to content

Commit 4c6635b

Browse files
authored
Add JSDoc types to internal scripts (#5305)
* Add type check for script files * Use script types * Add missing inquirer types
1 parent d56ac63 commit 4c6635b

15 files changed

+319
-50
lines changed

package-lock.json

+20
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@
8181
"test:package": "node scripts/test-package.js",
8282
"test:options": "node scripts/test-options.js",
8383
"test:only": "mocha test/test.js",
84-
"test:typescript": "shx rm -rf test/typescript/dist && shx cp -r dist test/typescript/ && tsc --noEmit -p test/typescript && tsc --noEmit",
84+
"test:typescript": "shx rm -rf test/typescript/dist && shx cp -r dist test/typescript/ && tsc --noEmit -p test/typescript && tsc --noEmit && tsc --noEmit -p scripts",
8585
"test:browser": "mocha test/browser/index.js",
8686
"watch": "rollup --config rollup.config.ts --configPlugin typescript --watch"
8787
},
@@ -125,6 +125,7 @@
125125
"@rollup/plugin-typescript": "11.1.5",
126126
"@rollup/pluginutils": "^5.1.0",
127127
"@types/estree": "1.0.5",
128+
"@types/inquirer": "^9.0.7",
128129
"@types/mocha": "^10.0.6",
129130
"@types/node": "18.0.0",
130131
"@types/yargs-parser": "^21.0.3",

scripts/declarations.d.ts

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
declare module 'github-api' {
2+
export interface Repo {
3+
listPullRequests({ state: string }): Promise<{
4+
data: { number: number; title: string; head: { sha: string } }[];
5+
}>;
6+
7+
getPullRequest(pr: number): Promise<{ data: { body: string; user: { login: string } } }>;
8+
9+
createRelease(release: { body: string; name: string; tag_name: string }): Promise<void>;
10+
}
11+
12+
export interface Issues {
13+
createIssueComment(issueNumber: number, text: string): Promise<void>;
14+
}
15+
16+
export default class GitHub {
17+
constructor({ token: string });
18+
19+
getRepo(organization: string, repository: string): Repo;
20+
21+
getIssues(organization: string, repository: string): Issues;
22+
}
23+
}

scripts/find-config.js

+4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import { readdir } from 'node:fs/promises';
22
import { resolve } from 'node:path';
33

4+
/**
5+
* @param {string} targetDirectory
6+
* @return {Promise<string>}
7+
*/
48
export async function findConfigFileName(targetDirectory) {
59
const filesInWorkingDirectory = new Set(await readdir(targetDirectory));
610
for (const extension of ['mjs', 'cjs', 'ts', 'js']) {

scripts/helpers.js

+26-13
Original file line numberDiff line numberDiff line change
@@ -5,24 +5,32 @@ import { blue, bold, cyan, green, magenta, red, yellow } from './colors.js';
55
const colors = [cyan, yellow, blue, red, green, magenta];
66
let nextColorIndex = 0;
77

8+
/**
9+
* @param {string} command
10+
* @param {string[]} parameters
11+
* @param {Parameters<typeof spawn>[2]=} options
12+
* @return {Promise<void>}
13+
*/
814
export function runWithEcho(command, parameters, options) {
915
const color = colors[nextColorIndex];
1016
nextColorIndex = (nextColorIndex + 1) % colors.length;
11-
return new Promise((resolve, reject) => {
12-
const cmdString = formatCommand(command, parameters);
13-
console.error(bold(`\n${color`Run>`} ${cmdString}`));
17+
return /** @type {Promise<void>} */ (
18+
new Promise((resolve, reject) => {
19+
const cmdString = formatCommand(command, parameters);
20+
console.error(bold(`\n${color('Run>')} ${cmdString}`));
1421

15-
const childProcess = spawn(command, parameters, { stdio: 'inherit', ...options });
22+
const childProcess = spawn(command, parameters, { stdio: 'inherit', ...options });
1623

17-
childProcess.on('close', code => {
18-
if (code) {
19-
reject(new Error(`"${cmdString}" exited with code ${code}.`));
20-
} else {
21-
console.error(bold(`${color`Finished>`} ${cmdString}\n`));
22-
resolve();
23-
}
24-
});
25-
});
24+
childProcess.on('close', code => {
25+
if (code) {
26+
reject(new Error(`"${cmdString}" exited with code ${code}.`));
27+
} else {
28+
console.error(bold(`${color('Finished>')} ${cmdString}\n`));
29+
resolve();
30+
}
31+
});
32+
})
33+
);
2634
}
2735

2836
/**
@@ -48,6 +56,11 @@ export function runAndGetStdout(command, parameters) {
4856
});
4957
}
5058

59+
/**
60+
* @param {string} command
61+
* @param {string[]} parameters
62+
* @return {string}
63+
*/
5164
function formatCommand(command, parameters) {
5265
return [command, ...parameters].join(' ');
5366
}

scripts/perf-init.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,13 @@ rmSync(TARGET_DIR, {
2424
recursive: true
2525
});
2626

27-
const [, repo, , branch] = VALID_REPO.exec(repoWithBranch);
27+
const repoWithBranchMatch = VALID_REPO.exec(repoWithBranch);
28+
if (!repoWithBranchMatch) {
29+
throw new Error('Could not match repository and branch.');
30+
}
31+
const [, repo, , branch] = repoWithBranchMatch;
2832

29-
const gitArguments = ['clone', '--depth', 1, '--progress'];
33+
const gitArguments = ['clone', '--depth', '1', '--progress'];
3034
if (branch) {
3135
console.error(`Cloning branch "${branch}" of "${repo}"...`);
3236
gitArguments.push('--branch', branch);

scripts/perf.js

+96-13
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,14 @@ import { loadConfigFile } from '../dist/loadConfigFile.js';
1111
import { rollup } from '../dist/rollup.js';
1212
import { findConfigFileName } from './find-config.js';
1313

14+
/**
15+
* @typedef {Record<string,{memory:number,time:number}>} PersistedTimings
16+
*/
17+
18+
/**
19+
* @typedef {Record<string, [number, number, number][]>} AccumulatedTimings
20+
*/
21+
1422
const initialDirectory = cwd();
1523
const targetDirectory = fileURLToPath(new URL('../perf', import.meta.url).href);
1624
const perfFile = fileURLToPath(new URL('../perf/rollup.perf.json', import.meta.url).href);
@@ -51,6 +59,12 @@ console.info(
5159

5260
await calculatePrintAndPersistTimings(configs.options[0], await getExistingTimings());
5361

62+
/**
63+
* @param {number[]} times
64+
* @param {number} runs
65+
* @param {number} discarded
66+
* @return {number}
67+
*/
5468
function getSingleAverage(times, runs, discarded) {
5569
const actualDiscarded = Math.min(discarded, runs - 1);
5670
return (
@@ -63,7 +77,16 @@ function getSingleAverage(times, runs, discarded) {
6377
);
6478
}
6579

80+
/**
81+
* @param {AccumulatedTimings} accumulatedMeasurements
82+
* @param {number} runs
83+
* @param {number} discarded
84+
* @return {PersistedTimings}
85+
*/
6686
function getAverage(accumulatedMeasurements, runs, discarded) {
87+
/**
88+
* @type {PersistedTimings}
89+
*/
6790
const average = {};
6891
for (const label of Object.keys(accumulatedMeasurements)) {
6992
average[label] = {
@@ -82,50 +105,80 @@ function getAverage(accumulatedMeasurements, runs, discarded) {
82105
return average;
83106
}
84107

108+
/**
109+
* @param {import('rollup').MergedRollupOptions} config
110+
* @param {PersistedTimings} existingTimings
111+
* @return {Promise<void>}
112+
*/
85113
async function calculatePrintAndPersistTimings(config, existingTimings) {
86-
const timings = await buildAndGetTimings(config);
87-
for (const label of Object.keys(timings)) {
88-
timings[label] = [timings[label]];
114+
const serializedTimings = await buildAndGetTimings(config);
115+
/**
116+
* @type {Record<string, [number, number, number][]>}
117+
*/
118+
const accumulatedTimings = {};
119+
for (const label of Object.keys(serializedTimings)) {
120+
accumulatedTimings[label] = [serializedTimings[label]];
89121
}
90122
for (let currentRun = 1; currentRun < numberOfRunsToAverage; currentRun++) {
91123
const numberOfLinesToClear = printMeasurements(
92-
getAverage(timings, currentRun, numberOfDiscardedResults),
124+
getAverage(accumulatedTimings, currentRun, numberOfDiscardedResults),
93125
existingTimings,
94126
/^#/
95127
);
96128
console.info(`Completed run ${currentRun}.`);
97129
const currentTimings = await buildAndGetTimings(config);
98130
clearLines(numberOfLinesToClear);
99-
for (const label of Object.keys(timings)) {
131+
for (const label of Object.keys(accumulatedTimings)) {
100132
if (currentTimings.hasOwnProperty(label)) {
101-
timings[label].push(currentTimings[label]);
133+
accumulatedTimings[label].push(currentTimings[label]);
102134
} else {
103-
delete timings[label];
135+
delete accumulatedTimings[label];
104136
}
105137
}
106138
}
107-
const averageTimings = getAverage(timings, numberOfRunsToAverage, numberOfDiscardedResults);
139+
const averageTimings = getAverage(
140+
accumulatedTimings,
141+
numberOfRunsToAverage,
142+
numberOfDiscardedResults
143+
);
108144
printMeasurements(averageTimings, existingTimings);
109-
if (Object.keys(existingTimings).length === 0) persistTimings(averageTimings);
145+
if (Object.keys(existingTimings).length === 0) {
146+
persistTimings(averageTimings);
147+
}
110148
}
111149

150+
/**
151+
* @param {import('rollup').MergedRollupOptions} config
152+
* @return {Promise<import('rollup').SerializedTimings>}
153+
*/
112154
async function buildAndGetTimings(config) {
113155
config.perf = true;
114-
if (Array.isArray(config.output)) {
115-
config.output = config.output[0];
116-
}
156+
const output = Array.isArray(config.output) ? config.output[0] : config.output;
157+
// @ts-expect-error garbage collection may not be enabled
117158
gc();
118159
chdir(targetDirectory);
119160
const bundle = await rollup(config);
120161
chdir(initialDirectory);
121-
await bundle.generate(config.output);
162+
await bundle.generate(output);
163+
if (!bundle.getTimings) {
164+
throw new Error('Timings not found in the bundle.');
165+
}
122166
return bundle.getTimings();
123167
}
124168

169+
/**
170+
* @param {PersistedTimings} average
171+
* @param {PersistedTimings} existingAverage
172+
* @param {RegExp} filter
173+
* @return {number}
174+
*/
125175
function printMeasurements(average, existingAverage, filter = /.*/) {
126176
const printedLabels = Object.keys(average).filter(label => filter.test(label));
127177
console.info('');
128178
for (const label of printedLabels) {
179+
/**
180+
* @type {function(string): string}
181+
*/
129182
let color = identity;
130183
if (label[0] === '#') {
131184
color = bold;
@@ -148,10 +201,16 @@ function printMeasurements(average, existingAverage, filter = /.*/) {
148201
return printedLabels.length + 2;
149202
}
150203

204+
/**
205+
* @param {number} numberOfLines
206+
*/
151207
function clearLines(numberOfLines) {
152208
console.info('\u001B[A' + '\u001B[2K\u001B[A'.repeat(numberOfLines));
153209
}
154210

211+
/**
212+
* @return {PersistedTimings}
213+
*/
155214
function getExistingTimings() {
156215
try {
157216
const timings = JSON.parse(readFileSync(perfFile, 'utf8'));
@@ -164,6 +223,9 @@ function getExistingTimings() {
164223
}
165224
}
166225

226+
/**
227+
* @param {PersistedTimings} timings
228+
*/
167229
function persistTimings(timings) {
168230
try {
169231
writeFileSync(perfFile, JSON.stringify(timings, null, 2), 'utf8');
@@ -174,7 +236,15 @@ function persistTimings(timings) {
174236
}
175237
}
176238

239+
/**
240+
* @param {number} currentTime
241+
* @param {number} persistedTime
242+
* @return {string}
243+
*/
177244
function getFormattedTime(currentTime, persistedTime = currentTime) {
245+
/**
246+
* @type {function(string): string}
247+
*/
178248
let color = identity,
179249
formattedTime = `${currentTime.toFixed(0)}ms`;
180250
const absoluteDeviation = Math.abs(currentTime - persistedTime);
@@ -191,7 +261,15 @@ function getFormattedTime(currentTime, persistedTime = currentTime) {
191261
return color(formattedTime);
192262
}
193263

264+
/**
265+
* @param {number} currentMemory
266+
* @param {number} persistedMemory
267+
* @return {string}
268+
*/
194269
function getFormattedMemory(currentMemory, persistedMemory = currentMemory) {
270+
/**
271+
* @type {function(string): string}
272+
*/
195273
let color = identity,
196274
formattedMemory = prettyBytes(currentMemory);
197275
const absoluteDeviation = Math.abs(currentMemory - persistedMemory);
@@ -204,6 +282,11 @@ function getFormattedMemory(currentMemory, persistedMemory = currentMemory) {
204282
return color(formattedMemory);
205283
}
206284

285+
/**
286+
* @template T
287+
* @param {T} x
288+
* @returns {T}
289+
*/
207290
function identity(x) {
208291
return x;
209292
}

0 commit comments

Comments
 (0)