solid-optimizer 1.0.0-next.4 → 1.0.0-next.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/value.ts CHANGED
@@ -240,6 +240,15 @@ export function truthiness(node: Node, lookup: ConstantLookup): boolean | undefi
240
240
  return value ? !!value.value : undefined;
241
241
  }
242
242
 
243
+ function areSideEffectFree(nodes: readonly Node[]): boolean {
244
+ for (const node of nodes) {
245
+ if (!isSideEffectFree(node)) {
246
+ return false;
247
+ }
248
+ }
249
+ return true;
250
+ }
251
+
243
252
  /**
244
253
  * Whether skipping `node` entirely loses nothing observable.
245
254
  *
@@ -259,7 +268,7 @@ export function isSideEffectFree(node: Node): boolean {
259
268
  case 'ParenthesizedExpression':
260
269
  return isSideEffectFree(node.expression);
261
270
  case 'TemplateLiteral':
262
- return node.expressions.every(isSideEffectFree);
271
+ return areSideEffectFree(node.expressions);
263
272
  case 'UnaryExpression':
264
273
  // `delete` changes its target.
265
274
  return node.operator !== 'delete' && isSideEffectFree(node.argument);
@@ -275,7 +284,7 @@ export function isSideEffectFree(node: Node): boolean {
275
284
  case 'LogicalExpression':
276
285
  return isSideEffectFree(node.left) && isSideEffectFree(node.right);
277
286
  case 'SequenceExpression':
278
- return node.expressions.every(isSideEffectFree);
287
+ return areSideEffectFree(node.expressions);
279
288
  case 'ConditionalExpression':
280
289
  return (
281
290
  isSideEffectFree(node.test) &&
@@ -284,18 +293,24 @@ export function isSideEffectFree(node: Node): boolean {
284
293
  );
285
294
  case 'ArrayExpression':
286
295
  // A spread iterates its argument, which is observable.
287
- return node.elements.every(
288
- (element) =>
289
- element === null || (element.type !== 'SpreadElement' && isSideEffectFree(element)),
290
- );
296
+ for (const element of node.elements) {
297
+ if (element !== null && (element.type === 'SpreadElement' || !isSideEffectFree(element))) {
298
+ return false;
299
+ }
300
+ }
301
+ return true;
291
302
  case 'ObjectExpression':
292
- return node.properties.every(
293
- (property) =>
294
- // A spread reads the source's own properties, which a getter observes.
295
- property.type === 'Property' &&
296
- (!property.computed || isSideEffectFree(property.key)) &&
297
- isSideEffectFree(property.value),
298
- );
303
+ for (const property of node.properties) {
304
+ // A spread reads the source's own properties, which a getter observes.
305
+ if (
306
+ property.type !== 'Property' ||
307
+ (property.computed && !isSideEffectFree(property.key)) ||
308
+ !isSideEffectFree(property.value)
309
+ ) {
310
+ return false;
311
+ }
312
+ }
313
+ return true;
299
314
  default:
300
315
  // A class is never skippable. Evaluating one runs its heritage
301
316
  // expression, computed keys, static fields, and static blocks.
@@ -333,8 +348,10 @@ export function arrayLiteralLength(node: Node): number | undefined {
333
348
  if (node.type !== 'ArrayExpression') {
334
349
  return undefined;
335
350
  }
336
- if (node.elements.some((element) => element?.type === 'SpreadElement')) {
337
- return undefined;
351
+ for (const element of node.elements) {
352
+ if (element?.type === 'SpreadElement') {
353
+ return undefined;
354
+ }
338
355
  }
339
356
  return node.elements.length;
340
357
  }
@@ -24,18 +24,33 @@ export function sharedGlobals(
24
24
  }
25
25
  }
26
26
  const environments = Object.values(config.environments);
27
- const defines =
28
- environments.length > 0
29
- ? environments.map((environment) => environment.define ?? config.define ?? {})
30
- : [config.define ?? {}];
31
- const keys = new Set(defines.flatMap((define) => Object.keys(define)));
27
+ const defines: Record<string, unknown>[] = [];
28
+ if (environments.length > 0) {
29
+ for (const environment of environments) {
30
+ defines.push(environment.define ?? config.define ?? {});
31
+ }
32
+ } else {
33
+ defines.push(config.define ?? {});
34
+ }
35
+ const keys = new Set<string>();
36
+ for (const define of defines) {
37
+ for (const key of Object.keys(define)) {
38
+ keys.add(key);
39
+ }
40
+ }
32
41
  for (const key of keys) {
33
- const values = defines.map((define) => defineValue(define[key]));
34
- const first = values.at(0);
35
- if (
36
- first !== undefined &&
37
- values.every((value) => value !== undefined && Object.is(value.value, first.value))
38
- ) {
42
+ // Every environment must define the key as the same value.
43
+ let first: { value: Primitive } | undefined;
44
+ let same = true;
45
+ for (const define of defines) {
46
+ const value = defineValue(define[key]);
47
+ first ??= value;
48
+ if (value === undefined || !Object.is(value.value, first?.value)) {
49
+ same = false;
50
+ break;
51
+ }
52
+ }
53
+ if (first !== undefined && same) {
39
54
  globals[key] = first.value;
40
55
  }
41
56
  }
package/src/vite/index.ts CHANGED
@@ -54,7 +54,7 @@ import {
54
54
 
55
55
  export interface OptimizerOptions extends Pick<
56
56
  CompileOptions,
57
- 'fold' | 'inline' | 'alwaysInline' | 'contexts' | 'memos' | 'maxPasses'
57
+ 'fold' | 'inline' | 'alwaysInline' | 'contexts' | 'memos' | 'conditionals' | 'maxPasses'
58
58
  > {
59
59
  /**
60
60
  * Where the optimizer runs.
@@ -145,6 +145,42 @@ export const Sample = () => (
145
145
  </div>
146
146
  );`;
147
147
 
148
+ /** The references that are the name of a JSX tag. */
149
+ function findTags(references: readonly Node[], parents: ReturnType<typeof collectParents>): Node[] {
150
+ const tags: Node[] = [];
151
+ for (const reference of references) {
152
+ const parent = parents.get(reference);
153
+ if (
154
+ (parent?.type === 'JSXOpeningElement' || parent?.type === 'JSXClosingElement') &&
155
+ parent.name === reference
156
+ ) {
157
+ tags.push(reference);
158
+ }
159
+ }
160
+ return tags;
161
+ }
162
+
163
+ function findSkipReason(
164
+ skipped: readonly { name: string; reason: string }[],
165
+ name: string,
166
+ ): string | undefined {
167
+ for (const entry of skipped) {
168
+ if (entry.name === name) {
169
+ return entry.reason;
170
+ }
171
+ }
172
+ return undefined;
173
+ }
174
+
175
+ function hasSpreadAttribute(attributes: readonly { type: string }[]): boolean {
176
+ for (const attribute of attributes) {
177
+ if (attribute.type === 'JSXSpreadAttribute') {
178
+ return true;
179
+ }
180
+ }
181
+ return false;
182
+ }
183
+
148
184
  /**
149
185
  * Whether the code spreads anything onto an intrinsic element, or onto
150
186
  * `<Dynamic>`, which becomes one once its `component` is known.
@@ -162,7 +198,7 @@ function spreadsOntoElement(code: string, filename: string): boolean {
162
198
  node.type === 'JSXOpeningElement' &&
163
199
  node.name.type === 'JSXIdentifier' &&
164
200
  (isIntrinsicTag(node.name.name) || node.name.name === 'Dynamic') &&
165
- node.attributes.some((attribute) => attribute.type === 'JSXSpreadAttribute')
201
+ hasSpreadAttribute(node.attributes)
166
202
  ) {
167
203
  found = true;
168
204
  return;
@@ -216,7 +252,12 @@ function stripQuery(id: string): string {
216
252
  * source maps, since chaining the maps of a large chunk takes a while.
217
253
  */
218
254
  function combineMaps(wanted: boolean, maps: (string | null | undefined)[]): string | null {
219
- const present = maps.filter((map): map is string => typeof map === 'string');
255
+ const present: string[] = [];
256
+ for (const map of maps) {
257
+ if (typeof map === 'string') {
258
+ present.push(map);
259
+ }
260
+ }
220
261
  if (!wanted || present.length === 0) {
221
262
  return null;
222
263
  }
@@ -293,6 +334,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
293
334
  alwaysInline: optimizer.alwaysInline,
294
335
  contexts: optimizer.contexts,
295
336
  memos: optimizer.memos,
337
+ conditionals: optimizer.conditionals,
296
338
  maxPasses: optimizer.maxPasses,
297
339
  builtIns: [...builtIns],
298
340
  moduleSources,
@@ -465,27 +507,35 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
465
507
  transform: string,
466
508
  ): Promise<{ constants: ImportedConstants; partial: boolean }> {
467
509
  let partial = false;
468
- const entries = await Promise.all(
469
- imports.map(async (specifier) => {
470
- const target = await resolveConstantModule(context, specifier, importer);
471
- if (target === undefined || visiting.has(target.id)) {
472
- return undefined;
473
- }
474
- const result = await constantsOf(context, target, visiting, transform);
475
- partial ||= result.partial;
476
- if (!result.constants || Object.keys(result.constants.exports).length === 0) {
477
- return undefined;
478
- }
479
- return [specifier, result.constants.exports] as const;
480
- }),
481
- );
482
- return {
483
- constants: Object.fromEntries(entries.filter((entry) => entry !== undefined)),
484
- partial,
485
- };
510
+ async function readImport(
511
+ specifier: string,
512
+ ): Promise<readonly [string, Readonly<Record<string, Primitive>>] | undefined> {
513
+ const target = await resolveConstantModule(context, specifier, importer);
514
+ if (target === undefined || visiting.has(target.id)) {
515
+ return undefined;
516
+ }
517
+ const result = await readConstants(context, target, visiting, transform);
518
+ partial ||= result.partial;
519
+ if (!result.constants || Object.keys(result.constants.exports).length === 0) {
520
+ return undefined;
521
+ }
522
+ return [specifier, result.constants.exports] as const;
523
+ }
524
+ const reading = [];
525
+ for (const specifier of imports) {
526
+ reading.push(readImport(specifier));
527
+ }
528
+ const entries = await Promise.all(reading);
529
+ const constants: Record<string, Readonly<Record<string, Primitive>>> = {};
530
+ for (const entry of entries) {
531
+ if (entry !== undefined) {
532
+ constants[entry[0]] = entry[1];
533
+ }
534
+ }
535
+ return { constants, partial };
486
536
  }
487
537
 
488
- async function constantsOf(
538
+ async function readConstants(
489
539
  context: Rollup.PluginContext,
490
540
  target: { id: string; jsx: boolean },
491
541
  visiting: ReadonlySet<string>,
@@ -653,7 +703,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
653
703
  * modules are transformed in. Modules without JSX count too, since reading
654
704
  * their constants can load a module with JSX.
655
705
  */
656
- async function localImportsOf(context: Rollup.PluginContext, id: string): Promise<string[]> {
706
+ async function findLocalImports(context: Rollup.PluginContext, id: string): Promise<string[]> {
657
707
  let pending = localImports.get(id);
658
708
  if (!pending) {
659
709
  pending = (async () => {
@@ -684,12 +734,18 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
684
734
  }
685
735
  }
686
736
  }
687
- const resolved = await Promise.all(
688
- [...sources].map(async (source) => context.resolve(source, id)),
689
- );
690
- return resolved
691
- .filter((target) => target && !target.external && !target.id.includes('/node_modules/'))
692
- .map((target) => target?.id ?? '');
737
+ const resolving = [];
738
+ for (const source of sources) {
739
+ resolving.push(context.resolve(source, id));
740
+ }
741
+ const resolved = await Promise.all(resolving);
742
+ const local: string[] = [];
743
+ for (const target of resolved) {
744
+ if (target && !target.external && !target.id.includes('/node_modules/')) {
745
+ local.push(target.id);
746
+ }
747
+ }
748
+ return local;
693
749
  })();
694
750
  localImports.set(id, pending);
695
751
  }
@@ -711,9 +767,18 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
711
767
  for (const id of frontier) {
712
768
  seen.add(id);
713
769
  }
770
+ const reading = [];
771
+ for (const id of frontier) {
772
+ reading.push(findLocalImports(context, id));
773
+ }
714
774
  // oxlint-disable-next-line no-await-in-loop
715
- const next = await Promise.all(frontier.map(async (id) => localImportsOf(context, id)));
716
- frontier = [...new Set(next.flat())].filter((id) => !seen.has(id));
775
+ const next = await Promise.all(reading);
776
+ frontier = [];
777
+ for (const id of new Set(next.flat())) {
778
+ if (!seen.has(id)) {
779
+ frontier.push(id);
780
+ }
781
+ }
717
782
  }
718
783
  return false;
719
784
  }
@@ -813,14 +878,24 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
813
878
  let pending = usageIndexes.get(key);
814
879
  if (!pending) {
815
880
  pending = (async () => {
816
- const entries = await Promise.all(
817
- [...context.getModuleIds()]
818
- .filter((id) => context.getModuleInfo(id)?.isEntry === true)
819
- .map(async (id) => scriptEntries(context, id)),
820
- );
881
+ const reading = [];
882
+ for (const id of context.getModuleIds()) {
883
+ if (context.getModuleInfo(id)?.isEntry === true) {
884
+ reading.push(scriptEntries(context, id));
885
+ }
886
+ }
887
+ const entries = await Promise.all(reading);
821
888
  // A script the index cannot read could use any export.
822
- const known = entries.every((scripts) => scripts !== undefined);
823
- return buildUsageIndex(known ? entries.flat() : [], {
889
+ const scriptIds: string[] = [];
890
+ let known = true;
891
+ for (const scripts of entries) {
892
+ if (scripts === undefined) {
893
+ known = false;
894
+ break;
895
+ }
896
+ scriptIds.push(...scripts);
897
+ }
898
+ return buildUsageIndex(known ? scriptIds : [], {
824
899
  resolve: async (source, importer) => {
825
900
  const resolved = await context.resolve(source, importer);
826
901
  return !resolved || resolved.external || resolved.id.includes('/node_modules/')
@@ -888,7 +963,12 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
888
963
  if (!file.includes('/node_modules/')) {
889
964
  return true;
890
965
  }
891
- return (optimizer.packages ?? []).some((name) => file.includes(`/node_modules/${name}/`));
966
+ for (const name of optimizer.packages ?? []) {
967
+ if (file.includes(`/node_modules/${name}/`)) {
968
+ return true;
969
+ }
970
+ }
971
+ return false;
892
972
  };
893
973
 
894
974
  /** The listed packages already warned about, by environment. */
@@ -900,9 +980,13 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
900
980
  * copies them would hydrate different markup.
901
981
  */
902
982
  const warnExternalPackage = (context: Rollup.PluginContext, source: string): void => {
903
- const name = (optimizer.packages ?? []).find(
904
- (item) => source === item || source.startsWith(`${item}/`),
905
- );
983
+ let name: string | undefined;
984
+ for (const item of optimizer.packages ?? []) {
985
+ if (source === item || source.startsWith(`${item}/`)) {
986
+ name = item;
987
+ break;
988
+ }
989
+ }
906
990
  const key = environmentKey(context, name ?? '');
907
991
  if (name === undefined || warnedPackages.has(key)) {
908
992
  return;
@@ -1047,7 +1131,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1047
1131
  // The components copied here that leave their module, by module.
1048
1132
  const absorbed = new Map<string, Set<string>>();
1049
1133
  // How many modules use the original of a copy, this one included.
1050
- const usersOf = (copy: Copy): number => {
1134
+ const countUsers = (copy: Copy): number => {
1051
1135
  const [module = '', exported = ''] = copy.key.split('\0');
1052
1136
  return usage.users(module, exported, id, absorbed);
1053
1137
  };
@@ -1100,13 +1184,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1100
1184
  for (const specifier of statement.specifiers) {
1101
1185
  const binding = scopes.root.bindings.get(specifier.local.name);
1102
1186
  // Only tags are copied. The import stays for any other use.
1103
- const tags = (binding?.references ?? []).filter((reference) => {
1104
- const parent = parents.get(reference);
1105
- return (
1106
- (parent?.type === 'JSXOpeningElement' || parent?.type === 'JSXClosingElement') &&
1107
- parent.name === reference
1108
- );
1109
- });
1187
+ const tags = findTags(binding?.references ?? [], parents);
1110
1188
  if (
1111
1189
  specifier.type === 'ImportNamespaceSpecifier' ||
1112
1190
  binding?.imported === undefined ||
@@ -1149,36 +1227,48 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1149
1227
  edit.append(`\n${copy.text}\n`);
1150
1228
  }
1151
1229
  edit.append(`\n${imports.join('\n')}\n`);
1230
+ const importedContexts: Record<string, string[]> = {};
1231
+ for (const [module, exported] of contexts) {
1232
+ importedContexts[module] = [...exported];
1233
+ }
1234
+ const sharedComponents: Record<string, number> = {};
1235
+ const alwaysInlineComponents: string[] = [];
1236
+ for (const copy of copies) {
1237
+ const users = countUsers(copy);
1238
+ if (users !== 1) {
1239
+ sharedComponents[copy.name] = users;
1240
+ }
1241
+ if (copy.fromPackage) {
1242
+ alwaysInlineComponents.push(copy.name);
1243
+ }
1244
+ }
1152
1245
  result = compile(edit.toString(), {
1153
1246
  ...compileOptionsOfModule,
1154
1247
  filename,
1155
1248
  sourceMap: wantsMaps(),
1156
- importedContexts: Object.fromEntries(
1157
- [...contexts].map(([module, exported]) => [module, [...exported]]),
1158
- ),
1249
+ importedContexts,
1159
1250
  // The original of a copy stays in its module for its other users.
1160
- sharedComponents: Object.fromEntries(
1161
- copies
1162
- .map((copy): [string, number] => [copy.name, usersOf(copy)])
1163
- .filter(([, users]) => users !== 1),
1164
- ),
1251
+ sharedComponents,
1165
1252
  // The estimate cannot see what a package's own modules use, so a
1166
1253
  // copy of its component never counts its declaration, or the
1167
1254
  // runtime code only it used, as removed. Listing the package asks
1168
1255
  // for its components to inline wherever they can be.
1169
- alwaysInlineComponents: copies
1170
- .filter((copy) => copy.fromPackage)
1171
- .map((copy) => copy.name),
1256
+ alwaysInlineComponents,
1172
1257
  });
1173
1258
  const left = analyzeScopes(parse(filename, result.code)).root.bindings;
1174
- const stuck = copies.filter((copy) => left.has(copy.name));
1259
+ const stuck = [];
1260
+ for (const copy of copies) {
1261
+ if (left.has(copy.name)) {
1262
+ stuck.push(copy);
1263
+ }
1264
+ }
1175
1265
  if (stuck.length === 0) {
1176
1266
  break;
1177
1267
  }
1178
1268
  for (const copy of stuck) {
1179
1269
  excluded.add(copy.key);
1180
1270
  copies.splice(copies.indexOf(copy), 1);
1181
- const reason = result.skipped?.find((entry) => entry.name === copy.name)?.reason;
1271
+ const reason = findSkipReason(result.skipped ?? [], copy.name);
1182
1272
  copySkips?.push({
1183
1273
  pass: 'inline',
1184
1274
  reason: `copy-${reason ?? 'left'}`,
@@ -1190,8 +1280,15 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1190
1280
  if (!result || !edit) {
1191
1281
  break;
1192
1282
  }
1193
- // Their uses of other components move here with them.
1194
- for (const copy of copies.filter((item) => usersOf(item) === 1)) {
1283
+ // Their uses of other components move here with them. Count every copy's
1284
+ // users first, since moving one changes what the next one counts.
1285
+ const sole: Copy[] = [];
1286
+ for (const copy of copies) {
1287
+ if (countUsers(copy) === 1) {
1288
+ sole.push(copy);
1289
+ }
1290
+ }
1291
+ for (const copy of sole) {
1195
1292
  const [module = '', exported = ''] = copy.key.split('\0');
1196
1293
  absorbed.set(module, new Set([...(absorbed.get(module) ?? []), exported]));
1197
1294
  }
@@ -1330,7 +1427,13 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1330
1427
  return { code, map: combineMaps(wantsMaps(), maps) };
1331
1428
  }
1332
1429
 
1333
- const main = plugins.find((plugin) => plugin.name === 'solid');
1430
+ let main: Plugin | undefined;
1431
+ for (const plugin of plugins) {
1432
+ if (plugin.name === 'solid') {
1433
+ main = plugin;
1434
+ break;
1435
+ }
1436
+ }
1334
1437
  const originalTransform = main?.transform;
1335
1438
  const originalHandler =
1336
1439
  typeof originalTransform === 'function' ? originalTransform : originalTransform?.handler;
@@ -75,7 +75,7 @@ interface TopLevelFunction {
75
75
  * The function a top-level binding holds: `function A() {}`, or
76
76
  * `const A = () => ...`.
77
77
  */
78
- function functionOf(binding: Binding): TopLevelFunction | undefined {
78
+ function findTopLevelFunction(binding: Binding): TopLevelFunction | undefined {
79
79
  const { declaration } = binding;
80
80
  if (declaration.type === 'FunctionDeclaration') {
81
81
  return { binding, fn: declaration, kind: 'declaration' };
@@ -156,10 +156,26 @@ export function readReexport(
156
156
  return undefined;
157
157
  }
158
158
 
159
+ function addDeclared(
160
+ exports: Map<string, Binding>,
161
+ declarators: readonly { id: { type: string; name?: string } }[],
162
+ bindings: ReadonlyMap<string, Binding>,
163
+ ): void {
164
+ for (const declarator of declarators) {
165
+ const binding =
166
+ declarator.id.type === 'Identifier' && declarator.id.name !== undefined
167
+ ? bindings.get(declarator.id.name)
168
+ : undefined;
169
+ if (binding !== undefined) {
170
+ exports.set(binding.name, binding);
171
+ }
172
+ }
173
+ }
174
+
159
175
  /**
160
176
  * The names a module exports, each with the top-level binding it exports.
161
177
  */
162
- function exportsOf(program: Program, scopes: ScopeAnalysis): Map<string, Binding> {
178
+ function collectExports(program: Program, scopes: ScopeAnalysis): Map<string, Binding> {
163
179
  const exports = new Map<string, Binding>();
164
180
  const { bindings } = scopes.root;
165
181
  for (const statement of program.body) {
@@ -171,12 +187,7 @@ function exportsOf(program: Program, scopes: ScopeAnalysis): Map<string, Binding
171
187
  exports.set(declaration.id.name, binding);
172
188
  }
173
189
  } else if (declaration?.type === 'VariableDeclaration') {
174
- const declared = declaration.declarations.map((declarator) =>
175
- declarator.id.type === 'Identifier' ? bindings.get(declarator.id.name) : undefined,
176
- );
177
- for (const binding of declared.filter((item) => item !== undefined)) {
178
- exports.set(binding.name, binding);
179
- }
190
+ addDeclared(exports, declaration.declarations, bindings);
180
191
  }
181
192
  for (const specifier of statement.specifiers) {
182
193
  const local = specifier.local.type === 'Identifier' ? specifier.local.name : undefined;
@@ -234,12 +245,12 @@ function outerBindings(fn: Node, self: Binding, scopes: ScopeAnalysis): Map<Node
234
245
  export function exposeLocals(code: string, filename: string): EditResult | undefined {
235
246
  const program = parse(filename, code);
236
247
  const scopes = analyzeScopes(program);
237
- const exports = exportsOf(program, scopes);
248
+ const exports = collectExports(program, scopes);
238
249
  const exported = new Set(exports.values());
239
250
  const needed = new Set<Binding>();
240
251
  for (const [name, binding] of exports) {
241
252
  const component =
242
- isCapitalized(binding.name) || name === 'default' ? functionOf(binding) : undefined;
253
+ isCapitalized(binding.name) || name === 'default' ? findTopLevelFunction(binding) : undefined;
243
254
  if (!component) {
244
255
  continue;
245
256
  }
@@ -253,9 +264,10 @@ export function exposeLocals(code: string, filename: string): EditResult | undef
253
264
  return undefined;
254
265
  }
255
266
  const s = new MagicString(code);
256
- const specifiers = [...needed].map(
257
- (binding) => `${binding.name} as ${LOCAL_EXPORT}${binding.name}`,
258
- );
267
+ const specifiers: string[] = [];
268
+ for (const binding of needed) {
269
+ specifiers.push(`${binding.name} as ${LOCAL_EXPORT}${binding.name}`);
270
+ }
259
271
  s.append(`\nexport { ${specifiers.join(', ')} };\n`);
260
272
  return { code: s.toString(), map: generateMap(s, filename) };
261
273
  }
@@ -339,10 +351,10 @@ export function readExportedComponent(
339
351
  ): ExportedComponent | undefined {
340
352
  const program = parse(filename, code);
341
353
  const scopes = analyzeScopes(program);
342
- const exports = exportsOf(program, scopes);
354
+ const exports = collectExports(program, scopes);
343
355
  const named = exports.get(exportName);
344
356
  const binding = named ? aliasedBinding(named) : undefined;
345
- const component = binding ? functionOf(binding) : undefined;
357
+ const component = binding ? findTopLevelFunction(binding) : undefined;
346
358
  if (!binding || !component) {
347
359
  return undefined;
348
360
  }
@@ -33,17 +33,22 @@ export function summarizeSkips(skips: readonly Skip[]): ReasonSummary[] {
33
33
  group.names.set(skip.name, (group.names.get(skip.name) ?? 0) + 1);
34
34
  groups.set(key, group);
35
35
  }
36
- return [...groups.values()]
37
- .map(({ pass, reason, names }) => ({
36
+ const summaries: ReasonSummary[] = [];
37
+ for (const { pass, reason, names } of groups.values()) {
38
+ let count = 0;
39
+ for (const times of names.values()) {
40
+ count += times;
41
+ }
42
+ summaries.push({
38
43
  pass,
39
44
  reason,
40
- count: [...names.values()].reduce((sum, count) => sum + count, 0),
45
+ count,
41
46
  names: [...names].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])),
42
- }))
43
- .sort(
44
- (a, b) =>
45
- b.count - a.count || a.pass.localeCompare(b.pass) || a.reason.localeCompare(b.reason),
46
- );
47
+ });
48
+ }
49
+ return summaries.sort(
50
+ (a, b) => b.count - a.count || a.pass.localeCompare(b.pass) || a.reason.localeCompare(b.reason),
51
+ );
47
52
  }
48
53
 
49
54
  /** The most names listed for a reason. */
@@ -58,11 +63,15 @@ export function formatReport(report: OptimizerReport): string {
58
63
  if (summaries.length === 0) {
59
64
  lines.push(' nothing');
60
65
  }
61
- const reasonWidth = Math.max(0, ...summaries.map((summary) => summary.reason.length));
66
+ let reasonWidth = 0;
62
67
  for (const summary of summaries) {
63
- const shown = summary.names
64
- .slice(0, NAMES_SHOWN)
65
- .map(([name, count]) => (count > 1 ? `${name}×${String(count)}` : name));
68
+ reasonWidth = Math.max(reasonWidth, summary.reason.length);
69
+ }
70
+ for (const summary of summaries) {
71
+ const shown: string[] = [];
72
+ for (const [name, count] of summary.names.slice(0, NAMES_SHOWN)) {
73
+ shown.push(count > 1 ? `${name}×${String(count)}` : name);
74
+ }
66
75
  if (summary.names.length > NAMES_SHOWN) {
67
76
  shown.push(`${String(summary.names.length - NAMES_SHOWN)} more`);
68
77
  }