Skip to content

Commit

Permalink
more type fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
dnalborczyk committed Dec 29, 2021
1 parent 1a6b965 commit 67f74e2
Show file tree
Hide file tree
Showing 18 changed files with 101 additions and 93 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
17 changes: 11 additions & 6 deletions cli/run/batchWarnings.ts
Expand Up @@ -248,17 +248,22 @@ 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>(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];
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
46 changes: 23 additions & 23 deletions src/Chunk.ts
Expand Up @@ -108,7 +108,7 @@ function getGlobalName(
globals: GlobalsOption,
hasExports: boolean,
warn: WarningHandler
) {
): string | undefined {
const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
if (globalName) {
return globalName;
Expand All @@ -126,7 +126,7 @@ function getGlobalName(
}

export default class Chunk {
entryModules: Module[] = [];
readonly entryModules: Module[] = [];
execIndex: number;
exportMode: 'none' | 'named' | 'default' = 'named';
facadeModule: Module | null = null;
Expand All @@ -136,27 +136,27 @@ export default class Chunk {
suggestedVariableName: string;
variableName = '';

private accessedGlobalsByScope = new Map<ChildScope, Set<string>>();
private readonly accessedGlobalsByScope = new Map<ChildScope, Set<string>>();
private dependencies = new Set<ExternalModule | Chunk>();
private dynamicDependencies = new Set<ExternalModule | Chunk>();
private dynamicEntryModules: Module[] = [];
private readonly dynamicDependencies = new Set<ExternalModule | Chunk>();
private readonly dynamicEntryModules: Module[] = [];
private dynamicName: string | null = null;
private exportNamesByVariable = new Map<Variable, string[]>();
private exports = new Set<Variable>();
private exportsByName: Record<string, Variable> = Object.create(null);
private readonly exportNamesByVariable = new Map<Variable, string[]>();
private readonly exports = new Set<Variable>();
private readonly exportsByName: Record<string, Variable> = Object.create(null);
private fileName: string | null = null;
private implicitEntryModules: Module[] = [];
private implicitlyLoadedBefore = new Set<Chunk>();
private imports = new Set<Variable>();
private readonly implicitlyLoadedBefore = new Set<Chunk>();
private readonly imports = new Set<Variable>();
private indentString: string = undefined as never;
private readonly isEmpty: boolean = true;
private isEmpty = true;
private name: string | null = null;
private renderedDependencies: Map<ExternalModule | Chunk, ModuleDeclarationDependency> | null =
null;
private renderedExports: ChunkExports | null = null;
private renderedHash: string = undefined as never;
private renderedModuleSources = new Map<Module, MagicString>();
private renderedModules: {
private renderedHash: string | undefined = undefined;
private readonly renderedModuleSources = new Map<Module, MagicString>();
private readonly renderedModules: {
[moduleId: string]: RenderedModule;
} = Object.create(null);
private renderedSource: MagicStringBundle | null = null;
Expand Down Expand Up @@ -251,7 +251,7 @@ export default class Chunk {
return chunk;
}

canModuleBeFacade(module: Module, exposedVariables: Set<Variable>): boolean {
canModuleBeFacade(module: Module, exposedVariables: ReadonlySet<Variable>): boolean {
const moduleExportNamesByVariable = module.getExportNamesByVariable();
for (const exposedVariable of this.exports) {
if (!moduleExportNamesByVariable.has(exposedVariable)) {
Expand Down Expand Up @@ -429,9 +429,9 @@ export default class Chunk {
preserveModulesRelativeDir: string,
options: NormalizedOutputOptions,
existingNames: Record<string, unknown>,
unsetOptions: Set<string>
unsetOptions: ReadonlySet<string>
): string {
const id = this.orderedModules[0].id;
const [{ id }] = this.orderedModules;
const sanitizedId = this.outputOptions.sanitizeFileName(id);
let path: string;

Expand Down Expand Up @@ -641,7 +641,7 @@ export default class Chunk {
this.renderedSource = magicString.trim();
}

this.renderedHash = undefined as never;
this.renderedHash = undefined;

if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
const chunkName = this.getChunkName();
Expand Down Expand Up @@ -811,9 +811,9 @@ export default class Chunk {
}

private addDependenciesToChunk(
moduleDependencies: Set<Module | ExternalModule>,
moduleDependencies: ReadonlySet<Module | ExternalModule>,
chunkDependencies: Set<Chunk | ExternalModule>
) {
): void {
for (const module of moduleDependencies) {
if (module instanceof Module) {
const chunk = this.chunkByModule.get(module);
Expand All @@ -826,7 +826,7 @@ export default class Chunk {
}
}

private assignFacadeName({ fileName, name }: FacadeName, facadedModule: Module) {
private assignFacadeName({ fileName, name }: FacadeName, facadedModule: Module): void {
if (fileName) {
this.fileName = fileName;
} else {
Expand Down Expand Up @@ -870,7 +870,7 @@ export default class Chunk {
hash.update(
[addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':')
);
hash.update(options.format as string);
hash.update(options.format);
const dependenciesForHashing = new Set<Chunk | ExternalModule>([this]);
for (const current of dependenciesForHashing) {
if (current instanceof ExternalModule) {
Expand Down Expand Up @@ -1306,7 +1306,7 @@ export default class Chunk {
break;
}
}
const usedNames = new Set<string>(['Object', 'Promise']);
const usedNames = new Set(['Object', 'Promise']);
if (this.needsExportsShim) {
usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
}
Expand Down
2 changes: 1 addition & 1 deletion src/ModuleLoader.ts
Expand Up @@ -176,7 +176,7 @@ export class ModuleLoader {
importer: string | undefined,
customOptions: CustomPluginOptions | undefined,
isEntry: boolean | undefined,
skip: { importer: string | undefined; plugin: Plugin; source: string }[] | null = null
skip: readonly { importer: string | undefined; plugin: Plugin; source: string }[] | null = null
): Promise<ResolvedId | null> => {
return this.addDefaultsToResolvedId(
this.getNormalizedResolvedIdWithoutDefaults(
Expand Down
12 changes: 6 additions & 6 deletions src/utils/PluginDriver.ts
Expand Up @@ -69,19 +69,19 @@ function throwInvalidHookError(hookName: string, pluginName: string) {
}

export class PluginDriver {
public emitFile: EmitFile;
public readonly emitFile: EmitFile;
public finaliseAssets: () => void;
public getFileName: (fileReferenceId: string) => string;
public setOutputBundle: (
public readonly setOutputBundle: (
outputBundle: OutputBundleWithPlaceholders,
outputOptions: NormalizedOutputOptions,
facadeChunkByModule: Map<Module, Chunk>
) => void;

private fileEmitter: FileEmitter;
private pluginCache: Record<string, SerializablePluginCache> | undefined;
private pluginContexts = new Map<Plugin, PluginContext>();
private plugins: Plugin[];
private readonly fileEmitter: FileEmitter;
private readonly pluginCache: Record<string, SerializablePluginCache> | undefined;
private readonly pluginContexts = new Map<Plugin, PluginContext>();
private readonly plugins: Plugin[];

constructor(
private readonly graph: Graph,
Expand Down

0 comments on commit 67f74e2

Please sign in to comment.