From 551a4c211fbbc8a69f0d19de93e594d1f568c2c7 Mon Sep 17 00:00:00 2001 From: Evan Shaw Date: Wed, 13 Mar 2019 20:11:11 +1300 Subject: [PATCH 1/5] Enable strictNullChecks There were 400 errors to fix and most of the mwere fixed by adding explicit type assertions at every error site. It would be a good idea to go back and clean some of these up later. There are a few places that I changed the logic or the types, which I've tried to point out in the pull request comments. --- src/Chunk.ts | 98 ++++++++++++---------- src/ExternalModule.ts | 4 +- src/Graph.ts | 25 +++--- src/Module.ts | 55 +++++++----- src/ast/CallOptions.ts | 2 +- src/ast/nodes/BinaryExpression.ts | 10 ++- src/ast/nodes/BlockStatement.ts | 1 + src/ast/nodes/BreakStatement.ts | 2 +- src/ast/nodes/CallExpression.ts | 10 +-- src/ast/nodes/ConditionalExpression.ts | 8 +- src/ast/nodes/ExportAllDeclaration.ts | 2 +- src/ast/nodes/ExportDefaultDeclaration.ts | 11 ++- src/ast/nodes/ExportNamedDeclaration.ts | 4 +- src/ast/nodes/Identifier.ts | 2 +- src/ast/nodes/IfStatement.ts | 4 +- src/ast/nodes/Import.ts | 7 +- src/ast/nodes/ImportDeclaration.ts | 2 +- src/ast/nodes/LogicalExpression.ts | 10 +-- src/ast/nodes/MemberExpression.ts | 62 ++++++++------ src/ast/nodes/ObjectExpression.ts | 65 +++++++------- src/ast/nodes/Program.ts | 1 + src/ast/nodes/Property.ts | 24 ++++-- src/ast/nodes/ReturnStatement.ts | 2 +- src/ast/nodes/SequenceExpression.ts | 2 +- src/ast/nodes/ThisExpression.ts | 2 +- src/ast/nodes/UnaryExpression.ts | 6 +- src/ast/nodes/VariableDeclaration.ts | 13 +-- src/ast/nodes/YieldExpression.ts | 2 +- src/ast/nodes/shared/ClassNode.ts | 2 +- src/ast/nodes/shared/FunctionNode.ts | 2 +- src/ast/scopes/ReturnValueScope.ts | 2 +- src/ast/scopes/Scope.ts | 6 -- src/ast/values.ts | 8 +- src/ast/variables/ExportDefaultVariable.ts | 10 ++- src/ast/variables/LocalVariable.ts | 24 +++--- src/ast/variables/NamespaceVariable.ts | 2 +- src/chunk-optimization.ts | 2 +- src/finalisers/amd.ts | 4 +- src/finalisers/cjs.ts | 4 +- src/finalisers/iife.ts | 18 ++-- src/finalisers/shared/setupNamespace.ts | 2 +- src/finalisers/system.ts | 4 +- src/finalisers/umd.ts | 35 ++++---- src/rollup/index.ts | 30 ++++--- src/utils/addons.ts | 4 +- src/utils/assetHooks.ts | 24 +++--- src/utils/assignChunkIds.ts | 2 +- src/utils/chunkColouring.ts | 4 +- src/utils/collapseSourcemaps.ts | 14 +++- src/utils/deconflictChunk.ts | 6 +- src/utils/defaultPlugin.ts | 6 +- src/utils/executionOrder.ts | 2 +- src/utils/getIndentString.ts | 2 +- src/utils/mergeOptions.ts | 4 +- src/utils/pluginDriver.ts | 28 ++++--- src/utils/renderHelpers.ts | 4 +- src/utils/timers.ts | 6 +- src/utils/transform.ts | 4 +- src/watch/chokidar.ts | 2 +- src/watch/fileWatchers.ts | 4 +- src/watch/index.ts | 16 ++-- tsconfig.json | 1 + 62 files changed, 406 insertions(+), 318 deletions(-) diff --git a/src/Chunk.ts b/src/Chunk.ts index b278a01ba34..efaba302d91 100644 --- a/src/Chunk.ts +++ b/src/Chunk.ts @@ -112,20 +112,20 @@ export default class Chunk { facadeModule: Module | null = null; graph: Graph; hasDynamicImport: boolean = false; - id: string = undefined; - indentString: string = undefined; + id: string = undefined as any; + indentString: string = undefined as any; isEmpty: boolean; isManualChunk: boolean = false; orderedModules: Module[]; renderedModules: { [moduleId: string]: RenderedModule; }; - usedModules: Module[] = undefined; + usedModules: Module[] = undefined as any; variableName: string; private chunkName: string | void; - private dependencies: (ExternalModule | Chunk)[] = undefined; - private dynamicDependencies: (ExternalModule | Chunk)[] = undefined; + private dependencies: (ExternalModule | Chunk)[] = undefined as any; + private dynamicDependencies: (ExternalModule | Chunk)[] = undefined as any; private exportNames: { [name: string]: Variable } = Object.create(null); private exports = new Set(); private imports = new Set(); @@ -133,11 +133,11 @@ export default class Chunk { private renderedDeclarations: { dependencies: ChunkDependencies; exports: ChunkExports; - } = undefined; - private renderedHash: string = undefined; - private renderedModuleSources: MagicString[] = undefined; + } = undefined as any; + private renderedHash: string = undefined as any; + private renderedModuleSources: MagicString[] = undefined as any; private renderedSource: MagicStringBundle | null = null; - private renderedSourceLength: number = undefined; + private renderedSourceLength: number = undefined as any; constructor(graph: Graph, orderedModules: Module[]) { this.graph = graph; @@ -217,6 +217,7 @@ export default class Chunk { case 'name': return this.getChunkName(); } + return undefined as any; }), existingNames ); @@ -291,7 +292,7 @@ export default class Chunk { Object.keys(this.exportNames) .map(exportName => { const variable = this.exportNames[exportName]; - return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${ + return `${relativeId((variable.module as Module).id).replace(/\\/g, '/')}:${ variable.name }:${exportName}`; }) @@ -302,7 +303,7 @@ export default class Chunk { getRenderedSourceLength() { if (this.renderedSourceLength !== undefined) return this.renderedSourceLength; - return (this.renderedSourceLength = this.renderedSource.length()); + return (this.renderedSourceLength = (this.renderedSource as MagicStringBundle).length()); } getVariableExportName(variable: Variable) { @@ -341,7 +342,7 @@ export default class Chunk { } for (const variable of Array.from(chunk.imports)) { - if (!this.imports.has(variable) && variable.module.chunk !== this) { + if (!this.imports.has(variable) && (variable.module as Module).chunk !== this) { this.imports.add(variable); } } @@ -365,12 +366,14 @@ export default class Chunk { ) => { if (dep.imports) { for (const impt of dep.imports) { - impt.imported = this.getVariableExportName(oldExportNames[impt.imported]); + impt.imported = this.getVariableExportName(oldExportNames[impt.imported]) as string; } } if (dep.reexports) { for (const reexport of dep.reexports) { - reexport.imported = this.getVariableExportName(oldExportNames[reexport.imported]); + reexport.imported = this.getVariableExportName( + oldExportNames[reexport.imported] + ) as string; } } }; @@ -405,7 +408,7 @@ export default class Chunk { // go through the other chunks and update their dependencies // also update their import and reexport names in the process for (const c of chunkList) { - let includedDeclaration: ModuleDeclarationDependency; + let includedDeclaration: ModuleDeclarationDependency = undefined as any; for (let i = 0; i < c.dependencies.length; i++) { const dep = c.dependencies[i]; if ((dep === chunk || dep === this) && includedDeclaration) { @@ -444,9 +447,9 @@ export default class Chunk { const _ = options.compact ? '' : ' '; const renderOptions: RenderOptions = { - compact: options.compact, - dynamicImportFunction: options.dynamicImportFunction, - format: options.format, + compact: options.compact as boolean, + dynamicImportFunction: options.dynamicImportFunction as string, + format: options.format as string, freeze: options.freeze !== false, indent: this.indentString, namespaceToStringTag: options.namespaceToStringTag === true, @@ -455,7 +458,9 @@ export default class Chunk { // Make sure the direct dependencies of a chunk are present to maintain execution order for (const { module } of Array.from(this.imports)) { - const chunkOrExternal = module instanceof Module ? module.chunk : module; + const chunkOrExternal = (module instanceof Module ? module.chunk : module) as + | Chunk + | ExternalModule; if (this.dependencies.indexOf(chunkOrExternal) === -1) { this.dependencies.push(chunkOrExternal); } @@ -526,8 +531,8 @@ export default class Chunk { this.renderedSource = magicString.trim(); } - this.renderedSourceLength = undefined; - this.renderedHash = undefined; + this.renderedSourceLength = undefined as any; + this.renderedHash = undefined as any; if (this.getExportNames().length === 0 && this.getImportIds().length === 0 && this.isEmpty) { this.graph.warn({ @@ -550,7 +555,7 @@ export default class Chunk { if (!this.renderedSource) throw new Error('Internal error: Chunk render called before preRender'); - const finalise = finalisers[options.format]; + const finalise = finalisers[options.format as string]; if (!finalise) { error({ code: 'INVALID_OPTION', @@ -588,7 +593,7 @@ export default class Chunk { const hasExports = this.renderedDeclarations.exports.length !== 0 || this.renderedDeclarations.dependencies.some( - dep => dep.reexports && dep.reexports.length !== 0 + dep => (dep.reexports && dep.reexports.length !== 0) as boolean ); const usesTopLevelAwait = this.orderedModules.some(module => module.usesTopLevelAwait); @@ -609,11 +614,11 @@ export default class Chunk { exports: this.renderedDeclarations.exports, hasExports, indentString: this.indentString, - intro: addons.intro, + intro: addons.intro as string, isEntryModuleFacade: this.facadeModule !== null && this.facadeModule.isEntryPoint, namedExportsMode: this.exportMode !== 'default', needsAmdModule, - outro: addons.outro, + outro: addons.outro as string, usesTopLevelAwait, varOrConst: options.preferConst ? 'const' : 'var', warn: this.graph.warn.bind(this.graph) @@ -626,7 +631,7 @@ export default class Chunk { timeEnd('render format', 3); - let map: SourceMap = null; + let map: SourceMap = null as any; const chunkSourcemapChain: RawSourceMap[] = []; return renderChunk({ @@ -653,7 +658,7 @@ export default class Chunk { decodedMap, this.usedModules, chunkSourcemapChain, - options.sourcemapExcludeSources + options.sourcemapExcludeSources as boolean ); } else { map = magicString.generateMap({ file, includeContent: !options.sourcemapExcludeSources }); @@ -680,7 +685,7 @@ export default class Chunk { this.facadeModule = facadedModule; facadedModule.facadeChunk = this; for (const exportName of facadedModule.getAllExports()) { - const tracedVariable = facadedModule.getVariableForExportName(exportName); + const tracedVariable = facadedModule.getVariableForExportName(exportName) as Variable; this.exports.add(tracedVariable); this.exportNames[exportName] = tracedVariable; } @@ -706,7 +711,7 @@ export default class Chunk { ): boolean { const seen = new Set(); function visitDep(dep: Chunk | ExternalModule): boolean { - if (seen.has(dep)) return; + if (seen.has(dep)) return false; seen.add(dep); if (dep instanceof Chunk) { for (const subDep of dep.dependencies) { @@ -792,7 +797,14 @@ export default class Chunk { const module = this.orderedModules[i]; const code = this.renderedModuleSources[i]; for (const importMeta of module.importMetas) { - if (importMeta.renderFinalMechanism(code, this.id, options.format, options.compact)) + if ( + importMeta.renderFinalMechanism( + code, + this.id, + options.format as string, + options.compact as boolean + ) + ) usesMechanism = true; } } @@ -818,7 +830,7 @@ export default class Chunk { if (!module || module.chunk === this) continue; if (module instanceof Module) { exportModule = module.chunk; - importName = module.chunk.getVariableExportName(variable); + importName = module.chunk.getVariableExportName(variable) as string; } else { exportModule = module; importName = variable.name; @@ -838,7 +850,7 @@ export default class Chunk { for (const variable of importsAsArray) { const renderedVariable = variable instanceof ExportDefaultVariable && variable.referencesOriginal() - ? variable.getOriginalVariable() + ? (variable.getOriginalVariable() as Variable) : variable; if ( (variable.module instanceof Module @@ -851,8 +863,8 @@ export default class Chunk { const imported = variable.module instanceof ExternalModule ? variable.name - : variable.module.chunk.getVariableExportName(variable); - imports.push({ local, imported }); + : (variable.module as Module).chunk.getVariableExportName(variable); + imports.push({ local, imported: imported as string }); } } @@ -869,17 +881,17 @@ export default class Chunk { namedExportsMode = dep.exportMode !== 'default'; } - let id: string; - let globalName: string; + let id: string = undefined as any; + let globalName: string = undefined as any; if (dep instanceof ExternalModule) { id = dep.setRenderPath(options, inputBase); if (options.format === 'umd' || options.format === 'iife') { globalName = getGlobalName( dep, - options.globals, + options.globals as GlobalsOption, this.graph, exportsNames || exportsDefault - ); + ) as string; } } @@ -888,7 +900,7 @@ export default class Chunk { exportsNames, globalName, id, // chunk id updated on render - imports: imports.length > 0 ? imports : null, + imports: imports.length > 0 ? imports : (null as any), isChunk: !(dep).isExternal, name: dep.variableName, namedExportsMode, @@ -1022,7 +1034,7 @@ export default class Chunk { this.dependencies, this.imports, usedNames, - options.format, + options.format as string, options.interop !== false, this.graph.preserveModules ); @@ -1030,7 +1042,7 @@ export default class Chunk { private setUpModuleImports(module: Module) { for (const variable of Array.from(module.imports)) { - if (variable.module.chunk !== this) { + if ((variable.module as Module).chunk !== this) { this.imports.add(variable); if (variable.module instanceof Module) { variable.module.chunk.exports.add(variable); @@ -1040,8 +1052,8 @@ export default class Chunk { if (module.getOrCreateNamespace().included) { for (const reexportName of Object.keys(module.reexports)) { const reexport = module.reexports[reexportName]; - const variable = reexport.module.getVariableForExportName(reexport.localName); - if (variable.module.chunk !== this) { + const variable = reexport.module.getVariableForExportName(reexport.localName) as Variable; + if ((variable.module as Module).chunk !== this) { this.imports.add(variable); if (variable.module instanceof Module) { variable.module.chunk.exports.add(variable); diff --git a/src/ExternalModule.ts b/src/ExternalModule.ts index 0b5dae5f44c..ebebb1460e7 100644 --- a/src/ExternalModule.ts +++ b/src/ExternalModule.ts @@ -17,7 +17,7 @@ export default class ExternalModule { mostCommonSuggestion: number = 0; nameSuggestions: { [name: string]: number }; reexported: boolean = false; - renderPath: string = undefined; + renderPath: string = undefined as any; renormalizeRenderPath = false; used = false; variableName: string; @@ -30,7 +30,7 @@ export default class ExternalModule { this.execIndex = Infinity; const parts = id.split(/[\\/]/); - this.variableName = makeLegal(parts.pop()); + this.variableName = makeLegal(parts.pop() as string); this.nameSuggestions = Object.create(null); this.declarations = Object.create(null); diff --git a/src/Graph.ts b/src/Graph.ts index 3a3050a4975..240695dc2b1 100644 --- a/src/Graph.ts +++ b/src/Graph.ts @@ -92,9 +92,9 @@ export default class Graph { for (const key of Object.keys(cache)) cache[key][0]++; } } - this.preserveModules = options.preserveModules; + this.preserveModules = options.preserveModules as boolean; - this.cacheExpiry = options.experimentalCacheExpiry; + this.cacheExpiry = options.experimentalCacheExpiry as number; if (!options.input) { throw new Error('You must supply options.input to rollup'); @@ -152,7 +152,7 @@ export default class Graph { this.isExternal = id => ids.has(id); } - this.shimMissingExports = options.shimMissingExports; + this.shimMissingExports = options.shimMissingExports as boolean; this.scope = new GlobalScope(); this.context = String(options.context); @@ -391,7 +391,9 @@ export default class Graph { if (warning.plugin) str += `(${warning.plugin} plugin) `; if (warning.loc) - str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `; + str += `${relativeId(warning.loc.file as string)} (${warning.loc.line}:${ + warning.loc.column + }) `; str += warning.message; return str; @@ -501,7 +503,7 @@ export default class Graph { return cachedModule; } - return transform(this, sourceDescription, module); + return transform(this, sourceDescription, module) as Promise; }) .then((source: ModuleJSON) => { module.setSource(source); @@ -518,7 +520,7 @@ export default class Graph { module.exportAllSources.forEach(source => { const id = module.resolvedIds[source].id; const exportAllModule = this.moduleById.get(id); - if (exportAllModule.isExternal) return; + if ((exportAllModule as Module | ExternalModule).isExternal) return; for (const name in (exportAllModule).exportsAll) { if (name in module.exportsAll) { @@ -592,7 +594,7 @@ export default class Graph { const entryModules = entryAndChunkModules.slice(0, entryModuleIds.length); - let manualChunkModules: { [chunkName: string]: Module[] }; + let manualChunkModules: { [chunkName: string]: Module[] } = undefined as any; if (manualChunks) { manualChunkModules = {}; for (const chunkName of Object.keys(manualChunks)) { @@ -627,7 +629,7 @@ export default class Graph { }); } - return this.fetchModule(id, undefined); + return this.fetchModule(id, undefined as any); }); } @@ -689,6 +691,7 @@ export default class Graph { )}, but is already an existing non-external module id.` }); } + return (undefined as any) as Module; } else { return this.fetchModule(resolvedId.id, module.id); } @@ -701,16 +704,16 @@ export default class Graph { const importDescription = module.importDescriptions[importName]; if ( importDescription.name !== '*' && - !importDescription.module.getVariableForExportName(importDescription.name) + !(importDescription.module as Module).getVariableForExportName(importDescription.name) ) { module.warn( { code: 'NON_EXISTENT_EXPORT', message: `Non-existent export '${ importDescription.name - }' is imported from ${relativeId(importDescription.module.id)}`, + }' is imported from ${relativeId((importDescription.module as Module).id)}`, name: importDescription.name, - source: importDescription.module.id + source: (importDescription.module as Module).id }, importDescription.start ); diff --git a/src/Module.ts b/src/Module.ts index f46913dd9d3..38c26441b75 100644 --- a/src/Module.ts +++ b/src/Module.ts @@ -2,11 +2,14 @@ import * as acorn from 'acorn'; import * as ESTree from 'estree'; import { locate } from 'locate-character'; import MagicString from 'magic-string'; +import ClassDeclaration from './ast/nodes/ClassDeclaration'; import ExportAllDeclaration from './ast/nodes/ExportAllDeclaration'; import ExportDefaultDeclaration, { isExportDefaultDeclaration } from './ast/nodes/ExportDefaultDeclaration'; import ExportNamedDeclaration from './ast/nodes/ExportNamedDeclaration'; +import FunctionDeclaration from './ast/nodes/FunctionDeclaration'; +import Identifier from './ast/nodes/Identifier'; import Import from './ast/nodes/Import'; import ImportDeclaration from './ast/nodes/ImportDeclaration'; import ImportSpecifier from './ast/nodes/ImportSpecifier'; @@ -17,6 +20,7 @@ import * as NodeType from './ast/nodes/NodeType'; import Program from './ast/nodes/Program'; import { Node, NodeBase } from './ast/nodes/shared/Node'; import { isTemplateLiteral } from './ast/nodes/TemplateLiteral'; +import VariableDeclaration from './ast/nodes/VariableDeclaration'; import ModuleScope from './ast/scopes/ModuleScope'; import { EntityPathTracker } from './ast/utils/EntityPathTracker'; import extractNames from './ast/utils/extractNames'; @@ -153,7 +157,7 @@ function handleMissingExport( message: `'${exportName}' is not exported by ${relativeId(importedModule)}`, url: `https://rollupjs.org/guide/en#error-name-is-not-exported-by-module-` }, - importerStart + importerStart as number ); } @@ -163,7 +167,7 @@ const MISSING_EXPORT_SHIM_DESCRIPTION: ExportDescription = { export default class Module { chunk: Chunk; - chunkAlias: string = undefined; + chunkAlias: string = undefined as any; code: string; comments: CommentDescription[] = []; customTransformCache: boolean; @@ -178,7 +182,7 @@ export default class Module { entryPointsHash: Uint8Array = new Uint8Array(10); excludeFromSourcemap: boolean; execIndex: number = Infinity; - exportAllModules: (Module | ExternalModule)[] = null; + exportAllModules: (Module | ExternalModule)[] = null as any; exportAllSources: string[] = []; exports: { [name: string]: ExportDescription } = Object.create(null); exportsAll: { [name: string]: string } = Object.create(null); @@ -208,7 +212,7 @@ export default class Module { private esTreeAst: ESTree.Program; private graph: Graph; private magicString: MagicString; - private namespaceVariable: NamespaceVariable = undefined; + private namespaceVariable: NamespaceVariable = undefined as any; private transformDependencies: string[]; constructor(graph: Graph, id: string) { @@ -248,7 +252,7 @@ export default class Module { message: `Error when using sourcemap for reporting an error: ${e.message}`, pos }, - undefined + undefined as any ); } @@ -294,6 +298,7 @@ export default class Module { } else { return importArgument; } + return undefined as any; }); } @@ -393,6 +398,7 @@ export default class Module { this.shimMissingExport(name); return this.exportShimVariable; } + return undefined as any; } include(): void { @@ -410,7 +416,7 @@ export default class Module { } for (const exportName of this.getExports()) { - const variable = this.getVariableForExportName(exportName); + const variable = this.getVariableForExportName(exportName) as Variable; variable.deoptimizePath(UNKNOWN_PATH); if (!variable.included) { @@ -420,7 +426,7 @@ export default class Module { } for (const name of this.getReexports()) { - const variable = this.getVariableForExportName(name); + const variable = this.getVariableForExportName(name) as Variable; if (variable.isExternal) { variable.reexported = (variable).module.reexported = true; @@ -460,7 +466,7 @@ export default class Module { this.exportAllModules = this.exportAllSources.map(source => { const id = this.resolvedIds[source].id; - return this.graph.moduleById.get(id); + return this.graph.moduleById.get(id) as any; }); } @@ -485,14 +491,12 @@ export default class Module { this.originalCode = originalCode; this.originalSourcemap = originalSourcemap; this.sourcemapChain = sourcemapChain; - this.transformDependencies = transformDependencies; + this.transformDependencies = transformDependencies as string[]; this.customTransformCache = customTransformCache; timeStart('generate ast', 3); - this.esTreeAst = ( - (ast || tryParse(this, this.graph.acornParser, this.graph.acornOptions)) - ); + this.esTreeAst = ast || tryParse(this, this.graph.acornParser, this.graph.acornOptions); markPureCallExpressions(this.comments, this.esTreeAst); timeEnd('generate ast', 3); @@ -504,7 +508,7 @@ export default class Module { const fileName = this.id; this.magicString = new MagicString(code, { - filename: this.excludeFromSourcemap ? null : fileName, // don't include plugin helpers in sourcemap + filename: (this.excludeFromSourcemap ? null : fileName) as string, // don't include plugin helpers in sourcemap indentExclusionRanges: [] }); this.removeExistingSourceMap(); @@ -529,7 +533,8 @@ export default class Module { importDescriptions: this.importDescriptions, includeDynamicImport: this.includeDynamicImport.bind(this), includeVariable: this.includeVariable.bind(this), - isCrossChunkImport: importDescription => importDescription.module.chunk !== this.chunk, + isCrossChunkImport: importDescription => + (importDescription.module as Module).chunk !== this.chunk, magicString: this.magicString, module: this, moduleContext: this.context, @@ -577,7 +582,7 @@ export default class Module { if (name in this.importDescriptions) { const importDeclaration = this.importDescriptions[name]; - const otherModule = importDeclaration.module; + const otherModule = importDeclaration.module as Module | ExternalModule; if (!otherModule.isExternal && importDeclaration.name === '*') { return (otherModule).getOrCreateNamespace(); @@ -610,7 +615,7 @@ export default class Module { } private addDynamicImport(node: Import) { - this.dynamicImports.push({ node, alias: undefined, resolution: undefined }); + this.dynamicImports.push({ node, alias: undefined as any, resolution: undefined }); } private addExport( @@ -642,7 +647,7 @@ export default class Module { this.reexports[name] = { localName: specifier.local.name, - module: null, // filled in later, + module: null as any, // filled in later, source, start: specifier.start }; @@ -663,7 +668,7 @@ export default class Module { } this.exports.default = { - identifier: node.variable.getOriginalVariableName(), + identifier: node.variable.getOriginalVariableName() as string | undefined, localName: 'default', node }; @@ -672,7 +677,10 @@ export default class Module { // export var foo = 42; // export var a = 1, b = 2, c = 3; // export function foo () {} - const declaration = (node).declaration; + const declaration = (node).declaration as + | FunctionDeclaration + | ClassDeclaration + | VariableDeclaration; if (declaration.type === NodeType.VariableDeclaration) { for (const decl of declaration.declarations) { @@ -682,7 +690,7 @@ export default class Module { } } else { // export function foo () {} - const localName = declaration.id.name; + const localName = (declaration.id as Identifier).name; this.exports[localName] = { localName, node }; } } else { @@ -746,13 +754,14 @@ export default class Module { for (const name of Object.keys(specifiers)) { const specifier = specifiers[name]; const id = this.resolvedIds[specifier.source].id; - specifier.module = this.graph.moduleById.get(id); + specifier.module = this.graph.moduleById.get(id) as Module | ExternalModule | null; } } private includeDynamicImport(node: Import) { - const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node) - .resolution; + const resolution = (this.dynamicImports.find(dynamicImport => dynamicImport.node === node) as { + resolution: string | Module | ExternalModule | undefined; + }).resolution; if (resolution instanceof Module) { resolution.dynamicallyImportedBy.push(this); resolution.includeAllExports(); diff --git a/src/ast/CallOptions.ts b/src/ast/CallOptions.ts index 9f795869e40..6a29388fca2 100644 --- a/src/ast/CallOptions.ts +++ b/src/ast/CallOptions.ts @@ -27,7 +27,7 @@ export default class CallOptions implements CallCreateOptions { withNew: boolean; constructor( - { withNew = false, args = [], callIdentifier = undefined }: CallCreateOptions = {} as any + { withNew = false, args = [], callIdentifier = undefined as any }: CallCreateOptions = {} as any ) { this.withNew = withNew; this.args = args; diff --git a/src/ast/nodes/BinaryExpression.ts b/src/ast/nodes/BinaryExpression.ts index ed3a95da6de..18512b209c7 100644 --- a/src/ast/nodes/BinaryExpression.ts +++ b/src/ast/nodes/BinaryExpression.ts @@ -19,13 +19,15 @@ const binaryOperators: { '+': (left: any, right: any) => left + right, '-': (left: any, right: any) => left - right, '/': (left: any, right: any) => left / right, - '<': (left, right) => left < right, + '<': (left, right) => (left as NonNullable) < (right as NonNullable), '<<': (left: any, right: any) => left << right, - '<=': (left, right) => left <= right, + '<=': (left, right) => + (left as NonNullable) <= (right as NonNullable), '==': (left, right) => left == right, '===': (left, right) => left === right, - '>': (left, right) => left > right, - '>=': (left, right) => left >= right, + '>': (left, right) => (left as NonNullable) > (right as NonNullable), + '>=': (left, right) => + (left as NonNullable) >= (right as NonNullable), '>>': (left: any, right: any) => left >> right, '>>>': (left: any, right: any) => left >>> right, '^': (left: any, right: any) => left ^ right, diff --git a/src/ast/nodes/BlockStatement.ts b/src/ast/nodes/BlockStatement.ts index 8385331c84d..16b73a63b6b 100644 --- a/src/ast/nodes/BlockStatement.ts +++ b/src/ast/nodes/BlockStatement.ts @@ -33,6 +33,7 @@ export default class BlockStatement extends StatementBase { for (const node of this.body) { if (node.hasEffects(options)) return true; } + return false; } include(includeAllChildrenRecursively: boolean) { diff --git a/src/ast/nodes/BreakStatement.ts b/src/ast/nodes/BreakStatement.ts index 19967fdc6f2..84dc8e366ef 100644 --- a/src/ast/nodes/BreakStatement.ts +++ b/src/ast/nodes/BreakStatement.ts @@ -11,7 +11,7 @@ export default class BreakStatement extends StatementBase { return ( super.hasEffects(options) || !options.ignoreBreakStatements() || - (this.label && !options.ignoreLabel(this.label.name)) + !!(this.label && !options.ignoreLabel(this.label.name)) ); } } diff --git a/src/ast/nodes/CallExpression.ts b/src/ast/nodes/CallExpression.ts index b69dfb02e48..c25d203dfbc 100644 --- a/src/ast/nodes/CallExpression.ts +++ b/src/ast/nodes/CallExpression.ts @@ -165,7 +165,7 @@ export default class CallExpression extends NodeBase implements DeoptimizableEnt return ( path.length > 0 && !options.hasReturnExpressionBeenAccessedAtPath(path, this) && - this.returnExpression.hasEffectsWhenAccessedAtPath( + (this.returnExpression as ExpressionEntity).hasEffectsWhenAccessedAtPath( path, options.addAccessedReturnExpressionAtPath(path, this) ) @@ -176,7 +176,7 @@ export default class CallExpression extends NodeBase implements DeoptimizableEnt return ( path.length === 0 || (!options.hasReturnExpressionBeenAssignedAtPath(path, this) && - this.returnExpression.hasEffectsWhenAssignedAtPath( + (this.returnExpression as ExpressionEntity).hasEffectsWhenAssignedAtPath( path, options.addAssignedReturnExpressionAtPath(path, this) )) @@ -189,7 +189,7 @@ export default class CallExpression extends NodeBase implements DeoptimizableEnt options: ExecutionPathOptions ): boolean { if (options.hasReturnExpressionBeenCalledAtPath(path, this)) return false; - return this.returnExpression.hasEffectsWhenCalledAtPath( + return (this.returnExpression as ExpressionEntity).hasEffectsWhenCalledAtPath( path, callOptions, options.addCalledReturnExpressionAtPath(path, this) @@ -198,8 +198,8 @@ export default class CallExpression extends NodeBase implements DeoptimizableEnt include(includeAllChildrenRecursively: boolean) { super.include(includeAllChildrenRecursively); - if (!this.returnExpression.included) { - this.returnExpression.include(false); + if (!(this.returnExpression as ExpressionEntity).included) { + (this.returnExpression as ExpressionEntity).include(false); } } diff --git a/src/ast/nodes/ConditionalExpression.ts b/src/ast/nodes/ConditionalExpression.ts index 89b45624ccd..5069b3350c5 100644 --- a/src/ast/nodes/ConditionalExpression.ts +++ b/src/ast/nodes/ConditionalExpression.ts @@ -44,7 +44,7 @@ export default class ConditionalExpression extends NodeBase implements Deoptimiz // We did not track if there were reassignments to the previous branch. // Also, the return value might need to be reassigned. this.usedBranch = null; - this.unusedBranch.deoptimizePath(UNKNOWN_PATH); + (this.unusedBranch as ExpressionNode).deoptimizePath(UNKNOWN_PATH); for (const expression of this.expressionsToBeDeoptimized) { expression.deoptimizeCache(); } @@ -158,10 +158,10 @@ export default class ConditionalExpression extends NodeBase implements Deoptimiz { renderedParentType, isCalleeOfRenderedParent }: NodeRenderOptions = BLANK ) { if (!this.test.included) { - code.remove(this.start, this.usedBranch.start); - code.remove(this.usedBranch.end, this.end); + code.remove(this.start, (this.usedBranch as ExpressionNode).start); + code.remove((this.usedBranch as ExpressionNode).end, this.end); removeAnnotations(this, code); - this.usedBranch.render(code, options, { + (this.usedBranch as ExpressionNode).render(code, options, { isCalleeOfRenderedParent: renderedParentType ? isCalleeOfRenderedParent : (this.parent).callee === this, diff --git a/src/ast/nodes/ExportAllDeclaration.ts b/src/ast/nodes/ExportAllDeclaration.ts index d44786d6d55..db9cb969051 100644 --- a/src/ast/nodes/ExportAllDeclaration.ts +++ b/src/ast/nodes/ExportAllDeclaration.ts @@ -20,7 +20,7 @@ export default class ExportAllDeclaration extends NodeBase { } render(code: MagicString, _options: RenderOptions, { start, end }: NodeRenderOptions = BLANK) { - code.remove(start, end); + code.remove(start as number, end as number); } } diff --git a/src/ast/nodes/ExportDefaultDeclaration.ts b/src/ast/nodes/ExportDefaultDeclaration.ts index 34bab720c0b..9bea3d40581 100644 --- a/src/ast/nodes/ExportDefaultDeclaration.ts +++ b/src/ast/nodes/ExportDefaultDeclaration.ts @@ -48,10 +48,9 @@ export default class ExportDefaultDeclaration extends NodeBase { initialise() { this.included = false; + const declaration = this.declaration as FunctionDeclaration | ClassDeclaration; this.declarationName = - ((this.declaration).id && - (this.declaration).id.name) || - (this.declaration).name; + (declaration.id && declaration.id.name) || (this.declaration).name; this.variable = this.scope.addExportDefaultDeclaration( this.declarationName || this.context.getModuleName(), this, @@ -83,12 +82,12 @@ export default class ExportDefaultDeclaration extends NodeBase { // Remove altogether to prevent re-declaring the same variable if (options.format === 'system' && this.variable.exportName) { code.overwrite( - start, - end, + start as number, + end as number, `exports('${this.variable.exportName}', ${this.variable.getName()});` ); } else { - treeshakeNode(this, code, start, end); + treeshakeNode(this, code, start as number, end as number); } return; } else if (this.variable.included) { diff --git a/src/ast/nodes/ExportNamedDeclaration.ts b/src/ast/nodes/ExportNamedDeclaration.ts index 16824f2a81c..37a2fc4b6c2 100644 --- a/src/ast/nodes/ExportNamedDeclaration.ts +++ b/src/ast/nodes/ExportNamedDeclaration.ts @@ -23,7 +23,7 @@ export default class ExportNamedDeclaration extends NodeBase { } hasEffects(options: ExecutionPathOptions) { - return this.declaration && this.declaration.hasEffects(options); + return !!(this.declaration && this.declaration.hasEffects(options)); } initialise() { @@ -33,7 +33,7 @@ export default class ExportNamedDeclaration extends NodeBase { render(code: MagicString, options: RenderOptions, { start, end }: NodeRenderOptions = BLANK) { if (this.declaration === null) { - code.remove(start, end); + code.remove(start as number, end as number); } else { code.remove(this.start, this.declaration.start); (this.declaration).render(code, options, { start, end }); diff --git a/src/ast/nodes/Identifier.ts b/src/ast/nodes/Identifier.ts index b5cfbe77315..7133166f27f 100644 --- a/src/ast/nodes/Identifier.ts +++ b/src/ast/nodes/Identifier.ts @@ -133,7 +133,7 @@ export default class Identifier extends NodeBase implements PatternNode { this.bound = false; // To avoid later shape mutations if (!this.variable) { - this.variable = null; + this.variable = null as any; } } diff --git a/src/ast/nodes/IfStatement.ts b/src/ast/nodes/IfStatement.ts index bd39b7208b7..1233c66932a 100644 --- a/src/ast/nodes/IfStatement.ts +++ b/src/ast/nodes/IfStatement.ts @@ -81,7 +81,9 @@ export default class IfStatement extends StatementBase implements DeoptimizableE ? this.alternate === null || !this.alternate.included : !this.consequent.included) ) { - const singleRetainedBranch = this.testValue ? this.consequent : this.alternate; + const singleRetainedBranch = (this.testValue + ? this.consequent + : this.alternate) as StatementNode; code.remove(this.start, singleRetainedBranch.start); code.remove(singleRetainedBranch.end, this.end); removeAnnotations(this, code); diff --git a/src/ast/nodes/Import.ts b/src/ast/nodes/Import.ts index f285069d8d5..0c0bf4f84a7 100644 --- a/src/ast/nodes/Import.ts +++ b/src/ast/nodes/Import.ts @@ -44,6 +44,7 @@ const getDynamicImportMechanism = (options: RenderOptions): DynamicImportMechani right: ')' }; } + return undefined as any; }; export default class Import extends NodeBase { @@ -60,7 +61,7 @@ export default class Import extends NodeBase { initialise() { this.included = false; - this.resolutionNamespace = undefined; + this.resolutionNamespace = undefined as any; this.resolutionInterop = false; this.context.addDynamicImport(this); } @@ -95,8 +96,8 @@ export default class Import extends NodeBase { } } - setResolution(interop: boolean, namespace: string = undefined): void { + setResolution(interop: boolean, namespace?: string): void { this.resolutionInterop = interop; - this.resolutionNamespace = namespace; + this.resolutionNamespace = namespace as string; } } diff --git a/src/ast/nodes/ImportDeclaration.ts b/src/ast/nodes/ImportDeclaration.ts index 5604d7e79f3..ce7f375712f 100644 --- a/src/ast/nodes/ImportDeclaration.ts +++ b/src/ast/nodes/ImportDeclaration.ts @@ -26,7 +26,7 @@ export default class ImportDeclaration extends NodeBase { } render(code: MagicString, _options: RenderOptions, { start, end }: NodeRenderOptions = BLANK) { - code.remove(start, end); + code.remove(start as number, end as number); } } diff --git a/src/ast/nodes/LogicalExpression.ts b/src/ast/nodes/LogicalExpression.ts index db8fab9f029..9783a67a216 100644 --- a/src/ast/nodes/LogicalExpression.ts +++ b/src/ast/nodes/LogicalExpression.ts @@ -46,7 +46,7 @@ export default class LogicalExpression extends NodeBase implements Deoptimizable // We did not track if there were reassignments to any of the branches. // Also, the return values might need reassignment. this.usedBranch = null; - this.unusedBranch.deoptimizePath(UNKNOWN_PATH); + (this.unusedBranch as ExpressionNode).deoptimizePath(UNKNOWN_PATH); for (const expression of this.expressionsToBeDeoptimized) { expression.deoptimizeCache(); } @@ -139,7 +139,7 @@ export default class LogicalExpression extends NodeBase implements Deoptimizable if ( includeAllChildrenRecursively || this.usedBranch === null || - this.unusedBranch.shouldBeIncluded() + (this.unusedBranch as ExpressionNode).shouldBeIncluded() ) { this.left.include(includeAllChildrenRecursively); this.right.include(includeAllChildrenRecursively); @@ -162,10 +162,10 @@ export default class LogicalExpression extends NodeBase implements Deoptimizable { renderedParentType, isCalleeOfRenderedParent }: NodeRenderOptions = BLANK ) { if (!this.left.included || !this.right.included) { - code.remove(this.start, this.usedBranch.start); - code.remove(this.usedBranch.end, this.end); + code.remove(this.start, (this.usedBranch as ExpressionNode).start); + code.remove((this.usedBranch as ExpressionNode).end, this.end); removeAnnotations(this, code); - this.usedBranch.render(code, options, { + (this.usedBranch as ExpressionNode).render(code, options, { isCalleeOfRenderedParent: renderedParentType ? isCalleeOfRenderedParent : (this.parent).callee === this, diff --git a/src/ast/nodes/MemberExpression.ts b/src/ast/nodes/MemberExpression.ts index fbca8714740..eff34926bc4 100644 --- a/src/ast/nodes/MemberExpression.ts +++ b/src/ast/nodes/MemberExpression.ts @@ -78,7 +78,7 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE property: ExpressionNode; propertyKey: ObjectPathKey | null; type: NodeType.tMemberExpression; - variable: Variable = null; + variable: Variable = null as any; private bound: boolean; private expressionsToBeDeoptimized: DeoptimizableEntity[]; @@ -88,24 +88,26 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE if (this.bound) return; this.bound = true; const path = getPathIfNotComputed(this); - const baseVariable = path && this.scope.findVariable(path[0].key); - if (baseVariable && baseVariable.isNamespace) { - const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1)); - if (!resolvedVariable) { - super.bind(); - } else if (typeof resolvedVariable === 'string') { - this.replacement = resolvedVariable; - } else { - if (resolvedVariable.isExternal && (resolvedVariable).module) { - (resolvedVariable).module.suggestName(path[0].key); + if (path) { + const baseVariable = this.scope.findVariable(path[0].key); + if (baseVariable && baseVariable.isNamespace) { + const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1)); + if (!resolvedVariable) { + super.bind(); + } else if (typeof resolvedVariable === 'string') { + this.replacement = resolvedVariable; + } else { + if (resolvedVariable.isExternal && (resolvedVariable).module) { + (resolvedVariable).module.suggestName(path[0].key); + } + this.variable = resolvedVariable; + this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable); } - this.variable = resolvedVariable; - this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable); } - } else { - super.bind(); - if (this.propertyKey === null) this.analysePropertyKey(); + return; } + super.bind(); + if (this.propertyKey === null) this.analysePropertyKey(); } deoptimizeCache() { @@ -121,7 +123,7 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE this.variable.deoptimizePath(path); } else { if (this.propertyKey === null) this.analysePropertyKey(); - this.object.deoptimizePath([this.propertyKey, ...path]); + this.object.deoptimizePath([this.propertyKey as ObjectPathKey, ...path]); } } @@ -135,7 +137,11 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE } if (this.propertyKey === null) this.analysePropertyKey(); this.expressionsToBeDeoptimized.push(origin); - return this.object.getLiteralValueAtPath([this.propertyKey, ...path], recursionTracker, origin); + return this.object.getLiteralValueAtPath( + [this.propertyKey as ObjectPathKey, ...path], + recursionTracker, + origin + ); } getReturnExpressionWhenCalledAtPath( @@ -149,7 +155,7 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE if (this.propertyKey === null) this.analysePropertyKey(); this.expressionsToBeDeoptimized.push(origin); return this.object.getReturnExpressionWhenCalledAtPath( - [this.propertyKey, ...path], + [this.propertyKey as ObjectPathKey, ...path], recursionTracker, origin ); @@ -160,7 +166,7 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE this.property.hasEffects(options) || this.object.hasEffects(options) || (this.context.propertyReadSideEffects && - this.object.hasEffectsWhenAccessedAtPath([this.propertyKey], options)) + this.object.hasEffectsWhenAccessedAtPath([this.propertyKey as ObjectPathKey], options)) ); } @@ -171,14 +177,20 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE if (this.variable !== null) { return this.variable.hasEffectsWhenAccessedAtPath(path, options); } - return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey, ...path], options); + return this.object.hasEffectsWhenAccessedAtPath( + [this.propertyKey as ObjectPathKey, ...path], + options + ); } hasEffectsWhenAssignedAtPath(path: ObjectPath, options: ExecutionPathOptions): boolean { if (this.variable !== null) { return this.variable.hasEffectsWhenAssignedAtPath(path, options); } - return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey, ...path], options); + return this.object.hasEffectsWhenAssignedAtPath( + [this.propertyKey as ObjectPathKey, ...path], + options + ); } hasEffectsWhenCalledAtPath( @@ -190,7 +202,7 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, options); } return this.object.hasEffectsWhenCalledAtPath( - [this.propertyKey, ...path], + [this.propertyKey as ObjectPathKey, ...path], callOptions, options ); @@ -210,7 +222,7 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE initialise() { this.included = false; this.propertyKey = getResolvablePropertyKey(this); - this.variable = null; + this.variable = null as any; this.bound = false; this.replacement = null; this.expressionsToBeDeoptimized = []; @@ -226,7 +238,7 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE if (this.variable || this.replacement) { let replacement = this.variable ? this.variable.getName() : this.replacement; if (isCalleeOfDifferentParent) replacement = '0, ' + replacement; - code.overwrite(this.start, this.end, replacement, { + code.overwrite(this.start, this.end, replacement as string, { contentOnly: true, storeName: true }); diff --git a/src/ast/nodes/ObjectExpression.ts b/src/ast/nodes/ObjectExpression.ts index e926d1a2fd6..d8758ec7631 100644 --- a/src/ast/nodes/ObjectExpression.ts +++ b/src/ast/nodes/ObjectExpression.ts @@ -86,8 +86,8 @@ export default class ObjectExpression extends NodeBase { } const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1); for (const property of typeof key === 'string' - ? this.propertyMap[key] - ? this.propertyMap[key].propertiesRead + ? (this.propertyMap as PropertyMap)[key] + ? (this.propertyMap as PropertyMap)[key].propertiesRead : [] : this.properties) { property.deoptimizePath(subPath); @@ -112,9 +112,9 @@ export default class ObjectExpression extends NodeBase { if ( path.length === 1 && - !this.propertyMap[key] && + !(this.propertyMap as PropertyMap)[key] && !objectMembers[key] && - this.unmatchablePropertiesRead.length === 0 + (this.unmatchablePropertiesRead as (Property | SpreadElement)[]).length === 0 ) { if (!this.expressionsToBeDeoptimized[key]) { this.expressionsToBeDeoptimized[key] = [origin]; @@ -125,9 +125,9 @@ export default class ObjectExpression extends NodeBase { } if ( - !this.propertyMap[key] || - this.propertyMap[key].exactMatchRead === null || - this.propertyMap[key].propertiesRead.length > 1 + !(this.propertyMap as PropertyMap)[key] || + (this.propertyMap as PropertyMap)[key].exactMatchRead === null || + (this.propertyMap as PropertyMap)[key].propertiesRead.length > 1 ) return UNKNOWN_VALUE; @@ -136,11 +136,8 @@ export default class ObjectExpression extends NodeBase { } else { this.expressionsToBeDeoptimized[key].push(origin); } - return this.propertyMap[key].exactMatchRead.getLiteralValueAtPath( - path.slice(1), - recursionTracker, - origin - ); + return ((this.propertyMap as PropertyMap)[key] + .exactMatchRead as Property).getLiteralValueAtPath(path.slice(1), recursionTracker, origin); } getReturnExpressionWhenCalledAtPath( @@ -162,15 +159,16 @@ export default class ObjectExpression extends NodeBase { if ( path.length === 1 && objectMembers[key] && - this.unmatchablePropertiesRead.length === 0 && - (!this.propertyMap[key] || this.propertyMap[key].exactMatchRead === null) + this.unmatchablePropertiesRead!.length === 0 && + (!(this.propertyMap as PropertyMap)[key] || + (this.propertyMap as PropertyMap)[key].exactMatchRead === null) ) return getMemberReturnExpressionWhenCalled(objectMembers, key); if ( - !this.propertyMap[key] || - this.propertyMap[key].exactMatchRead === null || - this.propertyMap[key].propertiesRead.length > 1 + !(this.propertyMap as PropertyMap)[key] || + (this.propertyMap as PropertyMap)[key].exactMatchRead === null || + (this.propertyMap as PropertyMap)[key].propertiesRead.length > 1 ) return UNKNOWN_EXPRESSION; @@ -179,7 +177,8 @@ export default class ObjectExpression extends NodeBase { } else { this.expressionsToBeDeoptimized[key].push(origin); } - return this.propertyMap[key].exactMatchRead.getReturnExpressionWhenCalledAtPath( + return ((this.propertyMap as PropertyMap)[key] + .exactMatchRead as Property).getReturnExpressionWhenCalledAtPath( path.slice(1), recursionTracker, origin @@ -194,16 +193,16 @@ export default class ObjectExpression extends NodeBase { (this.hasUnknownDeoptimizedProperty || typeof key !== 'string' || this.deoptimizedPaths[key] || - !this.propertyMap[key] || - this.propertyMap[key].exactMatchRead === null) + !(this.propertyMap as PropertyMap)[key] || + (this.propertyMap as PropertyMap)[key].exactMatchRead === null) ) return true; const subPath = path.slice(1); for (const property of typeof key !== 'string' ? this.properties - : this.propertyMap[key] - ? this.propertyMap[key].propertiesRead + : (this.propertyMap as PropertyMap)[key] + ? (this.propertyMap as PropertyMap)[key].propertiesRead : []) { if (property.hasEffectsWhenAccessedAtPath(subPath, options)) return true; } @@ -218,8 +217,8 @@ export default class ObjectExpression extends NodeBase { (this.hasUnknownDeoptimizedProperty || typeof key !== 'string' || this.deoptimizedPaths[key] || - !this.propertyMap[key] || - this.propertyMap[key].exactMatchRead === null) + !(this.propertyMap as PropertyMap)[key] || + (this.propertyMap as PropertyMap)[key].exactMatchRead === null) ) return true; @@ -227,9 +226,9 @@ export default class ObjectExpression extends NodeBase { for (const property of typeof key !== 'string' ? this.properties : path.length > 1 - ? this.propertyMap[key].propertiesRead - : this.propertyMap[key] - ? this.propertyMap[key].propertiesSet + ? (this.propertyMap as PropertyMap)[key].propertiesRead + : (this.propertyMap as PropertyMap)[key] + ? (this.propertyMap as PropertyMap)[key].propertiesSet : []) { if (property.hasEffectsWhenAssignedAtPath(subPath, options)) return true; } @@ -247,13 +246,15 @@ export default class ObjectExpression extends NodeBase { this.hasUnknownDeoptimizedProperty || typeof key !== 'string' || this.deoptimizedPaths[key] || - (this.propertyMap[key] - ? !this.propertyMap[key].exactMatchRead + ((this.propertyMap as PropertyMap)[key] + ? !(this.propertyMap as PropertyMap)[key].exactMatchRead : path.length > 1 || !objectMembers[key]) ) return true; const subPath = path.slice(1); - for (const property of this.propertyMap[key] ? this.propertyMap[key].propertiesRead : []) { + for (const property of (this.propertyMap as PropertyMap)[key] + ? (this.propertyMap as PropertyMap)[key].propertiesRead + : []) { if (property.hasEffectsWhenCalledAtPath(subPath, callOptions, options)) return true; } if (path.length === 1 && objectMembers[key]) @@ -314,9 +315,9 @@ export default class ObjectExpression extends NodeBase { } else { key = String((property.key).value); } - const propertyMapProperty = this.propertyMap[key]; + const propertyMapProperty = (this.propertyMap as PropertyMap)[key]; if (!propertyMapProperty) { - this.propertyMap[key] = { + (this.propertyMap as PropertyMap)[key] = { exactMatchRead: isRead ? property : null, exactMatchWrite: isWrite ? property : null, propertiesRead: isRead ? [property, ...this.unmatchablePropertiesRead] : [], diff --git a/src/ast/nodes/Program.ts b/src/ast/nodes/Program.ts index 9f8bb45815e..f2ad851e9a9 100644 --- a/src/ast/nodes/Program.ts +++ b/src/ast/nodes/Program.ts @@ -13,6 +13,7 @@ export default class Program extends NodeBase { for (const node of this.body) { if (node.hasEffects(options)) return true; } + return false; } include(includeAllChildrenRecursively: boolean) { diff --git a/src/ast/nodes/Property.ts b/src/ast/nodes/Property.ts index 78848e50625..a6b283a477d 100644 --- a/src/ast/nodes/Property.ts +++ b/src/ast/nodes/Property.ts @@ -55,7 +55,7 @@ export default class Property extends NodeBase implements DeoptimizableEntity { if (this.kind === 'get') { if (path.length > 0) { if (this.returnExpression === null) this.updateReturnExpression(); - this.returnExpression.deoptimizePath(path); + (this.returnExpression as ExpressionEntity).deoptimizePath(path); } } else if (this.kind !== 'set') { this.value.deoptimizePath(path); @@ -72,7 +72,11 @@ export default class Property extends NodeBase implements DeoptimizableEntity { } if (this.kind === 'get') { if (this.returnExpression === null) this.updateReturnExpression(); - return this.returnExpression.getLiteralValueAtPath(path, recursionTracker, origin); + return (this.returnExpression as ExpressionEntity).getLiteralValueAtPath( + path, + recursionTracker, + origin + ); } return this.value.getLiteralValueAtPath(path, recursionTracker, origin); } @@ -87,7 +91,7 @@ export default class Property extends NodeBase implements DeoptimizableEntity { } if (this.kind === 'get') { if (this.returnExpression === null) this.updateReturnExpression(); - return this.returnExpression.getReturnExpressionWhenCalledAtPath( + return (this.returnExpression as ExpressionEntity).getReturnExpressionWhenCalledAtPath( path, recursionTracker, origin @@ -108,7 +112,8 @@ export default class Property extends NodeBase implements DeoptimizableEntity { this.accessorCallOptions, options.getHasEffectsWhenCalledOptions() ) || - (path.length > 0 && this.returnExpression.hasEffectsWhenAccessedAtPath(path, options)) + (path.length > 0 && + (this.returnExpression as ExpressionEntity).hasEffectsWhenAccessedAtPath(path, options)) ); } return this.value.hasEffectsWhenAccessedAtPath(path, options); @@ -116,7 +121,10 @@ export default class Property extends NodeBase implements DeoptimizableEntity { hasEffectsWhenAssignedAtPath(path: ObjectPath, options: ExecutionPathOptions): boolean { if (this.kind === 'get') { - return path.length === 0 || this.returnExpression.hasEffectsWhenAssignedAtPath(path, options); + return ( + path.length === 0 || + (this.returnExpression as ExpressionEntity).hasEffectsWhenAssignedAtPath(path, options) + ); } if (this.kind === 'set') { return ( @@ -137,7 +145,11 @@ export default class Property extends NodeBase implements DeoptimizableEntity { options: ExecutionPathOptions ) { if (this.kind === 'get') { - return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, options); + return (this.returnExpression as ExpressionEntity).hasEffectsWhenCalledAtPath( + path, + callOptions, + options + ); } return this.value.hasEffectsWhenCalledAtPath(path, callOptions, options); } diff --git a/src/ast/nodes/ReturnStatement.ts b/src/ast/nodes/ReturnStatement.ts index 23780a16c93..37e3ea0675a 100644 --- a/src/ast/nodes/ReturnStatement.ts +++ b/src/ast/nodes/ReturnStatement.ts @@ -11,7 +11,7 @@ export default class ReturnStatement extends StatementBase { hasEffects(options: ExecutionPathOptions) { return ( - !options.ignoreReturnAwaitYield() || (this.argument && this.argument.hasEffects(options)) + !options.ignoreReturnAwaitYield() || !!(this.argument && this.argument.hasEffects(options)) ); } diff --git a/src/ast/nodes/SequenceExpression.ts b/src/ast/nodes/SequenceExpression.ts index e26f658ccbd..c98b9ba64d7 100644 --- a/src/ast/nodes/SequenceExpression.ts +++ b/src/ast/nodes/SequenceExpression.ts @@ -113,7 +113,7 @@ export default class SequenceExpression extends NodeBase { // Round brackets are part of the actual parent and should be re-added in case the parent changed if (includedNodes > 1 && renderedParentType) { code.prependRight(firstStart, '('); - code.appendLeft(lastEnd, ')'); + code.appendLeft(lastEnd as number, ')'); } } } diff --git a/src/ast/nodes/ThisExpression.ts b/src/ast/nodes/ThisExpression.ts index 5da098b2224..b71be7b7029 100644 --- a/src/ast/nodes/ThisExpression.ts +++ b/src/ast/nodes/ThisExpression.ts @@ -28,7 +28,7 @@ export default class ThisExpression extends NodeBase { initialise() { this.included = false; - this.variable = null; + this.variable = null as any; this.alias = this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null; if (this.alias === 'undefined') { diff --git a/src/ast/nodes/UnaryExpression.ts b/src/ast/nodes/UnaryExpression.ts index daea53f020e..93945323c1e 100644 --- a/src/ast/nodes/UnaryExpression.ts +++ b/src/ast/nodes/UnaryExpression.ts @@ -10,12 +10,12 @@ const unaryOperators: { [operator: string]: (value: LiteralValue) => LiteralValueOrUnknown; } = { '!': value => !value, - '+': value => +value, - '-': value => -value, + '+': value => +(value as NonNullable), + '-': value => -(value as NonNullable), delete: () => UNKNOWN_VALUE, typeof: value => typeof value, void: () => undefined, - '~': value => ~value + '~': value => ~(value as NonNullable) }; export default class UnaryExpression extends NodeBase { diff --git a/src/ast/nodes/VariableDeclaration.ts b/src/ast/nodes/VariableDeclaration.ts index d103698589a..f8c76959144 100644 --- a/src/ast/nodes/VariableDeclaration.ts +++ b/src/ast/nodes/VariableDeclaration.ts @@ -15,7 +15,7 @@ import { NodeBase } from './shared/Node'; import VariableDeclarator from './VariableDeclarator'; function isReassignedExportsMember(variable: Variable): boolean { - return variable.renderBaseName && variable.exportName && variable.isReassigned; + return !!(variable.renderBaseName && variable.exportName) && variable.isReassigned; } function areAllDeclarationsIncludedAndNotExported(declarations: VariableDeclarator[]): boolean { @@ -24,7 +24,7 @@ function areAllDeclarationsIncludedAndNotExported(declarations: VariableDeclarat return false; } if (declarator.id.type === NodeType.Identifier) { - if (declarator.id.variable.exportName) return false; + if ((declarator.id.variable as Variable).exportName) return false; } else { const exportedVariables: Variable[] = []; declarator.id.addExportedVariables(exportedVariables); @@ -171,10 +171,11 @@ export default class VariableDeclaration extends NodeBase { if (options.format === 'system' && node.init !== null) { if (node.id.type !== NodeType.Identifier) { node.id.addExportedVariables(systemPatternExports); - } else if (node.id.variable.exportName) { + } else if ((node.id.variable as Variable).exportName) { code.prependLeft( code.original.indexOf('=', node.id.end) + 1, - ` exports('${node.id.variable.safeExportName || node.id.variable.exportName}',` + ` exports('${(node.id.variable as Variable).safeExportName || + (node.id.variable as Variable).exportName}',` ); nextSeparatorString += ')'; } @@ -199,7 +200,7 @@ export default class VariableDeclaration extends NodeBase { actualContentEnd = contentEnd; renderedContentEnd = end; hasRenderedContent = true; - lastSeparatorPos = separator; + lastSeparatorPos = separator as number; separatorString = nextSeparatorString; } if (hasRenderedContent) { @@ -207,7 +208,7 @@ export default class VariableDeclaration extends NodeBase { code, separatorString, lastSeparatorPos, - actualContentEnd, + actualContentEnd as number, renderedContentEnd, !isNoStatement, systemPatternExports diff --git a/src/ast/nodes/YieldExpression.ts b/src/ast/nodes/YieldExpression.ts index b06b611eee8..011ad2444a8 100644 --- a/src/ast/nodes/YieldExpression.ts +++ b/src/ast/nodes/YieldExpression.ts @@ -19,7 +19,7 @@ export default class YieldExpression extends NodeBase { hasEffects(options: ExecutionPathOptions) { return ( - !options.ignoreReturnAwaitYield() || (this.argument && this.argument.hasEffects(options)) + !options.ignoreReturnAwaitYield() || !!(this.argument && this.argument.hasEffects(options)) ); } diff --git a/src/ast/nodes/shared/ClassNode.ts b/src/ast/nodes/shared/ClassNode.ts index e17cdda287a..3f006dc46ad 100644 --- a/src/ast/nodes/shared/ClassNode.ts +++ b/src/ast/nodes/shared/ClassNode.ts @@ -31,7 +31,7 @@ export default class ClassNode extends NodeBase { ) { return ( this.body.hasEffectsWhenCalledAtPath(path, callOptions, options) || - (this.superClass && this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, options)) + !!(this.superClass && this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, options)) ); } diff --git a/src/ast/nodes/shared/FunctionNode.ts b/src/ast/nodes/shared/FunctionNode.ts index 3b4a635a250..93a625efbe9 100644 --- a/src/ast/nodes/shared/FunctionNode.ts +++ b/src/ast/nodes/shared/FunctionNode.ts @@ -41,7 +41,7 @@ export default class FunctionNode extends NodeBase { } hasEffects(options: ExecutionPathOptions) { - return this.id && this.id.hasEffects(options); + return !!(this.id && this.id.hasEffects(options)); } hasEffectsWhenAccessedAtPath(path: ObjectPath) { diff --git a/src/ast/scopes/ReturnValueScope.ts b/src/ast/scopes/ReturnValueScope.ts index 36042a067ab..030ee03a417 100644 --- a/src/ast/scopes/ReturnValueScope.ts +++ b/src/ast/scopes/ReturnValueScope.ts @@ -12,7 +12,7 @@ export default class ReturnValueScope extends ParameterScope { getReturnExpression(): ExpressionEntity { if (this.returnExpression === null) this.updateReturnExpression(); - return this.returnExpression; + return this.returnExpression as ExpressionEntity; } private updateReturnExpression() { diff --git a/src/ast/scopes/Scope.ts b/src/ast/scopes/Scope.ts index 8c02756b560..dd8fb902307 100644 --- a/src/ast/scopes/Scope.ts +++ b/src/ast/scopes/Scope.ts @@ -2,10 +2,7 @@ import { AstContext } from '../../Module'; import Identifier from '../nodes/Identifier'; import { ExpressionEntity } from '../nodes/shared/Expression'; import { UNDEFINED_EXPRESSION } from '../values'; -import ArgumentsVariable from '../variables/ArgumentsVariable'; -import ExportDefaultVariable from '../variables/ExportDefaultVariable'; import LocalVariable from '../variables/LocalVariable'; -import ThisVariable from '../variables/ThisVariable'; import Variable from '../variables/Variable'; import ChildScope from './ChildScope'; @@ -13,9 +10,6 @@ export default class Scope { children: ChildScope[] = []; variables: { [name: string]: Variable; - arguments?: ArgumentsVariable; - default?: ExportDefaultVariable; - this?: ThisVariable | LocalVariable; } = Object.create(null); addDeclaration( diff --git a/src/ast/values.ts b/src/ast/values.ts index 4e68c6c9eed..73041e322c4 100644 --- a/src/ast/values.ts +++ b/src/ast/values.ts @@ -30,7 +30,7 @@ interface RawMemberDescription { function assembleMemberDescriptions( memberDescriptions: { [key: string]: RawMemberDescription }, - inheritedDescriptions: MemberDescriptions = null + inheritedDescriptions: MemberDescriptions | null = null ): MemberDescriptions { return Object.create(inheritedDescriptions, memberDescriptions); } @@ -438,7 +438,7 @@ export function hasMemberEffectWhenCalled( if (typeof memberName !== 'string' || !members[memberName]) return true; if (members[memberName].mutatesSelf && parentIncluded) return true; if (!members[memberName].callsArgs) return false; - for (const argIndex of members[memberName].callsArgs) { + for (const argIndex of members[memberName].callsArgs as number[]) { if ( callOptions.args[argIndex] && callOptions.args[argIndex].hasEffectsWhenCalledAtPath( @@ -462,6 +462,6 @@ export function getMemberReturnExpressionWhenCalled( ): ExpressionEntity { if (typeof memberName !== 'string' || !members[memberName]) return UNKNOWN_EXPRESSION; return members[memberName].returnsPrimitive !== null - ? members[memberName].returnsPrimitive - : new members[memberName].returns(); + ? (members[memberName].returnsPrimitive as ExpressionEntity) + : new (members[memberName].returns as any)(); } diff --git a/src/ast/variables/ExportDefaultVariable.ts b/src/ast/variables/ExportDefaultVariable.ts index 0a47396b933..7c426f1f106 100644 --- a/src/ast/variables/ExportDefaultVariable.ts +++ b/src/ast/variables/ExportDefaultVariable.ts @@ -8,7 +8,7 @@ import LocalVariable from './LocalVariable'; import Variable from './Variable'; export function isExportDefaultVariable(variable: Variable): variable is ExportDefaultVariable { - return variable.isDefault; + return variable.isDefault as boolean; } export default class ExportDefaultVariable extends LocalVariable { @@ -44,7 +44,9 @@ export default class ExportDefaultVariable extends LocalVariable { } getName() { - return this.referencesOriginal() ? this.originalId.variable.getName() : super.getName(); + return this.referencesOriginal() + ? (this.originalId as Identifier).variable.getName() + : super.getName(); } getOriginalVariable(): Variable | null { @@ -61,7 +63,7 @@ export default class ExportDefaultVariable extends LocalVariable { setRenderNames(baseName: string | null, name: string | null) { if (this.referencesOriginal()) { - this.originalId.variable.setRenderNames(baseName, name); + (this.originalId as Identifier).variable.setRenderNames(baseName, name); } else { super.setRenderNames(baseName, name); } @@ -69,7 +71,7 @@ export default class ExportDefaultVariable extends LocalVariable { setSafeName(name: string | null) { if (this.referencesOriginal()) { - this.originalId.variable.setSafeName(name); + (this.originalId as Identifier).variable.setSafeName(name); } else { super.setSafeName(name); } diff --git a/src/ast/variables/LocalVariable.ts b/src/ast/variables/LocalVariable.ts index 54d82cc255a..b6e4c44d9f4 100644 --- a/src/ast/variables/LocalVariable.ts +++ b/src/ast/variables/LocalVariable.ts @@ -129,12 +129,11 @@ export default class LocalVariable extends Variable { return ( this.isReassigned || path.length > MAX_PATH_DEPTH || - (this.init && + !!( + this.init && !options.hasNodeBeenAccessedAtPath(path, this.init) && - this.init.hasEffectsWhenAccessedAtPath( - path, - options.addAccessedNodeAtPath(path, this.init) - )) + this.init.hasEffectsWhenAccessedAtPath(path, options.addAccessedNodeAtPath(path, this.init)) + ) ); } @@ -143,12 +142,11 @@ export default class LocalVariable extends Variable { if (path.length === 0) return false; return ( this.isReassigned || - (this.init && + !!( + this.init && !options.hasNodeBeenAssignedAtPath(path, this.init) && - this.init.hasEffectsWhenAssignedAtPath( - path, - options.addAssignedNodeAtPath(path, this.init) - )) + this.init.hasEffectsWhenAssignedAtPath(path, options.addAssignedNodeAtPath(path, this.init)) + ) ); } @@ -160,13 +158,15 @@ export default class LocalVariable extends Variable { if (path.length > MAX_PATH_DEPTH) return true; return ( this.isReassigned || - (this.init && + !!( + this.init && !options.hasNodeBeenCalledAtPathWithOptions(path, this.init, callOptions) && this.init.hasEffectsWhenCalledAtPath( path, callOptions, options.addCalledNodeAtPathWithOptions(path, this.init, callOptions) - )) + ) + ) ); } diff --git a/src/ast/variables/NamespaceVariable.ts b/src/ast/variables/NamespaceVariable.ts index ffb033ca55b..e7131d0de52 100644 --- a/src/ast/variables/NamespaceVariable.ts +++ b/src/ast/variables/NamespaceVariable.ts @@ -48,7 +48,7 @@ export default class NamespaceVariable extends Variable { id: this.module.id, message: `Cannot create an explicit namespace object for module "${this.context.getModuleName()}" because it contains a reexported external namespace` }, - undefined + undefined as any ); } this.included = true; diff --git a/src/chunk-optimization.ts b/src/chunk-optimization.ts index 757df08d1fe..86eff6daf1a 100644 --- a/src/chunk-optimization.ts +++ b/src/chunk-optimization.ts @@ -31,7 +31,7 @@ export function optimizeChunks( let execGroupIndex = 1; let seekingFirstMergeCandidate = true; - let lastChunk: Chunk, + let lastChunk: Chunk = undefined as any, chunk = execGroup[0], nextChunk = execGroup[1]; diff --git a/src/finalisers/amd.ts b/src/finalisers/amd.ts index cd6b63cfca9..2cfe1479f44 100644 --- a/src/finalisers/amd.ts +++ b/src/finalisers/amd.ts @@ -68,8 +68,8 @@ export default function amd( exports, dependencies, namedExportsMode, - options.interop, - options.compact + options.interop as boolean, + options.compact as boolean ); if (exportBlock) magicString.append(n + n + exportBlock); if (namedExportsMode && hasExports && isEntryModuleFacade && options.esModule) diff --git a/src/finalisers/cjs.ts b/src/finalisers/cjs.ts index a06b65e208f..068dafd38e4 100644 --- a/src/finalisers/cjs.ts +++ b/src/finalisers/cjs.ts @@ -112,8 +112,8 @@ export default function cjs( exports, dependencies, namedExportsMode, - options.interop, - options.compact, + options.interop as boolean, + options.compact as boolean, `module.exports${_}=${_}` ); diff --git a/src/finalisers/iife.ts b/src/finalisers/iife.ts index 1a66a775376..730ad34d38a 100644 --- a/src/finalisers/iife.ts +++ b/src/finalisers/iife.ts @@ -1,5 +1,5 @@ import { Bundle as MagicStringBundle } from 'magic-string'; -import { OutputOptions } from '../rollup/types'; +import { GlobalsOption, OutputOptions } from '../rollup/types'; import { error } from '../utils/error'; import { isLegal } from '../utils/identifierHelpers'; import { FinaliserOptions } from './index'; @@ -56,7 +56,7 @@ export default function iife( if (namedExportsMode && hasExports) { if (extend) { - deps.unshift(`${thisProp(name)}${_}=${_}${thisProp(name)}${_}||${_}{}`); + deps.unshift(`${thisProp(name as string)}${_}=${_}${thisProp(name as string)}${_}||${_}{}`); args.unshift('exports'); } else { deps.unshift('{}'); @@ -70,12 +70,18 @@ export default function iife( if (hasExports && (!extend || !namedExportsMode)) { wrapperIntro = - (useVariableAssignment ? `${varOrConst} ${name}` : thisProp(name)) + + (useVariableAssignment ? `${varOrConst} ${name}` : thisProp(name as string)) + `${_}=${_}${wrapperIntro}`; } if (isNamespaced && hasExports) { - wrapperIntro = setupNamespace(name, 'this', options.globals, options.compact) + wrapperIntro; + wrapperIntro = + setupNamespace( + name as string, + 'this', + options.globals as GlobalsOption, + options.compact as boolean + ) + wrapperIntro; } let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`; @@ -94,8 +100,8 @@ export default function iife( exports, dependencies, namedExportsMode, - options.interop, - options.compact + options.interop as boolean, + options.compact as boolean ); if (exportBlock) magicString.append(n + n + exportBlock); if (outro) magicString.append(outro); diff --git a/src/finalisers/shared/setupNamespace.ts b/src/finalisers/shared/setupNamespace.ts index ca8dfd2cca5..bfa78ee82fe 100644 --- a/src/finalisers/shared/setupNamespace.ts +++ b/src/finalisers/shared/setupNamespace.ts @@ -42,7 +42,7 @@ export function assignToDeepVariable( let acc = root; let deepAssignment = parts .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`)) - .concat(`${acc}${property(last)}`) + .concat(`${acc}${property(last as string)}`) .join(`,${_}`) .concat(`${_}=${_}${assignment}`); if (parts.length > 0) { diff --git a/src/finalisers/system.ts b/src/finalisers/system.ts index 5502862cfc2..cde7b56fd08 100644 --- a/src/finalisers/system.ts +++ b/src/finalisers/system.ts @@ -19,7 +19,7 @@ function getStarExcludes({ dependencies, exports }: ModuleDeclarations): Set, + starExcludes: Set | undefined, varOrConst: string, _: string, t: string, @@ -97,7 +97,7 @@ export default function system( const dependencyIds = dependencies.map(m => `'${m.id}'`); const importBindings: string[] = []; - let starExcludes: Set; + let starExcludes: Set | undefined = undefined; const setters: string[] = []; dependencies.forEach(({ imports, reexports }) => { diff --git a/src/finalisers/umd.ts b/src/finalisers/umd.ts index 86c91032f29..c8fca343a79 100644 --- a/src/finalisers/umd.ts +++ b/src/finalisers/umd.ts @@ -1,5 +1,5 @@ import { Bundle as MagicStringBundle } from 'magic-string'; -import { OutputOptions } from '../rollup/types'; +import { GlobalsOption, OutputOptions } from '../rollup/types'; import { error } from '../utils/error'; import { FinaliserOptions } from './index'; import { compactEsModuleExport, esModuleExport } from './shared/esModuleExport'; @@ -63,11 +63,11 @@ export default function umd( cjsDeps.unshift(`exports`); globalDeps.unshift( assignToDeepVariable( - options.name, + options.name as string, globalVar, - options.globals, - options.compact, - `${options.extend ? `${globalProp(options.name, globalVar)}${_}||${_}` : ''}{}` + options.globals as GlobalsOption, + options.compact as boolean, + `${options.extend ? `${globalProp(options.name as string, globalVar)}${_}||${_}` : ''}{}` ) ); @@ -92,10 +92,10 @@ export default function umd( if (!namedExportsMode && hasExports) { factory = `var ${noConflictExportsVar}${_}=${_}${assignToDeepVariable( - options.name, + options.name as string, globalVar, - options.globals, - options.compact, + options.globals as GlobalsOption, + options.compact as boolean, `${factoryVar}(${globalDeps.join(`,${_}`)})` )};`; } else if (namedExportsMode) { @@ -106,21 +106,22 @@ export default function umd( } iifeExport = `(function${_}()${_}{${n}` + - `${t}${t}var current${_}=${_}${safeAccess(options.name, globalVar, _)};${n}` + + `${t}${t}var current${_}=${_}${safeAccess(options.name as string, globalVar, _)};${n}` + `${t}${t}${factory}${n}` + `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}function${_}()${_}{${_}` + - `${globalProp(options.name, globalVar)}${_}=${_}current;${_}return ${noConflictExportsVar}${ - options.compact ? '' : '; ' - }};${n}` + + `${globalProp( + options.name as string, + globalVar + )}${_}=${_}current;${_}return ${noConflictExportsVar}${options.compact ? '' : '; '}};${n}` + `${t}}())`; } else { iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`; if (!namedExportsMode && hasExports) { iifeExport = assignToDeepVariable( - options.name, + options.name as string, globalVar, - options.globals, - options.compact, + options.globals as GlobalsOption, + options.compact as boolean, iifeExport ); } @@ -156,8 +157,8 @@ export default function umd( exports, dependencies, namedExportsMode, - options.interop, - options.compact + options.interop as boolean, + options.compact as boolean ); if (exportBlock) magicString.append(n + n + exportBlock); if (namedExportsMode && hasExports && options.esModule) diff --git a/src/rollup/index.ts b/src/rollup/index.ts index 20d82f14808..17e6a0458b2 100644 --- a/src/rollup/index.ts +++ b/src/rollup/index.ts @@ -21,7 +21,9 @@ import { OutputChunk, OutputOptions, Plugin, + PluginContext, RollupBuild, + RollupCache, RollupOutput, RollupWatcher } from './types'; @@ -137,7 +139,7 @@ export default function rollup(rawInputOptions: GenericConfigObject): Promise ({ - ...context, - ...generateAssetPluginHooks - })) + .hookSeq( + 'generateBundle', + [outputOptions, outputBundle, isWrite], + context => + ({ + ...context, + ...generateAssetPluginHooks + } as PluginContext) + ) .then(() => { // throw errors for assets not finalised with a source assets.forEach(asset => { @@ -280,7 +287,7 @@ export default function rollup(rawInputOptions: GenericConfigObject): Promise((rawOutputOptions: GenericConfigObject) => { const promise = generate(rawOutputOptions, false).then(result => createOutput(result)); Object.defineProperty(promise, 'code', throwAsyncGenerateError); @@ -377,7 +384,10 @@ function writeOutputFile( outputFile: OutputAsset | OutputChunk, outputOptions: OutputOptions ): Promise { - const filename = resolve(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName); + const filename = resolve( + outputOptions.dir || dirname(outputOptions.file as string), + outputFile.fileName + ); let writeSourceMapPromise: Promise; let source: string | Buffer; if (isOutputAsset(outputFile)) { @@ -400,7 +410,7 @@ function writeOutputFile( .then(() => writeSourceMapPromise) .then( () => - !isOutputAsset(outputFile) && + (!isOutputAsset(outputFile) as any) && graph.pluginDriver.hookSeq('onwrite', [ { bundle: build, diff --git a/src/utils/addons.ts b/src/utils/addons.ts index fe6d30f53fb..2a55e2a3b08 100644 --- a/src/utils/addons.ts +++ b/src/utils/addons.ts @@ -9,7 +9,9 @@ export interface Addons { outro?: string; } -function evalIfFn(strOrFn: string | (() => string | Promise)): string | Promise { +function evalIfFn( + strOrFn: string | (() => string | Promise) | undefined +): string | Promise { switch (typeof strOrFn) { case 'function': return strOrFn(); diff --git a/src/utils/assetHooks.ts b/src/utils/assetHooks.ts index 619757f426a..b0acef4c9f4 100644 --- a/src/utils/assetHooks.ts +++ b/src/utils/assetHooks.ts @@ -36,6 +36,7 @@ export function getAssetFileName( case 'ext': return extname(asset.name).substr(1); } + return undefined as any; }), existingNames ); @@ -54,7 +55,7 @@ export function createAssetPluginHooks( message: `Plugin error creating asset, name is not a plain (non relative or absolute URL) string name.` }); - let assetId: string; + let assetId: string = undefined as any; do { const assetHash = sha256(); if (assetId) { @@ -66,8 +67,9 @@ export function createAssetPluginHooks( assetId = assetHash.digest('hex').substr(0, 8); } while (assetsById.has(assetId)); - const asset: Asset = { name, source, fileName: undefined }; - if (outputBundle && source !== undefined) finaliseAsset(asset, outputBundle, assetFileNames); + const asset: Asset = { name, source: source as any, fileName: undefined as any }; + if (outputBundle && source !== undefined) + finaliseAsset(asset, outputBundle, assetFileNames as string); assetsById.set(assetId, asset); return assetId; }, @@ -78,11 +80,11 @@ export function createAssetPluginHooks( code: 'ASSET_NOT_FOUND', message: `Plugin error - Unable to set asset source for unknown asset ${assetId}.` }); - if (asset.source !== undefined) + if ((asset as Asset).source !== undefined) error({ code: 'ASSET_SOURCE_ALREADY_SET', message: `Plugin error - Unable to set asset source for ${ - asset.name + (asset as Asset).name }, source already set.` }); if (typeof source !== 'string' && !source) @@ -90,8 +92,8 @@ export function createAssetPluginHooks( code: 'ASSET_SOURCE_MISSING', message: `Plugin error creating asset ${name}, setAssetSource call without a source.` }); - asset.source = source; - if (outputBundle) finaliseAsset(asset, outputBundle, assetFileNames); + (asset as Asset).source = source as string | Buffer; + if (outputBundle) finaliseAsset(asset as Asset, outputBundle, assetFileNames as string); }, getAssetFileName(assetId: string) { const asset = assetsById.get(assetId); @@ -100,12 +102,12 @@ export function createAssetPluginHooks( code: 'ASSET_NOT_FOUND', message: `Plugin error - Unable to get asset filename for unknown asset ${assetId}.` }); - if (asset.fileName === undefined) + if ((asset as Asset).fileName === undefined) error({ code: 'ASSET_NOT_FINALISED', message: `Plugin error - Unable to get asset file name for asset ${assetId}. Ensure that the source is set and that generate is called first.` }); - return asset.fileName; + return (asset as Asset).fileName; } }; } @@ -126,10 +128,10 @@ export function createTransformEmitAsset(assetsById: Map, emitAss assets, emitAsset: (name: string, source?: string | Buffer) => { const assetId = emitAsset(name, source); - const asset = assetsById.get(assetId); + const asset = assetsById.get(assetId) as Asset; // distinguish transform assets assets.push({ - fileName: undefined, + fileName: undefined as any, name: asset.name, source: asset.source }); diff --git a/src/utils/assignChunkIds.ts b/src/utils/assignChunkIds.ts index 4386eb01e50..3e9037c6440 100644 --- a/src/utils/assignChunkIds.ts +++ b/src/utils/assignChunkIds.ts @@ -11,7 +11,7 @@ export function assignChunkIds( addons: Addons ) { const usedIds: Record = {}; - const [entryChunks, otherChunks] = chunks.reduce( + const [entryChunks, otherChunks] = chunks.reduce<[Chunk[], Chunk[]]>( ([entryChunks, otherChunks], chunk) => { (chunk.facadeModule && chunk.facadeModule.isEntryPoint ? entryChunks : otherChunks).push( chunk diff --git a/src/utils/chunkColouring.ts b/src/utils/chunkColouring.ts index 577c7da97da..418c77c2545 100644 --- a/src/utils/chunkColouring.ts +++ b/src/utils/chunkColouring.ts @@ -68,7 +68,7 @@ Try defining "${chunkName}" first in the manualChunks definitions of the Rollup for (currentEntry of entryModules) { handledEntryPoints[currentEntry.id] = true; currentEntryHash = randomUint8Array(10); - modulesVisitedForCurrentEntry = { [currentEntry.id]: null }; + modulesVisitedForCurrentEntry = { [currentEntry.id]: false }; addCurrentEntryColourToModule(currentEntry); } @@ -78,7 +78,7 @@ Try defining "${chunkName}" first in the manualChunks definitions of the Rollup } handledEntryPoints[currentEntry.id] = true; currentEntryHash = randomUint8Array(10); - modulesVisitedForCurrentEntry = { [currentEntry.id]: null }; + modulesVisitedForCurrentEntry = { [currentEntry.id]: false }; addCurrentEntryColourToModule(currentEntry); } } diff --git a/src/utils/collapseSourcemaps.ts b/src/utils/collapseSourcemaps.ts index 1a2c07bdf5a..ada564d1e16 100644 --- a/src/utils/collapseSourcemaps.ts +++ b/src/utils/collapseSourcemaps.ts @@ -57,7 +57,11 @@ class Link { const source = this.sources[segment[1]]; if (!source) continue; - const traced = source.traceSegment(segment[2], segment[3], this.names[segment[4]]); + const traced = source.traceSegment( + segment[2], + segment[3], + this.names[segment[4] as number] + ); if (traced) { // newer sources are more likely to be used, so search backwards. @@ -121,7 +125,11 @@ class Link { const source = this.sources[segment[1]]; if (!source) return null; - return source.traceSegment(segment[2], segment[3], this.names[segment[4]] || name); + return source.traceSegment( + segment[2], + segment[3], + this.names[segment[4] as number] || name + ); } if (segment[0] > column) { j = m - 1; @@ -209,7 +217,7 @@ export default function collapseSourcemaps( file = basename(file); } - sourcesContent = excludeContent ? null : sourcesContent; + sourcesContent = (excludeContent ? null : sourcesContent) as string[]; return new SourceMap({ file, sources, sourcesContent, names, mappings }); } diff --git a/src/utils/deconflictChunk.ts b/src/utils/deconflictChunk.ts index 71ee531193b..7d91e3ceb35 100644 --- a/src/utils/deconflictChunk.ts +++ b/src/utils/deconflictChunk.ts @@ -109,11 +109,13 @@ function deconflictImportsOther( variable.setRenderNames(module.variableName, null); } } else { - const chunk = module.chunk; + const chunk = (module as Module).chunk; if (chunk.exportMode === 'default' || (preserveModules && variable.isNamespace)) { variable.setRenderNames(null, chunk.variableName); } else { - variable.setRenderNames(chunk.variableName, module.chunk.getVariableExportName(variable)); + variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable) as + | string + | null); } } } diff --git a/src/utils/defaultPlugin.ts b/src/utils/defaultPlugin.ts index 6478e6a3410..5f6af4b08e2 100644 --- a/src/utils/defaultPlugin.ts +++ b/src/utils/defaultPlugin.ts @@ -1,4 +1,4 @@ -import { InputOptions, Plugin } from '../rollup/types'; +import { InputOptions, Plugin, ResolveIdHook } from '../rollup/types'; import { error } from './error'; import { lstatSync, readdirSync, readFileSync, realpathSync } from './fs'; // eslint-disable-line import { basename, dirname, isAbsolute, resolve } from './path'; @@ -6,7 +6,7 @@ import { basename, dirname, isAbsolute, resolve } from './path'; export function getRollupDefaultPlugin(options: InputOptions): Plugin { return { name: 'Rollup Core', - resolveId: createResolveId(options), + resolveId: createResolveId(options) as ResolveIdHook, load(id) { return readFileSync(id, 'utf-8'); }, @@ -63,7 +63,7 @@ function createResolveId(options: InputOptions) { // See https://nodejs.org/api/path.html#path_path_resolve_paths return addJsExtensionIfNecessary( resolve(importer ? dirname(importer) : resolve(), importee), - options.preserveSymlinks + options.preserveSymlinks as boolean ); }; } diff --git a/src/utils/executionOrder.ts b/src/utils/executionOrder.ts index 29f685abb78..fe2c71d075c 100644 --- a/src/utils/executionOrder.ts +++ b/src/utils/executionOrder.ts @@ -80,7 +80,7 @@ function getCyclePath(id: string, parentId: string, parents: { [id: string]: str let curId = parentId; while (curId !== id) { path.push(relativeId(curId)); - curId = parents[curId]; + curId = parents[curId] as string; if (!curId) break; } path.push(path[0]); diff --git a/src/utils/getIndentString.ts b/src/utils/getIndentString.ts index cec1d4c0a5b..fb63f21e94d 100644 --- a/src/utils/getIndentString.ts +++ b/src/utils/getIndentString.ts @@ -19,7 +19,7 @@ function guessIndentString(code: string) { // Otherwise, we need to guess the multiple const min = spaced.reduce((previous, current) => { - const numSpaces = /^ +/.exec(current)[0].length; + const numSpaces = (/^ +/.exec(current) as RegExpExecArray)[0].length; return Math.min(numSpaces, previous); }, Infinity); diff --git a/src/utils/mergeOptions.ts b/src/utils/mergeOptions.ts index 8f8c2629a98..01b7481b2fa 100644 --- a/src/utils/mergeOptions.ts +++ b/src/utils/mergeOptions.ts @@ -93,7 +93,7 @@ export default function mergeOptions({ outputOptions: any; } { const command = getCommandOptions(rawCommandOptions); - const inputOptions = getInputOptions(config, command, defaultOnWarnHandler); + const inputOptions = getInputOptions(config, command, defaultOnWarnHandler as WarningHandler); if (command.output) { Object.assign(command, command.output); @@ -119,7 +119,7 @@ export default function mergeOptions({ const validOutputOptions = Object.keys(outputOptions[0]); addUnknownOptionErrors( unknownOptionErrors, - outputOptions.reduce((allKeys, options) => allKeys.concat(Object.keys(options)), []), + outputOptions.reduce((allKeys, options) => allKeys.concat(Object.keys(options)), []), validOutputOptions, 'output option' ); diff --git a/src/utils/pluginDriver.ts b/src/utils/pluginDriver.ts index be80d7e3cff..8b1f89890a7 100644 --- a/src/utils/pluginDriver.ts +++ b/src/utils/pluginDriver.ts @@ -106,7 +106,7 @@ export function createPluginDriver( }); watcherDeprecationWarningShown = true; } - return watcher.on(event, handler); + return (watcher as RollupWatcher).on(event, handler); } const context: PluginContext = { @@ -126,7 +126,7 @@ export function createPluginDriver( isExternal(id: string, parentId: string, isResolved = false) { return graph.isExternal(id, parentId, isResolved); }, - getAssetFileName, + getAssetFileName: getAssetFileName as (assetId: string) => string, getModuleInfo: (moduleId: string) => { const foundModule = graph.moduleById.get(moduleId); if (foundModule == null) { @@ -163,7 +163,7 @@ export function createPluginDriver( addListener: deprecatedWatchListener, on: deprecatedWatchListener } - : undefined + : (undefined as any) }; return context; }); @@ -178,7 +178,7 @@ export function createPluginDriver( const plugin = plugins[pidx]; let context = pluginContexts[pidx]; const hook = (plugin)[hookName]; - if (!hook) return; + if (!hook) return undefined as any; const deprecatedHookNewName = deprecatedHookNames[hookName]; if (deprecatedHookNewName) @@ -210,6 +210,7 @@ export function createPluginDriver( err.hook = hookName; error(err); } + return undefined as any; } function runHook( @@ -222,7 +223,7 @@ export function createPluginDriver( const plugin = plugins[pidx]; let context = pluginContexts[pidx]; const hook = (plugin)[hookName]; - if (!hook) return; + if (!hook) return undefined as any; const deprecatedHookNewName = deprecatedHookNames[hookName]; if (deprecatedHookNewName) @@ -260,7 +261,7 @@ export function createPluginDriver( const pluginDriver: PluginDriver = { emitAsset, - getAssetFileName, + getAssetFileName: getAssetFileName as (assetId: string) => string, hasLoadersOrTransforms, // chains, ignores returns @@ -268,14 +269,15 @@ export function createPluginDriver( let promise: Promise = Promise.resolve(); for (let i = 0; i < plugins.length; i++) promise = promise.then(() => { - return runHook(name, args, i, false, hookContext); + return runHook(name, args as any[], i, false, hookContext); }); return promise; }, // chains, ignores returns hookSeqSync(name, args, hookContext) { - for (let i = 0; i < plugins.length; i++) runHookSync(name, args, i, false, hookContext); + for (let i = 0; i < plugins.length; i++) + runHookSync(name, args as any[], i, false, hookContext); }, // chains, first non-null result stops and returns @@ -284,7 +286,7 @@ export function createPluginDriver( for (let i = 0; i < plugins.length; i++) { promise = promise.then((result: any) => { if (result != null) return result; - return runHook(name, args, i, false, hookContext); + return runHook(name, args as any[], i, false, hookContext); }); } return promise; @@ -293,7 +295,7 @@ export function createPluginDriver( hookParallel(name, args, hookContext) { const promises: Promise[] = []; for (let i = 0; i < plugins.length; i++) { - const hookPromise = runHook(name, args, i, false, hookContext); + const hookPromise = runHook(name, args as any[], i, false, hookContext); if (!hookPromise) continue; promises.push(hookPromise); } @@ -364,7 +366,7 @@ export function createPluginCache(cache: SerializablePluginCache): PluginCache { } export function trackPluginCache(pluginCache: PluginCache) { - const result = { used: false, cache: undefined }; + const result = { used: false, cache: (undefined as any) as PluginCache }; result.cache = { has(id: string) { result.used = true; @@ -391,7 +393,7 @@ const noCache: PluginCache = { return false; }, get() { - return undefined; + return undefined as any; }, set() {}, delete() { @@ -420,7 +422,7 @@ const uncacheablePlugin: (pluginName: string) => PluginCache = pluginName => ({ }, get() { uncacheablePluginError(pluginName); - return undefined; + return undefined as any; }, set() { uncacheablePluginError(pluginName); diff --git a/src/utils/renderHelpers.ts b/src/utils/renderHelpers.ts index 00ce060c94b..1bd2925c0fa 100644 --- a/src/utils/renderHelpers.ts +++ b/src/utils/renderHelpers.ts @@ -106,7 +106,7 @@ export function renderStatementList( }) : currentNode.render(code, options); } else { - treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart); + treeshakeNode(currentNode, code, currentNodeStart as number, nextNodeStart); } } else { currentNode.render(code, options); @@ -162,7 +162,7 @@ export function getCommaSeparatedNodesWithBoundaries( splitUpNodes.push({ contentEnd: end, end, - node, + node: node as N, separator: null, start }); diff --git a/src/utils/timers.ts b/src/utils/timers.ts index 884b62dd484..fe82777223e 100644 --- a/src/utils/timers.ts +++ b/src/utils/timers.ts @@ -53,8 +53,8 @@ function timeStartImpl(label: string, level: number = 3) { if (!timers.hasOwnProperty(label)) { timers[label] = { memory: 0, - startMemory: undefined, - startTime: undefined, + startMemory: undefined as any, + startTime: undefined as any, time: 0, totalMemory: 0 }; @@ -128,7 +128,7 @@ export function initialiseTimers(inputOptions: InputOptions) { setTimeHelpers(); timeStart = timeStartImpl; timeEnd = timeEndImpl; - inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers); + inputOptions.plugins = (inputOptions.plugins as Plugin[]).map(getPluginWithTimers); } else { timeStart = NOOP; timeEnd = NOOP; diff --git a/src/utils/transform.ts b/src/utils/transform.ts index b388d3e5f4b..98cce0023ce 100644 --- a/src/utils/transform.ts +++ b/src/utils/transform.ts @@ -103,8 +103,8 @@ export default function transform( [curSource, id], transformReducer, (pluginContext, plugin) => { - curPlugin = plugin; - if (plugin.cacheKey) customTransformCache = true; + curPlugin = plugin as Plugin; + if (curPlugin.cacheKey) customTransformCache = true; else trackedPluginCache = trackPluginCache(pluginContext.cache); let emitAsset: EmitAsset; diff --git a/src/watch/chokidar.ts b/src/watch/chokidar.ts index ea1e361ca94..a0ad43b359a 100644 --- a/src/watch/chokidar.ts +++ b/src/watch/chokidar.ts @@ -6,7 +6,7 @@ let chokidar: typeof chokidarType; try { chokidar = relative('chokidar', process.cwd()); } catch (err) { - chokidar = null; + chokidar = null as any; } export default chokidar; diff --git a/src/watch/fileWatchers.ts b/src/watch/fileWatchers.ts index 0908a2bdf73..c0c60686619 100644 --- a/src/watch/fileWatchers.ts +++ b/src/watch/fileWatchers.ts @@ -15,7 +15,7 @@ export function addTask( isTransformDependency: boolean ) { if (!watchers.has(chokidarOptionsHash)) watchers.set(chokidarOptionsHash, new Map()); - const group = watchers.get(chokidarOptionsHash); + const group = watchers.get(chokidarOptionsHash) as Map; const watcher = group.get(id) || new FileWatcher(id, chokidarOptions, group); if (!watcher.fileExists) { @@ -26,7 +26,7 @@ export function addTask( } export function deleteTask(id: string, target: Task, chokidarOptionsHash: string) { - const group = watchers.get(chokidarOptionsHash); + const group = watchers.get(chokidarOptionsHash) as Map; const watcher = group.get(id); if (watcher) watcher.deleteTask(target, group); } diff --git a/src/watch/index.ts b/src/watch/index.ts index fdef0188b60..cf0ca21b543 100644 --- a/src/watch/index.ts +++ b/src/watch/index.ts @@ -5,6 +5,7 @@ import createFilter from 'rollup-pluginutils/src/createFilter.js'; import rollup, { setWatcher } from '../rollup/index'; import { InputOptions, + ModuleJSON, OutputOptions, RollupBuild, RollupCache, @@ -70,7 +71,7 @@ export class Watcher { if (this.buildTimeout) clearTimeout(this.buildTimeout); this.buildTimeout = setTimeout(() => { - this.buildTimeout = undefined; + this.buildTimeout = undefined as any; this.invalidatedIds.forEach(id => this.emit('change', id)); this.invalidatedIds.clear(); this.emit('restart'); @@ -128,7 +129,7 @@ export class Task { private watcher: Watcher; constructor(watcher: Watcher, config: RollupWatchOptions) { - this.cache = null; + this.cache = null as any; this.watcher = watcher; this.closed = false; @@ -141,7 +142,8 @@ export class Task { this.outputs = outputOptions; this.outputFiles = this.outputs.map(output => { - if (output.file || output.dir) return path.resolve(output.file || output.dir); + if (output.file || output.dir) return path.resolve(output.file || (output.dir as string)); + return undefined as any; }); const watchOptions = inputOptions.watch || {}; @@ -177,11 +179,11 @@ export class Task { invalidate(id: string, isTransformDependency: boolean) { this.invalidated = true; if (isTransformDependency) { - this.cache.modules.forEach(module => { + (this.cache.modules as ModuleJSON[]).forEach(module => { if (!module.transformDependencies || module.transformDependencies.indexOf(id) === -1) return; // effective invalidation - module.originalCode = null; + module.originalCode = null as any; }); } this.watcher.invalidate(id); @@ -207,13 +209,13 @@ export class Task { setWatcher(this.watcher.emitter); return rollup(options) .then(result => { - if (this.closed) return; + if (this.closed) return undefined as any; const watched = (this.watched = new Set()); this.cache = result.cache; this.watchFiles = result.watchFiles; - this.cache.modules.forEach(module => { + (this.cache.modules as ModuleJSON[]).forEach(module => { if (module.transformDependencies) { module.transformDependencies.forEach(depId => { watched.add(depId); diff --git a/tsconfig.json b/tsconfig.json index efb9aa74beb..21275b2672c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -11,6 +11,7 @@ "noUnusedParameters": true, "pretty": true, "skipLibCheck": true, + "strictNullChecks": true, "target": "es5" }, "include": [ From 07f0b10ac1b03d20694868443a326f051d1db580 Mon Sep 17 00:00:00 2001 From: Lukas Taegert-Atkinson Date: Fri, 17 May 2019 16:44:22 +0200 Subject: [PATCH 2/5] Revert logic changes to fix tests --- src/Chunk.ts | 2 +- src/ast/nodes/BreakStatement.ts | 2 +- src/ast/nodes/ExportNamedDeclaration.ts | 2 +- src/ast/nodes/MemberExpression.ts | 40 ++++++++++++++----------- src/ast/nodes/ReturnStatement.ts | 3 +- src/ast/nodes/VariableDeclaration.ts | 2 +- src/ast/nodes/YieldExpression.ts | 3 +- src/ast/nodes/shared/ClassNode.ts | 7 ++--- src/ast/nodes/shared/FunctionNode.ts | 2 +- src/ast/variables/LocalVariable.ts | 24 +++++++-------- src/finalisers/system.ts | 2 +- src/utils/chunkColouring.ts | 6 ++-- 12 files changed, 51 insertions(+), 44 deletions(-) diff --git a/src/Chunk.ts b/src/Chunk.ts index efaba302d91..c1150c856c9 100644 --- a/src/Chunk.ts +++ b/src/Chunk.ts @@ -711,7 +711,7 @@ export default class Chunk { ): boolean { const seen = new Set(); function visitDep(dep: Chunk | ExternalModule): boolean { - if (seen.has(dep)) return false; + if (seen.has(dep)) return undefined as any; seen.add(dep); if (dep instanceof Chunk) { for (const subDep of dep.dependencies) { diff --git a/src/ast/nodes/BreakStatement.ts b/src/ast/nodes/BreakStatement.ts index 84dc8e366ef..cb4eb5f6538 100644 --- a/src/ast/nodes/BreakStatement.ts +++ b/src/ast/nodes/BreakStatement.ts @@ -11,7 +11,7 @@ export default class BreakStatement extends StatementBase { return ( super.hasEffects(options) || !options.ignoreBreakStatements() || - !!(this.label && !options.ignoreLabel(this.label.name)) + ((this.label && !options.ignoreLabel(this.label.name)) as boolean) ); } } diff --git a/src/ast/nodes/ExportNamedDeclaration.ts b/src/ast/nodes/ExportNamedDeclaration.ts index 37a2fc4b6c2..fb3c1f03984 100644 --- a/src/ast/nodes/ExportNamedDeclaration.ts +++ b/src/ast/nodes/ExportNamedDeclaration.ts @@ -23,7 +23,7 @@ export default class ExportNamedDeclaration extends NodeBase { } hasEffects(options: ExecutionPathOptions) { - return !!(this.declaration && this.declaration.hasEffects(options)); + return (this.declaration && this.declaration.hasEffects(options)) as boolean; } initialise() { diff --git a/src/ast/nodes/MemberExpression.ts b/src/ast/nodes/MemberExpression.ts index eff34926bc4..280b00c19bc 100644 --- a/src/ast/nodes/MemberExpression.ts +++ b/src/ast/nodes/MemberExpression.ts @@ -88,26 +88,32 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE if (this.bound) return; this.bound = true; const path = getPathIfNotComputed(this); - if (path) { - const baseVariable = this.scope.findVariable(path[0].key); - if (baseVariable && baseVariable.isNamespace) { - const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1)); - if (!resolvedVariable) { - super.bind(); - } else if (typeof resolvedVariable === 'string') { - this.replacement = resolvedVariable; - } else { - if (resolvedVariable.isExternal && (resolvedVariable).module) { - (resolvedVariable).module.suggestName(path[0].key); - } - this.variable = resolvedVariable; - this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable); + const baseVariable = path && this.scope.findVariable(path[0].key); + if (baseVariable && baseVariable.isNamespace) { + const resolvedVariable = this.resolveNamespaceVariables( + baseVariable, + (path as PathWithPositions).slice(1) + ); + if (!resolvedVariable) { + super.bind(); + } else if (typeof resolvedVariable === 'string') { + this.replacement = resolvedVariable; + } else { + if (resolvedVariable.isExternal && (resolvedVariable).module) { + (resolvedVariable).module.suggestName( + (path as PathWithPositions)[0].key + ); } + this.variable = resolvedVariable; + this.scope.addNamespaceMemberAccess( + getStringFromPath(path as PathWithPositions), + resolvedVariable + ); } - return; + } else { + super.bind(); + if (this.propertyKey === null) this.analysePropertyKey(); } - super.bind(); - if (this.propertyKey === null) this.analysePropertyKey(); } deoptimizeCache() { diff --git a/src/ast/nodes/ReturnStatement.ts b/src/ast/nodes/ReturnStatement.ts index 37e3ea0675a..bc7b4d9dab2 100644 --- a/src/ast/nodes/ReturnStatement.ts +++ b/src/ast/nodes/ReturnStatement.ts @@ -11,7 +11,8 @@ export default class ReturnStatement extends StatementBase { hasEffects(options: ExecutionPathOptions) { return ( - !options.ignoreReturnAwaitYield() || !!(this.argument && this.argument.hasEffects(options)) + !options.ignoreReturnAwaitYield() || + ((this.argument && this.argument.hasEffects(options)) as boolean) ); } diff --git a/src/ast/nodes/VariableDeclaration.ts b/src/ast/nodes/VariableDeclaration.ts index f8c76959144..0f83f423114 100644 --- a/src/ast/nodes/VariableDeclaration.ts +++ b/src/ast/nodes/VariableDeclaration.ts @@ -15,7 +15,7 @@ import { NodeBase } from './shared/Node'; import VariableDeclarator from './VariableDeclarator'; function isReassignedExportsMember(variable: Variable): boolean { - return !!(variable.renderBaseName && variable.exportName) && variable.isReassigned; + return (variable.renderBaseName && variable.exportName && variable.isReassigned) as boolean; } function areAllDeclarationsIncludedAndNotExported(declarations: VariableDeclarator[]): boolean { diff --git a/src/ast/nodes/YieldExpression.ts b/src/ast/nodes/YieldExpression.ts index 011ad2444a8..b26b33bb66f 100644 --- a/src/ast/nodes/YieldExpression.ts +++ b/src/ast/nodes/YieldExpression.ts @@ -19,7 +19,8 @@ export default class YieldExpression extends NodeBase { hasEffects(options: ExecutionPathOptions) { return ( - !options.ignoreReturnAwaitYield() || !!(this.argument && this.argument.hasEffects(options)) + !options.ignoreReturnAwaitYield() || + ((this.argument && this.argument.hasEffects(options)) as boolean) ); } diff --git a/src/ast/nodes/shared/ClassNode.ts b/src/ast/nodes/shared/ClassNode.ts index 3f006dc46ad..eba037768a6 100644 --- a/src/ast/nodes/shared/ClassNode.ts +++ b/src/ast/nodes/shared/ClassNode.ts @@ -29,10 +29,9 @@ export default class ClassNode extends NodeBase { callOptions: CallOptions, options: ExecutionPathOptions ) { - return ( - this.body.hasEffectsWhenCalledAtPath(path, callOptions, options) || - !!(this.superClass && this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, options)) - ); + return (this.body.hasEffectsWhenCalledAtPath(path, callOptions, options) || + (this.superClass && + this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, options))) as boolean; } initialise() { diff --git a/src/ast/nodes/shared/FunctionNode.ts b/src/ast/nodes/shared/FunctionNode.ts index 93a625efbe9..4e3b5e7fe05 100644 --- a/src/ast/nodes/shared/FunctionNode.ts +++ b/src/ast/nodes/shared/FunctionNode.ts @@ -41,7 +41,7 @@ export default class FunctionNode extends NodeBase { } hasEffects(options: ExecutionPathOptions) { - return !!(this.id && this.id.hasEffects(options)); + return (this.id && this.id.hasEffects(options)) as boolean; } hasEffectsWhenAccessedAtPath(path: ObjectPath) { diff --git a/src/ast/variables/LocalVariable.ts b/src/ast/variables/LocalVariable.ts index b6e4c44d9f4..fd8c2720f01 100644 --- a/src/ast/variables/LocalVariable.ts +++ b/src/ast/variables/LocalVariable.ts @@ -129,11 +129,12 @@ export default class LocalVariable extends Variable { return ( this.isReassigned || path.length > MAX_PATH_DEPTH || - !!( - this.init && + ((this.init && !options.hasNodeBeenAccessedAtPath(path, this.init) && - this.init.hasEffectsWhenAccessedAtPath(path, options.addAccessedNodeAtPath(path, this.init)) - ) + this.init.hasEffectsWhenAccessedAtPath( + path, + options.addAccessedNodeAtPath(path, this.init) + )) as boolean) ); } @@ -142,11 +143,12 @@ export default class LocalVariable extends Variable { if (path.length === 0) return false; return ( this.isReassigned || - !!( - this.init && + ((this.init && !options.hasNodeBeenAssignedAtPath(path, this.init) && - this.init.hasEffectsWhenAssignedAtPath(path, options.addAssignedNodeAtPath(path, this.init)) - ) + this.init.hasEffectsWhenAssignedAtPath( + path, + options.addAssignedNodeAtPath(path, this.init) + )) as boolean) ); } @@ -158,15 +160,13 @@ export default class LocalVariable extends Variable { if (path.length > MAX_PATH_DEPTH) return true; return ( this.isReassigned || - !!( - this.init && + ((this.init && !options.hasNodeBeenCalledAtPathWithOptions(path, this.init, callOptions) && this.init.hasEffectsWhenCalledAtPath( path, callOptions, options.addCalledNodeAtPathWithOptions(path, this.init, callOptions) - ) - ) + )) as boolean) ); } diff --git a/src/finalisers/system.ts b/src/finalisers/system.ts index cde7b56fd08..d46d6538a46 100644 --- a/src/finalisers/system.ts +++ b/src/finalisers/system.ts @@ -97,7 +97,7 @@ export default function system( const dependencyIds = dependencies.map(m => `'${m.id}'`); const importBindings: string[] = []; - let starExcludes: Set | undefined = undefined; + let starExcludes: Set | undefined; const setters: string[] = []; dependencies.forEach(({ imports, reexports }) => { diff --git a/src/utils/chunkColouring.ts b/src/utils/chunkColouring.ts index 418c77c2545..5084b2e5932 100644 --- a/src/utils/chunkColouring.ts +++ b/src/utils/chunkColouring.ts @@ -9,7 +9,7 @@ export function assignChunkColouringHashes( manualChunkModules: Record ) { let currentEntry: Module, currentEntryHash: Uint8Array; - let modulesVisitedForCurrentEntry: { [id: string]: boolean }; + let modulesVisitedForCurrentEntry: { [id: string]: boolean | null }; const handledEntryPoints: { [id: string]: boolean } = {}; const dynamicImports: Module[] = []; @@ -68,7 +68,7 @@ Try defining "${chunkName}" first in the manualChunks definitions of the Rollup for (currentEntry of entryModules) { handledEntryPoints[currentEntry.id] = true; currentEntryHash = randomUint8Array(10); - modulesVisitedForCurrentEntry = { [currentEntry.id]: false }; + modulesVisitedForCurrentEntry = { [currentEntry.id]: null }; addCurrentEntryColourToModule(currentEntry); } @@ -78,7 +78,7 @@ Try defining "${chunkName}" first in the manualChunks definitions of the Rollup } handledEntryPoints[currentEntry.id] = true; currentEntryHash = randomUint8Array(10); - modulesVisitedForCurrentEntry = { [currentEntry.id]: false }; + modulesVisitedForCurrentEntry = { [currentEntry.id]: null }; addCurrentEntryColourToModule(currentEntry); } } From 4e4642b89bf8e9420740dd4e95ae1eceea61980c Mon Sep 17 00:00:00 2001 From: Lukas Taegert-Atkinson Date: Fri, 17 May 2019 16:59:52 +0200 Subject: [PATCH 3/5] Fix remaining missing types --- bin/src/logging.ts | 2 +- bin/src/run/batchWarnings.ts | 45 +++++++++++++++++++----------------- bin/src/run/build.ts | 12 ++++++---- bin/src/run/watch.ts | 25 ++++++++++++-------- browser/path.ts | 4 ++-- 5 files changed, 50 insertions(+), 38 deletions(-) diff --git a/bin/src/logging.ts b/bin/src/logging.ts index beabafab69f..c5cf9482633 100644 --- a/bin/src/logging.ts +++ b/bin/src/logging.ts @@ -20,7 +20,7 @@ export function handleError(err: RollupError, recover = false) { } if (err.loc) { - stderr(`${relativeId(err.loc.file || err.id)} (${err.loc.line}:${err.loc.column})`); + stderr(`${relativeId((err.loc.file || err.id) as string)} (${err.loc.line}:${err.loc.column})`); } else if (err.id) { stderr(relativeId(err.id)); } diff --git a/bin/src/run/batchWarnings.ts b/bin/src/run/batchWarnings.ts index bfc0e525de7..4483764411b 100644 --- a/bin/src/run/batchWarnings.ts +++ b/bin/src/run/batchWarnings.ts @@ -23,13 +23,13 @@ export default function batchWarnings() { warning = { code: 'UNKNOWN', message: warning }; } - if (warning.code in immediateHandlers) { - immediateHandlers[warning.code](warning); + if ((warning.code as string) in immediateHandlers) { + immediateHandlers[warning.code as string](warning); return; } - if (!allWarnings.has(warning.code)) allWarnings.set(warning.code, []); - allWarnings.get(warning.code).push(warning); + if (!allWarnings.has(warning.code as string)) allWarnings.set(warning.code as string, []); + (allWarnings.get(warning.code as string) as RollupWarning[]).push(warning); count += 1; }, @@ -44,7 +44,10 @@ export default function batchWarnings() { if (deferredHandlers[a]) return -1; if (deferredHandlers[b]) return 1; - return allWarnings.get(b).length - allWarnings.get(a).length; + return ( + (allWarnings.get(b) as RollupWarning[]).length - + (allWarnings.get(a) as RollupWarning[]).length + ); }); codes.forEach(code => { @@ -52,9 +55,9 @@ export default function batchWarnings() { const warnings = allWarnings.get(code); if (handler) { - handler.fn(warnings); + handler.fn(warnings as RollupWarning[]); } else { - warnings.forEach(warning => { + (warnings as RollupWarning[]).forEach(warning => { title(warning.message); if (warning.url) info(warning.url); @@ -91,12 +94,12 @@ const immediateHandlers: { title(`Missing shims for Node.js built-ins`); const detail = - warning.modules.length === 1 - ? `'${warning.modules[0]}'` - : `${warning.modules + (warning.modules as string[]).length === 1 + ? `'${(warning.modules as string[])[0]}'` + : `${(warning.modules as string[]) .slice(0, -1) .map((name: string) => `'${name}'`) - .join(', ')} and '${warning.modules.slice(-1)}'`; + .join(', ')} and '${(warning.modules as string[]).slice(-1)}'`; stderr( `Creating a browser bundle that depends on ${detail}. You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins` ); @@ -156,9 +159,9 @@ const deferredHandlers: { info('https://rollupjs.org/guide/en#error-name-is-not-exported-by-module-'); warnings.forEach(warning => { - stderr(tc.bold(warning.importer)); + stderr(tc.bold(warning.importer as string)); stderr(`${warning.missing} is not exported by ${warning.exporter}`); - stderr(tc.gray(warning.frame)); + stderr(tc.gray(warning.frame as string)); }); }, priority: 1 @@ -195,10 +198,10 @@ const deferredHandlers: { title(`Conflicting re-exports`); warnings.forEach(warning => { stderr( - `${tc.bold(relativeId(warning.reexporter))} re-exports '${ + `${tc.bold(relativeId(warning.reexporter as string))} re-exports '${ warning.name - }' from both ${relativeId(warning.sources[0])} and ${relativeId( - warning.sources[1] + }' from both ${relativeId((warning.sources as string[])[0])} and ${relativeId( + (warning.sources as string[])[1] )} (will be ignored)` ); }); @@ -213,7 +216,7 @@ const deferredHandlers: { `Use output.globals to specify browser global variable names corresponding to external modules` ); warnings.forEach(warning => { - stderr(`${tc.bold(warning.source)} (guessing '${warning.guess}')`); + stderr(`${tc.bold(warning.source as string)} (guessing '${warning.guess}')`); }); }, priority: 1 @@ -252,7 +255,7 @@ const deferredHandlers: { nestedByMessage.forEach(({ key: message, items }) => { title(`${plugin} plugin: ${message}`); items.forEach(warning => { - if (warning.url !== lastUrl) info((lastUrl = warning.url)); + if (warning.url !== lastUrl) info((lastUrl = warning.url as string)); if (warning.id) { let loc = relativeId(warning.id); @@ -290,10 +293,10 @@ function nest(array: T[], prop: string) { key }); - nested.push(lookup.get(key)); + nested.push(lookup.get(key) as { items: T[]; key: string }); } - lookup.get(key).items.push(item); + (lookup.get(key) as { items: T[]; key: string }).items.push(item); }); return nested; @@ -305,7 +308,7 @@ function showTruncatedWarnings(warnings: RollupWarning[]) { const sliced = nestedByModule.length > 5 ? nestedByModule.slice(0, 3) : nestedByModule; sliced.forEach(({ key: id, items }) => { stderr(tc.bold(relativeId(id))); - stderr(tc.gray(items[0].frame)); + stderr(tc.gray(items[0].frame as string)); if (items.length > 1) { stderr(`...and ${items.length - 1} other ${items.length > 2 ? 'occurrences' : 'occurrence'}`); diff --git a/bin/src/run/build.ts b/bin/src/run/build.ts index 2c3985199f2..f6ecbfb23c8 100644 --- a/bin/src/run/build.ts +++ b/bin/src/run/build.ts @@ -6,7 +6,8 @@ import { OutputAsset, OutputChunk, OutputOptions, - RollupBuild + RollupBuild, + SourceMap } from '../../../src/rollup/types'; import relativeId from '../../../src/utils/relativeId'; import { handleError, stderr } from '../logging'; @@ -23,9 +24,11 @@ export default function build( const useStdout = !outputOptions[0].file && !outputOptions[0].dir; const start = Date.now(); - const files = useStdout ? ['stdout'] : outputOptions.map(t => relativeId(t.file || t.dir)); + const files = useStdout + ? ['stdout'] + : outputOptions.map(t => relativeId(t.file || (t.dir as string))); if (!silent) { - let inputFiles: string; + let inputFiles: string = undefined as any; if (typeof inputOptions.input === 'string') { inputFiles = inputOptions.input; } else if (inputOptions.input instanceof Array) { @@ -58,7 +61,8 @@ export default function build( } else { source = (file).code; if (output.sourcemap === 'inline') { - source += `\n//# ${SOURCEMAPPING_URL}=${(file).map.toUrl()}\n`; + source += `\n//# ${SOURCEMAPPING_URL}=${((file) + .map as SourceMap).toUrl()}\n`; } } if (outputs.length > 1) diff --git a/bin/src/run/watch.ts b/bin/src/run/watch.ts index d09ab82bff2..08cd1192ead 100644 --- a/bin/src/run/watch.ts +++ b/bin/src/run/watch.ts @@ -8,7 +8,8 @@ import { InputOption, RollupBuild, RollupError, - RollupWatchOptions + RollupWatchOptions, + WatcherOptions } from '../../../src/rollup/types'; import mergeOptions from '../../../src/utils/mergeOptions'; import relativeId from '../../../src/utils/relativeId'; @@ -44,7 +45,9 @@ export default function watch( const initialConfigs = processConfigs(configs); - const clearScreen = initialConfigs.every(config => config.watch.clearScreen !== false); + const clearScreen = initialConfigs.every( + config => (config.watch as WatcherOptions).clearScreen !== false + ); const screen = alternateScreen(isTTY && clearScreen); screen.open(); @@ -77,7 +80,7 @@ export default function watch( if ( (merged.inputOptions).watch && - (merged.inputOptions).watch.clearScreen === false + ((merged.inputOptions).watch as WatcherOptions).clearScreen === false ) { processConfigsErr = stderr; } @@ -95,13 +98,13 @@ export default function watch( switch (event.code) { case 'FATAL': screen.close(); - handleError(event.error, true); + handleError(event.error as RollupError, true); process.exit(1); break; case 'ERROR': warnings.flush(); - handleError(event.error, true); + handleError(event.error as RollupError, true); break; case 'START': @@ -116,13 +119,15 @@ export default function watch( if (typeof input !== 'string') { input = Array.isArray(input) ? input.join(', ') - : Object.keys(input) + : Object.keys(>input) .map(key => (>input)[key]) .join(', '); } stderr( tc.cyan( - `bundles ${tc.bold(input)} → ${tc.bold(event.output.map(relativeId).join(', '))}...` + `bundles ${tc.bold(input)} → ${tc.bold( + (event.output as string[]).map(relativeId).join(', ') + )}...` ) ); } @@ -133,9 +138,9 @@ export default function watch( if (!silent) stderr( tc.green( - `created ${tc.bold(event.output.map(relativeId).join(', '))} in ${tc.bold( - ms(event.duration) - )}` + `created ${tc.bold( + (event.output as string[]).map(relativeId).join(', ') + )} in ${tc.bold(ms(event.duration))}` ) ); if (event.result && event.result.getTimings) { diff --git a/browser/path.ts b/browser/path.ts index 3d83c31e8af..a774121edcf 100644 --- a/browser/path.ts +++ b/browser/path.ts @@ -28,7 +28,7 @@ export function dirname(path: string) { } export function extname(path: string) { - const match = /\.[^.]+$/.exec(basename(path)); + const match = /\.[^.]+$/.exec(basename(path) as string); if (!match) return ''; return match[0]; } @@ -57,7 +57,7 @@ export function relative(from: string, to: string) { } export function resolve(...paths: string[]) { - let resolvedParts = paths.shift().split(/[/\\]/); + let resolvedParts = (paths.shift() as string).split(/[/\\]/); paths.forEach(path => { if (isAbsolute(path)) { From fa7434543bfe71fa256078d6d7003332455d5cc5 Mon Sep 17 00:00:00 2001 From: Lukas Taegert-Atkinson Date: Fri, 17 May 2019 17:58:45 +0200 Subject: [PATCH 4/5] Enforce consistent type-casting style --- bin/src/logging.ts | 4 ++-- bin/src/run/batchWarnings.ts | 2 +- bin/src/run/build.ts | 12 +++++------ bin/src/run/index.ts | 2 +- bin/src/run/watch.ts | 8 ++++---- src/Chunk.ts | 4 ++-- src/Graph.ts | 16 +++++++-------- src/Module.ts | 23 +++++++++++----------- src/ast/ExecutionPathOptions.ts | 2 +- src/ast/nodes/AwaitExpression.ts | 2 +- src/ast/nodes/BinaryExpression.ts | 2 +- src/ast/nodes/BlockStatement.ts | 4 ++-- src/ast/nodes/CatchClause.ts | 8 +++++--- src/ast/nodes/ClassDeclaration.ts | 7 ++----- src/ast/nodes/ConditionalExpression.ts | 2 +- src/ast/nodes/ExportDefaultDeclaration.ts | 2 +- src/ast/nodes/ExportNamedDeclaration.ts | 2 +- src/ast/nodes/FunctionDeclaration.ts | 7 ++----- src/ast/nodes/Identifier.ts | 8 ++++---- src/ast/nodes/Literal.ts | 2 +- src/ast/nodes/LogicalExpression.ts | 2 +- src/ast/nodes/MemberExpression.ts | 14 ++++++------- src/ast/nodes/ObjectExpression.ts | 2 +- src/ast/nodes/ObjectPattern.ts | 2 +- src/ast/nodes/SequenceExpression.ts | 2 +- src/ast/nodes/TaggedTemplateExpression.ts | 6 +++--- src/ast/nodes/TemplateLiteral.ts | 5 ++++- src/ast/nodes/ThisExpression.ts | 2 +- src/ast/nodes/UnaryExpression.ts | 2 +- src/ast/nodes/shared/FunctionNode.ts | 12 +++++------ src/ast/nodes/shared/Node.ts | 16 +++++++-------- src/ast/scopes/Scope.ts | 2 +- src/ast/variables/ArgumentsVariable.ts | 4 ++-- src/ast/variables/ExportDefaultVariable.ts | 6 +++--- src/ast/variables/LocalVariable.ts | 4 ++-- src/rollup/index.ts | 20 +++++++++---------- src/utils/collapseSourcemaps.ts | 12 +++++------ src/utils/error.ts | 2 +- src/utils/getOriginalLocation.ts | 2 +- src/utils/mergeOptions.ts | 4 ++-- src/utils/pluginDriver.ts | 12 +++++------ src/utils/pureComments.ts | 4 ++-- src/utils/timers.ts | 2 +- src/utils/transform.ts | 4 ++-- tslint.json | 1 + 45 files changed, 131 insertions(+), 132 deletions(-) diff --git a/bin/src/logging.ts b/bin/src/logging.ts index f38fda7d326..39e3f8f701a 100644 --- a/bin/src/logging.ts +++ b/bin/src/logging.ts @@ -9,8 +9,8 @@ export function handleError(err: RollupError, recover = false) { let description = err.message || err; if (err.name) description = `${err.name}: ${description}`; const message = - ((<{ plugin?: string }>err).plugin - ? `(${(<{ plugin?: string }>err).plugin} plugin) ${description}` + ((err as { plugin?: string }).plugin + ? `(${(err as { plugin?: string }).plugin} plugin) ${description}` : description) || err; stderr(tc.bold.red(`[!] ${tc.bold(message.toString())}`)); diff --git a/bin/src/run/batchWarnings.ts b/bin/src/run/batchWarnings.ts index 4483764411b..3d8b033394b 100644 --- a/bin/src/run/batchWarnings.ts +++ b/bin/src/run/batchWarnings.ts @@ -286,7 +286,7 @@ function nest(array: T[], prop: string) { const lookup = new Map(); array.forEach(item => { - const key = (item)[prop]; + const key = (item as any)[prop]; if (!lookup.has(key)) { lookup.set(key, { items: [], diff --git a/bin/src/run/build.ts b/bin/src/run/build.ts index f6ecbfb23c8..73fb65a2e2f 100644 --- a/bin/src/run/build.ts +++ b/bin/src/run/build.ts @@ -35,7 +35,7 @@ export default function build( inputFiles = inputOptions.input.join(', '); } else if (typeof inputOptions.input === 'object' && inputOptions.input !== null) { inputFiles = Object.keys(inputOptions.input) - .map(name => (>inputOptions.input)[name]) + .map(name => (inputOptions.input as Record)[name]) .join(', '); } stderr(tc.cyan(`\n${tc.bold(inputFiles)} → ${tc.bold(files.join(', '))}...`)); @@ -56,12 +56,12 @@ export default function build( return bundle.generate(output).then(({ output: outputs }) => { for (const file of outputs) { let source: string | Buffer; - if ((file).isAsset) { - source = (file).source; + if ((file as OutputAsset).isAsset) { + source = (file as OutputAsset).source; } else { - source = (file).code; + source = (file as OutputChunk).code; if (output.sourcemap === 'inline') { - source += `\n//# ${SOURCEMAPPING_URL}=${((file) + source += `\n//# ${SOURCEMAPPING_URL}=${((file as OutputChunk) .map as SourceMap).toUrl()}\n`; } } @@ -72,7 +72,7 @@ export default function build( }); } - return Promise.all(outputOptions.map(output => >bundle.write(output))).then( + return Promise.all(outputOptions.map(output => bundle.write(output) as Promise)).then( () => bundle ); }) diff --git a/bin/src/run/index.ts b/bin/src/run/index.ts index d3107c01993..e4206c80e8e 100644 --- a/bin/src/run/index.ts +++ b/bin/src/run/index.ts @@ -89,7 +89,7 @@ export default function runRollup(command: any) { .then(configs => execute(configFile, configs, command)) .catch(handleError); } else { - return execute(configFile, [{ input: null }], command); + return execute(configFile, [{ input: null }] as any, command); } } diff --git a/bin/src/run/watch.ts b/bin/src/run/watch.ts index 4b83a755503..477a5e59765 100644 --- a/bin/src/run/watch.ts +++ b/bin/src/run/watch.ts @@ -79,8 +79,8 @@ export default function watch( }); if ( - (merged.inputOptions).watch && - ((merged.inputOptions).watch as WatcherOptions).clearScreen === false + (merged.inputOptions as RollupWatchOptions).watch && + ((merged.inputOptions as RollupWatchOptions).watch as WatcherOptions).clearScreen === false ) { processConfigsErr = stderr; } @@ -119,8 +119,8 @@ export default function watch( if (typeof input !== 'string') { input = Array.isArray(input) ? input.join(', ') - : Object.keys(>input) - .map(key => (>input)[key]) + : Object.keys(input as Record) + .map(key => (input as Record)[key]) .join(', '); } stderr( diff --git a/src/Chunk.ts b/src/Chunk.ts index 1a8f8901108..6fdc53bc7a5 100644 --- a/src/Chunk.ts +++ b/src/Chunk.ts @@ -849,7 +849,7 @@ export default class Chunk { let importName: string; let needsLiveBinding = false; if (exportName[0] === '*') { - exportModule = this.graph.moduleById.get(exportName.substr(1)); + exportModule = this.graph.moduleById.get(exportName.substr(1)) as ExternalModule; importName = exportName = '*'; } else { const variable = this.exportNames[exportName]; @@ -930,7 +930,7 @@ export default class Chunk { globalName, id, // chunk id updated on render imports: imports.length > 0 ? imports : (null as any), - isChunk: !(dep).isExternal, + isChunk: !(dep as ExternalModule).isExternal, name: dep.variableName, namedExportsMode, reexports diff --git a/src/Graph.ts b/src/Graph.ts index b55cc7171ae..3e95d2b223f 100644 --- a/src/Graph.ts +++ b/src/Graph.ts @@ -116,11 +116,11 @@ export default class Graph { if (this.treeshake) { this.treeshakingOptions = options.treeshake ? { - annotations: (options.treeshake).annotations !== false, - moduleSideEffects: (options.treeshake).moduleSideEffects, + annotations: (options.treeshake as TreeshakingOptions).annotations !== false, + moduleSideEffects: (options.treeshake as TreeshakingOptions).moduleSideEffects, propertyReadSideEffects: - (options.treeshake).propertyReadSideEffects !== false, - pureExternalModules: (options.treeshake).pureExternalModules + (options.treeshake as TreeshakingOptions).propertyReadSideEffects !== false, + pureExternalModules: (options.treeshake as TreeshakingOptions).pureExternalModules } : { annotations: true, @@ -173,7 +173,7 @@ export default class Graph { acornPluginsToInject.push(injectBigInt); if (options.experimentalTopLevelAwait) { - (this.acornOptions).allowAwaitOutsideFunction = true; + (this.acornOptions as any).allowAwaitOutsideFunction = true; } const acornInjectPlugins = options.acornInjectPlugins; @@ -184,7 +184,7 @@ export default class Graph { ? [acornInjectPlugins] : []) ); - this.acornParser = acorn.Parser.extend(...acornPluginsToInject); + this.acornParser = acorn.Parser.extend(...acornPluginsToInject) as any; this.moduleLoader = new ModuleLoader( this, this.moduleById, @@ -356,10 +356,10 @@ export default class Graph { if (allDeleted) delete this.pluginCache[name]; } - return { + return { modules: this.modules.map(module => module.toJSON()), plugins: this.pluginCache - }; + } as any; } includeMarked(modules: Module[]) { diff --git a/src/Module.ts b/src/Module.ts index 50a48b483c6..0566c3e161d 100644 --- a/src/Module.ts +++ b/src/Module.ts @@ -281,7 +281,7 @@ export default class Module { return; } - for (const name of (module).getAllExports()) { + for (const name of (module as Module).getAllExports()) { if (name !== 'default') allExports[name] = true; } }); @@ -365,7 +365,7 @@ export default class Module { return this.getOrCreateNamespace(); } else { // export * from 'external' - const module = this.graph.moduleById.get(name.slice(1)); + const module = this.graph.moduleById.get(name.slice(1)) as ExternalModule; return module.getVariableForExportName('*'); } } @@ -440,7 +440,7 @@ export default class Module { const variable = this.getVariableForExportName(name) as Variable; if (variable.isExternal) { - variable.reexported = (variable).module.reexported = true; + variable.reexported = (variable as ExternalVariable).module.reexported = true; } else if (!variable.included) { variable.include(); variable.deoptimizePath(UNKNOWN_PATH); @@ -463,7 +463,7 @@ export default class Module { if (id) { const module = this.graph.moduleById.get(id); - this.dependencies.push(module); + this.dependencies.push(module as Module); } } for (const { resolution } of this.dynamicImports) { @@ -602,7 +602,7 @@ export default class Module { const otherModule = importDeclaration.module as Module | ExternalModule; if (!otherModule.isExternal && importDeclaration.name === '*') { - return (otherModule).getOrCreateNamespace(); + return (otherModule as Module).getOrCreateNamespace(); } const declaration = otherModule.getVariableForExportName(importDeclaration.name); @@ -638,7 +638,8 @@ export default class Module { private addExport( node: ExportAllDeclaration | ExportNamedDeclaration | ExportDefaultDeclaration ) { - const source = (node).source && (node).source.value; + const source = + (node as ExportAllDeclaration).source && (node as ExportAllDeclaration).source.value; // export { name } from './other' if (source) { @@ -649,7 +650,7 @@ export default class Module { // When an unknown import is encountered, we see if one of them can satisfy it. this.exportAllSources.push(source); } else { - for (const specifier of (node).specifiers) { + for (const specifier of (node as ExportNamedDeclaration).specifiers) { const name = specifier.exported.name; if (this.exports[name] || this.reexports[name]) { @@ -688,12 +689,12 @@ export default class Module { identifier: node.variable.getOriginalVariableName() as string | undefined, localName: 'default' }; - } else if ((node).declaration) { + } else if ((node as ExportNamedDeclaration).declaration) { // export var { foo, bar } = ... // export var foo = 42; // export var a = 1, b = 2, c = 3; // export function foo () {} - const declaration = (node).declaration as + const declaration = (node as ExportNamedDeclaration).declaration as | FunctionDeclaration | ClassDeclaration | VariableDeclaration; @@ -711,7 +712,7 @@ export default class Module { } } else { // export { foo, bar, baz } - for (const specifier of (node).specifiers) { + for (const specifier of (node as ExportNamedDeclaration).specifiers) { const localName = specifier.local.name; const exportedName = specifier.exported.name; @@ -755,7 +756,7 @@ export default class Module { ? 'default' : isNamespace ? '*' - : (specifier).imported.name; + : (specifier as ImportSpecifier).imported.name; this.importDescriptions[localName] = { source, start: specifier.start, name, module: null }; } } diff --git a/src/ast/ExecutionPathOptions.ts b/src/ast/ExecutionPathOptions.ts index d2a216a6c68..6aad03831d7 100644 --- a/src/ast/ExecutionPathOptions.ts +++ b/src/ast/ExecutionPathOptions.ts @@ -79,7 +79,7 @@ export class ExecutionPathOptions { } getArgumentsVariables(): ExpressionEntity[] { - return (this.get(OptionTypes.ARGUMENTS_VARIABLES) || []); + return (this.get(OptionTypes.ARGUMENTS_VARIABLES) || []) as ExpressionEntity[]; } getHasEffectsWhenCalledOptions() { diff --git a/src/ast/nodes/AwaitExpression.ts b/src/ast/nodes/AwaitExpression.ts index 46b19ccc0f7..231af82bb8c 100644 --- a/src/ast/nodes/AwaitExpression.ts +++ b/src/ast/nodes/AwaitExpression.ts @@ -20,7 +20,7 @@ export default class AwaitExpression extends NodeBase { let parent = this.parent; do { if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression) return; - } while ((parent = (parent).parent)); + } while ((parent = (parent as Node).parent as Node)); this.context.usesTopLevelAwait = true; } } diff --git a/src/ast/nodes/BinaryExpression.ts b/src/ast/nodes/BinaryExpression.ts index 18512b209c7..e7cb450981a 100644 --- a/src/ast/nodes/BinaryExpression.ts +++ b/src/ast/nodes/BinaryExpression.ts @@ -57,7 +57,7 @@ export default class BinaryExpression extends NodeBase { const operatorFn = binaryOperators[this.operator]; if (!operatorFn) return UNKNOWN_VALUE; - return operatorFn(leftValue, rightValue); + return operatorFn(leftValue as LiteralValue, rightValue as LiteralValue); } hasEffectsWhenAccessedAtPath(path: ObjectPath, _options: ExecutionPathOptions) { diff --git a/src/ast/nodes/BlockStatement.ts b/src/ast/nodes/BlockStatement.ts index 16b73a63b6b..56355a78ec4 100644 --- a/src/ast/nodes/BlockStatement.ts +++ b/src/ast/nodes/BlockStatement.ts @@ -24,8 +24,8 @@ export default class BlockStatement extends StatementBase { } createScope(parentScope: Scope) { - this.scope = (this.parent).preventChildBlockScope - ? parentScope + this.scope = (this.parent as Node).preventChildBlockScope + ? (parentScope as ChildScope) : new BlockScope(parentScope); } diff --git a/src/ast/nodes/CatchClause.ts b/src/ast/nodes/CatchClause.ts index fb247c2d32c..9d6b0cb10f6 100644 --- a/src/ast/nodes/CatchClause.ts +++ b/src/ast/nodes/CatchClause.ts @@ -26,9 +26,11 @@ export default class CatchClause extends NodeBase { } parseNode(esTreeNode: GenericEsTreeNode) { - this.body = ( - new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope) - ); + this.body = new this.context.nodeConstructors.BlockStatement( + esTreeNode.body, + this, + this.scope + ) as BlockStatement; super.parseNode(esTreeNode); } } diff --git a/src/ast/nodes/ClassDeclaration.ts b/src/ast/nodes/ClassDeclaration.ts index 7b54f22fcd1..917fc05d1e1 100644 --- a/src/ast/nodes/ClassDeclaration.ts +++ b/src/ast/nodes/ClassDeclaration.ts @@ -23,11 +23,8 @@ export default class ClassDeclaration extends ClassNode { parseNode(esTreeNode: GenericEsTreeNode) { if (esTreeNode.id !== null) { - this.id = ( - new this.context.nodeConstructors.Identifier(esTreeNode.id, this, ( - this.scope.parent - )) - ); + this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope + .parent as ChildScope) as Identifier; } super.parseNode(esTreeNode); } diff --git a/src/ast/nodes/ConditionalExpression.ts b/src/ast/nodes/ConditionalExpression.ts index 5069b3350c5..8b5a5688a34 100644 --- a/src/ast/nodes/ConditionalExpression.ts +++ b/src/ast/nodes/ConditionalExpression.ts @@ -164,7 +164,7 @@ export default class ConditionalExpression extends NodeBase implements Deoptimiz (this.usedBranch as ExpressionNode).render(code, options, { isCalleeOfRenderedParent: renderedParentType ? isCalleeOfRenderedParent - : (this.parent).callee === this, + : (this.parent as CallExpression).callee === this, renderedParentType: renderedParentType || this.parent.type }); } else { diff --git a/src/ast/nodes/ExportDefaultDeclaration.ts b/src/ast/nodes/ExportDefaultDeclaration.ts index bf547c45ce9..4354a2f5d15 100644 --- a/src/ast/nodes/ExportDefaultDeclaration.ts +++ b/src/ast/nodes/ExportDefaultDeclaration.ts @@ -58,7 +58,7 @@ export default class ExportDefaultDeclaration extends NodeBase { this.included = false; const declaration = this.declaration as FunctionDeclaration | ClassDeclaration; this.declarationName = - (declaration.id && declaration.id.name) || (this.declaration).name; + (declaration.id && declaration.id.name) || (this.declaration as Identifier).name; this.variable = this.scope.addExportDefaultDeclaration( this.declarationName || this.context.getModuleName(), this, diff --git a/src/ast/nodes/ExportNamedDeclaration.ts b/src/ast/nodes/ExportNamedDeclaration.ts index fb3c1f03984..626839ebcd8 100644 --- a/src/ast/nodes/ExportNamedDeclaration.ts +++ b/src/ast/nodes/ExportNamedDeclaration.ts @@ -36,7 +36,7 @@ export default class ExportNamedDeclaration extends NodeBase { code.remove(start as number, end as number); } else { code.remove(this.start, this.declaration.start); - (this.declaration).render(code, options, { start, end }); + (this.declaration as Node).render(code, options, { start, end }); } } } diff --git a/src/ast/nodes/FunctionDeclaration.ts b/src/ast/nodes/FunctionDeclaration.ts index 9eaf4488edd..37167e1324e 100644 --- a/src/ast/nodes/FunctionDeclaration.ts +++ b/src/ast/nodes/FunctionDeclaration.ts @@ -20,11 +20,8 @@ export default class FunctionDeclaration extends FunctionNode { parseNode(esTreeNode: GenericEsTreeNode) { if (esTreeNode.id !== null) { - this.id = ( - new this.context.nodeConstructors.Identifier(esTreeNode.id, this, ( - this.scope.parent - )) - ); + this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope + .parent as ChildScope) as Identifier; } super.parseNode(esTreeNode); } diff --git a/src/ast/nodes/Identifier.ts b/src/ast/nodes/Identifier.ts index 67ace347707..b8a138f1bea 100644 --- a/src/ast/nodes/Identifier.ts +++ b/src/ast/nodes/Identifier.ts @@ -41,10 +41,10 @@ export default class Identifier extends NodeBase implements PatternNode { } if ( this.variable !== null && - (this.variable).isLocal && - (this.variable).additionalInitializers !== null + (this.variable as LocalVariable).isLocal && + (this.variable as LocalVariable).additionalInitializers !== null ) { - (this.variable).consolidateInitializers(); + (this.variable as LocalVariable).consolidateInitializers(); } } @@ -60,7 +60,7 @@ export default class Identifier extends NodeBase implements PatternNode { this.variable = this.scope.addDeclaration(this, this.context, init, false); break; case 'parameter': - this.variable = (this.scope).addParameterDeclaration(this); + this.variable = (this.scope as FunctionScope).addParameterDeclaration(this); break; default: throw new Error(`Unexpected identifier kind ${kind}.`); diff --git a/src/ast/nodes/Literal.ts b/src/ast/nodes/Literal.ts index 77670b493fe..a68fbb60f18 100644 --- a/src/ast/nodes/Literal.ts +++ b/src/ast/nodes/Literal.ts @@ -73,7 +73,7 @@ export default class Literal extends NodeBase { render(code: MagicString, _options: RenderOptions) { if (typeof this.value === 'string') { - (<[number, number][]>code.indentExclusionRanges).push([this.start + 1, this.end - 1]); + (code.indentExclusionRanges as [number, number][]).push([this.start + 1, this.end - 1]); } } } diff --git a/src/ast/nodes/LogicalExpression.ts b/src/ast/nodes/LogicalExpression.ts index 9783a67a216..04c7b9ec05c 100644 --- a/src/ast/nodes/LogicalExpression.ts +++ b/src/ast/nodes/LogicalExpression.ts @@ -168,7 +168,7 @@ export default class LogicalExpression extends NodeBase implements Deoptimizable (this.usedBranch as ExpressionNode).render(code, options, { isCalleeOfRenderedParent: renderedParentType ? isCalleeOfRenderedParent - : (this.parent).callee === this, + : (this.parent as CallExpression).callee === this, renderedParentType: renderedParentType || this.parent.type }); } else { diff --git a/src/ast/nodes/MemberExpression.ts b/src/ast/nodes/MemberExpression.ts index 62d94ebe72d..24e192031f9 100644 --- a/src/ast/nodes/MemberExpression.ts +++ b/src/ast/nodes/MemberExpression.ts @@ -29,7 +29,7 @@ import { PatternNode } from './shared/Pattern'; function getResolvablePropertyKey(memberExpression: MemberExpression): string | null { return memberExpression.computed ? getResolvableComputedPropertyKey(memberExpression.property) - : (memberExpression.property).name; + : (memberExpression.property as Identifier).name; } function getResolvableComputedPropertyKey(propertyKey: ExpressionNode): string | null { @@ -102,8 +102,8 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE } else if (typeof resolvedVariable === 'string') { this.replacement = resolvedVariable; } else { - if (resolvedVariable.isExternal && (resolvedVariable).module) { - (resolvedVariable).module.suggestName( + if (resolvedVariable.isExternal && (resolvedVariable as ExternalVariable).module) { + (resolvedVariable as ExternalVariable).module.suggestName( (path as PathWithPositions)[0].key ); } @@ -288,12 +288,12 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE if (!baseVariable.isNamespace) return null; const exportName = path[0].key; const variable = baseVariable.isExternal - ? (baseVariable).module.getVariableForExportName(exportName) - : (baseVariable).context.traceExport(exportName); + ? (baseVariable as ExternalVariable).module.getVariableForExportName(exportName) + : (baseVariable as NamespaceVariable).context.traceExport(exportName); if (!variable) { const fileName = baseVariable.isExternal - ? (baseVariable).module.id - : (baseVariable).context.fileName; + ? (baseVariable as ExternalVariable).module.id + : (baseVariable as NamespaceVariable).context.fileName; this.context.warn( { code: 'MISSING_EXPORT', diff --git a/src/ast/nodes/ObjectExpression.ts b/src/ast/nodes/ObjectExpression.ts index d8758ec7631..0e50979a6f6 100644 --- a/src/ast/nodes/ObjectExpression.ts +++ b/src/ast/nodes/ObjectExpression.ts @@ -313,7 +313,7 @@ export default class ObjectExpression extends NodeBase { } else if (property.key instanceof Identifier) { key = property.key.name; } else { - key = String((property.key).value); + key = String((property.key as Literal).value); } const propertyMapProperty = (this.propertyMap as PropertyMap)[key]; if (!propertyMapProperty) { diff --git a/src/ast/nodes/ObjectPattern.ts b/src/ast/nodes/ObjectPattern.ts index 550fdc08582..6752f990c77 100644 --- a/src/ast/nodes/ObjectPattern.ts +++ b/src/ast/nodes/ObjectPattern.ts @@ -15,7 +15,7 @@ export default class ObjectPattern extends NodeBase implements PatternNode { addExportedVariables(variables: Variable[]): void { for (const property of this.properties) { if (property.type === NodeType.Property) { - ((property.value)).addExportedVariables(variables); + ((property.value as unknown) as PatternNode).addExportedVariables(variables); } else { property.argument.addExportedVariables(variables); } diff --git a/src/ast/nodes/SequenceExpression.ts b/src/ast/nodes/SequenceExpression.ts index c98b9ba64d7..d409e095243 100644 --- a/src/ast/nodes/SequenceExpression.ts +++ b/src/ast/nodes/SequenceExpression.ts @@ -103,7 +103,7 @@ export default class SequenceExpression extends NodeBase { node.render(code, options, { isCalleeOfRenderedParent: renderedParentType ? isCalleeOfRenderedParent - : (this.parent).callee === this, + : (this.parent as CallExpression).callee === this, renderedParentType: renderedParentType || this.parent.type }); } else { diff --git a/src/ast/nodes/TaggedTemplateExpression.ts b/src/ast/nodes/TaggedTemplateExpression.ts index adb427315fc..7e7f81860be 100644 --- a/src/ast/nodes/TaggedTemplateExpression.ts +++ b/src/ast/nodes/TaggedTemplateExpression.ts @@ -16,19 +16,19 @@ export default class TaggedTemplateExpression extends NodeBase { bind() { super.bind(); if (this.tag.type === NodeType.Identifier) { - const variable = this.scope.findVariable((this.tag).name); + const variable = this.scope.findVariable((this.tag as Identifier).name); if (variable.isNamespace) { this.context.error( { code: 'CANNOT_CALL_NAMESPACE', - message: `Cannot call a namespace ('${(this.tag).name}')` + message: `Cannot call a namespace ('${(this.tag as Identifier).name}')` }, this.start ); } - if ((this.tag).name === 'eval') { + if ((this.tag as Identifier).name === 'eval') { this.context.warn( { code: 'EVAL', diff --git a/src/ast/nodes/TemplateLiteral.ts b/src/ast/nodes/TemplateLiteral.ts index b38e52a122b..0bc820ca371 100644 --- a/src/ast/nodes/TemplateLiteral.ts +++ b/src/ast/nodes/TemplateLiteral.ts @@ -22,7 +22,10 @@ export default class TemplateLiteral extends NodeBase { } render(code: MagicString, options: RenderOptions) { - (<[number, number][]>code.indentExclusionRanges).push(<[number, number]>[this.start, this.end]); + (code.indentExclusionRanges as [number, number][]).push([this.start, this.end] as [ + number, + number + ]); super.render(code, options); } } diff --git a/src/ast/nodes/ThisExpression.ts b/src/ast/nodes/ThisExpression.ts index b71be7b7029..0647f8c0a4a 100644 --- a/src/ast/nodes/ThisExpression.ts +++ b/src/ast/nodes/ThisExpression.ts @@ -15,7 +15,7 @@ export default class ThisExpression extends NodeBase { bind() { super.bind(); - this.variable = this.scope.findVariable('this'); + this.variable = this.scope.findVariable('this') as ThisVariable; } hasEffectsWhenAccessedAtPath(path: ObjectPath, options: ExecutionPathOptions): boolean { diff --git a/src/ast/nodes/UnaryExpression.ts b/src/ast/nodes/UnaryExpression.ts index 93945323c1e..53ccd32acff 100644 --- a/src/ast/nodes/UnaryExpression.ts +++ b/src/ast/nodes/UnaryExpression.ts @@ -40,7 +40,7 @@ export default class UnaryExpression extends NodeBase { const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin); if (argumentValue === UNKNOWN_VALUE) return UNKNOWN_VALUE; - return unaryOperators[this.operator](argumentValue); + return unaryOperators[this.operator](argumentValue as LiteralValue); } hasEffects(options: ExecutionPathOptions): boolean { diff --git a/src/ast/nodes/shared/FunctionNode.ts b/src/ast/nodes/shared/FunctionNode.ts index 4e3b5e7fe05..44a0ca3fa5a 100644 --- a/src/ast/nodes/shared/FunctionNode.ts +++ b/src/ast/nodes/shared/FunctionNode.ts @@ -91,13 +91,11 @@ export default class FunctionNode extends NodeBase { } parseNode(esTreeNode: GenericEsTreeNode) { - this.body = ( - new this.context.nodeConstructors.BlockStatement( - esTreeNode.body, - this, - this.scope.hoistedBodyVarScope - ) - ); + this.body = new this.context.nodeConstructors.BlockStatement( + esTreeNode.body, + this, + this.scope.hoistedBodyVarScope + ) as BlockStatement; super.parseNode(esTreeNode); } } diff --git a/src/ast/nodes/shared/Node.ts b/src/ast/nodes/shared/Node.ts index 5c73239b28c..3ea2ca57dfc 100644 --- a/src/ast/nodes/shared/Node.ts +++ b/src/ast/nodes/shared/Node.ts @@ -110,7 +110,7 @@ export class NodeBase implements ExpressionNode { */ bind() { for (const key of this.keys) { - const value = (this)[key]; + const value = (this as GenericEsTreeNode)[key]; if (value === null || key === 'annotations') continue; if (Array.isArray(value)) { for (const child of value) { @@ -151,7 +151,7 @@ export class NodeBase implements ExpressionNode { hasEffects(options: ExecutionPathOptions): boolean { for (const key of this.keys) { - const value = (this)[key]; + const value = (this as GenericEsTreeNode)[key]; if (value === null || key === 'annotations') continue; if (Array.isArray(value)) { for (const child of value) { @@ -181,7 +181,7 @@ export class NodeBase implements ExpressionNode { include(includeAllChildrenRecursively: boolean) { this.included = true; for (const key of this.keys) { - const value = (this)[key]; + const value = (this as GenericEsTreeNode)[key]; if (value === null || key === 'annotations') continue; if (Array.isArray(value)) { for (const child of value) { @@ -225,11 +225,11 @@ export class NodeBase implements ExpressionNode { if (this.hasOwnProperty(key)) continue; const value = esTreeNode[key]; if (typeof value !== 'object' || value === null || key === 'annotations') { - (this)[key] = value; + (this as GenericEsTreeNode)[key] = value; } else if (Array.isArray(value)) { - (this)[key] = []; + (this as GenericEsTreeNode)[key] = []; for (const child of value) { - (this)[key].push( + (this as GenericEsTreeNode)[key].push( child === null ? null : new (this.context.nodeConstructors[child.type] || @@ -237,7 +237,7 @@ export class NodeBase implements ExpressionNode { ); } } else { - (this)[key] = new (this.context.nodeConstructors[value.type] || + (this as GenericEsTreeNode)[key] = new (this.context.nodeConstructors[value.type] || this.context.nodeConstructors.UnknownNode)(value, this, this.scope); } } @@ -245,7 +245,7 @@ export class NodeBase implements ExpressionNode { render(code: MagicString, options: RenderOptions) { for (const key of this.keys) { - const value = (this)[key]; + const value = (this as GenericEsTreeNode)[key]; if (value === null || key === 'annotations') continue; if (Array.isArray(value)) { for (const child of value) { diff --git a/src/ast/scopes/Scope.ts b/src/ast/scopes/Scope.ts index dd8fb902307..28b5ee9a976 100644 --- a/src/ast/scopes/Scope.ts +++ b/src/ast/scopes/Scope.ts @@ -20,7 +20,7 @@ export default class Scope { ) { const name = identifier.name; if (this.variables[name]) { - (this.variables[name]).addDeclaration(identifier, init); + (this.variables[name] as LocalVariable).addDeclaration(identifier, init); } else { this.variables[name] = new LocalVariable( identifier.name, diff --git a/src/ast/variables/ArgumentsVariable.ts b/src/ast/variables/ArgumentsVariable.ts index b78367cd6c7..af693040fbb 100644 --- a/src/ast/variables/ArgumentsVariable.ts +++ b/src/ast/variables/ArgumentsVariable.ts @@ -5,7 +5,7 @@ import { ObjectPath, UNKNOWN_EXPRESSION } from '../values'; import LocalVariable from './LocalVariable'; const getParameterVariable = (path: ObjectPath, options: ExecutionPathOptions) => { - const firstArgNum = parseInt(path[0], 10); + const firstArgNum = parseInt(path[0] as string, 10); return ( (firstArgNum < options.getArgumentsVariables().length && @@ -23,7 +23,7 @@ export default class ArgumentsVariable extends LocalVariable { } deoptimizePath(path: ObjectPath) { - const firstArgNum = parseInt(path[0], 10); + const firstArgNum = parseInt(path[0] as string, 10); if (path.length > 0) { if (firstArgNum >= 0 && this.parameters[firstArgNum]) { this.parameters[firstArgNum].deoptimizePath(path.slice(1)); diff --git a/src/ast/variables/ExportDefaultVariable.ts b/src/ast/variables/ExportDefaultVariable.ts index 7c426f1f106..403bc4c8d8d 100644 --- a/src/ast/variables/ExportDefaultVariable.ts +++ b/src/ast/variables/ExportDefaultVariable.ts @@ -28,12 +28,12 @@ export default class ExportDefaultVariable extends LocalVariable { if ( (declaration.type === NodeType.FunctionDeclaration || declaration.type === NodeType.ClassDeclaration) && - (declaration).id + (declaration as FunctionDeclaration | ClassDeclaration).id ) { this.hasId = true; - this.originalId = (declaration).id; + this.originalId = (declaration as FunctionDeclaration | ClassDeclaration).id; } else if (declaration.type === NodeType.Identifier) { - this.originalId = declaration; + this.originalId = declaration as Identifier; } } diff --git a/src/ast/variables/LocalVariable.ts b/src/ast/variables/LocalVariable.ts index 12cc3216389..99f32f99e0a 100644 --- a/src/ast/variables/LocalVariable.ts +++ b/src/ast/variables/LocalVariable.ts @@ -180,13 +180,13 @@ export default class LocalVariable extends Variable { for (const declaration of this.declarations) { // If node is a default export, it can save a tree-shaking run to include the full declaration now if (!declaration.included) declaration.include(false); - let node = declaration.parent; + let node = declaration.parent as Node; while (!node.included) { // We do not want to properly include parents in case they are part of a dead branch // in which case .include() might pull in more dead code node.included = true; if (node.type === NodeType.Program) break; - node = node.parent; + node = node.parent as Node; } } } diff --git a/src/rollup/index.ts b/src/rollup/index.ts index c9ee24e3cb8..c71f4579b55 100644 --- a/src/rollup/index.ts +++ b/src/rollup/index.ts @@ -30,7 +30,7 @@ import { } from './types'; function checkOutputOptions(options: OutputOptions) { - if (options.format === 'es6') { + if ((options.format as string) === 'es6') { error({ message: 'The "es6" output format is deprecated – use "esm" instead', url: `https://rollupjs.org/guide/en#output-format` @@ -238,7 +238,7 @@ export default function rollup(rawInputOptions: GenericConfigObject): Promise { - const outputChunk = outputBundle[chunk.id]; + const outputChunk = outputBundle[chunk.id] as OutputChunk; return chunk.render(outputOptions, addons, outputChunk).then(rendered => { outputChunk.code = rendered.code; outputChunk.map = rendered.map; @@ -294,16 +294,16 @@ export default function rollup(rawInputOptions: GenericConfigObject): Promise((rawOutputOptions: GenericConfigObject) => { + generate: ((rawOutputOptions: GenericConfigObject) => { const promise = generate(getOutputOptions(rawOutputOptions), false).then(result => createOutput(result) ); Object.defineProperty(promise, 'code', throwAsyncGenerateError); Object.defineProperty(promise, 'map', throwAsyncGenerateError); return promise; - }), + }) as any, watchFiles: Object.keys(graph.watchFiles), - write: ((rawOutputOptions: OutputOptions) => { + write: ((rawOutputOptions: OutputOptions) => { const outputOptions = getOutputOptions(rawOutputOptions); if (!outputOptions.dir && !outputOptions.file) { error({ @@ -315,7 +315,7 @@ export default function rollup(rawInputOptions: GenericConfigObject): Promisefile).isAsset) continue; + if ((file as OutputAsset).isAsset) continue; chunkCnt++; if (chunkCnt > 1) break; } @@ -344,7 +344,7 @@ export default function rollup(rawInputOptions: GenericConfigObject): Promise graph.pluginDriver.hookParallel('writeBundle', [bundle])) .then(() => createOutput(bundle)); }); - }) + }) as any }; if (inputOptions.perf === true) result.getTimings = getTimings; return result; @@ -361,10 +361,10 @@ enum SortingFileType { } function getSortingFileType(file: OutputAsset | OutputChunk): SortingFileType { - if ((file).isAsset) { + if ((file as OutputAsset).isAsset) { return SortingFileType.ASSET; } - if ((file).isEntry) { + if ((file as OutputChunk).isEntry) { return SortingFileType.ENTRY_CHUNK; } return SortingFileType.SECONDARY_CHUNK; @@ -384,7 +384,7 @@ function createOutput(outputBundle: Record): } function isOutputAsset(file: OutputAsset | OutputChunk): file is OutputAsset { - return (file).isAsset === true; + return (file as OutputAsset).isAsset === true; } function writeOutputFile( diff --git a/src/utils/collapseSourcemaps.ts b/src/utils/collapseSourcemaps.ts index 4c35c3d54ca..33332c9689c 100644 --- a/src/utils/collapseSourcemaps.ts +++ b/src/utils/collapseSourcemaps.ts @@ -97,7 +97,7 @@ class Link { names.push(traced.name); } - (tracedSegment)[4] = nameIndex; + (tracedSegment as SourceMapSegmentVector)[4] = nameIndex; } tracedLine.push(tracedSegment); @@ -168,7 +168,7 @@ export default function collapseSourcemaps( }; } - return new Link(map, [source]); + return new Link(map, [source]) as any; } const moduleSources = modules @@ -177,7 +177,7 @@ export default function collapseSourcemaps( let sourcemapChain = module.sourcemapChain; let source: Source; - const originalSourcemap = module.originalSourcemap; + const originalSourcemap = module.originalSourcemap as ExistingRawSourceMap; if (!originalSourcemap) { source = new Source(module.id, module.originalCode); } else { @@ -186,7 +186,7 @@ export default function collapseSourcemaps( if (sources == null || (sources.length <= 1 && sources[0] == null)) { source = new Source(module.id, sourcesContent[0]); - sourcemapChain = [originalSourcemap].concat(sourcemapChain); + sourcemapChain = [originalSourcemap as RawSourceMap].concat(sourcemapChain); } else { // TODO indiscriminately treating IDs and sources as normal paths is probably bad. const directory = dirname(module.id) || '.'; @@ -196,7 +196,7 @@ export default function collapseSourcemaps( (source, i) => new Source(resolve(directory, sourceRoot, source), sourcesContent[i]) ); - source = new Link(originalSourcemap, baseSources); + source = new Link(originalSourcemap as any, baseSources) as any; } } @@ -205,7 +205,7 @@ export default function collapseSourcemaps( return source; }); - let source = new Link(map, moduleSources); + let source = new Link(map as any, moduleSources); source = bundleSourcemapChain.reduce(linkMap, source); diff --git a/src/utils/error.ts b/src/utils/error.ts index c180f373f96..23785ecf50d 100644 --- a/src/utils/error.ts +++ b/src/utils/error.ts @@ -20,7 +20,7 @@ export function augmentCodeLocation( const { line, column } = pos; object.loc = { file: id, line, column }; } else { - object.pos = pos; + object.pos = pos as any; const { line, column } = locate(source, pos, { offsetLine: 1 }); object.loc = { file: id, line, column }; } diff --git a/src/utils/getOriginalLocation.ts b/src/utils/getOriginalLocation.ts index dc7d5bbb16c..358cc70a3ab 100644 --- a/src/utils/getOriginalLocation.ts +++ b/src/utils/getOriginalLocation.ts @@ -7,7 +7,7 @@ export function getOriginalLocation( const filteredSourcemapChain = sourcemapChain.filter(sourcemap => sourcemap.mappings); while (filteredSourcemapChain.length > 0) { - const sourcemap = filteredSourcemapChain.pop(); + const sourcemap = filteredSourcemapChain.pop() as ExistingRawSourceMap; const line: any = sourcemap.mappings[location.line - 1]; let locationFound = false; diff --git a/src/utils/mergeOptions.ts b/src/utils/mergeOptions.ts index 424deb2bf8a..5b26c3f57c9 100644 --- a/src/utils/mergeOptions.ts +++ b/src/utils/mergeOptions.ts @@ -218,8 +218,8 @@ function getInputOptions( }; // support rollup({ cache: prevBuildObject }) - if (inputOptions.cache && (inputOptions.cache).cache) - inputOptions.cache = (inputOptions.cache).cache; + if (inputOptions.cache && (inputOptions.cache as any).cache) + inputOptions.cache = (inputOptions.cache as any).cache; return inputOptions; } diff --git a/src/utils/pluginDriver.ts b/src/utils/pluginDriver.ts index 1bf064fb0c4..8e74d2e1d0f 100644 --- a/src/utils/pluginDriver.ts +++ b/src/utils/pluginDriver.ts @@ -217,11 +217,11 @@ export function createPluginDriver( graph.warn(warning); }, watcher: watcher - ? { - ...(watcher), + ? ({ + ...(watcher as EventEmitter), addListener: deprecatedWatchListener, on: deprecatedWatchListener - } + } as EventEmitter) : (undefined as any) }; return context; @@ -236,7 +236,7 @@ export function createPluginDriver( ): T { const plugin = plugins[pluginIndex]; let context = pluginContexts[pluginIndex]; - const hook = (plugin)[hookName]; + const hook = (plugin as any)[hookName]; if (!hook) return undefined as any; const deprecatedHookNewName = deprecatedHookNames[hookName]; @@ -281,7 +281,7 @@ export function createPluginDriver( ): Promise { const plugin = plugins[pluginIndex]; let context = pluginContexts[pluginIndex]; - const hook = (plugin)[hookName]; + const hook = (plugin as any)[hookName]; if (!hook) return undefined as any; const deprecatedHookNewName = deprecatedHookNames[hookName]; @@ -325,7 +325,7 @@ export function createPluginDriver( // chains, ignores returns hookSeq(name, args, hookContext) { - let promise: Promise = Promise.resolve(); + let promise: Promise = Promise.resolve() as any; for (let i = 0; i < plugins.length; i++) promise = promise.then(() => runHook(name, args as any[], i, false, hookContext)); return promise; diff --git a/src/utils/pureComments.ts b/src/utils/pureComments.ts index cfcc3a1b196..0605c6652e9 100644 --- a/src/utils/pureComments.ts +++ b/src/utils/pureComments.ts @@ -32,7 +32,7 @@ function markPureNode( node = node.expression; } if (node.type === 'CallExpression' || node.type === 'NewExpression') { - (node).annotatedPure = true; + (node as any).annotatedPure = true; } } @@ -40,7 +40,7 @@ const pureCommentRegex = /[@#]__PURE__/; const isPureComment = (comment: CommentDescription) => pureCommentRegex.test(comment.text); export function markPureCallExpressions(comments: CommentDescription[], esTreeAst: ESTree.Program) { - handlePureAnnotationsOfNode(esTreeAst, { + handlePureAnnotationsOfNode(esTreeAst as any, { commentIndex: 0, commentNodes: comments.filter(isPureComment) }); diff --git a/src/utils/timers.ts b/src/utils/timers.ts index 7ee9f1efcf3..3eafb44a764 100644 --- a/src/utils/timers.ts +++ b/src/utils/timers.ts @@ -119,7 +119,7 @@ function getPluginWithTimers(plugin: any, index: number): Plugin { timedPlugin[hook] = plugin[hook]; } } - return timedPlugin; + return timedPlugin as Plugin; } export function initialiseTimers(inputOptions: InputOptions) { diff --git a/src/utils/transform.ts b/src/utils/transform.ts index 28593130199..4a5430b212a 100644 --- a/src/utils/transform.ts +++ b/src/utils/transform.ts @@ -64,12 +64,12 @@ export default function transform( if (result && typeof result === 'object' && Array.isArray(result.dependencies)) { // not great, but a useful way to track this without assuming WeakMap - if (!(curPlugin).warnedTransformDependencies) + if (!(curPlugin as any).warnedTransformDependencies) this.warn({ code: 'TRANSFORM_DEPENDENCIES_DEPRECATED', message: `Returning "dependencies" from plugin transform hook is deprecated for using this.addWatchFile() instead.` }); - (curPlugin).warnedTransformDependencies = true; + (curPlugin as any).warnedTransformDependencies = true; if (!transformDependencies) transformDependencies = []; for (const dep of result.dependencies) transformDependencies.push(resolve(dirname(id), dep)); diff --git a/tslint.json b/tslint.json index c0c1012ee19..28b919c9f22 100644 --- a/tslint.json +++ b/tslint.json @@ -10,6 +10,7 @@ "alphabetize": true } ], + "no-angle-bracket-type-assertion": true, "no-inferrable-types": true, "no-string-literal": true, "no-unnecessary-type-assertion": true, From 49064487c981b00a8f6ca5db572a1e914d46e3dc Mon Sep 17 00:00:00 2001 From: Lukas Taegert-Atkinson Date: Fri, 17 May 2019 18:04:41 +0200 Subject: [PATCH 5/5] Explicitly list strict options we are still missing --- src/Module.ts | 10 +++++----- tsconfig.json | 43 +++++++++++++++++-------------------------- 2 files changed, 22 insertions(+), 31 deletions(-) diff --git a/src/Module.ts b/src/Module.ts index 0566c3e161d..ce0c688d565 100644 --- a/src/Module.ts +++ b/src/Module.ts @@ -109,7 +109,7 @@ export interface AstContext { preserveModules: boolean; propertyReadSideEffects: boolean; traceExport: (name: string) => Variable; - traceVariable: (name: string) => Variable; + traceVariable: (name: string) => Variable | null; treeshake: boolean; usesTopLevelAwait: boolean; warn: (warning: RollupWarning, pos: number) => void; @@ -354,12 +354,12 @@ export default class Module { getTransitiveDependencies() { return this.dependencies.concat( this.getReexports().map( - exportName => (this.getVariableForExportName(exportName) as Variable).module as Module + exportName => (this.getVariableForExportName(exportName)).module as Module ) ); } - getVariableForExportName(name: string, isExportAllSearch?: boolean): Variable | null { + getVariableForExportName(name: string, isExportAllSearch?: boolean): Variable { if (name[0] === '*') { if (name.length === 1) { return this.getOrCreateNamespace(); @@ -427,7 +427,7 @@ export default class Module { } for (const exportName of this.getExports()) { - const variable = this.getVariableForExportName(exportName) as Variable; + const variable = this.getVariableForExportName(exportName); variable.deoptimizePath(UNKNOWN_PATH); if (!variable.included) { @@ -437,7 +437,7 @@ export default class Module { } for (const name of this.getReexports()) { - const variable = this.getVariableForExportName(name) as Variable; + const variable = this.getVariableForExportName(name); if (variable.isExternal) { variable.reexported = (variable as ExternalVariable).module.reexported = true; diff --git a/tsconfig.json b/tsconfig.json index 814543069d1..8e8b711fab2 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,28 +1,19 @@ { - "compilerOptions": { - "allowSyntheticDefaultImports": true, - "diagnostics": true, - "lib": ["es6", "dom"], - "module": "commonjs", - "noEmitOnError": true, - "noImplicitAny": true, - "noImplicitThis": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "pretty": true, - "skipLibCheck": true, - "strictNullChecks": true, - "target": "es2015" - }, - "include": [ - "typings/**/*.d.ts", - "src", - "bin", - "browser" - ], - "exclude": [ - "dist", - "node_modules", - "test/typescript" - ] + "compilerOptions": { + "allowSyntheticDefaultImports": true, + "diagnostics": true, + "lib": ["es6", "dom"], + "module": "commonjs", + "noEmitOnError": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "pretty": true, + "skipLibCheck": true, + "strictPropertyInitialization": false, + "strictFunctionTypes": false, + "strict": true, + "target": "es2015" + }, + "include": ["typings/**/*.d.ts", "src", "bin", "browser"], + "exclude": ["dist", "node_modules", "test/typescript"] }