solid-optimizer 1.0.0-next.1 → 1.0.0-next.10

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.
@@ -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' };
@@ -94,10 +94,88 @@ function functionOf(binding: Binding): TopLevelFunction | undefined {
94
94
  return undefined;
95
95
  }
96
96
 
97
+ /**
98
+ * The binding a top-level alias like `const Button = ButtonRoot` names, or
99
+ * the binding itself when it is not one. Libraries often export a component
100
+ * under such a second name.
101
+ */
102
+ function aliasedBinding(binding: Binding): Binding {
103
+ let current = binding;
104
+ for (let depth = 0; depth < 8; depth += 1) {
105
+ const { declaration } = current;
106
+ if (
107
+ declaration.type !== 'VariableDeclarator' ||
108
+ current.kind !== 'const' ||
109
+ current.mutated ||
110
+ declaration.id !== current.identifier ||
111
+ !declaration.init
112
+ ) {
113
+ return current;
114
+ }
115
+ const init = unwrap(declaration.init);
116
+ const target = init.type === 'Identifier' ? current.scope.bindings.get(init.name) : undefined;
117
+ if (!target || target === current || target.mutated) {
118
+ return current;
119
+ }
120
+ current = target;
121
+ }
122
+ return current;
123
+ }
124
+
125
+ /**
126
+ * Where a module re-exports `exportName` from, like
127
+ * `export { t as Separator } from './chunk.jsx'`, or `undefined` when it
128
+ * does not re-export it by name.
129
+ */
130
+ export function readReexport(
131
+ code: string,
132
+ filename: string,
133
+ exportName: string,
134
+ ): { source: string; imported: string } | undefined {
135
+ const program = parse(filename, code);
136
+ for (const statement of program.body) {
137
+ if (
138
+ statement.type !== 'ExportNamedDeclaration' ||
139
+ !statement.source ||
140
+ statement.exportKind === 'type'
141
+ ) {
142
+ continue;
143
+ }
144
+ for (const specifier of statement.specifiers) {
145
+ const exported =
146
+ specifier.exported.type === 'Identifier'
147
+ ? specifier.exported.name
148
+ : specifier.exported.value;
149
+ const local =
150
+ specifier.local.type === 'Identifier' ? specifier.local.name : specifier.local.value;
151
+ if (exported === exportName && specifier.exportKind !== 'type') {
152
+ return { source: statement.source.value, imported: local };
153
+ }
154
+ }
155
+ }
156
+ return undefined;
157
+ }
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
+
97
175
  /**
98
176
  * The names a module exports, each with the top-level binding it exports.
99
177
  */
100
- function exportsOf(program: Program, scopes: ScopeAnalysis): Map<string, Binding> {
178
+ function collectExports(program: Program, scopes: ScopeAnalysis): Map<string, Binding> {
101
179
  const exports = new Map<string, Binding>();
102
180
  const { bindings } = scopes.root;
103
181
  for (const statement of program.body) {
@@ -109,12 +187,7 @@ function exportsOf(program: Program, scopes: ScopeAnalysis): Map<string, Binding
109
187
  exports.set(declaration.id.name, binding);
110
188
  }
111
189
  } else if (declaration?.type === 'VariableDeclaration') {
112
- const declared = declaration.declarations.map((declarator) =>
113
- declarator.id.type === 'Identifier' ? bindings.get(declarator.id.name) : undefined,
114
- );
115
- for (const binding of declared.filter((item) => item !== undefined)) {
116
- exports.set(binding.name, binding);
117
- }
190
+ addDeclared(exports, declaration.declarations, bindings);
118
191
  }
119
192
  for (const specifier of statement.specifiers) {
120
193
  const local = specifier.local.type === 'Identifier' ? specifier.local.name : undefined;
@@ -172,12 +245,12 @@ function outerBindings(fn: Node, self: Binding, scopes: ScopeAnalysis): Map<Node
172
245
  export function exposeLocals(code: string, filename: string): EditResult | undefined {
173
246
  const program = parse(filename, code);
174
247
  const scopes = analyzeScopes(program);
175
- const exports = exportsOf(program, scopes);
248
+ const exports = collectExports(program, scopes);
176
249
  const exported = new Set(exports.values());
177
250
  const needed = new Set<Binding>();
178
251
  for (const [name, binding] of exports) {
179
252
  const component =
180
- isCapitalized(binding.name) || name === 'default' ? functionOf(binding) : undefined;
253
+ isCapitalized(binding.name) || name === 'default' ? findTopLevelFunction(binding) : undefined;
181
254
  if (!component) {
182
255
  continue;
183
256
  }
@@ -191,9 +264,10 @@ export function exposeLocals(code: string, filename: string): EditResult | undef
191
264
  return undefined;
192
265
  }
193
266
  const s = new MagicString(code);
194
- const specifiers = [...needed].map(
195
- (binding) => `${binding.name} as ${LOCAL_EXPORT}${binding.name}`,
196
- );
267
+ const specifiers: string[] = [];
268
+ for (const binding of needed) {
269
+ specifiers.push(`${binding.name} as ${LOCAL_EXPORT}${binding.name}`);
270
+ }
197
271
  s.append(`\nexport { ${specifiers.join(', ')} };\n`);
198
272
  return { code: s.toString(), map: generateMap(s, filename) };
199
273
  }
@@ -277,9 +351,10 @@ export function readExportedComponent(
277
351
  ): ExportedComponent | undefined {
278
352
  const program = parse(filename, code);
279
353
  const scopes = analyzeScopes(program);
280
- const exports = exportsOf(program, scopes);
281
- const binding = exports.get(exportName);
282
- const component = binding ? functionOf(binding) : undefined;
354
+ const exports = collectExports(program, scopes);
355
+ const named = exports.get(exportName);
356
+ const binding = named ? aliasedBinding(named) : undefined;
357
+ const component = binding ? findTopLevelFunction(binding) : undefined;
283
358
  if (!binding || !component) {
284
359
  return undefined;
285
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
  }
@@ -58,6 +58,24 @@ function freshName(scopes: ScopeAnalysis, base: string): string {
58
58
  return name;
59
59
  }
60
60
 
61
+ function isAllGenerated(specifiers: readonly ImportDeclarationSpecifier[]): boolean {
62
+ for (const specifier of specifiers) {
63
+ if (!isGeneratedSpecifier(specifier)) {
64
+ return false;
65
+ }
66
+ }
67
+ return true;
68
+ }
69
+
70
+ function hasStatement(functions: readonly { statement: Node }[], statement: Node): boolean {
71
+ for (const entry of functions) {
72
+ if (entry.statement === statement) {
73
+ return true;
74
+ }
75
+ }
76
+ return false;
77
+ }
78
+
61
79
  /**
62
80
  * Whether an import specifier was added by Solid's JSX transform, which
63
81
  * names every helper it imports `_$name`.
@@ -194,7 +212,12 @@ export function addMarker(
194
212
  }
195
213
  const call = `${MARKER}({ ${entries.join(', ')} })`;
196
214
  const s = new MagicString(code);
197
- const functions = topLevelFunctions(program).filter(({ fn }) => containsJSX(fn));
215
+ const functions: { statement: Node; fn: Node }[] = [];
216
+ for (const entry of topLevelFunctions(program)) {
217
+ if (containsJSX(entry.fn)) {
218
+ functions.push(entry);
219
+ }
220
+ }
198
221
  for (const { fn } of functions) {
199
222
  if (
200
223
  fn.type !== 'FunctionDeclaration' &&
@@ -214,10 +237,13 @@ export function addMarker(
214
237
  s.appendLeft(body.end, '; }');
215
238
  }
216
239
  }
217
- const outside = program.body.some(
218
- (statement) =>
219
- !functions.some((entry) => entry.statement === statement) && containsJSX(statement),
220
- );
240
+ let outside = false;
241
+ for (const statement of program.body) {
242
+ if (!hasStatement(functions, statement) && containsJSX(statement)) {
243
+ outside = true;
244
+ break;
245
+ }
246
+ }
221
247
  s.append(
222
248
  `\nimport { ${specifiers.join(', ')} } from ${JSON.stringify(options.moduleName)};\n` +
223
249
  (outside ? `${call};\n` : ''),
@@ -353,7 +379,7 @@ export function linkHelpers(
353
379
  if (
354
380
  statement.type !== 'ImportDeclaration' ||
355
381
  statement.source.value !== moduleName ||
356
- !statement.specifiers.every(isGeneratedSpecifier)
382
+ !isAllGenerated(statement.specifiers)
357
383
  ) {
358
384
  continue;
359
385
  }
package/src/vite/usage.ts CHANGED
@@ -123,12 +123,26 @@ class Usage implements UsageIndex {
123
123
  const users = new Set([user]);
124
124
  for (const [importer, containers] of usage.importers) {
125
125
  const moved = absorbed.get(importer);
126
- users.add([...containers].every((name) => moved?.has(name) === true) ? user : importer);
126
+ users.add(hasEvery(containers, moved) ? user : importer);
127
127
  }
128
128
  // A module the component's module imports never gets a copy of it, so
129
129
  // the original stays for it.
130
- return [...users].some((id) => this.reaches(module, id)) ? 0 : users.size;
130
+ for (const id of users) {
131
+ if (this.reaches(module, id)) {
132
+ return 0;
133
+ }
134
+ }
135
+ return users.size;
136
+ }
137
+ }
138
+
139
+ function hasEvery(names: Iterable<string>, set: ReadonlySet<string> | undefined): boolean {
140
+ for (const name of names) {
141
+ if (set?.has(name) !== true) {
142
+ return false;
143
+ }
131
144
  }
145
+ return true;
132
146
  }
133
147
 
134
148
  function isTagName(reference: Node, parents: Parents): boolean {
@@ -147,9 +161,13 @@ function declaredNames(declaration: Node | null | undefined): string[] {
147
161
  return [declaration.id.name];
148
162
  }
149
163
  if (declaration?.type === 'VariableDeclaration') {
150
- return declaration.declarations.flatMap((declarator) =>
151
- declarator.id.type === 'Identifier' ? [declarator.id.name] : [],
152
- );
164
+ const names: string[] = [];
165
+ for (const declarator of declaration.declarations) {
166
+ if (declarator.id.type === 'Identifier') {
167
+ names.push(declarator.id.name);
168
+ }
169
+ }
170
+ return names;
153
171
  }
154
172
  return [];
155
173
  }
@@ -206,7 +224,7 @@ function recordModule(
206
224
  // A module that uses its own export keeps it, whoever else copies it.
207
225
  const exported = exportedBindings(program, scopes);
208
226
  // The export names of the top-level declaration a use sits in.
209
- const containersOf = (reference: Node): string[] => {
227
+ const findContainers = (reference: Node): string[] => {
210
228
  let node: Node = reference;
211
229
  let parent = parents.get(node);
212
230
  while (parent && parent.type !== 'Program') {
@@ -232,7 +250,12 @@ function recordModule(
232
250
  }
233
251
  }
234
252
  }
235
- const names = bindings.flatMap((binding) => (binding ? (exported.get(binding) ?? []) : []));
253
+ const names: string[] = [];
254
+ for (const binding of bindings) {
255
+ if (binding) {
256
+ names.push(...(exported.get(binding) ?? []));
257
+ }
258
+ }
236
259
  return names.length > 0 ? names : [UNEXPORTED];
237
260
  };
238
261
 
@@ -244,7 +267,7 @@ function recordModule(
244
267
  }
245
268
  if (imported !== '*') {
246
269
  if (isTagName(reference, parents)) {
247
- usage.tag(target, imported, id, containersOf(reference));
270
+ usage.tag(target, imported, id, findContainers(reference));
248
271
  } else {
249
272
  usage.other(target, imported);
250
273
  }
@@ -254,7 +277,7 @@ function recordModule(
254
277
  const member = parents.get(reference);
255
278
  if (member?.type === 'JSXMemberExpression' && member.object === reference) {
256
279
  if (isTagName(member, parents)) {
257
- usage.tag(target, member.property.name, id, containersOf(reference));
280
+ usage.tag(target, member.property.name, id, findContainers(reference));
258
281
  } else {
259
282
  usage.other(target, member.property.name);
260
283
  }
@@ -299,14 +322,18 @@ function recordModule(
299
322
  }
300
323
 
301
324
  for (const [binding, names] of exported) {
302
- const used = binding.references.some((reference) => {
325
+ let used = false;
326
+ for (const reference of binding.references) {
303
327
  const parent = parents.get(reference);
304
- return (
328
+ if (
305
329
  parent?.type !== 'ExportSpecifier' &&
306
330
  parent?.type !== 'ExportDefaultDeclaration' &&
307
331
  !isClosingTagName(reference, parents)
308
- );
309
- });
332
+ ) {
333
+ used = true;
334
+ break;
335
+ }
336
+ }
310
337
  if (used) {
311
338
  for (const name of names) {
312
339
  usage.other(id, name);
@@ -316,7 +343,7 @@ function recordModule(
316
343
  }
317
344
 
318
345
  /** The import specifiers a module loads, statically or with `import()`. */
319
- function specifiersOf(program: Program): { static: Set<string>; dynamic: Set<string> } {
346
+ function collectSpecifiers(program: Program): { static: Set<string>; dynamic: Set<string> } {
320
347
  const statics = new Set<string>();
321
348
  const dynamics = new Set<string>();
322
349
  for (const statement of program.body) {
@@ -360,46 +387,60 @@ export async function buildUsageIndex(
360
387
  usage.all(entry);
361
388
  }
362
389
  const seen = new Set<string>();
363
- let frontier = entries.filter((id) => SCRIPT.test(id.replace(/\?.*$/, '')));
390
+ let frontier: string[] = [];
391
+ for (const id of entries) {
392
+ if (SCRIPT.test(id.replace(/\?.*$/, ''))) {
393
+ frontier.push(id);
394
+ }
395
+ }
364
396
  while (frontier.length > 0) {
365
397
  for (const id of frontier) {
366
398
  seen.add(id);
367
399
  }
368
- // oxlint-disable-next-line no-await-in-loop
369
- const next = await Promise.all(
370
- frontier.map(async (id) => {
371
- const code = await host.read(id);
372
- let program: Program;
373
- try {
374
- program = parse(id.replace(/\?.*$/, ''), code ?? '');
375
- } catch {
376
- return [];
400
+ async function readModule(id: string): Promise<string[]> {
401
+ const code = await host.read(id);
402
+ let program: Program;
403
+ try {
404
+ program = parse(id.replace(/\?.*$/, ''), code ?? '');
405
+ } catch {
406
+ return [];
407
+ }
408
+ const { static: statics, dynamic } = collectSpecifiers(program);
409
+ const targets = new Map<string, string>();
410
+ async function resolveSource(source: string): Promise<void> {
411
+ const target = await host.resolve(source, id);
412
+ if (target !== undefined) {
413
+ targets.set(source, target);
377
414
  }
378
- const { static: statics, dynamic } = specifiersOf(program);
379
- const targets = new Map<string, string>();
380
- await Promise.all(
381
- [...statics, ...dynamic].map(async (source) => {
382
- const target = await host.resolve(source, id);
383
- if (target !== undefined) {
384
- targets.set(source, target);
385
- }
386
- }),
387
- );
388
- // A module loaded with `import()` is used as a whole.
389
- for (const source of dynamic) {
390
- const target = targets.get(source);
391
- if (target !== undefined) {
392
- usage.all(target);
393
- }
415
+ }
416
+ const resolving: Promise<void>[] = [];
417
+ for (const source of [...statics, ...dynamic]) {
418
+ resolving.push(resolveSource(source));
419
+ }
420
+ await Promise.all(resolving);
421
+ // A module loaded with `import()` is used as a whole.
422
+ for (const source of dynamic) {
423
+ const target = targets.get(source);
424
+ if (target !== undefined) {
425
+ usage.all(target);
394
426
  }
395
- recordModule(usage, id, program, targets);
396
- usage.imports.set(id, [...targets.values()]);
397
- return [...targets.values()];
398
- }),
399
- );
400
- frontier = [...new Set(next.flat())].filter(
401
- (id) => !seen.has(id) && SCRIPT.test(id.replace(/\?.*$/, '')),
402
- );
427
+ }
428
+ recordModule(usage, id, program, targets);
429
+ usage.imports.set(id, [...targets.values()]);
430
+ return [...targets.values()];
431
+ }
432
+ const reading: Promise<string[]>[] = [];
433
+ for (const id of frontier) {
434
+ reading.push(readModule(id));
435
+ }
436
+ // oxlint-disable-next-line no-await-in-loop
437
+ const next = await Promise.all(reading);
438
+ frontier = [];
439
+ for (const id of new Set(next.flat())) {
440
+ if (!seen.has(id) && SCRIPT.test(id.replace(/\?.*$/, ''))) {
441
+ frontier.push(id);
442
+ }
443
+ }
403
444
  }
404
445
  return usage;
405
446
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"compile-BRCj4UN7.d.mts","names":[],"sources":["../src/value.ts","../src/context.ts","../src/constants.ts","../src/compile.ts"],"mappings":";;;;KAUY;;;;KC0DA;;;;;UAMK;WACN,MAAM;;WAEN;;WAEA;;;;;;;;KC5DC,oBAAoB,SAAS,eAAe,SAAS,eAAe;;;UCF/D;;;;;;;EAOf;;;;;;;EAOA;;;;;;EAMA;;;;;;;EAOA;;;;;;;EAOA;;;;;;;EAOA;;;;;;;EAOA;;;;;;EAMA,iBAAiB,SAAS;;;;;;;EAO1B;;;;;;EAMA,oBAAoB;;;;;;EAMpB,kBAAkB,SAAS,eAAe;;;;;;EAM1C,mBAAmB,SAAS;;;;;;;;EAQ5B,mBAAmB,SAAS;;;;;;;;EAQ5B;;;;;;;;EAQA;;;;;;EAMA;;;;;;;EAOA;;UAGe;EACf;;EAEA,KAAK;;;;;EAKL,UAAU;;;;;;;;;;;;;iBAmGI,QAAQ,cAAc,UAAS,iBAAsB;UA0DpD;;;;;EAKf;;;;;;EAMA,SAAS,eAAe;;;;;;;;iBASV,oBACd,cACA,UAAS,KAAK,wEACb"}