solid-optimizer 0.3.0 → 0.4.0

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/vite/index.ts CHANGED
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import { readFile } from 'node:fs/promises';
18
18
  import { createRequire } from 'node:module';
19
+ import path from 'node:path';
19
20
  import remapping from '@jridgewell/remapping';
20
21
  import type * as Babel from '@babel/core';
21
22
  import MagicString from 'magic-string';
@@ -26,20 +27,23 @@ import type { Options as SolidPluginOptions } from 'vite-plugin-solid';
26
27
  import solidPlugin from 'vite-plugin-solid';
27
28
  import type { CompileOptions, CompileResult, ModuleConstants } from '../compile';
28
29
  import { compile, readModuleConstants } from '../compile';
29
- import { collectParents, parse } from '../ast';
30
+ import { collectParents, forEachChild, isIntrinsicTag, parse } from '../ast';
30
31
  import { analyzeScopes } from '../scope';
31
32
  import { CONTEXT_SAFE_PRIMITIVES } from '../provider';
32
33
  import type { ImportedConstants } from '../constants';
33
34
  import type { Primitive } from '../value';
35
+ import type { Skip } from '../context';
36
+ import type { OptimizerReport } from './report';
37
+ import { formatReport } from './report';
34
38
  import { exposeLocals, readExportedComponent } from './inject';
35
39
  import { nameNamespaceTags } from './namespace';
40
+ import { protectRefs, restoreRefs } from './refs';
36
41
  import type { UsageIndex } from './usage';
37
42
  import { buildUsageIndex } from './usage';
38
43
  import {
39
44
  MARKER,
40
45
  MissingHelperError,
41
46
  addMarker,
42
- generatedImports,
43
47
  linkHelpers,
44
48
  readMarkers,
45
49
  repairJSXSequences,
@@ -71,8 +75,19 @@ export interface OptimizerOptions extends Pick<
71
75
  * @default false
72
76
  */
73
77
  dev?: boolean;
78
+ /**
79
+ * Report what the optimizer leaves alone in each build, and why: each
80
+ * component call that stays a call, each provider that stays, and each
81
+ * memo that stays. `true` prints the report. A function receives it
82
+ * instead, once per build environment.
83
+ *
84
+ * @default false
85
+ */
86
+ report?: boolean | ((report: OptimizerReport) => void);
74
87
  }
75
88
 
89
+ export type { OptimizerReport } from './report';
90
+
76
91
  export interface Options extends Partial<SolidPluginOptions> {
77
92
  /** Set to `false` to use `vite-plugin-solid` as it is. */
78
93
  optimizer?: OptimizerOptions | false;
@@ -127,6 +142,43 @@ function withRelated(helpers: readonly string[]): Set<string> {
127
142
  return result;
128
143
  }
129
144
 
145
+ /**
146
+ * The common kinds of attribute: a class, any other attribute, events, and
147
+ * children. Inlining a component turns a spread onto an element into
148
+ * attributes like these, in a module that may not use their helpers itself.
149
+ * A rarer kind, like `style`, can still need a helper no module imports.
150
+ * The chunk is then lowered without optimizing it.
151
+ */
152
+ const ATTRIBUTE_SAMPLE = `const a = () => 0;
153
+ export const Sample = () => (
154
+ <div class={a()} id={a()} onClick={a()} onScroll={a()}>{a()}</div>
155
+ );`;
156
+
157
+ /** Whether the code spreads anything onto an intrinsic element. */
158
+ function spreadsOntoElement(code: string, filename: string): boolean {
159
+ if (!code.includes('...')) {
160
+ return false;
161
+ }
162
+ let found = false;
163
+ const visit = (node: Node): void => {
164
+ if (found) {
165
+ return;
166
+ }
167
+ if (
168
+ node.type === 'JSXOpeningElement' &&
169
+ node.name.type === 'JSXIdentifier' &&
170
+ isIntrinsicTag(node.name.name) &&
171
+ node.attributes.some((attribute) => attribute.type === 'JSXSpreadAttribute')
172
+ ) {
173
+ found = true;
174
+ return;
175
+ }
176
+ forEachChild(node, visit);
177
+ };
178
+ visit(parse(filename, code));
179
+ return found;
180
+ }
181
+
130
182
  function loadCompiler(): Compiler {
131
183
  // Use the Babel and preset `vite-plugin-solid` uses, so both lower JSX the same way.
132
184
  const require = createRequire(import.meta.url);
@@ -149,13 +201,14 @@ function lower(
149
201
  code: string,
150
202
  filename: string,
151
203
  options: JSXOptions,
204
+ sourceMaps: boolean,
152
205
  ): { code: string; map: string | undefined } {
153
206
  const result = compiler.babel.transformSync(code, {
154
207
  filename,
155
208
  sourceFileName: filename,
156
209
  presets: [[compiler.preset, options]],
157
210
  ast: false,
158
- sourceMaps: true,
211
+ sourceMaps,
159
212
  configFile: false,
160
213
  babelrc: false,
161
214
  parserOpts: {
@@ -169,13 +222,55 @@ function lower(
169
222
  return { code: result.code, map: result.map ? JSON.stringify(result.map) : undefined };
170
223
  }
171
224
 
225
+ /**
226
+ * The helpers `babel-preset-solid` imports from `moduleName` to lower `code`.
227
+ * Only the AST is built, since its code would only be read for its imports.
228
+ */
229
+ function helpersOf(
230
+ compiler: Compiler,
231
+ code: string,
232
+ filename: string,
233
+ options: JSXOptions,
234
+ moduleName: string,
235
+ ): string[] {
236
+ const result = compiler.babel.transformSync(code, {
237
+ filename,
238
+ presets: [[compiler.preset, options]],
239
+ ast: true,
240
+ code: false,
241
+ configFile: false,
242
+ babelrc: false,
243
+ parserOpts: {
244
+ plugins: /\.[mc]?tsx$/i.test(filename) ? ['jsx', 'typescript'] : ['jsx'],
245
+ },
246
+ });
247
+ const names: string[] = [];
248
+ for (const statement of result?.ast?.program.body ?? []) {
249
+ if (statement.type !== 'ImportDeclaration' || statement.source.value !== moduleName) {
250
+ continue;
251
+ }
252
+ for (const specifier of statement.specifiers) {
253
+ // Generated imports are named `_$helper`, which the module's own are not.
254
+ if (specifier.type === 'ImportSpecifier' && specifier.local.name.startsWith('_$')) {
255
+ const { imported } = specifier;
256
+ names.push(imported.type === 'StringLiteral' ? imported.value : imported.name);
257
+ }
258
+ }
259
+ }
260
+ return names;
261
+ }
262
+
172
263
  function stripQuery(id: string): string {
173
264
  return id.replace(/\?.*$/, '');
174
265
  }
175
266
 
176
- function combineMaps(maps: (string | null | undefined)[]): string | null {
267
+ /**
268
+ * Chains the maps of each step into one, or `null` when the build writes no
269
+ * source maps, since chaining the maps of a large chunk takes a while.
270
+ */
271
+ function combineMaps(wanted: boolean, maps: (string | null | undefined)[]): string | null {
177
272
  const present = maps.filter((map): map is string => typeof map === 'string');
178
- if (present.length === 0) {
273
+ if (!wanted || present.length === 0) {
179
274
  return null;
180
275
  }
181
276
  return remapping(present.reverse(), () => null).toString();
@@ -241,9 +336,35 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
241
336
  maxPasses: optimizer.maxPasses,
242
337
  builtIns: [...builtIns],
243
338
  moduleSources,
339
+ report: optimizer.report !== undefined && optimizer.report !== false,
244
340
  };
245
341
 
246
342
  let config: ResolvedConfig | undefined;
343
+ /**
344
+ * A skip's name with the module it names, like `Card (/app/src/card.tsx)`,
345
+ * relative to the project root, or to `node_modules` for a package.
346
+ */
347
+ const shortName = (name: string): string =>
348
+ name.replace(/\((\/.*)\)$/, (whole, file: string) => {
349
+ const index = file.lastIndexOf('/node_modules/');
350
+ if (index !== -1) {
351
+ return `(${file.slice(index + '/node_modules/'.length)})`;
352
+ }
353
+ return config ? `(${path.relative(config.root, file)})` : whole;
354
+ });
355
+
356
+ /** What the final compile of each chunk or module left alone, by environment. */
357
+ const skips = new Map<string, Skip[]>();
358
+ const addSkips = (context: { environment?: { name: string } }, list?: readonly Skip[]): void => {
359
+ if (!list) {
360
+ return;
361
+ }
362
+ const environment = context.environment?.name ?? 'client';
363
+ const entries = skips.get(environment) ?? [];
364
+ entries.push(...list.map((skip) => ({ ...skip, name: shortName(skip.name) })));
365
+ skips.set(environment, entries);
366
+ };
367
+
247
368
  let compiler: Compiler | undefined;
248
369
  let filter: ((id: string) => boolean) | undefined;
249
370
  const getCompiler = (): Compiler => {
@@ -252,6 +373,8 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
252
373
  };
253
374
 
254
375
  const isBuild = (): boolean => config?.command === 'build';
376
+ /** Whether the output needs source maps: while serving, or when the build writes them. */
377
+ const wantsMaps = (): boolean => !isBuild() || Boolean(config?.build.sourcemap);
255
378
 
256
379
  /**
257
380
  * The JSX options the official plugin passes for a posture, so the
@@ -265,6 +388,19 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
265
388
  return { ...posture, ...solidOptions.solid };
266
389
  };
267
390
 
391
+ let sampleHelpers: string[] | undefined;
392
+ /** The helpers the JSX transform uses for attributes in chunk mode. */
393
+ const attributeHelpers = (): string[] => {
394
+ sampleHelpers ??= helpersOf(
395
+ getCompiler(),
396
+ ATTRIBUTE_SAMPLE,
397
+ 'sample.jsx',
398
+ jsxOptions(false),
399
+ moduleName,
400
+ );
401
+ return sampleHelpers;
402
+ };
403
+
268
404
  /**
269
405
  * Whether client builds keep JSX until chunks are rendered.
270
406
  */
@@ -402,12 +538,13 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
402
538
  const filename = stripQuery(id);
403
539
  // The dev server cannot give back the code of a loaded module.
404
540
  if (optimizer.fold === false || !isBuild()) {
405
- return { ...compileOptions, filename };
541
+ return { ...compileOptions, filename, sourceMap: wantsMaps() };
406
542
  }
407
543
  const { imports } = readModuleConstants(code, { filename });
408
544
  return {
409
545
  ...compileOptions,
410
546
  filename,
547
+ sourceMap: wantsMaps(),
411
548
  importedConstants: await importedConstants(context, imports, filename, new Set([filename])),
412
549
  };
413
550
  }
@@ -668,6 +805,8 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
668
805
  readonly importAs: (base: string, imported: string, from: string) => string;
669
806
  /** The code of a module with JSX to copy from, or `undefined` to skip it. */
670
807
  readonly load: (target: string) => Promise<string | undefined>;
808
+ /** Where the copies that are not made are recorded, when the report is on. */
809
+ readonly skips: Skip[] | undefined;
671
810
  }
672
811
 
673
812
  /**
@@ -681,14 +820,23 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
681
820
  imported: string,
682
821
  state: CopyState,
683
822
  ): Promise<{ key: string; text: (name: string) => string } | undefined> {
823
+ const skip = (reason: string): void => {
824
+ state.skips?.push({ pass: 'inline', reason, name: `${imported} (${source})` });
825
+ };
684
826
  const resolved = await context.resolve(source, id);
685
- if (
686
- !resolved ||
687
- resolved.external ||
688
- resolved.id === id ||
689
- resolved.id.includes('/node_modules/') ||
690
- !isJSXModule(resolved.id)
691
- ) {
827
+ if (!resolved || resolved.external) {
828
+ skip('copy-external');
829
+ return undefined;
830
+ }
831
+ if (resolved.id.includes('/node_modules/')) {
832
+ skip('copy-package');
833
+ return undefined;
834
+ }
835
+ if (resolved.id === id) {
836
+ return undefined;
837
+ }
838
+ if (!isJSXModule(resolved.id)) {
839
+ skip('copy-not-jsx');
692
840
  return undefined;
693
841
  }
694
842
  const key = `${resolved.id}\0${imported}`;
@@ -696,11 +844,28 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
696
844
  return undefined;
697
845
  }
698
846
  const loaded = await state.load(resolved.id);
699
- const component = loaded
700
- ? readExportedComponent(loaded, stripQuery(resolved.id), imported, moduleSources)
701
- : undefined;
847
+ if (loaded === undefined) {
848
+ state.excluded.add(key);
849
+ skip('copy-cycle');
850
+ return undefined;
851
+ }
852
+ const component = readExportedComponent(
853
+ loaded,
854
+ stripQuery(resolved.id),
855
+ imported,
856
+ moduleSources,
857
+ );
702
858
  if (!component) {
703
859
  state.excluded.add(key);
860
+ skip('copy-shape');
861
+ return undefined;
862
+ }
863
+ // Its copy would still call a component of that module, so the call
864
+ // site gains nothing. Moving its template out of its module makes both
865
+ // compress worse.
866
+ if (component.wrapsLocal) {
867
+ state.excluded.add(key);
868
+ skip('copy-wrapper');
704
869
  return undefined;
705
870
  }
706
871
  // Each import of the module resolves from it, so the copy imports the same module.
@@ -711,6 +876,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
711
876
  const target = await context.resolve(dependency.source, resolved.id);
712
877
  if (!target) {
713
878
  state.excluded.add(key);
879
+ skip('copy-external');
714
880
  return undefined;
715
881
  }
716
882
  targets.set(dependency.source, target.external ? dependency.source : target.id);
@@ -745,9 +911,11 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
745
911
  id: string,
746
912
  compileOptionsOfModule: CompileOptions,
747
913
  load: (target: string) => Promise<string | undefined>,
748
- ): Promise<{ code: string; maps: string[] } | undefined> {
914
+ copySkips?: Skip[],
915
+ ): Promise<{ code: string; maps: string[]; skipped?: Skip[] } | undefined> {
749
916
  const filename = stripQuery(id);
750
917
  const maps: string[] = [];
918
+ let skipped: Skip[] | undefined;
751
919
  const excluded = new Set<string>();
752
920
  const usage = await usageIndex(context);
753
921
  // The components copied here that leave their module, by module.
@@ -760,6 +928,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
760
928
  // The contexts the copies import, which the provider pass needs to know.
761
929
  const contexts = new Map<string, Set<string>>();
762
930
  let code = source;
931
+ const copyNames = new Map<string, string>();
763
932
  for (let round = 0; round < 4; round += 1) {
764
933
  const program = parse(filename, code);
765
934
  const scopes = analyzeScopes(program);
@@ -825,7 +994,12 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
825
994
  contexts,
826
995
  importAs,
827
996
  load,
997
+ skips: copySkips,
828
998
  });
999
+ if (copy && copySkips) {
1000
+ // A copy the inline pass leaves behind is recorded under the reason it gave.
1001
+ copyNames.set(copy.key, `${binding.imported} (${statement.source.value})`);
1002
+ }
829
1003
  if (copy) {
830
1004
  const name = fresh(specifier.local.name);
831
1005
  copies.push({ key: copy.key, name, tags, text: copy.text(name) });
@@ -851,7 +1025,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
851
1025
  result = compile(edit.toString(), {
852
1026
  ...compileOptionsOfModule,
853
1027
  filename,
854
- sourceMap: true,
1028
+ sourceMap: wantsMaps(),
855
1029
  importedContexts: Object.fromEntries(
856
1030
  [...contexts].map(([module, exported]) => [module, [...exported]]),
857
1031
  ),
@@ -870,6 +1044,12 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
870
1044
  for (const copy of stuck) {
871
1045
  excluded.add(copy.key);
872
1046
  copies.splice(copies.indexOf(copy), 1);
1047
+ const reason = result.skipped?.find((entry) => entry.name === copy.name)?.reason;
1048
+ copySkips?.push({
1049
+ pass: 'inline',
1050
+ reason: `copy-${reason ?? 'left'}`,
1051
+ name: copyNames.get(copy.key) ?? copy.name,
1052
+ });
873
1053
  }
874
1054
  result = undefined;
875
1055
  }
@@ -881,15 +1061,18 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
881
1061
  const [module = '', exported = ''] = copy.key.split('\0');
882
1062
  absorbed.set(module, new Set([...(absorbed.get(module) ?? []), exported]));
883
1063
  }
884
- maps.push(
885
- edit.generateMap({ source: filename, hires: true, includeContent: true }).toString(),
886
- );
1064
+ if (wantsMaps()) {
1065
+ maps.push(
1066
+ edit.generateMap({ source: filename, hires: true, includeContent: true }).toString(),
1067
+ );
1068
+ }
887
1069
  if (result.map) {
888
1070
  maps.push(result.map.toString());
889
1071
  }
890
1072
  code = result.code;
1073
+ ({ skipped } = result);
891
1074
  }
892
- return code === source ? undefined : { code, maps };
1075
+ return code === source ? undefined : { code, maps, skipped };
893
1076
  }
894
1077
 
895
1078
  /**
@@ -920,13 +1103,17 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
920
1103
  // Components imported from other modules inline here, so the bundler
921
1104
  // drops them, and what only they used, before it splits the chunks.
922
1105
  if (moduleCompileOptions.inline !== false) {
1106
+ const copySkips: Skip[] | undefined = compileOptions.report ? [] : undefined;
923
1107
  const imported = await inlineImports(
924
1108
  context,
925
1109
  code,
926
1110
  id,
927
1111
  moduleCompileOptions,
928
1112
  async (target) => loadModule(context, id, target),
1113
+ copySkips,
929
1114
  );
1115
+ // The rest of the report comes from the chunk this module ends up in.
1116
+ addSkips(context, copySkips);
930
1117
  if (imported) {
931
1118
  code = imported.code;
932
1119
  maps.push(...imported.maps);
@@ -947,14 +1134,32 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
947
1134
  : compile(code, { ...moduleCompileOptions, sourceMap: false });
948
1135
  const needed = new Set<string>();
949
1136
  for (const version of new Set([code, inlined?.code ?? code])) {
950
- const dryRun = lower(getCompiler(), version, filename, jsxOptions(false));
951
- for (const helper of generatedImports(dryRun.code, filename, moduleName)) {
1137
+ for (const helper of helpersOf(
1138
+ getCompiler(),
1139
+ version,
1140
+ filename,
1141
+ jsxOptions(false),
1142
+ moduleName,
1143
+ )) {
1144
+ needed.add(helper);
1145
+ }
1146
+ }
1147
+ // A component inlined into another module of the chunk can turn its
1148
+ // spread into any attribute.
1149
+ if (moduleCompileOptions.inline !== false && spreadsOntoElement(code, filename)) {
1150
+ for (const helper of attributeHelpers()) {
952
1151
  needed.add(helper);
953
1152
  }
954
1153
  }
1154
+ // The bundler has to see that a `ref` writes its variable. See `refs.ts`.
1155
+ const protectedRefs = protectRefs(code, filename);
1156
+ if (protectedRefs) {
1157
+ code = protectedRefs.code;
1158
+ maps.push(protectedRefs.map);
1159
+ }
955
1160
  preserved.add(id);
956
1161
  if (needed.size === 0) {
957
- return code === source ? null : { code, map: combineMaps(maps) };
1162
+ return code === source ? null : { code, map: combineMaps(wantsMaps(), maps) };
958
1163
  }
959
1164
  const marked = addMarker(code, filename, {
960
1165
  moduleName,
@@ -964,11 +1169,11 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
964
1169
  builtIns: new Set([...builtIns, 'createContext', ...CONTEXT_SAFE_PRIMITIVES]),
965
1170
  });
966
1171
  if (!marked) {
967
- return code === source ? null : { code, map: combineMaps(maps) };
1172
+ return code === source ? null : { code, map: combineMaps(wantsMaps(), maps) };
968
1173
  }
969
1174
  return {
970
1175
  code: marked.code,
971
- map: combineMaps([...maps, marked.map]),
1176
+ map: combineMaps(wantsMaps(), [...maps, marked.map]),
972
1177
  };
973
1178
  }
974
1179
 
@@ -994,6 +1199,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
994
1199
  moduleConstants.clear();
995
1200
  jsxImports.clear();
996
1201
  usageIndexes.clear();
1202
+ skips.delete(this.environment.name);
997
1203
  },
998
1204
  watchChange() {
999
1205
  moduleConstants.clear();
@@ -1018,13 +1224,22 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1018
1224
  const maps: (string | null | undefined)[] = [result.map?.toString()];
1019
1225
  // Components imported from other modules inline here too. The server
1020
1226
  // and client builds read the same modules, so they inline the same ones.
1227
+ let { skipped } = result;
1021
1228
  if (isBuild() && sourceOptions.inline !== false) {
1022
- const imported = await inlineImports(this, code, id, sourceOptions, async (target) =>
1023
- loadRecorded(this, id, target),
1229
+ const copySkips: Skip[] | undefined = compileOptions.report ? [] : undefined;
1230
+ const imported = await inlineImports(
1231
+ this,
1232
+ code,
1233
+ id,
1234
+ sourceOptions,
1235
+ async (target) => loadRecorded(this, id, target),
1236
+ copySkips,
1024
1237
  );
1238
+ addSkips(this, copySkips);
1025
1239
  if (imported) {
1026
1240
  code = imported.code;
1027
1241
  maps.push(...imported.maps);
1242
+ skipped = imported.skipped ?? skipped;
1028
1243
  }
1029
1244
  // Entries get the extra exports too. The server and client builds
1030
1245
  // have different entries, and both have to copy the same components.
@@ -1034,11 +1249,12 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1034
1249
  maps.push(exposed.map);
1035
1250
  }
1036
1251
  }
1252
+ addSkips(this, skipped);
1037
1253
  recorded.set(environmentKey(this, id), code);
1038
1254
  if (code === source) {
1039
1255
  return null;
1040
1256
  }
1041
- return { code, map: combineMaps(maps) };
1257
+ return { code, map: combineMaps(wantsMaps(), maps) };
1042
1258
  },
1043
1259
  };
1044
1260
 
@@ -1077,16 +1293,26 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1077
1293
  if (!runtime) {
1078
1294
  return null;
1079
1295
  }
1080
- let optimized: CompileResult | undefined = compile(runtime.code, {
1296
+ const restored = restoreRefs(runtime.code, filename);
1297
+ const chunkCode = restored?.code ?? runtime.code;
1298
+ let optimized: CompileResult | undefined = compile(chunkCode, {
1081
1299
  ...compileOptions,
1082
1300
  filename,
1301
+ sourceMap: wantsMaps(),
1083
1302
  constantVars: true,
1084
1303
  builtInAliases: runtime.builtInAliases,
1085
1304
  });
1086
- let lowered = lower(getCompiler(), optimized.code, filename, jsxOptions(false));
1305
+ let lowered = lower(
1306
+ getCompiler(),
1307
+ optimized.code,
1308
+ filename,
1309
+ jsxOptions(false),
1310
+ wantsMaps(),
1311
+ );
1087
1312
  let linked: { code: string; map: string };
1088
1313
  try {
1089
1314
  linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
1315
+ addSkips(this, optimized.skipped);
1090
1316
  } catch (error) {
1091
1317
  if (!(error instanceof MissingHelperError)) {
1092
1318
  throw error;
@@ -1097,14 +1323,16 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1097
1323
  // so the chunks do not have to match anything else.
1098
1324
  this.warn(`${error.message} ${filename} is not optimized.`);
1099
1325
  optimized = undefined;
1100
- lowered = lower(getCompiler(), runtime.code, filename, jsxOptions(false));
1326
+ addSkips(this, [{ pass: 'inline', reason: 'missing-helper', name: filename }]);
1327
+ lowered = lower(getCompiler(), chunkCode, filename, jsxOptions(false), wantsMaps());
1101
1328
  linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
1102
1329
  }
1103
1330
  return {
1104
1331
  code: linked.code,
1105
- map: combineMaps([
1332
+ map: combineMaps(wantsMaps(), [
1106
1333
  repaired?.map,
1107
1334
  runtime.map,
1335
+ restored?.map,
1108
1336
  optimized?.map?.toString(),
1109
1337
  lowered.map,
1110
1338
  linked.map,
@@ -1114,6 +1342,21 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1114
1342
  },
1115
1343
  };
1116
1344
 
1345
+ // Prints the report once every chunk is rendered.
1346
+ chunkPlugin.generateBundle = function generateBundle() {
1347
+ const { report } = optimizer;
1348
+ if (report === undefined || report === false) {
1349
+ return;
1350
+ }
1351
+ const environment = this.environment.name;
1352
+ const result: OptimizerReport = { environment, skips: skips.get(environment) ?? [] };
1353
+ if (typeof report === 'function') {
1354
+ report(result);
1355
+ } else {
1356
+ this.environment.logger.info(formatReport(result));
1357
+ }
1358
+ };
1359
+
1117
1360
  // Runs after `vite:oxc` strips types, which reports the module as plain
1118
1361
  // JavaScript, and before the built-in plugins that parse it again.
1119
1362
  const moduleTypePlugin: Plugin = {
@@ -14,7 +14,7 @@
14
14
  * adds when the module is transformed.
15
15
  */
16
16
  import MagicString from 'magic-string';
17
- import type { Node, Program } from 'oxc-parser';
17
+ import type { Expression, Node, Program } from 'oxc-parser';
18
18
  import { forEachChild, parse, unwrap } from '../ast';
19
19
  import type { Binding, ScopeAnalysis } from '../scope';
20
20
  import { analyzeScopes } from '../scope';
@@ -213,6 +213,45 @@ export interface ExportedComponent {
213
213
  * as `rename` gives it.
214
214
  */
215
215
  readonly copy: (name: string, rename: ReadonlyMap<string, string>) => string;
216
+ /**
217
+ * Whether the component only returns a call of another component of its
218
+ * module, like `(props) => <Icon {...props}><path /></Icon>`.
219
+ */
220
+ readonly wrapsLocal: boolean;
221
+ }
222
+
223
+ /**
224
+ * Whether a function returns JSX whose root calls a component declared at
225
+ * the top of its own module.
226
+ */
227
+ function returnsLocalCall(fn: TopLevelFunction['fn'], scopes: ScopeAnalysis): boolean {
228
+ if (
229
+ fn.type !== 'FunctionDeclaration' &&
230
+ fn.type !== 'FunctionExpression' &&
231
+ fn.type !== 'ArrowFunctionExpression'
232
+ ) {
233
+ return false;
234
+ }
235
+ const { body } = fn;
236
+ if (!body) {
237
+ return false;
238
+ }
239
+ let root: Expression | null | undefined;
240
+ if (body.type === 'BlockStatement') {
241
+ const last = body.body.at(-1);
242
+ root = last?.type === 'ReturnStatement' ? last.argument : undefined;
243
+ } else {
244
+ root = body;
245
+ }
246
+ if (!root) {
247
+ return false;
248
+ }
249
+ const inner = unwrap(root);
250
+ if (inner.type !== 'JSXElement' || inner.openingElement.name.type !== 'JSXIdentifier') {
251
+ return false;
252
+ }
253
+ const binding = scopes.references.get(inner.openingElement.name);
254
+ return binding !== undefined && binding.scope === scopes.root && binding.kind !== 'import';
216
255
  }
217
256
 
218
257
  /**
@@ -307,5 +346,5 @@ export function readExportedComponent(
307
346
  }
308
347
  return `const ${name} = ${s.slice(component.fn.start, component.fn.end)};`;
309
348
  };
310
- return { dependencies, copy };
349
+ return { dependencies, copy, wrapsLocal: returnsLocalCall(component.fn, scopes) };
311
350
  }