solid-optimizer 1.0.0-next.0 → 1.0.0-next.2

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
@@ -17,6 +17,7 @@
17
17
  import { readFile } from 'node:fs/promises';
18
18
  import { createRequire } from 'node:module';
19
19
  import path from 'node:path';
20
+ import { gzipSync } from 'node:zlib';
20
21
  import remapping from '@jridgewell/remapping';
21
22
  import MagicString from 'magic-string';
22
23
  import type * as SolidCompiler from '@solidjs/compiler';
@@ -24,7 +25,7 @@ import type { Options as SolidPluginOptions } from '@solidjs/vite-plugin';
24
25
  import solidPlugin from '@solidjs/vite-plugin';
25
26
  import type { Node, Program } from 'oxc-parser';
26
27
  import type { Plugin, ResolvedConfig, Rollup } from 'vite';
27
- import { createFilter, transformWithOxc } from 'vite';
28
+ import { createFilter, minifySync, transformWithOxc } from 'vite';
28
29
  import type { CompileOptions, CompileResult, ModuleConstants } from '../compile';
29
30
  import { compile, readModuleConstants } from '../compile';
30
31
  import { collectParents, forEachChild, isIntrinsicTag, parse } from '../ast';
@@ -36,7 +37,7 @@ import { sharedGlobals } from './globals';
36
37
  import type { Skip } from '../context';
37
38
  import type { OptimizerReport } from './report';
38
39
  import { formatReport } from './report';
39
- import { exposeLocals, readExportedComponent } from './inject';
40
+ import { exposeLocals, readExportedComponent, readReexport } from './inject';
40
41
  import { nameNamespaceTags } from './namespace';
41
42
  import { protectRefs, restoreRefs } from './refs';
42
43
  import type { UsageIndex } from './usage';
@@ -79,6 +80,16 @@ export interface OptimizerOptions extends Pick<
79
80
  * @default false
80
81
  */
81
82
  report?: boolean | ((report: OptimizerReport) => void);
83
+ /**
84
+ * Packages whose components can be copied into the modules that use
85
+ * them, like `['@kobalte/core']`. A package has to publish its JSX, as
86
+ * most Solid libraries do through the `solid` export condition. A copy
87
+ * lets the bundler drop the original, and the runtime code only it used,
88
+ * even when the package lands in another chunk.
89
+ *
90
+ * @default []
91
+ */
92
+ packages?: readonly string[];
82
93
  }
83
94
 
84
95
  export type { OptimizerReport } from './report';
@@ -122,15 +133,22 @@ const LAZY_PLACEHOLDER = /"__SOLID_LAZY_MODULE__:([^"]+)"/g;
122
133
  * The common kinds of attribute: a class, any other attribute, events, and
123
134
  * children. Inlining a component turns a spread onto an element into
124
135
  * attributes like these, in a module that may not use their helpers itself.
125
- * A rarer kind, like `style`, can still need a helper no module imports.
126
- * The chunk is then lowered without optimizing it.
136
+ * A `ref` can come through a spread too, and a link with a dynamic attribute
137
+ * claims its element. A rarer kind, like `style`, can still need a helper no
138
+ * module imports. The chunk is then lowered without optimizing it.
127
139
  */
128
140
  const ATTRIBUTE_SAMPLE = `const a = () => 0;
129
141
  export const Sample = () => (
130
- <div class={a()} id={a()} onClick={a()} onScroll={a()}>{a()}</div>
142
+ <div class={a()} id={a()} onClick={a()} onScroll={a()}>
143
+ {a()}
144
+ <a href="/" title={a()} ref={a} />
145
+ </div>
131
146
  );`;
132
147
 
133
- /** Whether the code spreads anything onto an intrinsic element. */
148
+ /**
149
+ * Whether the code spreads anything onto an intrinsic element, or onto
150
+ * `<Dynamic>`, which becomes one once its `component` is known.
151
+ */
134
152
  function spreadsOntoElement(code: string, filename: string): boolean {
135
153
  if (!code.includes('...')) {
136
154
  return false;
@@ -143,7 +161,7 @@ function spreadsOntoElement(code: string, filename: string): boolean {
143
161
  if (
144
162
  node.type === 'JSXOpeningElement' &&
145
163
  node.name.type === 'JSXIdentifier' &&
146
- isIntrinsicTag(node.name.name) &&
164
+ (isIntrinsicTag(node.name.name) || node.name.name === 'Dynamic') &&
147
165
  node.attributes.some((attribute) => attribute.type === 'JSXSpreadAttribute')
148
166
  ) {
149
167
  found = true;
@@ -155,6 +173,32 @@ function spreadsOntoElement(code: string, filename: string): boolean {
155
173
  return found;
156
174
  }
157
175
 
176
+ /** A chunk optimized and lowered one way, ready to be compared with another. */
177
+ interface ChunkCandidate {
178
+ readonly optimized: CompileResult;
179
+ readonly lowered: SolidCompiler.TransformResult;
180
+ readonly linked: { code: string; map: string };
181
+ }
182
+
183
+ /**
184
+ * How many bytes a chunk takes once minified and gzipped. Minifying drops
185
+ * the runtime code nothing calls anymore, which is what the comparison is
186
+ * for, so it counts even when the build does not minify.
187
+ */
188
+ function shippedSize(candidate: ChunkCandidate, filename: string): number {
189
+ const minified = minifySync(filename, candidate.linked.code, {
190
+ module: true,
191
+ compress: true,
192
+ mangle: true,
193
+ });
194
+ return gzipSync(minified.code).length;
195
+ }
196
+
197
+ /** Whether a module, or the module of a copy's key, is in `node_modules`. */
198
+ function isPackageModule(id: string): boolean {
199
+ return stripQuery(id).replaceAll('\\', '/').includes('/node_modules/');
200
+ }
201
+
158
202
  function loadCompiler(): Compiler {
159
203
  // Use the compiler `@solidjs/vite-plugin` uses, so both lower JSX the same way.
160
204
  const require = createRequire(import.meta.url);
@@ -257,8 +301,15 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
257
301
 
258
302
  /** What the final compile of each chunk or module left alone, by environment. */
259
303
  const skips = new Map<string, Skip[]>();
260
- const addSkips = (context: { environment?: { name: string } }, list?: readonly Skip[]): void => {
261
- if (!list) {
304
+ const addSkips = (
305
+ context: { environment?: { name: string } },
306
+ list?: readonly Skip[],
307
+ module?: string,
308
+ ): void => {
309
+ // A package's own modules are compiled too, but what they leave alone
310
+ // is not something the app can change. A call of a package's component
311
+ // in the app is still reported, from the app's module.
312
+ if (!list || (module !== undefined && isPackageModule(module))) {
262
313
  return;
263
314
  }
264
315
  const environment = context.environment?.name ?? 'client';
@@ -786,6 +837,8 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
786
837
  interface Copy {
787
838
  /** The module and export the copy comes from. */
788
839
  readonly key: string;
840
+ /** Whether it comes from a package in `optimizer.packages`. */
841
+ readonly fromPackage: boolean;
789
842
  readonly name: string;
790
843
  /** The tags in the importer that call it. */
791
844
  readonly tags: Node[];
@@ -805,6 +858,40 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
805
858
  readonly skips: Skip[] | undefined;
806
859
  }
807
860
 
861
+ /**
862
+ * Whether components can be copied from a module: one of the app's, or
863
+ * one of a package listed in `optimizer.packages`.
864
+ */
865
+ const isCopyable = (id: string): boolean => {
866
+ const file = stripQuery(id).replaceAll('\\', '/');
867
+ if (!file.includes('/node_modules/')) {
868
+ return true;
869
+ }
870
+ return (optimizer.packages ?? []).some((name) => file.includes(`/node_modules/${name}/`));
871
+ };
872
+
873
+ /** The listed packages already warned about, by environment. */
874
+ const warnedPackages = new Set<string>();
875
+
876
+ /**
877
+ * Warns once when a listed package is external, like a server build that
878
+ * leaves it to Node. Its components are not copied there, so a build that
879
+ * copies them would hydrate different markup.
880
+ */
881
+ const warnExternalPackage = (context: Rollup.PluginContext, source: string): void => {
882
+ const name = (optimizer.packages ?? []).find(
883
+ (item) => source === item || source.startsWith(`${item}/`),
884
+ );
885
+ const key = environmentKey(context, name ?? '');
886
+ if (name === undefined || warnedPackages.has(key)) {
887
+ return;
888
+ }
889
+ warnedPackages.add(key);
890
+ context.warn(
891
+ `[solid-optimizer] ${name} is external in this build, so its components are not copied. Bundle it, like with \`ssr.noExternal\`, so every build copies the same components.`,
892
+ );
893
+ };
894
+
808
895
  /**
809
896
  * Reads the component `source` exports as `imported`, and imports what it
810
897
  * needs into the importer. `undefined` when it cannot be copied.
@@ -813,21 +900,43 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
813
900
  context: Rollup.PluginContext,
814
901
  id: string,
815
902
  source: string,
816
- imported: string,
903
+ requested: string,
817
904
  state: CopyState,
818
905
  ): Promise<{ key: string; text: (name: string) => string } | undefined> {
819
906
  const skip = (reason: string): void => {
820
- state.skips?.push({ pass: 'inline', reason, name: `${imported} (${source})` });
907
+ state.skips?.push({ pass: 'inline', reason, name: `${requested} (${source})` });
821
908
  };
822
- const resolved = await context.resolve(source, id);
909
+ // The export's name in the module that declares it, past any re-exports.
910
+ let imported = requested;
911
+ let resolved = await context.resolve(source, id);
823
912
  if (!resolved || resolved.external) {
913
+ warnExternalPackage(context, source);
824
914
  skip('copy-external');
825
915
  return undefined;
826
916
  }
827
- if (resolved.id.includes('/node_modules/')) {
917
+ if (!isCopyable(resolved.id)) {
828
918
  skip('copy-package');
829
919
  return undefined;
830
920
  }
921
+ // A module that re-exports the component by name, like a library's
922
+ // entry, leads to the module that declares it.
923
+ for (let depth = 0; depth < 8 && isJSXModule(resolved.id); depth += 1) {
924
+ // oxlint-disable-next-line no-await-in-loop
925
+ const code = await state.load(resolved.id);
926
+ const reexport =
927
+ code === undefined ? undefined : readReexport(code, stripQuery(resolved.id), imported);
928
+ if (!reexport) {
929
+ break;
930
+ }
931
+ // oxlint-disable-next-line no-await-in-loop
932
+ const next = await context.resolve(reexport.source, resolved.id);
933
+ if (!next || next.external || !isCopyable(next.id)) {
934
+ skip('copy-package');
935
+ return undefined;
936
+ }
937
+ resolved = next;
938
+ imported = reexport.imported;
939
+ }
831
940
  if (resolved.id === id) {
832
941
  return undefined;
833
942
  }
@@ -998,7 +1107,8 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
998
1107
  }
999
1108
  if (copy) {
1000
1109
  const name = fresh(specifier.local.name);
1001
- copies.push({ key: copy.key, name, tags, text: copy.text(name) });
1110
+ const fromPackage = isPackageModule(copy.key);
1111
+ copies.push({ key: copy.key, fromPackage, name, tags, text: copy.text(name) });
1002
1112
  }
1003
1113
  }
1004
1114
  }
@@ -1031,6 +1141,13 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1031
1141
  .map((copy): [string, number] => [copy.name, usersOf(copy)])
1032
1142
  .filter(([, users]) => users !== 1),
1033
1143
  ),
1144
+ // The estimate cannot see what a package's own modules use, so a
1145
+ // copy of its component never counts its declaration, or the
1146
+ // runtime code only it used, as removed. Listing the package asks
1147
+ // for its components to inline wherever they can be.
1148
+ alwaysInlineComponents: copies
1149
+ .filter((copy) => copy.fromPackage)
1150
+ .map((copy) => copy.name),
1034
1151
  });
1035
1152
  const left = analyzeScopes(parse(filename, result.code)).root.bindings;
1036
1153
  const stuck = copies.filter((copy) => left.has(copy.name));
@@ -1117,7 +1234,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1117
1234
  copySkips,
1118
1235
  );
1119
1236
  // The rest of the report comes from the chunk this module ends up in.
1120
- addSkips(context, copySkips);
1237
+ addSkips(context, copySkips, id);
1121
1238
  if (imported) {
1122
1239
  code = imported.code;
1123
1240
  maps.push(...imported.maps);
@@ -1248,7 +1365,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1248
1365
  async (target) => loadRecorded(this, id, target),
1249
1366
  copySkips,
1250
1367
  );
1251
- addSkips(this, copySkips);
1368
+ addSkips(this, copySkips, id);
1252
1369
  if (imported) {
1253
1370
  code = imported.code;
1254
1371
  maps.push(...imported.maps);
@@ -1262,7 +1379,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1262
1379
  maps.push(exposed.map);
1263
1380
  }
1264
1381
  }
1265
- addSkips(this, skipped);
1382
+ addSkips(this, skipped, id);
1266
1383
  recorded.set(environmentKey(this, id), code);
1267
1384
  if (code === source) {
1268
1385
  return null;
@@ -1315,29 +1432,54 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1315
1432
  filename: `${filename}.jsx`,
1316
1433
  sourceMap: wantsMaps(),
1317
1434
  });
1318
- let optimized: CompileResult | undefined = compile(chunkCode, {
1435
+ const chunkOptions: CompileOptions = {
1319
1436
  ...compileOptions,
1320
1437
  filename,
1321
1438
  sourceMap: wantsMaps(),
1322
1439
  constantVars: true,
1323
1440
  builtInAliases: runtime.builtInAliases,
1324
- });
1441
+ };
1442
+ // Each module keeps the helpers its own JSX needs, and a merged tree
1443
+ // can need one none of them did. Such a candidate is left out.
1444
+ let missing: MissingHelperError | undefined;
1445
+ const lowerCandidate = (optimized: CompileResult): ChunkCandidate | undefined => {
1446
+ const lowered = lowerChunk(optimized.code);
1447
+ try {
1448
+ const linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
1449
+ return { optimized, lowered, linked };
1450
+ } catch (error) {
1451
+ if (!(error instanceof MissingHelperError)) {
1452
+ throw error;
1453
+ }
1454
+ missing ??= error;
1455
+ return undefined;
1456
+ }
1457
+ };
1458
+ let chosen = lowerCandidate(compile(chunkCode, chunkOptions));
1459
+ // The estimate weighs each component on its own. It cannot see the
1460
+ // runtime code that only leaves the chunk once every call that needs
1461
+ // it is inlined, like `<Dynamic>`, `merge()`, and `omit()` behind a
1462
+ // headless library's components. So the chunk is also built with
1463
+ // every component inlined that can be, and the smaller one is kept,
1464
+ // as minified and gzipped.
1465
+ if (compileOptions.alwaysInline !== true) {
1466
+ const always = compile(chunkCode, { ...chunkOptions, alwaysInline: true });
1467
+ const other = always.code === chosen?.optimized.code ? undefined : lowerCandidate(always);
1468
+ if (other && (!chosen || shippedSize(other, filename) < shippedSize(chosen, filename))) {
1469
+ chosen = other;
1470
+ }
1471
+ }
1472
+ let optimized: CompileResult | undefined;
1325
1473
  let linked: { code: string; map: string };
1326
1474
  let lowered: SolidCompiler.TransformResult;
1327
- try {
1328
- lowered = lowerChunk(optimized.code);
1329
- linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
1475
+ if (chosen) {
1476
+ ({ optimized, lowered, linked } = chosen);
1330
1477
  addSkips(this, optimized.skipped);
1331
- } catch (error) {
1332
- if (!(error instanceof MissingHelperError)) {
1333
- throw error;
1334
- }
1335
- // Each module keeps the helpers its own JSX needs, and a merged
1336
- // tree can need one none of them did. Without it, the chunk is
1337
- // lowered as its modules were written. Chunk mode never hydrates,
1338
- // so the chunks do not have to match anything else.
1339
- this.warn(`${error.message} ${filename} is not optimized.`);
1340
- optimized = undefined;
1478
+ } else {
1479
+ // Without the helper, the chunk is lowered as its modules were
1480
+ // written. Chunk mode never hydrates, so the chunks do not have to
1481
+ // match anything else.
1482
+ this.warn(`${missing?.message ?? ''} ${filename} is not optimized.`);
1341
1483
  addSkips(this, [{ pass: 'inline', reason: 'missing-helper', name: filename }]);
1342
1484
  lowered = lowerChunk(chunkCode);
1343
1485
  linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
@@ -94,6 +94,68 @@ 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
+
97
159
  /**
98
160
  * The names a module exports, each with the top-level binding it exports.
99
161
  */
@@ -278,7 +340,8 @@ export function readExportedComponent(
278
340
  const program = parse(filename, code);
279
341
  const scopes = analyzeScopes(program);
280
342
  const exports = exportsOf(program, scopes);
281
- const binding = exports.get(exportName);
343
+ const named = exports.get(exportName);
344
+ const binding = named ? aliasedBinding(named) : undefined;
282
345
  const component = binding ? functionOf(binding) : undefined;
283
346
  if (!binding || !component) {
284
347
  return undefined;
@@ -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"}