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

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/dist/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as readModuleConstants, c as SkipPass, i as compile, l as Primitive, n as CompileResult, o as ImportedConstants, r as ModuleConstants, s as Skip, t as CompileOptions } from "./compile-BRCj4UN7.mjs";
1
+ import { a as readModuleConstants, c as SkipPass, i as compile, l as Primitive, n as CompileResult, o as ImportedConstants, r as ModuleConstants, s as Skip, t as CompileOptions } from "./compile-CwH9mvHD.mjs";
2
2
  export { type CompileOptions, type CompileResult, type ImportedConstants, type ModuleConstants, type Primitive, type Skip, type SkipPass, compile, readModuleConstants };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { n as readModuleConstants, t as compile } from "./compile-BpoiBa6b.mjs";
1
+ import { n as readModuleConstants, t as compile } from "./compile-sCZdwEKG.mjs";
2
2
  export { compile, readModuleConstants };
package/dist/vite.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { s as Skip, t as CompileOptions } from "./compile-BRCj4UN7.mjs";
1
+ import { s as Skip, t as CompileOptions } from "./compile-CwH9mvHD.mjs";
2
2
  import { Options as Options$1 } from "@solidjs/vite-plugin";
3
3
  import { Plugin } from "vite";
4
4
  //#region src/vite/report.d.ts
@@ -35,6 +35,16 @@ export interface OptimizerOptions extends Pick<CompileOptions, 'fold' | 'inline'
35
35
  * @default false
36
36
  */
37
37
  report?: boolean | ((report: OptimizerReport) => void);
38
+ /**
39
+ * Packages whose components can be copied into the modules that use
40
+ * them, like `['@kobalte/core']`. A package has to publish its JSX, as
41
+ * most Solid libraries do through the `solid` export condition. A copy
42
+ * lets the bundler drop the original, and the runtime code only it used,
43
+ * even when the package lands in another chunk.
44
+ *
45
+ * @default []
46
+ */
47
+ packages?: readonly string[];
38
48
  }
39
49
  export interface Options extends Partial<Options$1> {
40
50
  /** Set to `false` to use `@solidjs/vite-plugin` as it is. */
@@ -1 +1 @@
1
- {"version":3,"file":"vite.d.mts","names":["SolidPluginOptions"],"sources":["../src/vite/report.ts","../src/vite/index.ts"],"mappings":";;;;;UAUiB;;WAEN;WACA,gBAAgB;;;;iBCwCV,yBAAyB,KACxC;;;;;;;;;EAWA;;;;;;EAMA;;;;;;;;;EASA,qBAAqB,QAAQ;;iBAKd,gBAAgB,QAAQA;;EAEvC,YAAY;;wBAuIU,eAAe,UAAS,UAAe"}
1
+ {"version":3,"file":"vite.d.mts","names":["SolidPluginOptions"],"sources":["../src/vite/report.ts","../src/vite/index.ts"],"mappings":";;;;;UAUiB;;WAEN;WACA,gBAAgB;;;;iBCyCV,yBAAyB,KACxC;;;;;;;;;EAWA;;;;;;EAMA;;;;;;;;;EASA,qBAAqB,QAAQ;;;;;;;;;;EAU7B;;iBAKe,gBAAgB,QAAQA;;EAEvC,YAAY;;wBAwKU,eAAe,UAAS,UAAe"}
package/dist/vite.mjs CHANGED
@@ -1,12 +1,13 @@
1
- import { a as lookup, c as forEachChild, d as unwrap, i as analyzeScopes, l as isIntrinsicTag, n as readModuleConstants, o as scopeAt, r as CONTEXT_SAFE_PRIMITIVES, s as collectParents, t as compile, u as parse } from "./compile-BpoiBa6b.mjs";
1
+ import { a as lookup, c as forEachChild, d as unwrap, i as analyzeScopes, l as isIntrinsicTag, n as readModuleConstants, o as scopeAt, r as CONTEXT_SAFE_PRIMITIVES, s as collectParents, t as compile, u as parse } from "./compile-sCZdwEKG.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import remapping from "@jridgewell/remapping";
4
4
  import MagicString from "magic-string";
5
5
  import { parseSync } from "oxc-parser";
6
6
  import { readFile } from "node:fs/promises";
7
7
  import path from "node:path";
8
+ import { gzipSync } from "node:zlib";
8
9
  import solidPlugin from "@solidjs/vite-plugin";
9
- import { createFilter, transformWithOxc } from "vite";
10
+ import { createFilter, minifySync, transformWithOxc } from "vite";
10
11
  //#region src/vite/globals.ts
11
12
  /**
12
13
  * The `define` entries and `import.meta.env` values that are the same in
@@ -400,6 +401,42 @@ function functionOf(binding) {
400
401
  }
401
402
  }
402
403
  /**
404
+ * The binding a top-level alias like `const Button = ButtonRoot` names, or
405
+ * the binding itself when it is not one. Libraries often export a component
406
+ * under such a second name.
407
+ */
408
+ function aliasedBinding(binding) {
409
+ let current = binding;
410
+ for (let depth = 0; depth < 8; depth += 1) {
411
+ const { declaration } = current;
412
+ if (declaration.type !== "VariableDeclarator" || current.kind !== "const" || current.mutated || declaration.id !== current.identifier || !declaration.init) return current;
413
+ const init = unwrap(declaration.init);
414
+ const target = init.type === "Identifier" ? current.scope.bindings.get(init.name) : void 0;
415
+ if (!target || target === current || target.mutated) return current;
416
+ current = target;
417
+ }
418
+ return current;
419
+ }
420
+ /**
421
+ * Where a module re-exports `exportName` from, like
422
+ * `export { t as Separator } from './chunk.jsx'`, or `undefined` when it
423
+ * does not re-export it by name.
424
+ */
425
+ function readReexport(code, filename, exportName) {
426
+ const program = parse(filename, code);
427
+ for (const statement of program.body) {
428
+ if (statement.type !== "ExportNamedDeclaration" || !statement.source || statement.exportKind === "type") continue;
429
+ for (const specifier of statement.specifiers) {
430
+ const exported = specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value;
431
+ const local = specifier.local.type === "Identifier" ? specifier.local.name : specifier.local.value;
432
+ if (exported === exportName && specifier.exportKind !== "type") return {
433
+ source: statement.source.value,
434
+ imported: local
435
+ };
436
+ }
437
+ }
438
+ }
439
+ /**
403
440
  * The names a module exports, each with the top-level binding it exports.
404
441
  */
405
442
  function exportsOf(program, scopes) {
@@ -494,7 +531,8 @@ function readExportedComponent(code, filename, exportName, moduleSources) {
494
531
  const program = parse(filename, code);
495
532
  const scopes = analyzeScopes(program);
496
533
  const exports = exportsOf(program, scopes);
497
- const binding = exports.get(exportName);
534
+ const named = exports.get(exportName);
535
+ const binding = named ? aliasedBinding(named) : void 0;
498
536
  const component = binding ? functionOf(binding) : void 0;
499
537
  if (!binding || !component) return;
500
538
  const exportNames = /* @__PURE__ */ new Map();
@@ -908,20 +946,27 @@ const LAZY_PLACEHOLDER = /"__SOLID_LAZY_MODULE__:([^"]+)"/g;
908
946
  * The common kinds of attribute: a class, any other attribute, events, and
909
947
  * children. Inlining a component turns a spread onto an element into
910
948
  * attributes like these, in a module that may not use their helpers itself.
911
- * A rarer kind, like `style`, can still need a helper no module imports.
912
- * The chunk is then lowered without optimizing it.
949
+ * A `ref` can come through a spread too, and a link with a dynamic attribute
950
+ * claims its element. A rarer kind, like `style`, can still need a helper no
951
+ * module imports. The chunk is then lowered without optimizing it.
913
952
  */
914
953
  const ATTRIBUTE_SAMPLE = `const a = () => 0;
915
954
  export const Sample = () => (
916
- <div class={a()} id={a()} onClick={a()} onScroll={a()}>{a()}</div>
955
+ <div class={a()} id={a()} onClick={a()} onScroll={a()}>
956
+ {a()}
957
+ <a href="/" title={a()} ref={a} />
958
+ </div>
917
959
  );`;
918
- /** Whether the code spreads anything onto an intrinsic element. */
960
+ /**
961
+ * Whether the code spreads anything onto an intrinsic element, or onto
962
+ * `<Dynamic>`, which becomes one once its `component` is known.
963
+ */
919
964
  function spreadsOntoElement(code, filename) {
920
965
  if (!code.includes("...")) return false;
921
966
  let found = false;
922
967
  const visit = (node) => {
923
968
  if (found) return;
924
- if (node.type === "JSXOpeningElement" && node.name.type === "JSXIdentifier" && isIntrinsicTag(node.name.name) && node.attributes.some((attribute) => attribute.type === "JSXSpreadAttribute")) {
969
+ if (node.type === "JSXOpeningElement" && node.name.type === "JSXIdentifier" && (isIntrinsicTag(node.name.name) || node.name.name === "Dynamic") && node.attributes.some((attribute) => attribute.type === "JSXSpreadAttribute")) {
925
970
  found = true;
926
971
  return;
927
972
  }
@@ -930,6 +975,23 @@ function spreadsOntoElement(code, filename) {
930
975
  visit(parse(filename, code));
931
976
  return found;
932
977
  }
978
+ /**
979
+ * How many bytes a chunk takes once minified and gzipped. Minifying drops
980
+ * the runtime code nothing calls anymore, which is what the comparison is
981
+ * for, so it counts even when the build does not minify.
982
+ */
983
+ function shippedSize(candidate, filename) {
984
+ const minified = minifySync(filename, candidate.linked.code, {
985
+ module: true,
986
+ compress: true,
987
+ mangle: true
988
+ });
989
+ return gzipSync(minified.code).length;
990
+ }
991
+ /** Whether a module, or the module of a copy's key, is in `node_modules`. */
992
+ function isPackageModule(id) {
993
+ return stripQuery(id).replaceAll("\\", "/").includes("/node_modules/");
994
+ }
933
995
  function loadCompiler() {
934
996
  const require = createRequire(import.meta.url);
935
997
  return createRequire(require.resolve("@solidjs/vite-plugin"))("@solidjs/compiler");
@@ -1009,8 +1071,8 @@ function solidOptimizer(options = {}) {
1009
1071
  };
1010
1072
  /** What the final compile of each chunk or module left alone, by environment. */
1011
1073
  const skips = /* @__PURE__ */ new Map();
1012
- const addSkips = (context, list) => {
1013
- if (!list) return;
1074
+ const addSkips = (context, list, module) => {
1075
+ if (!list || module !== void 0 && isPackageModule(module)) return;
1014
1076
  const environment = context.environment?.name ?? "client";
1015
1077
  const entries = skips.get(environment) ?? [];
1016
1078
  entries.push(...list);
@@ -1331,6 +1393,19 @@ function solidOptimizer(options = {}) {
1331
1393
  })).code;
1332
1394
  }
1333
1395
  /**
1396
+ * The scripts a virtual entry runs, like the server entry `start` mode
1397
+ * generates: the app's modules it imports. It has no file to read, and
1398
+ * the server and client builds have to see the same uses of each export.
1399
+ * `undefined` when the entry has not been loaded or imports none.
1400
+ */
1401
+ function virtualEntryScripts(context, id) {
1402
+ const info = context.getModuleInfo(id);
1403
+ if (!info || info.code === null) return;
1404
+ const scripts = [];
1405
+ for (const imported of [...info.importedIds, ...info.dynamicallyImportedIds]) if (!imported.startsWith("\0") && !imported.includes("/node_modules/")) scripts.push(imported);
1406
+ return scripts.length > 0 ? scripts : void 0;
1407
+ }
1408
+ /**
1334
1409
  * The scripts an entry runs: the entry itself, or the module scripts of an
1335
1410
  * HTML entry. `undefined` when an HTML entry has an inline module script,
1336
1411
  * whose imports the usage index cannot read.
@@ -1341,7 +1416,7 @@ function solidOptimizer(options = {}) {
1341
1416
  try {
1342
1417
  html = await readFile(stripQuery(id), "utf8");
1343
1418
  } catch {
1344
- return;
1419
+ return virtualEntryScripts(context, id);
1345
1420
  }
1346
1421
  const scripts = [];
1347
1422
  for (const [tag] of html.matchAll(/<script\b[^>]*>/gi)) {
@@ -1393,26 +1468,63 @@ function solidOptimizer(options = {}) {
1393
1468
  return `import { ${imported} as ${local} } from ${from};`;
1394
1469
  }
1395
1470
  /**
1471
+ * Whether components can be copied from a module: one of the app's, or
1472
+ * one of a package listed in `optimizer.packages`.
1473
+ */
1474
+ const isCopyable = (id) => {
1475
+ const file = stripQuery(id).replaceAll("\\", "/");
1476
+ if (!file.includes("/node_modules/")) return true;
1477
+ return (optimizer.packages ?? []).some((name) => file.includes(`/node_modules/${name}/`));
1478
+ };
1479
+ /** The listed packages already warned about, by environment. */
1480
+ const warnedPackages = /* @__PURE__ */ new Set();
1481
+ /**
1482
+ * Warns once when a listed package is external, like a server build that
1483
+ * leaves it to Node. Its components are not copied there, so a build that
1484
+ * copies them would hydrate different markup.
1485
+ */
1486
+ const warnExternalPackage = (context, source) => {
1487
+ const name = (optimizer.packages ?? []).find((item) => source === item || source.startsWith(`${item}/`));
1488
+ const key = environmentKey(context, name ?? "");
1489
+ if (name === void 0 || warnedPackages.has(key)) return;
1490
+ warnedPackages.add(key);
1491
+ context.warn(`[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.`);
1492
+ };
1493
+ /**
1396
1494
  * Reads the component `source` exports as `imported`, and imports what it
1397
1495
  * needs into the importer. `undefined` when it cannot be copied.
1398
1496
  */
1399
- async function copyImported(context, id, source, imported, state) {
1497
+ async function copyImported(context, id, source, requested, state) {
1400
1498
  const skip = (reason) => {
1401
1499
  state.skips?.push({
1402
1500
  pass: "inline",
1403
1501
  reason,
1404
- name: `${imported} (${source})`
1502
+ name: `${requested} (${source})`
1405
1503
  });
1406
1504
  };
1407
- const resolved = await context.resolve(source, id);
1505
+ let imported = requested;
1506
+ let resolved = await context.resolve(source, id);
1408
1507
  if (!resolved || resolved.external) {
1508
+ warnExternalPackage(context, source);
1409
1509
  skip("copy-external");
1410
1510
  return;
1411
1511
  }
1412
- if (resolved.id.includes("/node_modules/")) {
1512
+ if (!isCopyable(resolved.id)) {
1413
1513
  skip("copy-package");
1414
1514
  return;
1415
1515
  }
1516
+ for (let depth = 0; depth < 8 && isJSXModule(resolved.id); depth += 1) {
1517
+ const code = await state.load(resolved.id);
1518
+ const reexport = code === void 0 ? void 0 : readReexport(code, stripQuery(resolved.id), imported);
1519
+ if (!reexport) break;
1520
+ const next = await context.resolve(reexport.source, resolved.id);
1521
+ if (!next || next.external || !isCopyable(next.id)) {
1522
+ skip("copy-package");
1523
+ return;
1524
+ }
1525
+ resolved = next;
1526
+ imported = reexport.imported;
1527
+ }
1416
1528
  if (resolved.id === id) return;
1417
1529
  if (!isJSXModule(resolved.id)) {
1418
1530
  skip("copy-not-jsx");
@@ -1529,8 +1641,10 @@ function solidOptimizer(options = {}) {
1529
1641
  if (copy && copySkips) copyNames.set(copy.key, `${binding.imported} (${statement.source.value})`);
1530
1642
  if (copy) {
1531
1643
  const name = fresh(specifier.local.name);
1644
+ const fromPackage = isPackageModule(copy.key);
1532
1645
  copies.push({
1533
1646
  key: copy.key,
1647
+ fromPackage,
1534
1648
  name,
1535
1649
  tags,
1536
1650
  text: copy.text(name)
@@ -1553,7 +1667,8 @@ function solidOptimizer(options = {}) {
1553
1667
  filename,
1554
1668
  sourceMap: wantsMaps(),
1555
1669
  importedContexts: Object.fromEntries([...contexts].map(([module, exported]) => [module, [...exported]])),
1556
- sharedComponents: Object.fromEntries(copies.map((copy) => [copy.name, usersOf(copy)]).filter(([, users]) => users !== 1))
1670
+ sharedComponents: Object.fromEntries(copies.map((copy) => [copy.name, usersOf(copy)]).filter(([, users]) => users !== 1)),
1671
+ alwaysInlineComponents: copies.filter((copy) => copy.fromPackage).map((copy) => copy.name)
1557
1672
  });
1558
1673
  const left = analyzeScopes(parse(filename, result.code)).root.bindings;
1559
1674
  const stuck = copies.filter((copy) => left.has(copy.name));
@@ -1615,7 +1730,7 @@ function solidOptimizer(options = {}) {
1615
1730
  if (moduleCompileOptions.inline !== false) {
1616
1731
  const copySkips = compileOptions.report ? [] : void 0;
1617
1732
  const imported = await inlineImports(context, code, id, moduleCompileOptions, async (target) => loadModule(context, id, target), copySkips);
1618
- addSkips(context, copySkips);
1733
+ addSkips(context, copySkips, id);
1619
1734
  if (imported) {
1620
1735
  code = imported.code;
1621
1736
  maps.push(...imported.maps);
@@ -1713,7 +1828,7 @@ function solidOptimizer(options = {}) {
1713
1828
  if (isBuild() && sourceOptions.inline !== false) {
1714
1829
  const copySkips = compileOptions.report ? [] : void 0;
1715
1830
  const imported = await inlineImports(this, code, id, sourceOptions, async (target) => loadRecorded(this, id, target), copySkips);
1716
- addSkips(this, copySkips);
1831
+ addSkips(this, copySkips, id);
1717
1832
  if (imported) {
1718
1833
  code = imported.code;
1719
1834
  maps.push(...imported.maps);
@@ -1725,7 +1840,7 @@ function solidOptimizer(options = {}) {
1725
1840
  maps.push(exposed.map);
1726
1841
  }
1727
1842
  }
1728
- addSkips(this, skipped);
1843
+ addSkips(this, skipped, id);
1729
1844
  recorded.set(environmentKey(this, id), code);
1730
1845
  if (code === source) return null;
1731
1846
  return {
@@ -1766,23 +1881,45 @@ function solidOptimizer(options = {}) {
1766
1881
  filename: `${filename}.jsx`,
1767
1882
  sourceMap: wantsMaps()
1768
1883
  });
1769
- let optimized = compile(chunkCode, {
1884
+ const chunkOptions = {
1770
1885
  ...compileOptions,
1771
1886
  filename,
1772
1887
  sourceMap: wantsMaps(),
1773
1888
  constantVars: true,
1774
1889
  builtInAliases: runtime.builtInAliases
1775
- });
1890
+ };
1891
+ let missing;
1892
+ const lowerCandidate = (optimized) => {
1893
+ const lowered = lowerChunk(optimized.code);
1894
+ try {
1895
+ return {
1896
+ optimized,
1897
+ lowered,
1898
+ linked: linkHelpers(lowered.code, filename, moduleName, runtime.helpers)
1899
+ };
1900
+ } catch (error) {
1901
+ if (!(error instanceof MissingHelperError)) throw error;
1902
+ missing ??= error;
1903
+ return;
1904
+ }
1905
+ };
1906
+ let chosen = lowerCandidate(compile(chunkCode, chunkOptions));
1907
+ if (compileOptions.alwaysInline !== true) {
1908
+ const always = compile(chunkCode, {
1909
+ ...chunkOptions,
1910
+ alwaysInline: true
1911
+ });
1912
+ const other = always.code === chosen?.optimized.code ? void 0 : lowerCandidate(always);
1913
+ if (other && (!chosen || shippedSize(other, filename) < shippedSize(chosen, filename))) chosen = other;
1914
+ }
1915
+ let optimized;
1776
1916
  let linked;
1777
1917
  let lowered;
1778
- try {
1779
- lowered = lowerChunk(optimized.code);
1780
- linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
1918
+ if (chosen) {
1919
+ ({optimized, lowered, linked} = chosen);
1781
1920
  addSkips(this, optimized.skipped);
1782
- } catch (error) {
1783
- if (!(error instanceof MissingHelperError)) throw error;
1784
- this.warn(`${error.message} ${filename} is not optimized.`);
1785
- optimized = void 0;
1921
+ } else {
1922
+ this.warn(`${missing?.message ?? ""} ${filename} is not optimized.`);
1786
1923
  addSkips(this, [{
1787
1924
  pass: "inline",
1788
1925
  reason: "missing-helper",