Skip to content

Commit

Permalink
refactor: type fixes (#4326)
Browse files Browse the repository at this point in the history
* make queue readonly

* extract QueueItem type, use array literal, add function return type

* make readqueue readonly, make maxparallel private and pass via constructor

* extract and re-use task type, fix load result return type

* fix source description condition

* make props readonly

* remove unknown from generic parameter

* convert to async function, make types readonly

* fix more queue types

* remove test config file

* remove unneeded type assertion

* add more return types

* re-use getexports method

* remove type import

* more type fixes

* more type fixes

* fix: use generic constraint

* more readonly

* simplify type declaration

* remove truthy check

* clone imports set

* remove type assertion

* remove type declaration

* Improve coverage

Co-authored-by: Lukas Taegert-Atkinson <lukas.taegert-atkinson@tngtech.com>
Co-authored-by: Lukas Taegert-Atkinson <lukastaegert@users.noreply.github.com>
  • Loading branch information
3 people committed Jan 5, 2022
1 parent ae674c9 commit 205e861
Show file tree
Hide file tree
Showing 40 changed files with 296 additions and 265 deletions.
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

0 comments on commit 205e861

Please sign in to comment.