Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: type fixes #4326

Merged
merged 25 commits into from Jan 5, 2022
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
9c9b191
make queue readonly
dnalborczyk Dec 28, 2021
7579eb3
extract QueueItem type, use array literal, add function return type
dnalborczyk Dec 28, 2021
2643e02
make readqueue readonly, make maxparallel private and pass via constr…
dnalborczyk Dec 28, 2021
c090f47
extract and re-use task type, fix load result return type
dnalborczyk Dec 28, 2021
025c10b
fix source description condition
dnalborczyk Dec 28, 2021
0424454
make props readonly
dnalborczyk Dec 28, 2021
d77fe60
remove unknown from generic parameter
dnalborczyk Dec 28, 2021
031c05f
convert to async function, make types readonly
dnalborczyk Dec 28, 2021
bf20062
fix more queue types
dnalborczyk Dec 28, 2021
3430f18
remove test config file
dnalborczyk Dec 28, 2021
c02018f
remove unneeded type assertion
dnalborczyk Dec 28, 2021
0041dc0
add more return types
dnalborczyk Dec 28, 2021
5318c32
re-use getexports method
dnalborczyk Dec 28, 2021
dd95b3f
remove type import
dnalborczyk Dec 28, 2021
1a6b965
more type fixes
dnalborczyk Dec 29, 2021
67f74e2
more type fixes
dnalborczyk Dec 29, 2021
26944ab
fix: use generic constraint
dnalborczyk Dec 29, 2021
f343a77
more readonly
dnalborczyk Dec 29, 2021
ddcd502
simplify type declaration
dnalborczyk Dec 29, 2021
89fe1fb
remove truthy check
dnalborczyk Dec 29, 2021
faa4528
clone imports set
dnalborczyk Dec 29, 2021
6814d5b
remove type assertion
dnalborczyk Dec 29, 2021
b8de2b6
remove type declaration
dnalborczyk Dec 29, 2021
4f12139
Improve coverage
lukastaegert Jan 5, 2022
940baea
Merge branch 'master' into queue-cleanup-types
lukastaegert Jan 5, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions browser/resolveId.ts
Expand Up @@ -13,9 +13,9 @@ export async function resolveId(
importer: string | undefined,
customOptions: CustomPluginOptions | undefined,
isEntry: boolean | undefined,
skip: { importer: string | undefined; plugin: Plugin; source: string }[] | null
skip: readonly { importer: string | undefined; plugin: Plugin; source: string }[] | null
) => Promise<ResolvedId | null>,
skip: { importer: string | undefined; plugin: Plugin; source: string }[] | null,
skip: readonly { importer: string | undefined; plugin: Plugin; source: string }[] | null,
customOptions: CustomPluginOptions | undefined,
isEntry: boolean
): Promise<ResolveIdResult> {
Expand Down
8 changes: 4 additions & 4 deletions build-plugins/generate-license-file.ts
@@ -1,9 +1,9 @@
import fs from 'fs';
import { readFileSync, writeFileSync } from 'fs';
import { PluginImpl } from 'rollup';
import license, { Dependency, Person } from 'rollup-plugin-license';

function generateLicenseFile(dependencies: Dependency[]) {
const coreLicense = fs.readFileSync('LICENSE-CORE.md');
const coreLicense = readFileSync('LICENSE-CORE.md');
const licenses = new Set();
const dependencyLicenseTexts = dependencies
.sort(({ name: nameA }, { name: nameB }) => (nameA! > nameB! ? 1 : -1))
Expand Down Expand Up @@ -52,9 +52,9 @@ function generateLicenseFile(dependencies: Dependency[]) {
`${Array.from(licenses).join(', ')}\n\n` +
`# Bundled dependencies:\n` +
dependencyLicenseTexts;
const existingLicenseText = fs.readFileSync('LICENSE.md', 'utf8');
const existingLicenseText = readFileSync('LICENSE.md', 'utf8');
if (existingLicenseText !== licenseText) {
fs.writeFileSync('LICENSE.md', licenseText);
writeFileSync('LICENSE.md', licenseText);
console.warn('LICENSE.md updated. You should commit the updated file.');
}
}
Expand Down
19 changes: 12 additions & 7 deletions cli/run/batchWarnings.ts
Expand Up @@ -248,20 +248,25 @@ const deferredHandlers: {
}
};

function title(str: string) {
function title(str: string): void {
stderr(bold(yellow(`(!) ${str}`)));
}

function info(url: string) {
function info(url: string): void {
stderr(gray(url));
}

function nest<T>(array: T[], prop: string) {
const nested: { items: T[]; key: string }[] = [];
const lookup = new Map<string, { items: T[]; key: string }>();
interface Nested<T> {
items: T[];
key: string;
}

function nest<T extends Record<string, any>>(array: readonly T[], prop: string): Nested<T>[] {
const nested: Nested<T>[] = [];
const lookup = new Map<string, Nested<T>>();

for (const item of array) {
const key = (item as any)[prop];
const key = item[prop];
getOrCreate(lookup, key, () => {
const items = {
items: [],
Expand All @@ -275,7 +280,7 @@ function nest<T>(array: T[], prop: string) {
return nested;
}

function showTruncatedWarnings(warnings: RollupWarning[]) {
function showTruncatedWarnings(warnings: readonly RollupWarning[]): void {
const nestedByModule = nest(warnings, 'id');

const displayedByModule = nestedByModule.length > 5 ? nestedByModule.slice(0, 3) : nestedByModule;
Expand Down
5 changes: 4 additions & 1 deletion cli/run/commandPlugins.ts
Expand Up @@ -38,7 +38,10 @@ export async function addPluginsFromCommandOption(
}
}

async function loadAndRegisterPlugin(inputOptions: InputOptions, pluginText: string) {
async function loadAndRegisterPlugin(
inputOptions: InputOptions,
pluginText: string
): Promise<void> {
let plugin: any = null;
let pluginArg: any = undefined;
if (pluginText[0] === '{') {
Expand Down
6 changes: 3 additions & 3 deletions cli/run/getConfigPath.ts
@@ -1,5 +1,5 @@
import { readdirSync } from 'fs';
import * as path from 'path';
import { resolve } from 'path';
import relative from 'require-relative';
import { handleError } from '../logging';

Expand All @@ -8,7 +8,7 @@ const DEFAULT_CONFIG_BASE = 'rollup.config';
export function getConfigPath(commandConfig: string | true): string {
const cwd = process.cwd();
if (commandConfig === true) {
return path.resolve(findConfigFileNameInCwd());
return resolve(findConfigFileNameInCwd());
}
if (commandConfig.slice(0, 5) === 'node:') {
const pkgName = commandConfig.slice(5);
Expand All @@ -28,7 +28,7 @@ export function getConfigPath(commandConfig: string | true): string {
}
}
}
return path.resolve(commandConfig);
return resolve(commandConfig);
}

function findConfigFileNameInCwd(): string {
Expand Down
18 changes: 9 additions & 9 deletions cli/run/loadConfigFile.ts
@@ -1,5 +1,5 @@
import * as fs from 'fs';
import * as path from 'path';
import { realpathSync } from 'fs';
import { extname, isAbsolute } from 'path';
import { pathToFileURL } from 'url';
import * as rollup from '../../src/node-entry';
import { MergedRollupOptions } from '../../src/rollup/types';
Expand All @@ -12,7 +12,7 @@ import { stderr } from '../logging';
import batchWarnings, { BatchWarnings } from './batchWarnings';
import { addCommandPluginsToInputOptions, addPluginsFromCommandOption } from './commandPlugins';

function supportsNativeESM() {
function supportsNativeESM(): boolean {
return Number(/^v(\d+)/.exec(process.version)![1]) >= 13;
}

Expand Down Expand Up @@ -44,7 +44,7 @@ async function loadConfigFile(
fileName: string,
commandOptions: Record<string, unknown>
): Promise<GenericConfigObject[]> {
const extension = path.extname(fileName);
const extension = extname(fileName);

const configFileExport =
commandOptions.configPlugin ||
Expand All @@ -68,7 +68,7 @@ async function getDefaultFromTranspiledConfigFile(
const warnings = batchWarnings();
const inputOptions = {
external: (id: string) =>
(id[0] !== '.' && !path.isAbsolute(id)) || id.slice(-5, id.length) === '.json',
(id[0] !== '.' && !isAbsolute(id)) || id.slice(-5, id.length) === '.json',
input: fileName,
onwarn: warnings.add,
plugins: [],
Expand Down Expand Up @@ -102,9 +102,9 @@ async function getDefaultFromTranspiledConfigFile(
return loadConfigFromBundledFile(fileName, code);
}

async function loadConfigFromBundledFile(fileName: string, bundledCode: string) {
const resolvedFileName = fs.realpathSync(fileName);
const extension = path.extname(resolvedFileName);
async function loadConfigFromBundledFile(fileName: string, bundledCode: string): Promise<unknown> {
const resolvedFileName = realpathSync(fileName);
const extension = extname(resolvedFileName);
const defaultLoader = require.extensions[extension];
require.extensions[extension] = (module: NodeModule, requiredFileName: string) => {
if (requiredFileName === resolvedFileName) {
Expand Down Expand Up @@ -132,7 +132,7 @@ async function loadConfigFromBundledFile(fileName: string, bundledCode: string)
}
}

async function getConfigList(configFileExport: any, commandOptions: any) {
async function getConfigList(configFileExport: any, commandOptions: any): Promise<any[]> {
const config = await (typeof configFileExport === 'function'
? configFileExport(commandOptions)
: configFileExport);
Expand Down
2 changes: 1 addition & 1 deletion cli/run/resetScreen.ts
Expand Up @@ -4,7 +4,7 @@ import { stderr } from '../logging';
const CLEAR_SCREEN = '\u001Bc';

export function getResetScreen(
configs: MergedRollupOptions[],
configs: readonly MergedRollupOptions[],
allowClearScreen: boolean | undefined
): (heading: string) => void {
let clearScreen = allowClearScreen;
Expand Down
14 changes: 7 additions & 7 deletions cli/run/watch-cli.ts
@@ -1,4 +1,4 @@
import fs from 'fs';
import { type FSWatcher, readFileSync } from 'fs';
import chokidar from 'chokidar';
import dateTime from 'date-time';
import ms from 'pretty-ms';
Expand All @@ -22,17 +22,17 @@ export async function watch(command: Record<string, any>): Promise<void> {
let configs: MergedRollupOptions[];
let warnings: BatchWarnings;
let watcher: RollupWatcher;
let configWatcher: fs.FSWatcher;
let configWatcher: FSWatcher;
const configFile = command.config ? getConfigPath(command.config) : null;

onExit(close);
process.on('uncaughtException' as any, close);
process.on('uncaughtException', close);
if (!process.stdin.isTTY) {
process.stdin.on('end', close);
process.stdin.resume();
}

async function loadConfigFromFileAndTrack(configFile: string) {
async function loadConfigFromFileAndTrack(configFile: string): Promise<void> {
let reloadingConfig = false;
let aborted = false;
let configFileData: string | null = null;
Expand All @@ -42,7 +42,7 @@ export async function watch(command: Record<string, any>): Promise<void> {

async function reloadConfigFile() {
try {
const newConfigFileData = fs.readFileSync(configFile, 'utf-8');
const newConfigFileData = readFileSync(configFile, 'utf-8');
if (newConfigFileData === configFileData) {
return;
}
Expand Down Expand Up @@ -83,7 +83,7 @@ export async function watch(command: Record<string, any>): Promise<void> {

const resetScreen = getResetScreen(configs!, isTTY);

function start(configs: MergedRollupOptions[]) {
function start(configs: MergedRollupOptions[]): void {
try {
watcher = rollup.watch(configs as any);
} catch (err: any) {
Expand Down Expand Up @@ -144,7 +144,7 @@ export async function watch(command: Record<string, any>): Promise<void> {
});
}

function close(code: number | null) {
function close(code: number | null): void {
process.removeListener('uncaughtException', close);
// removing a non-existent listener is a no-op
process.stdin.removeListener('end', close);
Expand Down
16 changes: 8 additions & 8 deletions src/Bundle.ts
Expand Up @@ -30,8 +30,8 @@ import { basename, isAbsolute } from './utils/path';
import { timeEnd, timeStart } from './utils/timers';

export default class Bundle {
private facadeChunkByModule = new Map<Module, Chunk>();
private includedNamespaces = new Set<Module>();
private readonly facadeChunkByModule = new Map<Module, Chunk>();
private readonly includedNamespaces = new Set<Module>();

constructor(
private readonly outputOptions: NormalizedOutputOptions,
Expand Down Expand Up @@ -82,7 +82,7 @@ export default class Bundle {
}

private async addFinalizedChunksToBundle(
chunks: Chunk[],
chunks: readonly Chunk[],
inputBase: string,
addons: Addons,
outputBundle: OutputBundleWithPlaceholders,
Expand Down Expand Up @@ -122,11 +122,11 @@ export default class Bundle {
}

private assignChunkIds(
chunks: Chunk[],
chunks: readonly Chunk[],
inputBase: string,
addons: Addons,
bundle: OutputBundleWithPlaceholders
) {
): void {
const entryChunks: Chunk[] = [];
const otherChunks: Chunk[] = [];
for (const chunk of chunks) {
Expand All @@ -137,7 +137,7 @@ export default class Bundle {
}

// make sure entry chunk names take precedence with regard to deconflicting
const chunksForNaming: Chunk[] = entryChunks.concat(otherChunks);
const chunksForNaming = entryChunks.concat(otherChunks);
for (const chunk of chunksForNaming) {
if (this.outputOptions.file) {
chunk.id = basename(this.outputOptions.file);
Expand Down Expand Up @@ -241,7 +241,7 @@ export default class Bundle {
}

private prerenderChunks(
chunks: Chunk[],
chunks: readonly Chunk[],
inputBase: string,
snippets: GenerateCodeSnippets
): void {
Expand All @@ -254,7 +254,7 @@ export default class Bundle {
}
}

function getAbsoluteEntryModulePaths(chunks: Chunk[]): string[] {
function getAbsoluteEntryModulePaths(chunks: readonly Chunk[]): string[] {
const absoluteEntryModulePaths: string[] = [];
for (const chunk of chunks) {
for (const entryModule of chunk.entryModules) {
Expand Down