Skip to content

Commit 275dc2f

Browse files
authored
refactor: some code and type fixes (#4413)
* use readonly set * refactor: re-use Array.prototype.map, remove Array.from map function * refactor: remove else block * refactor: use logical nullish assignment * fix: types * fix: add generic parameters for Map * refactor: simplify * fix: remove type assertion * refactor: create map instance only once * refactor: use object.entries over .keys * refactor: simplify * refactor: simplify * remove unnecassary .values call * refactor: simplify, use substring * remove unnecassary .entries * refactor: simplify * fix: replace deprecated .substr with .substring * Revert "refactor: re-use Array.prototype.map, remove Array.from map function" This reverts commit 055f4a0. * add comment * fix hash update * remove initial id base assignment * remove breaks, return early * remove default case * return early * add generic type parameters, remove eslint-disable * use object shorthand * order nit * reference from this * simplify, use map/filter
1 parent 51cab92 commit 275dc2f

File tree

18 files changed

+84
-104
lines changed

18 files changed

+84
-104
lines changed

cli/run/batchWarnings.ts

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,11 @@ export interface BatchWarnings {
1414

1515
export default function batchWarnings(): BatchWarnings {
1616
let count = 0;
17-
let deferredWarnings = new Map<keyof typeof deferredHandlers, RollupWarning[]>();
17+
const deferredWarnings = new Map<keyof typeof deferredHandlers, RollupWarning[]>();
1818
let warningOccurred = false;
1919

2020
return {
21-
add: (warning: RollupWarning) => {
21+
add(warning: RollupWarning) {
2222
count += 1;
2323
warningOccurred = true;
2424

@@ -48,7 +48,7 @@ export default function batchWarnings(): BatchWarnings {
4848
return count;
4949
},
5050

51-
flush: () => {
51+
flush() {
5252
if (count === 0) return;
5353

5454
const codes = Array.from(deferredWarnings.keys()).sort(
@@ -59,7 +59,7 @@ export default function batchWarnings(): BatchWarnings {
5959
deferredHandlers[code](deferredWarnings.get(code)!);
6060
}
6161

62-
deferredWarnings = new Map();
62+
deferredWarnings.clear();
6363
count = 0;
6464
},
6565

@@ -72,7 +72,7 @@ export default function batchWarnings(): BatchWarnings {
7272
const immediateHandlers: {
7373
[code: string]: (warning: RollupWarning) => void;
7474
} = {
75-
MISSING_NODE_BUILTINS: warning => {
75+
MISSING_NODE_BUILTINS(warning) {
7676
title(`Missing shims for Node.js built-ins`);
7777

7878
stderr(
@@ -82,7 +82,7 @@ const immediateHandlers: {
8282
);
8383
},
8484

85-
UNKNOWN_OPTION: warning => {
85+
UNKNOWN_OPTION(warning) {
8686
title(`You have passed an unrecognized option`);
8787
stderr(warning.message);
8888
}
@@ -138,7 +138,7 @@ const deferredHandlers: {
138138
}
139139
},
140140

141-
MIXED_EXPORTS: warnings => {
141+
MIXED_EXPORTS(warnings) {
142142
title('Mixing named and default exports');
143143
info(`https://rollupjs.org/guide/en/#outputexports`);
144144
stderr(bold('The following entry modules are using named and default exports together:'));
@@ -204,9 +204,7 @@ const deferredHandlers: {
204204
title(`Broken sourcemap`);
205205
info('https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect');
206206

207-
const plugins = [
208-
...new Set(warnings.map(warning => warning.plugin).filter(Boolean))
209-
] as string[];
207+
const plugins = [...new Set(warnings.map(({ plugin }) => plugin).filter(Boolean))] as string[];
210208
stderr(
211209
`Plugins that transform code (such as ${printQuotedStringList(
212210
plugins
@@ -224,13 +222,12 @@ const deferredHandlers: {
224222
title('Unresolved dependencies');
225223
info('https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency');
226224

227-
const dependencies = new Map();
225+
const dependencies = new Map<string, string[]>();
228226
for (const warning of warnings) {
229-
getOrCreate(dependencies, warning.source, () => []).push(warning.importer);
227+
getOrCreate(dependencies, warning.source, () => []).push(warning.importer!);
230228
}
231229

232-
for (const dependency of dependencies.keys()) {
233-
const importers = dependencies.get(dependency);
230+
for (const [dependency, importers] of dependencies) {
234231
stderr(`${bold(dependency)} (imported by ${importers.join(', ')})`);
235232
}
236233
},
@@ -243,7 +240,7 @@ const deferredHandlers: {
243240
' imported from external module "' +
244241
warning.source +
245242
'" but never used in ' +
246-
printQuotedStringList((warning.sources as string[]).map(id => relativeId(id)))
243+
printQuotedStringList(warning.sources!.map(id => relativeId(id)))
247244
);
248245
}
249246
}

cli/run/index.ts

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { env } from 'process';
12
import type { MergedRollupOptions } from '../../src/rollup/types';
23
import { isWatchEnabled } from '../../src/utils/options/mergeOptions';
34
import { getAliasName } from '../../src/utils/relativeId';
@@ -48,11 +49,7 @@ export default async function runRollup(command: Record<string, any>): Promise<v
4849
environment.forEach((arg: string) => {
4950
arg.split(',').forEach((pair: string) => {
5051
const [key, ...value] = pair.split(':');
51-
if (value.length) {
52-
process.env[key] = value.join(':');
53-
} else {
54-
process.env[key] = String(true);
55-
}
52+
env[key] = value.length === 0 ? String(true) : value.join(':');
5653
});
5754
});
5855
}

cli/run/timings.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,9 @@ import type { SerializedTimings } from '../../src/rollup/types';
33
import { bold, underline } from '../../src/utils/colors';
44

55
export function printTimings(timings: SerializedTimings): void {
6-
Object.keys(timings).forEach(label => {
6+
Object.entries(timings).forEach(([label, [time, memory, total]]) => {
77
const appliedColor =
88
label[0] === '#' ? (label[1] !== '#' ? underline : bold) : (text: string) => text;
9-
const [time, memory, total] = timings[label];
109
const row = `${label}: ${time.toFixed(0)}ms, ${prettyBytes(memory)} / ${prettyBytes(total)}`;
1110
console.info(appliedColor(row));
1211
});

src/Bundle.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ export default class Bundle {
3535

3636
constructor(
3737
private readonly outputOptions: NormalizedOutputOptions,
38-
private readonly unsetOptions: Set<string>,
38+
private readonly unsetOptions: ReadonlySet<string>,
3939
private readonly inputOptions: NormalizedInputOptions,
4040
private readonly pluginDriver: PluginDriver,
4141
private readonly graph: Graph
@@ -189,14 +189,14 @@ export default class Bundle {
189189
);
190190
(file as OutputAsset).type = 'asset';
191191
}
192-
if (this.outputOptions.validate && typeof (file as OutputChunk).code == 'string') {
192+
if (this.outputOptions.validate && 'code' in file) {
193193
try {
194-
this.graph.contextParse((file as OutputChunk).code, {
194+
this.graph.contextParse(file.code, {
195195
allowHashBang: true,
196196
ecmaVersion: 'latest'
197197
});
198198
} catch (err: any) {
199-
this.inputOptions.onwarn(errChunkInvalid(file as OutputChunk, err));
199+
this.inputOptions.onwarn(errChunkInvalid(file, err));
200200
}
201201
}
202202
}

src/Chunk.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@ export default class Chunk {
319319
const facades: Chunk[] = [];
320320
const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
321321
const exposedVariables = new Set<Variable>(
322-
this.dynamicEntryModules.map(module => module.namespace)
322+
this.dynamicEntryModules.map(({ namespace }) => namespace)
323323
);
324324
for (const module of entryModules) {
325325
if (module.preserveSignature) {
@@ -333,6 +333,7 @@ export default class Chunk {
333333
new Set(
334334
module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)
335335
),
336+
// mapping must run after Set 'name' dedupe
336337
name => ({
337338
name
338339
})
@@ -451,7 +452,7 @@ export default class Chunk {
451452
const extension = extname(sanitizedId);
452453
const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
453454
assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
454-
ext: () => extension.substr(1),
455+
ext: () => extension.substring(1),
455456
extname: () => extension,
456457
format: () => options.format as string,
457458
name: () => this.getChunkName()
@@ -467,7 +468,7 @@ export default class Chunk {
467468
const extension = extname(sanitizedId);
468469
const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
469470
assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
470-
ext: () => extension.substr(1),
471+
ext: () => extension.substring(1),
471472
extname: () => extension,
472473
format: () => options.format as string,
473474
name: () => getAliasName(sanitizedId)
@@ -1162,7 +1163,7 @@ export default class Chunk {
11621163
let imported: string;
11631164
let needsLiveBinding = false;
11641165
if (exportName[0] === '*') {
1165-
const id = exportName.substr(1);
1166+
const id = exportName.substring(1);
11661167
if (interop(id) === 'defaultOnly') {
11671168
this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
11681169
}

src/Module.ts

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -264,12 +264,13 @@ export default class Module {
264264
const {
265265
dynamicImports,
266266
dynamicImporters,
267-
reexportDescriptions,
268267
implicitlyLoadedAfter,
269268
implicitlyLoadedBefore,
270-
sources,
271-
importers
269+
importers,
270+
reexportDescriptions,
271+
sources
272272
} = this;
273+
273274
this.info = {
274275
ast: null,
275276
code: null,
@@ -281,13 +282,7 @@ export default class Module {
281282
get dynamicallyImportedIds() {
282283
// We cannot use this.dynamicDependencies because this is needed before
283284
// dynamicDependencies are populated
284-
const dynamicallyImportedIds: string[] = [];
285-
for (const { id } of dynamicImports) {
286-
if (id) {
287-
dynamicallyImportedIds.push(id);
288-
}
289-
}
290-
return dynamicallyImportedIds;
285+
return dynamicImports.map(({ id }) => id).filter((id): id is string => id != null);
291286
},
292287
get dynamicImporters() {
293288
return dynamicImporters.sort();
@@ -305,7 +300,7 @@ export default class Module {
305300
false,
306301
options
307302
);
308-
return module.info.moduleSideEffects;
303+
return this.moduleSideEffects;
309304
},
310305
id,
311306
get implicitlyLoadedAfterOneOf() {

src/ModuleLoader.ts

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -439,9 +439,8 @@ export class ModuleLoader {
439439
return error(errInternalIdCannotBeExternal(source, importer));
440440
}
441441
return Promise.resolve(externalModule);
442-
} else {
443-
return this.fetchModule(resolvedId, importer, false, false);
444442
}
443+
return this.fetchModule(resolvedId, importer, false, false);
445444
}
446445

447446
private async fetchStaticDependencies(
@@ -673,13 +672,11 @@ export class ModuleLoader {
673672
} as ResolvedId;
674673
}
675674
if (resolution == null) {
676-
return (module.resolvedIds[specifier] =
677-
module.resolvedIds[specifier] ||
678-
this.handleResolveId(
679-
await this.resolveId(specifier, module.id, EMPTY_OBJECT, false),
680-
specifier,
681-
module.id
682-
));
675+
return (module.resolvedIds[specifier] ??= this.handleResolveId(
676+
await this.resolveId(specifier, module.id, EMPTY_OBJECT, false),
677+
specifier,
678+
module.id
679+
));
683680
}
684681
return this.handleResolveId(
685682
this.getResolvedIdWithDefaults(

src/ast/nodes/MetaProperty.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ export default class MetaProperty extends NodeBase {
4343
getReferencedFileName(outputPluginDriver: PluginDriver): string | null {
4444
const metaProperty = this.metaProperty as string | null;
4545
if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
46-
return outputPluginDriver.getFileName(metaProperty.substr(FILE_PREFIX.length));
46+
return outputPluginDriver.getFileName(metaProperty.substring(FILE_PREFIX.length));
4747
}
4848
return null;
4949
}
@@ -91,23 +91,23 @@ export default class MetaProperty extends NodeBase {
9191
let chunkReferenceId: string | null = null;
9292
let fileName: string;
9393
if (metaProperty.startsWith(FILE_PREFIX)) {
94-
referenceId = metaProperty.substr(FILE_PREFIX.length);
94+
referenceId = metaProperty.substring(FILE_PREFIX.length);
9595
fileName = outputPluginDriver.getFileName(referenceId);
9696
} else if (metaProperty.startsWith(ASSET_PREFIX)) {
9797
warnDeprecation(
9898
`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`,
9999
true,
100100
this.context.options
101101
);
102-
assetReferenceId = metaProperty.substr(ASSET_PREFIX.length);
102+
assetReferenceId = metaProperty.substring(ASSET_PREFIX.length);
103103
fileName = outputPluginDriver.getFileName(assetReferenceId);
104104
} else {
105105
warnDeprecation(
106106
`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`,
107107
true,
108108
this.context.options
109109
);
110-
chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length);
110+
chunkReferenceId = metaProperty.substring(CHUNK_PREFIX.length);
111111
fileName = outputPluginDriver.getFileName(chunkReferenceId);
112112
}
113113
const relativePath = normalize(relative(dirname(chunkId), fileName));

src/ast/values.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -236,9 +236,8 @@ export function getLiteralMembersForValue<T extends LiteralValue = LiteralValue>
236236
return literalNumberMembers;
237237
case 'string':
238238
return literalStringMembers;
239-
default:
240-
return Object.create(null);
241239
}
240+
return Object.create(null);
242241
}
243242

244243
export function hasMemberEffectWhenCalled(

src/rollup/rollup.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -137,12 +137,11 @@ function applyOptionHook(watchMode: boolean) {
137137
}
138138

139139
function normalizePlugins(plugins: readonly Plugin[], anonymousPrefix: string): void {
140-
for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) {
141-
const plugin = plugins[pluginIndex];
140+
plugins.forEach((plugin, index) => {
142141
if (!plugin.name) {
143-
plugin.name = `${anonymousPrefix}${pluginIndex + 1}`;
142+
plugin.name = `${anonymousPrefix}${index + 1}`;
144143
}
145-
}
144+
});
146145
}
147146

148147
async function handleGenerateWrite(

0 commit comments

Comments
 (0)